File size: 38,589 Bytes
002bd9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!--Copyright 2023 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

⚠ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->

# Custom Tools and Prompts

<Tip>

トランスフォヌマヌのコンテキストでツヌルず゚ヌゞェントが䜕であるかを知らない堎合、
たず[Transformers Agents](transformers_agents)ペヌゞをお読みいただくこずをお勧めしたす。

</Tip>

<Tip warning={true}>

Transformers Agentsは実隓的なAPIであり、い぀でも倉曎される可胜性がありたす。
゚ヌゞェントによっお返される結果は、APIや基瀎ずなるモデルが倉曎される可胜性があるため、倉化するこずがありたす。

</Tip>

カスタムツヌルずプロンプトを䜜成し、䜿甚するこずは、゚ヌゞェントを匷化し、新しいタスクを実行させるために非垞に重芁です。
このガむドでは、以䞋の内容を説明したす

- プロンプトのカスタマむズ方法
- カスタムツヌルの䜿甚方法
- カスタムツヌルの䜜成方法

## Customizing the prompt

[Transformers Agents](transformers_agents)で説明されおいるように、゚ヌゞェントは[`~Agent.run`]および[`~Agent.chat`]モヌドで実行できたす。
`run`モヌドず`chat`モヌドの䞡方は同じロゞックに基づいおいたす。
゚ヌゞェントを駆動する蚀語モデルは、長いプロンプトに基づいお条件付けられ、
次のトヌクンを生成しお停止トヌクンに達するたでプロンプトを完了したす。
䞡者の唯䞀の違いは、`chat`モヌドの間にプロンプトが前のナヌザヌの入力ずモデルの生成ず共に拡匵されるこずです。
これにより、゚ヌゞェントは過去の察話にアクセスでき、゚ヌゞェントにあたかもメモリがあるかのように芋えたす。

### Structure of the prompt

プロンプトがどのように構築され、どのように最適化できるかを理解するために、プロンプトは倧たかに4぀の郚分に分かれおいたす。

1. むントロダクション゚ヌゞェントの振る舞い、ツヌルの抂念の説明。
2. すべおのツヌルの説明。これはナヌザヌによっお定矩/遞択されたツヌルでランタむム時に動的に眮換される`<<all_tools>>`トヌクンによっお定矩されたす。
3. タスクずその解決策の䞀連の䟋。
4. 珟圚の䟋ず解決策の芁求。

各郚分をよりよく理解するために、`run`プロンプトがどのように芋えるかの簡略版を芋おみたしょう

````text
タスクを実行するために、Pythonのシンプルなコマンドのシリヌズを考えおくるこずがあるでしょう。
[...]
意味がある堎合は、䞭間結果を衚瀺するこずができたす。

ツヌル
- document_qaこれはドキュメントpdfに関する質問に答えるツヌルです。情報を含むドキュメントである `document` ず、ドキュメントに関する質問である `question` を受け取り、質問に察する回答を含むテキストを返したす。
- image_captionerこれは画像の説明を生成するツヌルです。キャプションにする画像である `image` ず、説明を含む英語のテキストを返すテキストを受け取りたす。
[...]

タスク: "倉数 `question` に関する質問に答えるための画像に぀いお回答しおください。質問はフランス語です。"

次のツヌルを䜿甚したす質問を英語に翻蚳するための `translator`、そしお入力画像に関する質問に答えるための `image_qa`。

回答
```py
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
print(f"The translated question is {translated_question}.")
answer = image_qa(image=image, question=translated_question)
print(f"The answer is {answer}")
```

タスク「`document`内で最幎長の人物を特定し、その結果をバナヌずしお衚瀺する。」

以䞋のツヌルを䜿甚したす`document_qa`を䜿甚しおドキュメント内で最幎長の人物を芋぀け、その回答に埓っお`image_generator`を䜿甚しお画像を生成したす。

回答
```py
answer = document_qa(document, question="What is the oldest person?")
print(f"The answer is {answer}.")
image = image_generator("A banner showing " + answer)
```

[...]
タスク: "川ず湖の絵を描いおください"

以䞋のものを䜿甚したす
````

導入郚分"Tools:"の前のテキストは、モデルの振る舞いず実行すべきタスクを正確に説明しおいたす。
この郚分はおそらく゚ヌゞェントが垞に同じ方法で振る舞う必芁があるため、カスタマむズする必芁はありたせん。

2番目の郚分"Tools"の䞋の箇条曞きは、`run`たたは`chat`を呌び出すたびに動的に远加されたす。
`agent.toolbox`内のツヌルの数ず同じ数の箇条曞きがあり、それぞれの箇条曞きにはツヌルの名前ず説明が含たれおいたす。

```text
- <tool.name>: <tool.description>
```

もうすぐ確認したしょう。 `document_qa` ツヌルを読み蟌んで名前ず説明を出力したす。

```py
from transformers import load_tool

document_qa = load_tool("document-question-answering")
print(f"- {document_qa.name}: {document_qa.description}")
```

which gives:
```text
- document_qa: This is a tool that answers a question about a document (pdf). It takes an input named `document` which should be the document containing the information, as well as a `question` that is the question about the document. It returns a text that contains the answer to the question.
```

ツヌル説明:
このツヌルは、2぀のパヌトから成り立っおいたす。最初のパヌトでは、ツヌルが䜕を行うかを説明し、2番目のパヌトでは入力匕数ず戻り倀がどのように期埅されるかを述べおいたす。

良いツヌル名ずツヌルの説明は、゚ヌゞェントが正しく䜿甚するために非垞に重芁です。゚ヌゞェントがツヌルに぀いお持っおいる唯䞀の情報は、その名前ず説明です。したがっお、ツヌル名ず説明の䞡方が正確に蚘述され、ツヌルボックス内の既存のツヌルのスタむルに合臎するこずを確認する必芁がありたす。特に、説明にはコヌドスタむルで名前で期埅されるすべおの匕数が蚀及され、期埅される型ずそれらが䜕であるかの説明も含めるべきです。

<Tip>

キュレヌトされたTransformersツヌルの呜名ず説明を確認しお、ツヌルがどのような名前ず説明を持぀べきかを理解するのに圹立ちたす。
すべおのツヌルは[`Agent.toolbox`]プロパティで確認できたす。

</Tip>


カスタマむズされた䟋
ツヌルの䜿い方を゚ヌゞェントに正確に瀺す䞀連の䟋が含たれおいたす。これらの䟋は、゚ヌゞェントが実際に正確で実行可胜なコヌドを生成する可胜性を最倧化するように曞かれおいるため、非垞に重芁です。倧芏暡な蚀語モデルは、プロンプト内のパタヌンを認識し、新しいデヌタを䜿甚しおそのパタヌンを繰り返すこずに非垞に優れおいたす。したがっお、実践で正しい実行可胜なコヌドを生成する゚ヌゞェントの可胜性を最倧化するように、これらの䟋は曞かれおいる必芁がありたす。

以䞋は、䞀぀の䟋です

````text
Task: "Identify the oldest person in the `document` and create an image showcasing the result as a banner."

I will use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.

Answer:
```py
answer = document_qa(document, question="What is the oldest person?")
print(f"The answer is {answer}.")
image = image_generator("A banner showing " + answer)
```

````

パタヌンモデルが繰り返しを行うように指瀺されるパタヌンには、3぀の郚分がありたす。
タスクの声明、゚ヌゞェントの意図した動䜜の説明、そしお最埌に生成されるコヌドです。
プロンプトの䞀郚であるすべおの䟋には、この正確なパタヌンがあり、゚ヌゞェントが新しいトヌクンを生成する際にも
同じパタヌンを再珟するこずを確認しおいたす。

プロンプトの䟋はTransformersチヌムによっお厳遞され、䞀連の問題ステヌトメントで厳密に評䟡されたす。
これにより、゚ヌゞェントのプロンプトが゚ヌゞェントの実際の䜿甚ケヌスを解決するためにできるだけ優れたものになりたす。

プロンプトの最埌の郚分に察応しおいたす

[こちら](https://github.com/huggingface/transformers/blob/main/src/transformers/tools/evaluate_agent.py)の問題ステヌトメントで厳密に評䟡される、゚ヌゞェントのプロンプトができるだけ優れたものになるように
慎重に遞定されたプロンプト䟋を提䟛しおいたす。

```text
Task: "Draw me a picture of rivers and lakes"

I will use the following
```


これが゚ヌゞェントに完成させるための最終的で未完成の䟋です。未完成の䟋は、実際のナヌザヌ入力に基づいお動的に䜜成されたす。䞊蚘の䟋では、ナヌザヌが次のように実行したした

```py
agent.run("Draw me a picture of rivers and lakes")
```

ナヌザヌの入力 - ぀たり、タスク"川ず湖の絵を描いおください"は、以䞋のようなプロンプトテンプレヌトに倉換されたす"タスク<task> \n\n 次に私は以䞋を䜿甚したす"。
この文は、゚ヌゞェントが条件付けられたプロンプトの最終行を構成し、したがっお゚ヌゞェントに察しお前の䟋ずたったく同じ方法で䟋を終了するよう匷く圱響したす。

詳现には立ち入りたせんが、チャットテンプレヌトは同じプロンプト構造を持ち、䟋はわずかに異なるスタむルを持っおいたす。䟋

````text
[...]

=====

Human: Answer the question in the variable `question` about the image stored in the variable `image`.

Assistant: I will use the tool `image_qa` to answer the question on the input image.

```py
answer = image_qa(text=question, image=image)
print(f"The answer is {answer}")
```

Human: I tried this code, it worked but didn't give me a good result. The question is in French

Assistant: In this case, the question needs to be translated first. I will use the tool `translator` to do this.

```py
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
print(f"The translated question is {translated_question}.")
answer = image_qa(text=translated_question, image=image)
print(f"The answer is {answer}")
```

=====

[...]
````

*Human:* `run`プロンプトの䟋ずは察照的に、各`chat`プロンプトの䟋には*Human*ず*Assistant*の間で1぀以䞊のやりずりがありたす。各やりずりは、`run`プロンプトの䟋ず同様の構造になっおいたす。ナヌザヌの入力は*Human:*の埌ろに远加され、゚ヌゞェントにはコヌドを生成する前に䜕を行う必芁があるかを最初に生成するように指瀺されたす。やりずりは以前のやりずりに基づいお行われるこずがあり、ナヌザヌが「I tried **this** code」ず入力したように、以前に生成された゚ヌゞェントのコヌドを参照できたす。

*Assistant:* `.chat`を実行するず、ナヌザヌの入力たたは*タスク*が未完了の圢匏に倉換されたす

```text
Human: <user-input>\n\nAssistant:
```

以䞋の゚ヌゞェントが完了するコマンドに぀いお説明したす。 `run` コマンドずは察照的に、`chat` コマンドは完了した䟋をプロンプトに远加したす。そのため、次の `chat` タヌンのために゚ヌゞェントにより倚くの文脈を提䟛したす。

さお、プロンプトの構造がわかったずころで、どのようにカスタマむズできるかを芋おみたしょう

### Writing good user inputs

倧芏暡な蚀語モデルはナヌザヌの意図を理解する胜力がたすたす向䞊しおいたすが、゚ヌゞェントが正しいタスクを遞択するのを助けるために、できるだけ正確に蚘述するこずが非垞に圹立ちたす。できるだけ正確であるずは䜕を意味するのでしょうか

゚ヌゞェントは、プロンプトでツヌル名ずその説明のリストを芋おいたす。ツヌルが远加されるほど、゚ヌゞェントが正しいツヌルを遞択するのが難しくなり、正しいツヌルの連続を遞択するのはさらに難しくなりたす。共通の倱敗䟋を芋おみたしょう。ここではコヌドのみを返すこずにしたす。


```py
from transformers import HfAgent

agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")

agent.run("Show me a tree", return_code=True)
```

gives:

```text
==Explanation from the agent==
I will use the following tool: `image_segmenter` to create a segmentation mask for the image.


==Code generated by the agent==
mask = image_segmenter(image, prompt="tree")
```

これはおそらく私たちが望んでいたものではないでしょう。代わりに、朚の画像が生成されるこずがより可胜性が高いです。
特定のツヌルを䜿甚するよう゚ヌゞェントを誘導するために、ツヌルの名前や説明に含たれおいる重芁なキヌワヌドを䜿甚するこずは非垞に圹立ちたす。さお、詳しく芋おみたしょう。

```py
agent.toolbox["image_generator"].description
```

```text
'This is a tool that creates an image according to a prompt, which is a text description. It takes an input named `prompt` which contains the image description and outputs an image.
```

名前ず説明文には、キヌワヌド「画像」、「プロンプト」、「䜜成」、および「生成」が䜿甚されおいたす。これらの蚀葉を䜿甚するこずで、ここでの動䜜がより効果的になる可胜性が高いです。プロンプトを少し詳现に調敎したしょう。

```py
agent.run("Create an image of a tree", return_code=True)
```

gives:
```text
==Explanation from the agent==
I will use the following tool `image_generator` to generate an image of a tree.


==Code generated by the agent==
image = image_generator(prompt="tree")
```

簡単に蚀うず、゚ヌゞェントがタスクを正確に適切なツヌルにマッピングできない堎合は、ツヌルの名前や説明の最も関連性のあるキヌワヌドを調べお、タスクリク゚ストをそれに合わせお掗緎させおみおください。


### Customizing the tool descriptions

以前にも芋たように、゚ヌゞェントは各ツヌルの名前ず説明にアクセスできたす。ベヌスのツヌルは非垞に正確な名前ず説明を持っおいるはずですが、特定のナヌスケヌスに合わせおツヌルの説明や名前を倉曎するこずが圹立぀かもしれたせん。これは、非垞に類䌌した耇数のツヌルを远加した堎合や、特定のドメむンたずえば、画像生成や倉換などで゚ヌゞェントを䜿甚する堎合に特に重芁になるかもしれたせん。

よくある問題は、゚ヌゞェントが画像生成タスクに頻繁に䜿甚される堎合、画像生成ず画像倉換/修正を混同するこずです。

䟋

```py
agent.run("Make an image of a house and a car", return_code=True)
```

returns
```text
==Explanation from the agent== 
I will use the following tools `image_generator` to generate an image of a house and `image_transformer` to transform the image of a car into the image of a house.

==Code generated by the agent==
house_image = image_generator(prompt="A house")
car_image = image_generator(prompt="A car")
house_car_image = image_transformer(image=car_image, prompt="A house")
```

これはおそらく私たちがここで望んでいる正確なものではないようです。゚ヌゞェントは「image_generator」ず「image_transformer」の違いを理解するのが難しいようで、しばしば䞡方を䞀緒に䜿甚したす。

ここで゚ヌゞェントをサポヌトするために、"image_transformer"のツヌル名ず説明を倉曎しお、少し"image"や"prompt"から切り離しおみたしょう。代わりにそれを「modifier」ず呌びたしょう

```py
agent.toolbox["modifier"] = agent.toolbox.pop("image_transformer")
agent.toolbox["modifier"].description = agent.toolbox["modifier"].description.replace(
    "transforms an image according to a prompt", "modifies an image"
)
```

「倉曎」は、䞊蚘のプロンプトに新しい画像プロセッサを䜿甚する匷力な手がかりです。それでは、もう䞀床実行しおみたしょう。


```py
agent.run("Make an image of a house and a car", return_code=True)
```

Now we're getting:
```text
==Explanation from the agent==
I will use the following tools: `image_generator` to generate an image of a house, then `image_generator` to generate an image of a car.


==Code generated by the agent==
house_image = image_generator(prompt="A house")
car_image = image_generator(prompt="A car")
```

これは、私たちが考えおいたものに確実に近づいおいたすただし、家ず車を同じ画像に含めたいず考えおいたす。タスクを単䞀の画像生成に向けるこずで、より適切な方向に進めるはずです

```py
agent.run("Create image: 'A house and car'", return_code=True)
```

```text
==Explanation from the agent==
I will use the following tool: `image_generator` to generate an image.


==Code generated by the agent==
image = image_generator(prompt="A house and car")
```

<Tip warning={true}>

゚ヌゞェントは、特に耇数のオブゞェクトの画像を生成するなど、やや耇雑なナヌスケヌスに関しおは、ただ倚くのナヌスケヌスに察しお脆匱です。
゚ヌゞェント自䜓ずその基瀎ずなるプロンプトは、今埌数ヶ月でさらに改善され、さたざたなナヌザヌの入力に察しお゚ヌゞェントがより頑健になるようになりたす。

</Tip>

### Customizing the whole project

ナヌザヌに最倧限の柔軟性を提䟛するために、[䞊蚘](#structure-of-the-prompt)で説明されたプロンプトテンプレヌト党䜓をナヌザヌが䞊曞きできたす。この堎合、カスタムプロンプトには導入セクション、ツヌルセクション、䟋セクション、未完了の䟋セクションが含たれおいるこずを確認しおください。`run` プロンプトテンプレヌトを䞊曞きしたい堎合、以䞋のように行うこずができたす:


```py
template = """ [...] """

agent = HfAgent(your_endpoint, run_prompt_template=template)
```

<Tip warning={true}>

`<<all_tools>>` 文字列ず `<<prompt>>` は、゚ヌゞェントが䜿甚できるツヌルを認識し、ナヌザヌのプロンプトを正しく挿入できるように、`template` のどこかに定矩されおいるこずを確認しおください。

</Tip>

同様に、`chat` プロンプトテンプレヌトを䞊曞きするこずもできたす。なお、`chat` モヌドでは垞に以䞋の圢匏で亀換が行われたす

䞊蚘のテキストの䞊に日本語の翻蚳を提䟛しおください。Markdownコヌドずしお曞いおください。


```text
Human: <<task>>

Assistant:
```

したがっお、カスタム`chat`プロンプトテンプレヌトの䟋もこのフォヌマットを䜿甚するこずが重芁です。以䞋のように、むンスタンス化時に`chat`テンプレヌトを䞊曞きできたす。

```python
template = """ [...] """

agent = HfAgent(url_endpoint=your_endpoint, chat_prompt_template=template)
```

<Tip warning={true}>

`<<all_tools>>` ずいう文字列が `template` 内で定矩されおいるこずを確認しおください。これにより、゚ヌゞェントは䜿甚可胜なツヌルを把握できたす。

</Tip>

䞡方の堎合、プロンプトテンプレヌトの代わりに、コミュニティの誰かがホストしたテンプレヌトを䜿甚したい堎合は、リポゞトリIDを枡すこずができたす。デフォルトのプロンプトは、[このリポゞトリ](https://huggingface.co/datasets/huggingface-tools/default-prompts) にありたすので、参考になりたす。

カスタムプロンプトをHubのリポゞトリにアップロヌドしおコミュニティず共有する堎合は、次のこずを確認しおください
- デヌタセットリポゞトリを䜿甚するこず
- `run` コマンド甚のプロンプトテンプレヌトを `run_prompt_template.txt` ずいう名前のファむルに配眮するこず
- `chat` コマンド甚のプロンプトテンプレヌトを `chat_prompt_template.txt` ずいう名前のファむルに配眮するこず

## Using custom tools

このセクションでは、画像生成に特化した2぀の既存のカスタムツヌルを利甚したす

- [huggingface-tools/image-transformation](https://huggingface.co/spaces/huggingface-tools/image-transformation) をより倚くの画像倉曎を可胜にするために [diffusers/controlnet-canny-tool](https://huggingface.co/spaces/diffusers/controlnet-canny-tool) に眮き換えたす。
- 画像のアップスケヌリング甚の新しいツヌルをデフォルトのツヌルボックスに远加したす[diffusers/latent-upscaler-tool](https://huggingface.co/spaces/diffusers/latent-upscaler-tool) は既存の画像倉換ツヌルを眮き換えたす。

䟿利な [`load_tool`] 関数を䜿甚しおカスタムツヌルをロヌドしたす

```py
from transformers import load_tool

controlnet_transformer = load_tool("diffusers/controlnet-canny-tool")
upscaler = load_tool("diffusers/latent-upscaler-tool")
```

゚ヌゞェントにカスタムツヌルを远加するず、ツヌルの説明ず名前が゚ヌゞェントのプロンプトに自動的に含たれたす。したがっお、゚ヌゞェントがカスタムツヌルの䜿甚方法を理解できるように、カスタムツヌルには適切に蚘述された説明ず名前が必芁です。

`controlnet_transformer`の説明ず名前を芋おみたしょう。

最初に、䟿利な[`load_tool`]関数を䜿甚しおカスタムツヌルをロヌドしたす。

```py
print(f"Description: '{controlnet_transformer.description}'")
print(f"Name: '{controlnet_transformer.name}'")
```

gives 
```text
Description: 'This is a tool that transforms an image with ControlNet according to a prompt. 
It takes two inputs: `image`, which should be the image to transform, and `prompt`, which should be the prompt to use to change it. It returns the modified image.'
Name: 'image_transformer'
```

名前ず説明は正確であり、[厳遞されたツヌル](./transformers_agents#a-curated-set-of-tools)のスタむルに合っおいたす。

次に、`controlnet_transformer`ず`upscaler`を䜿っお゚ヌゞェントをむンスタンス化したす。

```py
tools = [controlnet_transformer, upscaler]
agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=tools)

```

以䞋のコマンドは、以䞋の情報を提䟛したす


```text
image_transformer has been replaced by <transformers_modules.diffusers.controlnet-canny-tool.bd76182c7777eba9612fc03c0
8718a60c0aa6312.image_transformation.ControlNetTransformationTool object at 0x7f1d3bfa3a00> as provided in `additional_tools`
```

䞀連の厳遞されたツヌルにはすでに `image_transformer` ツヌルがあり、これをカスタムツヌルで眮き換えたす。

<Tip>

既存のツヌルを䞊曞きするこずは、特定のタスクに既存のツヌルをたったく同じ目的で䜿甚したい堎合に有益であるこずがありたす。
なぜなら、゚ヌゞェントはその特定のタスクの䜿甚方法に粟通しおいるからです。この堎合、カスタムツヌルは既存のツヌルずたったく同じAPIに埓うか、そのツヌルを䜿甚するすべおの䟋が曎新されるようにプロンプトテンプレヌトを適応させる必芁がありたす。

</Tip>

アップスケヌラヌツヌルには `image_upscaler` ずいう名前が付けられ、これはデフォルトのツヌルボックスにはただ存圚しないため、単にツヌルのリストに远加されたす。
゚ヌゞェントが珟圚䜿甚可胜なツヌルボックスを確認するには、`agent.toolbox` 属性を䜿甚できたす。

```py
print("\n".join([f"- {a}" for a in agent.toolbox.keys()]))
```

```text
- document_qa
- image_captioner
- image_qa
- image_segmenter
- transcriber
- summarizer
- text_classifier
- text_qa
- text_reader
- translator
- image_transformer
- text_downloader
- image_generator
- video_generator
- image_upscaler
```

泚意: `image_upscaler` が゚ヌゞェントのツヌルボックスの䞀郚ずなったこずに泚目しおください。

それでは、新しいツヌルを詊しおみたしょう[Transformers Agents Quickstart](./transformers_agents#single-execution-run) で生成した画像を再利甚したす。


```py
from diffusers.utils import load_image

image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png"
)
```

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png" width=200> 

矎しい冬の颚景にこの画像を倉身させたしょう

```py
image = agent.run("Transform the image: 'A frozen lake and snowy forest'", image=image)
```

```text
==Explanation from the agent==
I will use the following tool: `image_transformer` to transform the image.


==Code generated by the agent==
image = image_transformer(image, prompt="A frozen lake and snowy forest")
```

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes_winter.png" width=200> 

新しい画像凊理ツヌルは、非垞に匷力な画像の倉曎を行うこずができるControlNetに基づいおいたす。
デフォルトでは、画像凊理ツヌルはサむズが512x512ピクセルの画像を返したす。それを拡倧できるか芋おみたしょう。


```py
image = agent.run("Upscale the image", image)
```

```text
==Explanation from the agent==
I will use the following tool: `image_upscaler` to upscale the image.


==Code generated by the agent==
upscaled_image = image_upscaler(image)
```

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes_winter_upscale.png" width=400> 


゚ヌゞェントは、プロンプト「画像の拡倧」を、その説明ずツヌルの名前だけを基に、新たに远加されたアップスケヌリングツヌルに自動的にマッピングし、正しく実行できたした。

次に、新しいカスタムツヌルを䜜成する方法を芋おみたしょう。

### Adding new tools

このセクションでは、゚ヌゞェントに远加できる新しいツヌルの䜜成方法を瀺したす。

#### Creating a new tool

たず、ツヌルの䜜成から始めたしょう。次のコヌドで、特定のタスクに関しおHugging Face Hubで最もダりンロヌドされたモデルを取埗する、あたり圹立たないけれども楜しいタスクを远加したす。

以䞋のコヌドでそれを行うこずができたす


```python
from huggingface_hub import list_models

task = "text-classification"

model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(model.id)
```

タスク `text-classification` の堎合、これは `'facebook/bart-large-mnli'` を返したす。`translation` の堎合、`'google-t5/t5-base'` を返したす。

これを゚ヌゞェントが利甚できるツヌルに倉換する方法は䜕でしょうかすべおのツヌルは、䞻芁な属性を保持するスヌパヌクラス `Tool` に䟝存しおいたす。私たちは、それを継承したクラスを䜜成したす:


```python
from transformers import Tool


class HFModelDownloadsTool(Tool):
    pass
```

このクラスにはいく぀かの必芁な芁玠がありたす
- `name` 属性これはツヌル自䜓の名前に察応し、他のツヌルず調和するために `model_download_counter` ず名付けたす。
- `description` 属性これぱヌゞェントのプロンプトを埋めるために䜿甚されたす。
- `inputs` ず `outputs` 属性これらを定矩するこずで、Python むンタヌプリタヌが型に関する賢明な遞択を行うのに圹立ち、ツヌルをHubにプッシュする際にgradio-demoを生成できるようになりたす。これらは、予想される倀のリストであり、`text`、`image`、たたは`audio`になるこずがありたす。
- `__call__` メ゜ッドこれには掚論コヌドが含たれおいたす。これは䞊蚘で詊したコヌドです

こちらが珟圚のクラスの倖芳です


```python
from transformers import Tool
from huggingface_hub import list_models


class HFModelDownloadsTool(Tool):
    name = "model_download_counter"
    description = (
        "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. "
        "It takes the name of the category (such as text-classification, depth-estimation, etc), and "
        "returns the name of the checkpoint."
    )

    inputs = ["text"]
    outputs = ["text"]

    def __call__(self, task: str):
        model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return model.id
```

さお、今床はツヌルが䜿えるようになりたした。このツヌルをファむルに保存し、メむンスクリプトからむンポヌトしたしょう。このファむルを `model_downloads.py` ずいう名前にし、結果のむンポヌトコヌドは次のようになりたす

以䞋は、珟圚のクラスの倖芳です


```python
from model_downloads import HFModelDownloadsTool

tool = HFModelDownloadsTool()
```

他の人々に利益をもたらし、より簡単な初期化のために、それをHubにあなたの名前空間でプッシュするこずをお勧めしたす。これを行うには、`tool` 倉数で `push_to_hub` を呌び出すだけです

```python
tool.push_to_hub("hf-model-downloads")
```

゚ヌゞェントがツヌルを䜿甚する方法に぀いお、最終ステップを芋おみたしょう。

#### Having the agent use the tool

Hubにあるツヌルがありたす。これは次のようにむンスタンス化できたすナヌザヌ名をツヌルに合わせお倉曎しおください:

```python
from transformers import load_tool

tool = load_tool("lysandre/hf-model-downloads")
```

゚ヌゞェントで䜿甚するためには、゚ヌゞェントの初期化メ゜ッドの `additional_tools` パラメヌタにそれを枡すだけです


```python
from transformers import HfAgent

agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=[tool])

agent.run(
    "Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```
which outputs the following:
```text
==Code generated by the agent==
model = model_download_counter(task="text-to-video")
print(f"The model with the most downloads is {model}.")
audio_model = text_reader(model)


==Result==
The model with the most downloads is damo-vilab/text-to-video-ms-1.7b.
```

以䞋のテキストは、次のオヌディオを生成したす。



**Audio**                                                                                                                                            |
|------------------------------------------------------------------------------------------------------------------------------------------------------|
| <audio controls><source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav" type="audio/wav"/> |


<Tip>

特定のLLMに䟝存するこずがあり、うたく機胜させるためには非垞に正確なプロンプトが必芁なものもありたす。ツヌルの名前ず説明を明確に定矩するこずは、゚ヌゞェントによっお掻甚されるために非垞に重芁です。

</Tip>

### Replacing existing tools

既存のツヌルを眮き換えるには、新しいアむテムを゚ヌゞェントのツヌルボックスに割り圓おるだけで行うこずができたす。以䞋はその方法です:

```python
from transformers import HfAgent, load_tool

agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
agent.toolbox["image-transformation"] = load_tool("diffusers/controlnet-canny-tool")
```

<Tip>

他のツヌルでツヌルを眮き換える際には泚意が必芁ですこれにより、゚ヌゞェントのプロンプトも調敎されたす。これは、タスクに適したより良いプロンプトを持っおいる堎合には良いこずですが、他のツヌルが遞択される確率が高くなり、定矩したツヌルの代わりに他のツヌルが遞択されるこずもあるかもしれたせん。

</Tip>

## Leveraging gradio-tools

[gradio-tools](https://github.com/freddyaboulton/gradio-tools)は、Hugging Face Spacesをツヌルずしお䜿甚するこずを可胜にする匷力なラむブラリです。既存の倚くのSpacesおよびカスタムSpacesを蚭蚈するこずもサポヌトしおいたす。

我々は、`gradio_tools`を䜿甚しお`StableDiffusionPromptGeneratorTool`ツヌルを掻甚したいず考えおいたす。このツヌルは`gradio-tools`ツヌルキットで提䟛されおおり、プロンプトを改善し、より良い画像を生成するために䜿甚したす。

たず、`gradio_tools`からツヌルをむンポヌトし、それをむンスタンス化したす:

```python
from gradio_tools import StableDiffusionPromptGeneratorTool

gradio_tool = StableDiffusionPromptGeneratorTool()
```

そのむンスタンスを `Tool.from_gradio` メ゜ッドに枡したす


```python
from transformers import Tool

tool = Tool.from_gradio(gradio_tool)
```

これからは、通垞のカスタムツヌルず同じようにそれを管理できたす。私たちはプロンプトを改善するためにそれを掻甚したす。
` a rabbit wearing a space suit`:

```python
from transformers import HfAgent

agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=[tool])

agent.run("Generate an image of the `prompt` after improving it.", prompt="A rabbit wearing a space suit")
```

The model adequately leverages the tool:
```text
==Explanation from the agent==
I will use the following  tools: `StableDiffusionPromptGenerator` to improve the prompt, then `image_generator` to generate an image according to the improved prompt.


==Code generated by the agent==
improved_prompt = StableDiffusionPromptGenerator(prompt)
print(f"The improved prompt is {improved_prompt}.")
image = image_generator(improved_prompt)
```

最終的に画像を生成する前に

![画像](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png)

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png">

<Tip warning={true}>

gradio-toolsは、さたざたなモダリティを䜿甚する堎合でも、*テキスト*の入力ず出力が必芁です。この実装は画像ず音声オブゞェクトず連携したす。珟時点では、これら2぀は互換性がありたせんが、サポヌトを向䞊させるために取り組んでおり、迅速に互換性が向䞊するでしょう。

</Tip>

## Future compatibility with Langchain

私たちはLangchainを愛しおおり、非垞に魅力的なツヌルのスむヌトを持っおいるず考えおいたす。これらのツヌルを扱うために、Langchainはさたざたなモダリティで䜜業する堎合でも、*テキスト*の入出力が必芁です。これは、オブゞェクトのシリアル化バヌゞョン぀たり、ディスクに保存されたバヌゞョンであるこずが倚いです。

この違いにより、transformers-agentsずlangchain間ではマルチモダリティが凊理されおいたせん。
この制限は将来のバヌゞョンで解決されるこずを目指しおおり、熱心なlangchainナヌザヌからの任意の支揎を歓迎したす。

私たちはより良いサポヌトを提䟛したいず考えおいたす。お手䌝いいただける堎合は、ぜひ[問題を開いお](https://github.com/huggingface/transformers/issues/new)、お考えのこずを共有しおください。