AutoGen AgentChat は、メッセージに応答する様々な方法を備えた、プリセットされたエージェントのセットを提供しています。ここでは Assistant Agent について詳細を説明します。
AutoGen AgentChat : Tutorial : エージェント
作成 : クラスキャット・セールスインフォメーション
作成日時 : 04/22/2025
* 本記事は github microsoft/autogen の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
AutoGen AgentChat : Tutorial : エージェント
AutoGen AgentChat は、メッセージに応答する様々な方法を備えた、プリセットされたエージェントのセットを提供しています。すべてのエージェントは以下の属性とメソッドを共有します :
- name : エージェントの一意な名前。
- description : テキストでのエージェントの説明。
- on_messages() : BaseChatMessage のサブクラスであるメッセージのシークエンスをエージェントに送信し、Response を取得します。エージェントはステートフルであることが想定されていて、このメソッドは完全な履歴ではなく、新しいメッセージとともに呼び出されることが想定されていることに注意することは重要です。
- on_messages_stream() : on_messages() と同じですが、BaseAgentEvent か BaseChatMessage をサブクラス化したメッセージのイテレータを、続いて最後の項目として Response を返します。
- on_reset() : エージェントをその初期状態にリセットします。
- run() と run_stream(): それぞれ on_messages() と on_messages_stream() を呼び出す便利なメソッドですが、Teams と同じインターフェイスを提供します。
AgentChat メッセージタイプについての詳細については autogen_agentchat.messages をご覧ください。
Assistant Agent
AssistantAgent は、言語モデルを使用して、ツールを使用する能力を持つ組み込みエージェントです。
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import StructuredMessage, TextMessage
from autogen_agentchat.ui import Console
from autogen_core import CancellationToken
from autogen_ext.models.openai import OpenAIChatCompletionClient
# web を情報検索するツールの定義。
async def web_search(query: str) -> str:
"""Find information on the web"""
return "AutoGen is a programming framework for building multi-agent applications."
# OpenAI GPT-4o モデルを使用するエージェントの作成。
model_client = OpenAIChatCompletionClient(
model="gpt-4o",
# api_key="YOUR_API_KEY",
)
agent = AssistantAgent(
name="assistant",
model_client=model_client,
tools=[web_search],
system_message="Use tools to solve tasks.",
)
レスポンスの取得
on_messages() メソッドを使用して指定のメッセージへのエージェントのレスポンスを取得できます。
async def assistant_run() -> None:
response = await agent.on_messages(
[TextMessage(content="Find information on AutoGen", source="user")],
cancellation_token=CancellationToken(),
)
print(response.inner_messages)
print(response.chat_message)
# Use asyncio.run(assistant_run()) when running in a script.
await assistant_run()
[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=598, completion_tokens=16), content=[FunctionCall(id='call_9UWYM1CgE3ZbnJcSJavNDB79', arguments='{"query":"AutoGen"}', name='web_search')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content='AutoGen is a programming framework for building multi-agent applications.', call_id='call_9UWYM1CgE3ZbnJcSJavNDB79', is_error=False)], type='ToolCallExecutionEvent')] source='assistant' models_usage=None content='AutoGen is a programming framework for building multi-agent applications.' type='ToolCallSummaryMessage'
on_messages() メソッドへの呼び出しは、chat_message 属性のエージェントの最終的なレスポンスと、(最終的なレスポンスに至ったエージェントの「思考プロセス」をストアする) inner_messages 属性に内部メッセージのリストを含む、Response を返します。
Note : on_messages() はエージェントの内部状態を更新することに注意することは重要です – それはエージェントの履歴にメッセージを追加します。 従ってこのメソッドは新しいメッセージとともに呼び出す必要があります。同じメッセージや完全な履歴でこのメッセージを繰り返し呼び出すべきではありません。
run() メソッドを呼び出すこともできます、これは on_messages() を呼び出す便利なメソッドです。それは Teams と同じ I/F に従い、TaskResult オブジェクトを返します。
マルチモーダル入力
AssistantAgent は入力を MultiModalMessage として提供することでマルチモーダル入力を処理できます。
from io import BytesIO
import PIL
import requests
from autogen_agentchat.messages import MultiModalMessage
from autogen_core import Image
# Create a multi-modal message with random image and text.
pil_image = PIL.Image.open(BytesIO(requests.get("https://picsum.photos/300/200").content))
img = Image(pil_image)
multi_modal_message = MultiModalMessage(content=["Can you describe the content of this image?", img], source="user")
img
# Use asyncio.run(...) when running in a script.
response = await agent.on_messages([multi_modal_message], CancellationToken())
print(response.chat_message)
The image depicts a vintage car, likely from the 1930s or 1940s, with a sleek, classic design. The car seems to be customized or well-maintained, as indicated by its shiny exterior and lowered stance. It has a prominent grille and round headlights. There's a license plate on the front with the text "FARMER BOY." The setting appears to be a street with old-style buildings in the background, suggesting a historical or retro theme.
MultiModalMessage を run() メソッドへのタスク入力として使用することもできます。
ストリーミング・メッセージ
on_messages_stream() メソッドを使用して、エージェントにより生成されるとき各メッセージをストリームし、メッセージがコンソールに表示されるとき Console を使用してそれらを出力することもできます。
async def assistant_run_stream() -> None:
# Option 1: read each message from the stream (as shown in the previous example).
# async for message in agent.on_messages_stream(
# [TextMessage(content="Find information on AutoGen", source="user")],
# cancellation_token=CancellationToken(),
# ):
# print(message)
# Option 2: use Console to print all messages as they appear.
await Console(
agent.on_messages_stream(
[TextMessage(content="Find information on AutoGen", source="user")],
cancellation_token=CancellationToken(),
),
output_stats=True, # Enable stats printing.
)
# Use asyncio.run(assistant_run_stream()) when running in a script.
await assistant_run_stream()
---------- assistant ---------- [FunctionCall(id='call_fSp5iTGVm2FKw5NIvfECSqNd', arguments='{"query":"AutoGen information"}', name='web_search')] [Prompt tokens: 61, Completion tokens: 16] ---------- assistant ---------- [FunctionExecutionResult(content='AutoGen is a programming framework for building multi-agent applications.', call_id='call_fSp5iTGVm2FKw5NIvfECSqNd')] ---------- assistant ---------- AutoGen is a programming framework designed for building multi-agent applications. If you need more detailed information or specific aspects about AutoGen, feel free to ask! [Prompt tokens: 93, Completion tokens: 32] ---------- Summary ---------- Number of inner messages: 2 Total prompt tokens: 154 Total completion tokens: 48 Duration: 4.30 seconds
on_messages_stream() メソッドは、エージェントにより生成された各 inner メッセージを生成する非同期ジェネレータを返します。その最終的な項目は chat_message 属性のレスポンス・メッセージです。
メッセージから、アシスタントエージェントが web_search ツールを使用して情報を収集し、検索結果に基づいて応答したことを観察できます。
run_stream() を使用して on_messages_stream() と同じストリーミング動作を得ることもできます。それは Teams と同じ I/F に従います。
ツールの使用
大規模言語モデル (LLM) は通常なテキストやコード・レスポンスの生成に限定されています。けれども、多くの複雑なタスクは、API やデータベースからのデータの取得のような、特定のアクションを遂行する外部ツールを使用する機能から恩恵を受けます。
この制限に対処するため、最新の LLM は利用可能なツール・スキーマ (ツールとそれらの引数の説明) のリストを受け取り、ツール呼び出しメッセージを生成できるようになっています。この機能は ツール呼び出し や 関数呼び出し と呼ばれ、知的なエージェントベースのアプリケーションを構築する際のポピュラーなパターンになってきました。Refer to the documentation from OpenAI and Anthropic for more information about tool calling in LLMs.
AgentChat では、AssistantAgent はツールを使用して特定のアクションを遂行することができます。web_search ツールはアシスタント・エージェントが Web を情報検索できるようにするツールの一つです。カスタムツールは Python 関数や BaseTool のサブクラスであり得ます。
デフォルトでは、AssistantAgent がツールを実行すると、レスポンス内の ToolCallSummaryMessage の文字列としてツールの出力が返されます。ツールが自然言語で整形式文字を返さない場合、AssistantAgent コンストラクタで reflect_on_tool_use=True パラメータを設定することで、モデルがツールの出力を要約するようにリフレクション・ステップを追加できます。
組み込みツール
AutoGen Extension は、Assistant Agent で使用できる組み込みツールのセットを提供します。autogen_ext.tools 名前空間で利用可能なすべてのツールについては API ドキュメント をご覧ください。例えば、以下のツールがあります :
- graphrag : GraphRAG インデックスを使用するためのツール。
- http : HTTP リクエストを行うためのツール。
- langchain : LangChain ツールを使用するためのアダプター。
- mcp : MCP サーバを使用するためのツール。
関数ツール
AssistantAgent は Python 関数をエージェントがツールとして使用できる FunctionTool に自動的に変換し、関数シグネチャと docstring からツールスキーマを自動生成します。
web_search_func ツールは関数ツールの例です。スキーマは自動生成されます。
from autogen_core.tools import FunctionTool
# Define a tool using a Python function.
async def web_search_func(query: str) -> str:
"""Find information on the web"""
return "AutoGen is a programming framework for building multi-agent applications."
# This step is automatically performed inside the AssistantAgent if the tool is a Python function.
web_search_function_tool = FunctionTool(web_search_func, description="Find information on the web")
# The schema is provided to the model during AssistantAgent's on_messages call.
web_search_function_tool.schema
{'name': 'web_search_func', 'description': 'Find information on the web', 'parameters': {'type': 'object', 'properties': {'query': {'description': 'query', 'title': 'Query', 'type': 'string'}}, 'required': ['query'], 'additionalProperties': False}, 'strict': False}
Model Context Protocol ツール
AssistantAgent はまた、mcp_server_tools() を使用して Model Context Protocol (MCP) サーバからサービスを受けるツールを利用できます。
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.mcp import StdioServerParams, mcp_server_tools
# Get the fetch tool from mcp-server-fetch.
fetch_mcp_server = StdioServerParams(command="uvx", args=["mcp-server-fetch"])
tools = await mcp_server_tools(fetch_mcp_server)
# Create an agent that can use the fetch tool.
model_client = OpenAIChatCompletionClient(model="gpt-4o")
agent = AssistantAgent(name="fetcher", model_client=model_client, tools=tools, reflect_on_tool_use=True) # type: ignore
# Let the agent fetch the content of a URL and summarize it.
result = await agent.run(task="Summarize the content of https://en.wikipedia.org/wiki/Seattle")
assert isinstance(result.messages[-1], TextMessage)
print(result.messages[-1].content)
# Close the connection to the model client.
await model_client.close()
Seattle, located in Washington state, is the most populous city in the state and a major city in the Pacific Northwest region of the United States. It's known for its vibrant cultural scene, significant economic presence, and rich history. Here are some key points about Seattle from the Wikipedia page: 1. **History and Geography**: Seattle is situated between Puget Sound and Lake Washington, with the Cascade Range to the east and the Olympic Mountains to the west. Its history is deeply rooted in Native American heritage and its development was accelerated with the arrival of settlers in the 19th century. The city was officially incorporated in 1869. 2. **Economy**: Seattle is a major economic hub with a diverse economy anchored by sectors like aerospace, technology, and retail. It's home to influential companies such as Amazon and Starbucks, and has a significant impact on the tech industry due to companies like Microsoft and other technology enterprises in the surrounding area. 3. **Cultural Significance**: Known for its music scene, Seattle was the birthplace of grunge music in the early 1990s. It also boasts significant attractions like the Space Needle, Pike Place Market, and the Seattle Art Museum. 4. **Education and Innovation**: The city hosts important educational institutions, with the University of Washington being a leading research university. Seattle is recognized for fostering innovation and is a leader in environmental sustainability efforts. 5. **Demographics and Diversity**: Seattle is noted for its diverse population, reflected in its rich cultural tapestry. It has seen a significant increase in population, leading to urban development and changes in its social landscape. These points highlight Seattle as a dynamic city with a significant cultural, economic, and educational influence within the United States and beyond.
Langchain ツール
Langchain ライブラリからのツールもそれらを LangChainToolAdapter でラップすることで使用できます。
import pandas as pd
from autogen_ext.tools.langchain import LangChainToolAdapter
from langchain_experimental.tools.python.tool import PythonAstREPLTool
df = pd.read_csv("https://raw.githubusercontent.com/pandas-dev/pandas/main/doc/data/titanic.csv")
tool = LangChainToolAdapter(PythonAstREPLTool(locals={"df": df}))
model_client = OpenAIChatCompletionClient(model="gpt-4o")
agent = AssistantAgent(
"assistant", tools=[tool], model_client=model_client, system_message="Use the `df` variable to access the dataset."
)
await Console(
agent.on_messages_stream(
[TextMessage(content="What's the average age of the passengers?", source="user")], CancellationToken()
),
output_stats=True,
)
await model_client.close()
---------- assistant ---------- [FunctionCall(id='call_BEYRkf53nBS1G2uG60wHP0zf', arguments='{"query":"df[\'Age\'].mean()"}', name='python_repl_ast')] [Prompt tokens: 111, Completion tokens: 22] ---------- assistant ---------- [FunctionExecutionResult(content='29.69911764705882', call_id='call_BEYRkf53nBS1G2uG60wHP0zf')] ---------- assistant ---------- 29.69911764705882 ---------- Summary ---------- Number of inner messages: 2 Total prompt tokens: 111 Total completion tokens: 22 Duration: 0.62 seconds
Response(chat_message=ToolCallSummaryMessage(source='assistant', models_usage=None, content='29.69911764705882', type='ToolCallSummaryMessage'), inner_messages=[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=111, completion_tokens=22), content=[FunctionCall(id='call_BEYRkf53nBS1G2uG60wHP0zf', arguments='{"query":"df[\'Age\'].mean()"}', name='python_repl_ast')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content='29.69911764705882', call_id='call_BEYRkf53nBS1G2uG60wHP0zf')], type='ToolCallExecutionEvent')])
並列ツール呼び出し
幾つかのモデルは並列ツール呼び出しをサポートします、これは複数のツールを同時に呼び出す必要があるタスクに役立ちます。デフォルトでは、モデルクライアントが複数のツール呼び出しを生成する場合、AssistantAgent はツールを並列に呼び出します。
ツールが互いに干渉する可能性がある副作用を持つ場合や、エージェントの動作が異なるモデル間で一貫している必要がある場合、並列ツール呼び出しを無効にしたい場合があるかもしれません。これはモデルクライアントレベルで行われる必要があります。
OpenAIChatCompletionClient と AzureOpenAIChatCompletionClient については、並列ツール呼び出しを無効にするには parallel_tool_calls=False を設定します。
model_client_no_parallel_tool_call = OpenAIChatCompletionClient(
model="gpt-4o",
parallel_tool_calls=False, # type: ignore
)
agent_no_parallel_tool_call = AssistantAgent(
name="assistant",
model_client=model_client_no_parallel_tool_call,
tools=[web_search],
system_message="Use tools to solve tasks.",
)
エージェントをループで実行する
AssistantAgent は 1 ステップずつ実行します : 一つのモデル呼び出し、続いて一つのツール呼び出し (or 並列ツール呼び出し)、そしてオプションのリフレクション。
それをループで実行するには、例えば、ツール呼び出しを生成しなくなるまで実行します、Single-Agent Team を参照してください。
構造化出力
構造化出力は、アプリケーションにより提供される事前定義されたスキーマを持つ構造化 JSON テキストをモデルが返すことを可能にします。JSON-モードとは異なり、スキーマは Pydantic BaseModel クラスとして提供できます、これは出力を検証するためにも使用できます。
AssistantAgent コンストラクタで output_content_type パラメータで基底モデルクラスを指定すれば、エージェントはコンテンツのタイプが基底モデルクラスのタイプである StructuredMessage で応答します。
このようにして、エージェントのレスポンスをアプリケーションに直接統合し、モデルの出力を構造化オブジェクトとして使用できます。
構造化出力はまた、エージェントのレスポンスに連鎖思考 (Chain-of-Thought) 推論を組み込むのにも役立ちます。構造化出力をアシスタント・エージェントで使用する方法については以下の例をご覧ください。
from typing import Literal
from pydantic import BaseModel
# The response format for the agent as a Pydantic base model.
class AgentResponse(BaseModel):
thoughts: str
response: Literal["happy", "sad", "neutral"]
# Create an agent that uses the OpenAI GPT-4o model.
model_client = OpenAIChatCompletionClient(model="gpt-4o")
agent = AssistantAgent(
"assistant",
model_client=model_client,
system_message="Categorize the input as happy, sad, or neutral following the JSON format.",
# Define the output content type of the agent.
output_content_type=AgentResponse,
)
result = await Console(agent.run_stream(task="I am happy."))
# Check the last message in the result, validate its type, and print the thoughts and response.
assert isinstance(result.messages[-1], StructuredMessage)
assert isinstance(result.messages[-1].content, AgentResponse)
print("Thought: ", result.messages[-1].content.thoughts)
print("Response: ", result.messages[-1].content.response)
await model_client.close()
---------- user ---------- I am happy.
---------- assistant ---------- { "thoughts": "The user explicitly states they are happy.", "response": "happy" } Thought: The user explicitly states they are happy. Response: happy
その他のプリセット・・エージェント
以下のプリセット・エージェントが利用可能です :
- UserProxyAgent : ユーザ入力を受け取りそれをレスポンスとして返すエージェント。
- CodeExecutorAgent : コードを実行できるエージェント。
- OpenAIAssistantAgent : OpenAI Assistant により支援される、カスタムツールを使用できるエージェント。
- MultimodalWebSurfer : Web を検索して情報を求めて Web ページにアクセスできるマルチモーダル・エージェント。
- FileSurfer : ローカルファイルを情報を求めて検索してブラウズできるエージェント。
- VideoSurfer : 情報を求めて動画を視聴できるエージェント。
以上