今更ながら「Transformers」に入門する ⑦TUTORIALS: Agent 101: Agents and tools
以下の続き。
Agents and tools
エージェントの触りの部分。
このチュートリアルは日本語が用意されていないので注意。
エージェントとはなにか?
- 大規模言語モデル(LLM)は、因果言語モデリング(一連のトークンの次のトークンを予測する)向けにトレーニングされており、幅広いタスクに対応できる
- ただし、論理的推論・計算・検索思考といったタスクに弱い傾向がある。
- 「エージェント」はこの弱点を克服できる
- 「エージェント」とは?
- LLMをエンジンとして活用し、「ツール」にアクセスできるシステム
- 「ツール」
- 特定のタスクを実行するための関数
- エージェントが使い方を理解するための説明が付与される
エージェントの種類
-
Code Agent
- 一連のアクションを計画し、それをまとめて実行するPythonコードを生成する。
- ツールの異なる入力・出力形式を柔軟に処理可能。
- マルチモーダルタスクに適している。
- すべてのアクションを一度に実行する効率的な方式。
-
React Agent
- 推論タスクに特化している。
- アクションを1つずつ計画・実行し、その結果を次のアクションに反映させる。
- ReActフレームワーク(Yaoら, 2022)に基づき、観察結果を活用して効率的に処理。
- タイプ:
- ReactJsonAgent: ツール呼び出しをJSON形式で出力。
- ReactCodeAgent: ツール呼び出しをコードブロックとして出力し、コーディング性能の高いLLMに最適。
referred from https://huggingface.co/docs/transformers/v4.48.0/en/agents , and translated into Japanese by kun432
Transformersでエージェントを構築する
Colaboratory T4で。
transformers
パッケージはagents
というextraを持っているので、これを有効化。
!pip install -U transformers[agents] bitsandbytes
!pip install torch
!pip freeze | egrep -i "transformers|bitsandbytes|torch"
最初にLLMとやり取りするための関数を定義する。会話履歴を渡すとLLMからの応答が返るようなもの。また、stop_sequences
で渡されたシーケンスで出力を停止する。モデルはLlama-3.2の一番小さいモデルにした。HuggingFaceの仕組みをあまり理解していないのだけども、大きなモデルを使用しようとするとサイズが大きすぎる、とか、有料じゃないと使えない、的なエラーになる。おそらくHuggingFace上でモデルのAPIが用意される仕組みらしい。
from huggingface_hub import login, InferenceClient
from google.colab import userdata
login(userdata.get('HF_TOKEN')) # HF_TOKENをColaboratoryのシークレットに登録しておくこと
client = InferenceClient(model="meta-llama/Llama-3.2-1B-Instruct")
def llm_engine(messages, stop_sequences=["Task"]) -> str:
response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000)
answer = response.choices[0].message.content
return answer
コードを実行するCodeAgentを初期化して、LLMとやり取りする関数をエンジンとして指定する。これにより、エージェントへのリクエストがLLMを介して推論され、ツールの実行等が行われる仕組みらしい。
from transformers import CodeAgent, HfApiEngine
llm_engine = HfApiEngine(model="meta-llama/Llama-3.2-1B-Instruct")
agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)
agent.run(
"Could you translate this sentence from French, say it out loud and return the audio.",
sentence="Où est la boulangerie la plus proche?",
)
======== New task ========
Could you translate this sentence from French, say it out loud and return the audio.
You have been provided with these initial arguments: {'sentence': 'Où est la boulangerie la plus proche?'}.
=== Agent thoughts:
>>> Agent is executing the code below:
text = {'sentence': 'Où est la boulangerie la plus proche?'}
translated_text = translator(question=text['sentence'], src_lang="French", tgt_lang="English")
print(f'Translation: {translated_text}.translated_text')
answer = image_qa(image=text['sentence'], question=translated_text)
audio_answer = transcriber(audio=answer)
print(f'Summary: {audio_answer}.summary')
print(f'Audio: {audio_answer}.audio.')
caption = 'La boulangerie la plus proche.'
text_to_speech(text_to_speech vlas=audio_answer)
audio_summary = text_to_speech(audio_to_sound(text=audio_answer))
print(f'Caption: {caption}.caption')
print(f'Audio: {audio_summary}.audio.')
====
Error in execution: The code generated by the agent is not valid.
invalid syntax. Perhaps you forgot a comma? (<unknown>, line 11). Be sure to provide correct code.
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 886, in evaluate_python_code
expression = ast.parse(code)
File "/usr/lib/python3.10/ast.py", line 50, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 11
text_to_speech(text_to_speech vlas=audio_answer)
^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/transformers/agents/agents.py", line 701, in run
output = self.python_evaluator(
File "/usr/local/lib/python3.10/dist-packages/transformers/agents/python_interpreter.py", line 888, in evaluate_python_code
raise SyntaxError(f"The code generated by the agent is not valid.\n{e}")
SyntaxError: The code generated by the agent is not valid.
invalid syntax. Perhaps you forgot a comma? (<unknown>, line 11)
Error in execution: The code generated by the agent is not valid.\ninvalid syntax. Perhaps you forgot a comma? (<unknown>, line 11). Be sure to provide correct code.
エラーになってしまっているのだが、与えられたタスクに対してエージェントが推論、そこからコードを生成・実行しようとしているのがわかる。
で、色々調べてみると、どうやらOpenAI APIを使うこともできるらしい。
HuggingFace有料アカウントでない限り、そちらを使うほうが良いのかもという気がした。
HuggingFaceのエコシステムを理解していないので、果たしてどこまで試せるかなぁ・・・というところ。
OpenAI APIが使えるならできそうな気もするので、気が向いたら試してみようかな、というところ。
あとエージェントのより進んだ使い方のチュートリアルもある。
推論に関してのチュートリアルは一通りやってみた。これまではモデルカードを見ながら見様見真似でやっていたのが、推論での使い方について基礎的な知識は得れたかなと思う(基礎の中の基礎かもしれないが)。
ファインチューニングについてはじっくり腰を据えてやる必要があるかなと思うので、一旦はここまで。