コンテキスト管理
コンテキストは多義的な用語です。考慮すべきコンテキストには主に 2 つのクラスがあります:
- ローカルコンテキスト — 実行中にコードがアクセスできるもの。ツールに必要な依存関係やデータ、
onHandoff
のようなコールバック、ライフサイクルフックなど - エージェント/LLM コンテキスト — 応答生成時に言語モデルが参照できるもの
ローカルコンテキスト
Section titled “ローカルコンテキスト”ローカルコンテキストは RunContext<T>
型で表現します。状態や依存関係を保持する任意のオブジェクトを作成し、それを Runner.run()
に渡します。すべてのツール呼び出しとフックは RunContext
ラッパーを受け取り、そのオブジェクトを読み書きできます。
import { Agent, run, RunContext, tool } from '@openai/agents';import { z } from 'zod';
interface UserInfo { name: string; uid: number;}
const fetchUserAge = tool({ name: 'fetch_user_age', description: 'Return the age of the current user', parameters: z.object({}), execute: async ( _args, runContext?: RunContext<UserInfo>, ): Promise<string> => { return `User ${runContext?.context.name} is 47 years old`; },});
async function main() { const userInfo: UserInfo = { name: 'John', uid: 123 };
const agent = new Agent<UserInfo>({ name: 'Assistant', tools: [fetchUserAge], });
const result = await run(agent, 'What is the age of the user?', { context: userInfo, });
console.log(result.finalOutput); // The user John is 47 years old.}
if (require.main === module) { main().catch(console.error);}
1 回の実行に参加するすべてのエージェント、ツール、フックは同じ型のコンテキストを使用する必要があります。
ローカルコンテキストの使用例:
- 実行に関するデータ(ユーザー名、ID など)
- ロガーやデータフェッチャーなどの依存関係
- ヘルパー関数
エージェント/LLM コンテキスト
Section titled “エージェント/LLM コンテキスト”LLM が呼び出されると、参照できるデータは会話履歴に含まれるものだけです。追加情報を利用可能にするには、次のような方法があります:
- エージェントの
instructions
(システムまたは開発者メッセージ)に追加する。これは静的な文字列でも、コンテキストを受け取って文字列を返す関数でも可 Runner.run()
を呼び出すときにinput
に含める。これは instructions の手法に近いですが、メッセージを chain of command の下位に配置できます- 関数ツール経由で公開し、LLM がオンデマンドでデータを取得できるようにする
- リトリーバルや Web 検索ツールを使い、ファイル、データベース、または Web の関連データに基づいて応答をグラウンディングする