File size: 32,540 Bytes
bb9389b
409acf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82014e8
409acf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c259a6
bb9389b
409acf6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "883e3354-1538-4f98-bf42-67552215bba3",
      "metadata": {
        "id": "883e3354-1538-4f98-bf42-67552215bba3"
      },
      "source": [
        "# Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b45bd52f-03e9-419f-8110-1013ff45fb1b",
      "metadata": {
        "tags": [],
        "id": "b45bd52f-03e9-419f-8110-1013ff45fb1b"
      },
      "outputs": [],
      "source": [
        "from huggingface_hub import InferenceClient, login"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "dc9f0411-8bf2-4a20-a6ea-331a2a486b8e",
      "metadata": {
        "tags": [],
        "id": "dc9f0411-8bf2-4a20-a6ea-331a2a486b8e",
        "outputId": "cb57d6e8-7d61-49ca-ec60-05594a7d5842",
        "colab": {
          "referenced_widgets": [
            "515c96c357454fdc9a38ecc995ff1b3d"
          ]
        }
      },
      "outputs": [
        {
          "data": {
            "application/vnd.jupyter.widget-view+json": {
              "model_id": "515c96c357454fdc9a38ecc995ff1b3d",
              "version_major": 2,
              "version_minor": 0
            },
            "text/plain": [
              "VBox(children=(HTML(value='<center> <img\\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "login()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4c254d6f-f3a1-49c1-815e-36e41e75ca25",
      "metadata": {
        "id": "4c254d6f-f3a1-49c1-815e-36e41e75ca25"
      },
      "source": [
        "<div class=\"alert alert-danger\" role=\"alert\" style=\"display: flex; align-items: center;\">\n",
        "    <div style=\"text-align: center; padding-right: 10px;\">\n",
        "        <i class=\"fa fa-exclamation-triangle fa-2x\"></i>\n",
        "    </div>\n",
        "    <div style=\"display: flex; align-items: center; margin-top: 4px;\"> <!-- Added margin-top to lower the text -->\n",
        "        <strong>Warning: You will need to point to a model/deployment that is running.</strong>\n",
        "    </div>\n",
        "</div>\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "84e6cb89-30d3-4ef5-8063-07783798e045",
      "metadata": {
        "id": "84e6cb89-30d3-4ef5-8063-07783798e045"
      },
      "outputs": [],
      "source": [
        "MODEL = \"CohereForAI/c4ai-command-r-plus\"\n",
        "client = InferenceClient(MODEL)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f5fe63f8-dea2-4c61-b6ce-29f173e4c4eb",
      "metadata": {
        "id": "f5fe63f8-dea2-4c61-b6ce-29f173e4c4eb"
      },
      "source": [
        "# Translation\n",
        "Our goal is to explore translation between English and Arabic and how prompt engineering can impact it. There has been [some work](https://arxiv.org/pdf/2308.01391), but we didn't find as much as we were hoping, especially for open source models.\n",
        "\n",
        "We have created a dataset across 6 domains and want to compare each method by having human rankers. We also have human translations to ground these rankings."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "c5bee77b-da1c-43b3-ab14-d15e871f7502",
      "metadata": {
        "id": "c5bee77b-da1c-43b3-ab14-d15e871f7502"
      },
      "source": [
        "## Baseline\n",
        "\n",
        "For our baseline we will translate with a simple system prompt and instruction."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a98b9b67-e68b-43b2-b8e9-0ed1cf85591f",
      "metadata": {
        "id": "a98b9b67-e68b-43b2-b8e9-0ed1cf85591f"
      },
      "source": [
        "### System Prompt\n",
        "This is a pretty basic system prompt. We give a role, and an assumed understanding. We also push for goals like \"highly motivated and detail-oriented\".\n",
        "\n",
        "> You are a skilled translator with extensive experience in English to Arabic translations. You possess a deep understanding of the linguistic, cultural, and contextual nuances essential for accurate and effective translation between these languages. Highly motivated and detail-oriented, you are committed to delivering translations that maintain the integrity and intent of the original text. Your role is crucial in ensuring clear and precise communication in our multilingual system."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "032c86d2-868e-4fa6-b03e-58f1c41434cc",
      "metadata": {
        "tags": [],
        "id": "032c86d2-868e-4fa6-b03e-58f1c41434cc"
      },
      "outputs": [],
      "source": [
        "system_prompt = \"\"\"You are a skilled translator with extensive experience in English and Arabic translations. You possess a deep understanding of the linguistic, cultural, and contextual nuances essential for accurate and effective translation between these languages. Highly motivated and detail-oriented, you are committed to delivering translations that maintain the integrity and intent of the original text. Your role is crucial in ensuring clear and precise communication in our multilingual system.\"\"\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "803ddeba-03de-4f13-95d1-5fb097058cf2",
      "metadata": {
        "id": "803ddeba-03de-4f13-95d1-5fb097058cf2"
      },
      "source": [
        "### Instruction\n",
        "> Translate this from arabic to english: {translation_input}.\n",
        ">\n",
        "> Translation:\n",
        "\n",
        "We will use a simple instruction to get a translation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b7f1722c-c484-4e22-a025-53f95943fc76",
      "metadata": {
        "id": "b7f1722c-c484-4e22-a025-53f95943fc76"
      },
      "outputs": [],
      "source": [
        "def baseline_chat_completion(system_prompt, translation_input):\n",
        "    \"\"\"\n",
        "    Generates a completion for a chat conversation using a specified system prompt and a user input.\n",
        "    \"\"\"\n",
        "    messages = [\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": f\"Translate this from english to arabic: {translation_input}.\\nTranslation: \",\n",
        "        },\n",
        "    ]\n",
        "    return client.chat_completion(messages, max_tokens=10_000)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "96a0ba0b-be47-4eb0-bbc2-c82b0ea1b72e",
      "metadata": {
        "tags": [],
        "id": "96a0ba0b-be47-4eb0-bbc2-c82b0ea1b72e"
      },
      "outputs": [],
      "source": [
        "translation_input = \"Float like a butterfly sting like a bee – his hands can’t hit what his eyes can’t see.\"\n",
        "response = baseline_chat_completion(\n",
        "    system_prompt,\n",
        "    translation_input,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2bca574c-461d-4822-b0dd-b12a3b9846b3",
      "metadata": {
        "id": "2bca574c-461d-4822-b0dd-b12a3b9846b3"
      },
      "source": [
        "### Token Cost\n",
        "Here we can see that the cost is quite cheap, only 92 tokens!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4e305b1e-56e0-44da-8c17-496cbcc35fad",
      "metadata": {
        "tags": [],
        "id": "4e305b1e-56e0-44da-8c17-496cbcc35fad",
        "outputId": "a97a8a75-e2e6-4ac3-e7ac-db674a1f46c9"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "120"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response.usage.prompt_tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "ef24fe6b-d801-4f3e-95ad-cb7f67247bc3",
      "metadata": {
        "tags": [],
        "id": "ef24fe6b-d801-4f3e-95ad-cb7f67247bc3",
        "outputId": "0d7417e1-b648-40aa-eba7-5f1b0dc962b3"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "يطير كالفراشة ويلسع كالنحلة - لا يمكن ليديه أن تصيبا ما لا تستطيع عيناه رؤيته.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a9cdf02-d590-4bcf-a7a8-e6b7817ba715",
      "metadata": {
        "id": "3a9cdf02-d590-4bcf-a7a8-e6b7817ba715"
      },
      "source": [
        "## Manual Purpose Driven Translation\n",
        "\n",
        "[Optimizing Machine Translation through Prompt Engineering](https://arxiv.org/pdf/2308.01391) has done some good exploratory work in examining how prompt engineering can impact translation. They were working between Japanese and English and showed that translations influenced by prompts tailored to **specific purposes** and **target audiences** generally adhered more closely to the translation specifications, suggesting that such prompted translations could be more culturally and contextually appropriate than standard machine translations.\n",
        "\n",
        "### Prompt\n",
        "One of the approaches in the paper was to include the purpose and target audience specification. This was motivated by the author’s experience as a professional translator, leading to the conclusion that these two parameters are essential even in everyday translation work. You can find the prompt below adapted for Arabic to English:\n",
        "\n",
        "> Translate the following English [source text] into Arabic. Please fulfill the following conditions when translating.    \n",
        "> Purpose of the translation: `<Manual description>`  \n",
        "> Target audience: `<Manual description>`  \n",
        "> [source text] `{translation_input}`  \n",
        "> [translated text]\n",
        "\n",
        "You can see that we need to provide the Purpose and the Target Audience for each translation. This makes sense as we will be able to steer our model appropriately, but the drawback is that we need to do this for each subject. In the real world this likely won't scale and is rather tedious.\n",
        "\n",
        "Lets go ahead and create these for each of our datasets."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4714f6a2-fd0b-48ee-80bc-860f40ee2baa",
      "metadata": {
        "tags": [],
        "id": "4714f6a2-fd0b-48ee-80bc-860f40ee2baa"
      },
      "outputs": [],
      "source": [
        "dataset_to_purpose_target = {\n",
        "    \"ELRC-24ss\": {\n",
        "        \"purpose\": \"Enhancing understanding and knowledge about COVID-19 and health-related topics.\",\n",
        "        \"audience\": \"Individuals seeking reliable and comprehensible information about COVID-19 and related health topics.\",\n",
        "    },\n",
        "    \"GNOME-25ss\": {\n",
        "        \"purpose\": \"Facilitating localization and translation of GNOME software.\",\n",
        "        \"audience\": \"Translators and developers working on GNOME projects.\"\n",
        "    },\n",
        "    \"HPLT-25ss\": {\n",
        "        \"purpose\": \"Providing multilingual data for high-performance language technologies.\",\n",
        "        \"audience\": \"Researchers and developers working on multilingual NLP applications.\"\n",
        "    },\n",
        "    \"OpenSubtitles-25ss\": {\n",
        "        \"purpose\": \"Creating parallel corpora from movie and TV subtitles.\",\n",
        "        \"audience\": \"Researchers and developers in NLP and machine translation. And Movies and TV Shows translators\"\n",
        "    },\n",
        "    \"TED2020-25ss\": {\n",
        "        \"purpose\": \"Generating multilingual sentence embeddings using TED transcripts.\",\n",
        "        \"audience\": \"Researchers and developers working on multilingual sentence embeddings.\"\n",
        "    },\n",
        "    \"UNPC-24ss\": {\n",
        "        \"purpose\": \"Offering a parallel corpus of United Nations documents for linguistic research.\",\n",
        "        \"audience\": \"Researchers and linguists studying multilingual and legal texts.\"\n",
        "    }\n",
        "}\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f865e9f8-7c63-4e72-b539-0d5916eda44f",
      "metadata": {
        "id": "f865e9f8-7c63-4e72-b539-0d5916eda44f"
      },
      "outputs": [],
      "source": [
        "def purpose_driven_chat_completion(system_prompt, translation_input, dataset):\n",
        "    \"\"\"\n",
        "    Generates a completion for a chat conversation using a specified system prompt and a user input.\n",
        "    \"\"\"\n",
        "\n",
        "    prompt = f\"\"\"Translate the following English [source text] into Arabic. Please fulfill the following conditions when translating.\n",
        "Purpose of the translation: {dataset_to_purpose_target[dataset]['purpose']}\n",
        "Target audience: {dataset_to_purpose_target[dataset]['audience']}\n",
        "[source text] `{translation_input}`\n",
        "[translated text] \"\"\"\n",
        "\n",
        "    messages = [\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": prompt,\n",
        "        },\n",
        "    ]\n",
        "    return client.chat_completion(messages, max_tokens=10_000)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "4115515d-cbcd-405a-b2e0-a805880a40c4",
      "metadata": {
        "tags": [],
        "id": "4115515d-cbcd-405a-b2e0-a805880a40c4"
      },
      "outputs": [],
      "source": [
        "translation_input = \"We have observed that when groups of stakeholders work to define … visions, this leads to debate over whether to emphasize ecosystem health or human well-being … Whether the priority is ecosystems or people greatly influences stakeholders' assessment of desirable ecological and social states.\"\n",
        "response = purpose_driven_chat_completion(system_prompt, translation_input, \"ELRC-24ss\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "6296d255-d11d-4df7-aa0e-1226ef3d963a",
      "metadata": {
        "tags": [],
        "id": "6296d255-d11d-4df7-aa0e-1226ef3d963a",
        "outputId": "45282f39-18ef-4dc0-f708-1113ca1769ce"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "208"
            ]
          },
          "execution_count": 12,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "response.usage.prompt_tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1f1c6dd0-11bf-4b88-9029-8bce1e7bcb1c",
      "metadata": {
        "tags": [],
        "id": "1f1c6dd0-11bf-4b88-9029-8bce1e7bcb1c",
        "outputId": "a12fc058-249f-4493-eb3e-f021c12651dc"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\"لقد لاحظنا أنه عندما تعمل مجموعات أصحاب المصلحة على تحديد ... الرؤى، فإن هذا يؤدي إلى نقاش حول ما إذا كان ينبغي التركيز على صحة النظام البيئي أو رفاهية الإنسان ... إن معرفة ما إذا كانت الأولوية للنظم البيئية أو للبشر تؤثر بشكل كبير على تقييم أصحاب المصلحة للحالات البيئية والاجتماعية المرغوبة.\"\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "898a909e-88a2-4efb-99ed-64ceee317037",
      "metadata": {
        "id": "898a909e-88a2-4efb-99ed-64ceee317037"
      },
      "source": [
        "## Automatic Purpose Driven Structured Generation Translation\n",
        "\n",
        "Manual Purpose Driven Translation is a great step in the right direction, but its challenging to scale. Instead of having the user submit these purposes and target audiences, what if we use a model to do that? The easiest way to get this input in a format that is convenient is going to be by using [structured generation](https://huggingface.co/blog/evaluation-structured-outputs) to get a json. We can easily do this in InferenceClient easily just by using [tools](https://huggingface.co/docs/huggingface_hub/en/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion.tools)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8aca3847-7f3d-43d3-8e80-0c7e2282073b",
      "metadata": {
        "id": "8aca3847-7f3d-43d3-8e80-0c7e2282073b"
      },
      "source": [
        "## Instruction"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2f5deb21-18fb-4c5b-9045-c7fe5e751c05",
      "metadata": {
        "id": "2f5deb21-18fb-4c5b-9045-c7fe5e751c05"
      },
      "source": [
        "Its usually helpful if we tell the LLM what we want to create when we prompt it. I have found using the tags like `<source text>` can be really useful to denote what you are specifying.\n",
        "\n",
        "> I want to translate the following \\<source text\\> from English into Arabic. But first I want to create a json that includes the following:  \n",
        "{\"intent\": \"\", \"subject\": \"\", \"assumptions relating to content\": \"\", \"purpose\": \"\", \"target audience\": \"\"}.  \n",
        "Can you fill this out and be specific to how this can help you translate in the next step? No need to translate yet!  \n",
        "\\<source text\\>  \n",
        "\\</source text\\>  "
      ]
    },
    {
      "cell_type": "markdown",
      "id": "55f02988-1c63-4f03-a5a6-ca86c83b3c17",
      "metadata": {
        "id": "55f02988-1c63-4f03-a5a6-ca86c83b3c17"
      },
      "source": [
        "## Tool Definition"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "affe3668-aa37-47b5-be37-a0bd5dabab56",
      "metadata": {
        "tags": [],
        "id": "affe3668-aa37-47b5-be37-a0bd5dabab56"
      },
      "outputs": [],
      "source": [
        "translation_tools = [\n",
        "    {\n",
        "        \"type\": \"function\",\n",
        "        \"function\": {\n",
        "            \"name\": \"get_translation_audience_purpose\",\n",
        "            \"description\": \"Get the background of a text to assist in translation\",\n",
        "            \"parameters\": {\n",
        "                \"type\": \"object\",\n",
        "                \"properties\": {\n",
        "                    \"subject\": {\n",
        "                        \"type\": \"string\",\n",
        "                        \"description\": \"The topic or central theme that the text revolves around.\",\n",
        "                    },\n",
        "                    \"assumptions relating to the content\": {\n",
        "                        \"type\": \"string\",\n",
        "                        \"description\": \"Write out any assumptions relating to the text.\",\n",
        "                    },\n",
        "                    \"purpose\": {\n",
        "                        \"type\": \"string\",\n",
        "                        \"description\": \"Why the text was written\",\n",
        "                    },\n",
        "                    \"audience\": {\n",
        "                        \"type\": \"string\",\n",
        "                        \"description\": \"The inferred audience that the text is written for.\",\n",
        "                    },\n",
        "                },\n",
        "                \"required\": [\n",
        "                    \"subject\",\n",
        "                    \"assumptions relating to the content\",\n",
        "                    \"purpose\",\n",
        "                    \"audience\",\n",
        "                ],\n",
        "            },\n",
        "        },\n",
        "    }\n",
        "]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b6436ce6-03af-4206-a283-0c2ecd17bd88",
      "metadata": {
        "id": "b6436ce6-03af-4206-a283-0c2ecd17bd88"
      },
      "outputs": [],
      "source": [
        "def tool_call_chat_completion(system_prompt, translation_input, tools):\n",
        "    \"\"\"\n",
        "    Generates a completion for a chat conversation using a specified system prompt and a user input.\n",
        "    \"\"\"\n",
        "\n",
        "    prompt = f\"\"\"I want to translate the following <source text> from English into Arabic. But first I want to create a json that includes the following:\n",
        "{{\"subject\": \"\", \"assumptions relating to content\": \"\", \"purpose\": \"\", \"target audience\": \"\"}}.\n",
        "Can you fill this out and be specific to how this can help you translate in the next step? No need to translate yet!\n",
        "<source text>\n",
        "{translation_input}\n",
        "</source text>\n",
        "\"\"\"\n",
        "    messages = [\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": prompt,\n",
        "        },\n",
        "    ]\n",
        "    return client.chat_completion(messages, max_tokens=10_000, tools=tools, tool_choice='get_translation_audience_purpose')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a731b2c0-54a3-4b8e-83f6-1663c759cf79",
      "metadata": {
        "tags": [],
        "id": "a731b2c0-54a3-4b8e-83f6-1663c759cf79"
      },
      "outputs": [],
      "source": [
        "translation_input = \"We have observed that when groups of stakeholders work to define … visions, this leads to debate over whether to emphasize ecosystem health or human well-being … Whether the priority is ecosystems or people greatly influences stakeholders' assessment of desirable ecological and social states.\"\n",
        "response = tool_call_chat_completion(system_prompt, translation_input, translation_tools)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "07e0f133-f6e1-4bc6-969c-da9d36bfba2f",
      "metadata": {
        "tags": [],
        "id": "07e0f133-f6e1-4bc6-969c-da9d36bfba2f",
        "outputId": "82e2506a-7336-4909-b8e4-fc52f671c511"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "454"
            ]
          },
          "execution_count": 17,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "function_call_tokens = response.usage.prompt_tokens\n",
        "function_call_tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "02be1827-7137-463f-a026-0b26dec6f552",
      "metadata": {
        "tags": [],
        "id": "02be1827-7137-463f-a026-0b26dec6f552",
        "outputId": "60cd7be7-b6ac-412b-e0bc-3b8d3088f2b2"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'assumptions relating to the content': 'The text assumes that the readers '\n",
            "                                        'understand the concept of stakeholder '\n",
            "                                        'groups and their potential differing '\n",
            "                                        'priorities regarding environmental '\n",
            "                                        'and social issues.',\n",
            " 'audience': 'The target audience for this text is likely individuals or '\n",
            "             'organizations involved in sustainability, ecology, or social '\n",
            "             'welfare fields, as well as stakeholders with an interest in '\n",
            "             'these areas.',\n",
            " 'purpose': 'The purpose of this text is to highlight the observations made '\n",
            "            'about the debates that arise when stakeholder groups define their '\n",
            "            'visions, specifically regarding the priority between ecosystem '\n",
            "            'health and human well-being, and how this priority influences '\n",
            "            'their assessment of desired ecological and social outcomes.',\n",
            " 'subject': 'Debates on Prioritizing Ecosystem vs. Human Well-being by '\n",
            "            'Stakeholder Groups'}\n"
          ]
        }
      ],
      "source": [
        "from pprint import pprint\n",
        "description_json = response.choices[0].message.tool_calls[0].function.arguments\n",
        "pprint(description_json)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7575bd09-2d20-49ae-bb10-162a0e469f16",
      "metadata": {
        "id": "7575bd09-2d20-49ae-bb10-162a0e469f16"
      },
      "outputs": [],
      "source": [
        "def automatic_purpose_driven_chat_completion(system_prompt, translation_input, description_json):\n",
        "    \"\"\"\n",
        "    Generates a completion for a chat conversation using a specified system prompt and a user input.\n",
        "    \"\"\"\n",
        "\n",
        "    prompt = f\"\"\"Given the following descriptive json translate <source text> from English to Arabic\n",
        "{description_json}\n",
        "<source text>\n",
        "{translation_input}\n",
        "</source text>\n",
        "Translation:\n",
        "\"\"\"\n",
        "    messages = [\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": prompt,\n",
        "        },\n",
        "    ]\n",
        "    return client.chat_completion(messages, max_tokens=10_000)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "32bccca0-c866-4006-84d1-d5b783b73689",
      "metadata": {
        "tags": [],
        "id": "32bccca0-c866-4006-84d1-d5b783b73689"
      },
      "outputs": [],
      "source": [
        "response = automatic_purpose_driven_chat_completion(system_prompt, translation_input, description_json)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b0867efb-39ea-4f9a-b073-2a84261f3821",
      "metadata": {
        "tags": [],
        "id": "b0867efb-39ea-4f9a-b073-2a84261f3821",
        "outputId": "485ece36-c47e-4d1d-cf50-bbe1a9960776"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "311"
            ]
          },
          "execution_count": 21,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "automatic_purpose_driven_tokens = response.usage.prompt_tokens\n",
        "automatic_purpose_driven_tokens"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "462ca84c-9ffd-4924-880d-e06b724caf02",
      "metadata": {
        "tags": [],
        "id": "462ca84c-9ffd-4924-880d-e06b724caf02",
        "outputId": "bf026405-eb15-4a28-8357-d99e174967e7"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Here is the translated text from English to Arabic:\n",
            "\n",
            "{\"افتراضات متعلقة بالمحتوى\": \"يفترض النص أن القراء يفهمون مفهوم مجموعات أصحاب المصلحة وأولوياتهم المختلفة المحتملة فيما يتعلق بالقضايا البيئية والاجتماعية.\", \"الجمهور\": \"الجمهور المستهدف لهذا النص هو على الأرجح أفراد أو منظمات تعمل في مجالات الاستدامة أو الإيكولوجيا أو الرعاية الاجتماعية، بالإضافة إلى أصحاب المصلحة المهتمين بهذه المجالات.\", \"الغرض\": \"الغرض من هذا النص هو تسليط الضوء على الملاحظات التي أبديت حول النقاشات التي تنشأ عندما تحدد مجموعات أصحاب المصلحة رؤيتها، خاصة فيما يتعلق بالأولوية بين صحة النظام البيئي ورفاهية الإنسان، وكيف تؤثر هذه الأولوية على تقييمها للنتائج الإيكولوجية والاجتماعية المرجوة.\", \"الموضوع\": \"النقاشات حول أولويات النظام البيئي مقابل رفاهية الإنسان من قبل مجموعات أصحاب المصلحة\": \"لقد لاحظنا أنه عندما تعمل مجموعات أصحاب المصلحة على تحديد الرؤى، فإن ذلك يؤدي إلى نقاش حول ما إذا كان ينبغي التركيز على صحة النظام البيئي أو رفاهية الإنسان... إن أولوية النظم البيئية أو البشر تؤثر بشكل كبير على تقييم أصحاب المصلحة للوضع الاجتماعي والإيكولوجي المرغوب.\"}\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1ec3b20b-8393-4fda-a51d-cf67984cc166",
      "metadata": {
        "id": "1ec3b20b-8393-4fda-a51d-cf67984cc166"
      },
      "source": [
        "# Push to the hub"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "6fc55725-216f-45dd-9c6d-dae77e16d606",
      "metadata": {
        "tags": [],
        "id": "6fc55725-216f-45dd-9c6d-dae77e16d606",
        "outputId": "d3b9b994-e3af-4f05-88b4-3b29778d1dc7"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "CommitInfo(commit_url='https://huggingface.co/arabic-translation-prompt-engineering/atpe-notebooks/commit/d112cc49a99a72106b75c3eae9be453264fb488d', commit_message='Upload baseline.ipynb with huggingface_hub', commit_description='', oid='d112cc49a99a72106b75c3eae9be453264fb488d', pr_url=None, pr_revision=None, pr_num=None)"
            ]
          },
          "execution_count": 23,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from huggingface_hub import HfApi\n",
        "\n",
        "api = HfApi()\n",
        "api.upload_file(\n",
        "    path_or_fileobj=\"baseline.ipynb\",\n",
        "    path_in_repo=\"baseline.ipynb\",\n",
        "    repo_id=\"arabic-translation-prompt-engineering/atpe-notebooks\",\n",
        "    repo_type=\"model\",\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "6f21f4cf-1872-4934-bb91-8aef311ed729",
      "metadata": {
        "id": "6f21f4cf-1872-4934-bb91-8aef311ed729"
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.9"
    },
    "colab": {
      "provenance": []
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}