transformers/docs/source/ja/custom_tools.md
Rockerz 9b7668c03a
add japanese documentation (#26138)
* udpaet

* update

* Update docs/source/ja/autoclass_tutorial.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* add codes workflows/build_pr_documentation.yml

* Create preprocessing.md

* added traning.md

* Create Model_sharing.md

* add quicktour.md

* new

* ll

* Create benchmark.md

* Create Tensorflow_model

* add

* add community.md

* add create_a_model

* create custom_model.md

* create_custom_tools.md

* create fast_tokenizers.md

* create

* add

* Update docs/source/ja/_toctree.yml

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* md

* add

* commit

* add

* h

* Update docs/source/ja/peft.md

Co-authored-by: Younes Belkada <49240599+younesbelkada@users.noreply.github.com>

* Update docs/source/ja/_toctree.yml

Co-authored-by: Younes Belkada <49240599+younesbelkada@users.noreply.github.com>

* Update docs/source/ja/_toctree.yml

Co-authored-by: Younes Belkada <49240599+younesbelkada@users.noreply.github.com>

* Suggested Update

* add perf_train_gpu_one.md

* added perf based MD files

* Modify toctree.yml and Add transmartion to md codes

* Add `serialization.md` and edit `_toctree.yml`

* add task summary and tasks explained

* Add and Modify files starting from T

* Add testing.md

* Create main_classes files

* delete main_classes folder

* Add toctree.yml

* Update llm_tutorail.md

* Update docs/source/ja/_toctree.yml

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update misspelled filenames

* Update docs/source/ja/_toctree.yml

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/_toctree.yml

* Update docs/source/ja/_toctree.yml

* missplled file names inmrpovements

* Update _toctree.yml

* close tip block

* close another tip block

* Update docs/source/ja/quicktour.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/pipeline_tutorial.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/pipeline_tutorial.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/preprocessing.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/peft.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/add_new_model.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/testing.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/task_summary.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/tasks_explained.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update glossary.md

* Update docs/source/ja/transformers_agents.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/llm_tutorial.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/create_a_model.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/torchscript.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/benchmarks.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/troubleshooting.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/troubleshooting.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/troubleshooting.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update docs/source/ja/add_new_model.md

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>

* Update perf_torch_compile.md

* Update Year to default in en documentation

* Final Update

---------

Co-authored-by: Steven Liu <59462357+stevhliu@users.noreply.github.com>
Co-authored-by: Younes Belkada <49240599+younesbelkada@users.noreply.github.com>
2023-10-11 10:26:37 -07:00

38 KiB
Raw Blame History

Custom Tools and Prompts

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

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

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

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

Customizing the prompt

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

Structure of the prompt

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

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

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

タスクを実行するために、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内のツヌルの数ず同じ数の箇条曞きがあり、それぞれの箇条曞きにはツヌルの名前ず説明が含たれおいたす。

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

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

from transformers import load_tool

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

which gives:

- 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番目のパヌトでは入力匕数ず戻り倀がどのように期埅されるかを述べおいたす。

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

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

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

以䞋は、䞀぀の䟋です

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

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

こちらの問題ステヌトメントで厳密に評䟡される、゚ヌゞェントのプロンプトができるだけ優れたものになるように 慎重に遞定されたプロンプト䟋を提䟛しおいたす。

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

I will use the following

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

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

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

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

[...]

=====

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を実行するず、ナヌザヌの入力たたはタスクが未完了の圢匏に倉換されたす

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

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

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

Writing good user inputs

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

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

from transformers import HfAgent

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

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

gives:

==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")

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

agent.toolbox["image_generator"].description
'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.

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

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

gives:

==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

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

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

䟋

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

returns

==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」ず呌びたしょう

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"
)

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

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

Now we're getting:

==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")

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

agent.run("Create image: 'A house and car'", return_code=True)
==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")

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

Customizing the whole project

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

template = """ [...] """

agent = HfAgent(your_endpoint, run_prompt_template=template)

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

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

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

Human: <<task>>

Assistant:

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

template = """ [...] """

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

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

䞡方の堎合、プロンプトテンプレヌトの代わりに、コミュニティの誰かがホストしたテンプレヌトを䜿甚したい堎合は、リポゞトリIDを枡すこずができたす。デフォルトのプロンプトは、このリポゞトリ にありたすので、参考になりたす。

カスタムプロンプトをHubのリポゞトリにアップロヌドしおコミュニティず共有する堎合は、次のこずを確認しおください

  • デヌタセットリポゞトリを䜿甚するこず
  • run コマンド甚のプロンプトテンプレヌトを run_prompt_template.txt ずいう名前のファむルに配眮するこず
  • chat コマンド甚のプロンプトテンプレヌトを chat_prompt_template.txt ずいう名前のファむルに配眮するこず

Using custom tools

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

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

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

from transformers import load_tool

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

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

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

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

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

gives

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'

名前ず説明は正確であり、厳遞されたツヌルのスタむルに合っおいたす。

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

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

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

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 ツヌルがあり、これをカスタムツヌルで眮き換えたす。

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

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

print("\n".join([f"- {a}" for a in agent.toolbox.keys()]))
- 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 で生成した画像を再利甚したす。

from diffusers.utils import load_image

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

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

image = agent.run("Transform the image: 'A frozen lake and snowy forest'", image=image)
==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")

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

image = agent.run("Upscale the image", image)
==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)

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

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

Adding new tools

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

Creating a new tool

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

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

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 の堎合、't5-base' を返したす。

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

from transformers import Tool


class HFModelDownloadsTool(Tool):
    pass

このクラスにはいく぀かの必芁な芁玠がありたす

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

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

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 ずいう名前にし、結果のむンポヌトコヌドは次のようになりたす

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

from model_downloads import HFModelDownloadsTool

tool = HFModelDownloadsTool()

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

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

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

Having the agent use the tool

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

from transformers import load_tool

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

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

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:

==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

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

Replacing existing tools

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

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")

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

Leveraging gradio-tools

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

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

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

from gradio_tools import StableDiffusionPromptGeneratorTool

gradio_tool = StableDiffusionPromptGeneratorTool()

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

from transformers import Tool

tool = Tool.from_gradio(gradio_tool)

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

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:

==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)

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

画像

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

Future compatibility with Langchain

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

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

私たちはより良いサポヌトを提䟛したいず考えおいたす。お手䌝いいただける堎合は、ぜひ問題を開いお、お考えのこずを共有しおください。