コンテンツにスキップ

コンテキスト管理

コンテキストは多義的な用語です。ここで扱う主なコンテキストは次の 2 種類です。

  1. コードからローカルに参照できるコンテキスト: ツール関数の実行時、on_handoff などのコールバック、ライフサイクルフック中に必要となるデータや依存関係です。
  2. LLM に提供されるコンテキスト: LLM が応答を生成する際に参照できるデータです。

ローカルコンテキスト

これは RunContextWrapper クラスと、その中の context プロパティで表現されます。動作の流れは次のとおりです。

  1. 任意の Python オブジェクトを作成します。一般的には dataclass や Pydantic オブジェクトを使います。
  2. そのオブジェクトを各種の実行メソッドに渡します(例: Runner.run(..., **context=whatever**))。
  3. すべてのツール呼び出しやライフサイクルフックに、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())
  1. これはコンテキストオブジェクトです。ここでは dataclass を使っていますが、任意の型を使用できます。
  2. これはツールです。RunContextWrapper[UserInfo] を受け取り、ツールの実装はコンテキストから読み取ります。
  3. エージェントにジェネリック型 UserInfo を付与し、型チェッカーがエラーを検出できるようにします(たとえば、異なるコンテキスト型を受け取るツールを渡そうとした場合)。
  4. run 関数にコンテキストを渡します。
  5. エージェントはツールを正しく呼び出し、年齢を取得します。

応用: 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],
)

ToolContextRunContextWrapper と同じ .context プロパティに加えて、現在のツール呼び出しに固有の追加フィールドを提供します:

  • tool_name – 呼び出されているツールの名前
  • tool_call_id – このツール呼び出しの一意の識別子
  • tool_arguments – ツールに渡された raw な引数文字列

実行時にツールレベルのメタデータが必要な場合は ToolContext を使用してください。
エージェントとツール間で一般的にコンテキストを共有するだけであれば、RunContextWrapper で十分です。


エージェント / LLM のコンテキスト

LLM が呼び出されると、参照できるのは会話履歴のデータ のみ です。つまり、LLM に新しいデータを利用させたい場合は、そのデータが履歴で参照できるようにする必要があります。方法はいくつかあります:

  1. エージェントの instructions に追加します。これは「system prompt(システムプロンプト)」や「developer message」とも呼ばれます。システムプロンプトは固定の文字列でも、コンテキストを受け取って文字列を出力する動的関数でも構いません。ユーザー名や現在の日付のように常に有用な情報に適した方法です。
  2. Runner.run 関数を呼び出す際の input に追加します。これは instructions の戦術に似ていますが、chain of command においてより下位のメッセージとして扱えます。
  3. 関数ツール経由で公開します。これはオンデマンドのコンテキストに有用で、LLM が必要に応じてデータ取得用のツールを呼び出せます。
  4. リトリーバルや Web 検索を使用します。これらは、ファイルやデータベース(リトリーバル)や Web(Web 検索)から関連データを取得できる特別なツールです。関連するコンテキストデータに基づいて応答を「グラウンディング」するのに役立ちます。