コンテキスト管理
コンテキストは多義的な用語です。ここで扱う主なコンテキストは次の 2 種類です。
- コードからローカルに参照できるコンテキスト: ツール関数の実行時、
on_handoffなどのコールバック、ライフサイクルフック中に必要となるデータや依存関係です。 - LLM に提供されるコンテキスト: LLM が応答を生成する際に参照できるデータです。
ローカルコンテキスト
これは RunContextWrapper クラスと、その中の context プロパティで表現されます。動作の流れは次のとおりです。
- 任意の Python オブジェクトを作成します。一般的には dataclass や Pydantic オブジェクトを使います。
- そのオブジェクトを各種の実行メソッドに渡します(例:
Runner.run(..., **context=whatever**))。 - すべてのツール呼び出しやライフサイクルフックに、
RunContextWrapper[T]というラッパーオブジェクトが渡されます。Tはコンテキストオブジェクトの型で、wrapper.contextからアクセスできます。
最重要ポイント: 特定のエージェント実行に関わるすべてのエージェント、ツール関数、ライフサイクルは、同じ 型 のコンテキストを使用する必要があります。
コンテキストは次のような用途に使えます:
- 実行に関する状況データ(例: ユーザー名 / UID その他のユーザー情報)
- 依存関係(例: ロガーオブジェクト、データフェッチャーなど)
- ヘルパー関数
注意
コンテキストオブジェクトは LLM に 送信されません。これは純粋にローカルなオブジェクトで、読み書きやメソッドの呼び出しができます。
import asyncio
from dataclasses import dataclass
from agents import Agent, RunContextWrapper, Runner, function_tool
@dataclass
class UserInfo: # (1)!
name: str
uid: int
@function_tool
async def fetch_user_age(wrapper: RunContextWrapper[UserInfo]) -> str: # (2)!
"""Fetch the age of the user. Call this function to get user's age information."""
return f"The user {wrapper.context.name} is 47 years old"
async def main():
user_info = UserInfo(name="John", uid=123)
agent = Agent[UserInfo]( # (3)!
name="Assistant",
tools=[fetch_user_age],
)
result = await Runner.run( # (4)!
starting_agent=agent,
input="What is the age of the user?",
context=user_info,
)
print(result.final_output) # (5)!
# The user John is 47 years old.
if __name__ == "__main__":
asyncio.run(main())
- これはコンテキストオブジェクトです。ここでは dataclass を使っていますが、任意の型を使用できます。
- これはツールです。
RunContextWrapper[UserInfo]を受け取り、ツールの実装はコンテキストから読み取ります。 - エージェントにジェネリック型
UserInfoを付与し、型チェッカーがエラーを検出できるようにします(たとえば、異なるコンテキスト型を受け取るツールを渡そうとした場合)。 run関数にコンテキストを渡します。- エージェントはツールを正しく呼び出し、年齢を取得します。
応用: ToolContext
実行中のツールに関する追加メタデータ(ツール名、呼び出し ID、raw な引数文字列など)にアクセスしたい場合があります。
そのために、RunContextWrapper を拡張した ToolContext クラスを使用できます。
from typing import Annotated
from pydantic import BaseModel, Field
from agents import Agent, Runner, function_tool
from agents.tool_context import ToolContext
class WeatherContext(BaseModel):
user_id: str
class Weather(BaseModel):
city: str = Field(description="The city name")
temperature_range: str = Field(description="The temperature range in Celsius")
conditions: str = Field(description="The weather conditions")
@function_tool
def get_weather(ctx: ToolContext[WeatherContext], city: Annotated[str, "The city to get the weather for"]) -> Weather:
print(f"[debug] Tool context: (name: {ctx.tool_name}, call_id: {ctx.tool_call_id}, args: {ctx.tool_arguments})")
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind.")
agent = Agent(
name="Weather Agent",
instructions="You are a helpful agent that can tell the weather of a given city.",
tools=[get_weather],
)
ToolContext は RunContextWrapper と同じ .context プロパティに加えて、現在のツール呼び出しに固有の追加フィールドを提供します:
tool_name– 呼び出されているツールの名前tool_call_id– このツール呼び出しの一意の識別子tool_arguments– ツールに渡された raw な引数文字列
実行時にツールレベルのメタデータが必要な場合は ToolContext を使用してください。
エージェントとツール間で一般的にコンテキストを共有するだけであれば、RunContextWrapper で十分です。
エージェント / LLM のコンテキスト
LLM が呼び出されると、参照できるのは会話履歴のデータ のみ です。つまり、LLM に新しいデータを利用させたい場合は、そのデータが履歴で参照できるようにする必要があります。方法はいくつかあります:
- エージェントの
instructionsに追加します。これは「system prompt(システムプロンプト)」や「developer message」とも呼ばれます。システムプロンプトは固定の文字列でも、コンテキストを受け取って文字列を出力する動的関数でも構いません。ユーザー名や現在の日付のように常に有用な情報に適した方法です。 Runner.run関数を呼び出す際のinputに追加します。これはinstructionsの戦術に似ていますが、chain of command においてより下位のメッセージとして扱えます。- 関数ツール経由で公開します。これはオンデマンドのコンテキストに有用で、LLM が必要に応じてデータ取得用のツールを呼び出せます。
- リトリーバルや Web 検索を使用します。これらは、ファイルやデータベース(リトリーバル)や Web(Web 検索)から関連データを取得できる特別なツールです。関連するコンテキストデータに基づいて応答を「グラウンディング」するのに役立ちます。