ストリーミング
Agents SDK は、モデルやその他の実行ステップの出力を段階的に配信できます。ストリーミングにより UI を応答性良く保ち、最終的な実行結果全体を待たずに ユーザー を更新できます。
ストリーミングの有効化
Section titled “ストリーミングの有効化”Runner.run()
に { stream: true }
オプションを渡すと、完全な実行結果ではなくストリーミングオブジェクトを取得できます:
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Storyteller', instructions: 'You are a storyteller. You will be given a topic and you will tell a story about it.',});
const result = await run(agent, 'Tell me a story about a cat.', { stream: true,});
ストリーミングが有効な場合、返される stream
は AsyncIterable
インターフェースを実装します。各イテレーションで、その実行内で何が起きたかを示すオブジェクトが得られます。ストリームは エージェント の実行の異なる部分を表す 3 種類のイベントのいずれかを返します。とはいえ、多くのアプリケーションが欲しいのはモデルのテキストだけなので、ストリームにはそのためのヘルパーがあります。
テキスト出力の取得
Section titled “テキスト出力の取得”stream.toTextStream()
を呼び出すと、生成されたテキストのストリームを取得できます。compatibleWithNodeStreams
が true
の場合、戻り値は通常の Node.js Readable
です。process.stdout
や他の出力先にそのままパイプできます。
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Storyteller', instructions: 'You are a storyteller. You will be given a topic and you will tell a story about it.',});
const result = await run(agent, 'Tell me a story about a cat.', { stream: true,});
result .toTextStream({ compatibleWithNodeStreams: true, }) .pipe(process.stdout);
stream.completed
の Promise は、実行と保留中のコールバックがすべて完了したときに解決されます。出力がもうないことを確実にする必要がある場合は、必ず await してください。
すべてのイベントの監視
Section titled “すべてのイベントの監視”for await
ループを使って、到着する各イベントを確認できます。役立つ情報として、低レベルなモデルイベント、エージェントの切り替え、SDK 固有の実行情報などがあります:
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Storyteller', instructions: 'You are a storyteller. You will be given a topic and you will tell a story about it.',});
const result = await run(agent, 'Tell me a story about a cat.', { stream: true,});
for await (const event of result) { // these are the raw events from the model if (event.type === 'raw_model_stream_event') { console.log(`${event.type} %o`, event.data); } // agent updated events if (event.type === 'agent_updated_stream_event') { console.log(`${event.type} %s`, event.agent.name); } // Agent SDK specific events if (event.type === 'run_item_stream_event') { console.log(`${event.type} %o`, event.item); }}
完全なスクリプトは the streamed example を参照してください。プレーンテキストのストリームと 元 のイベントストリームの両方を出力します。
イベントタイプ
Section titled “イベントタイプ”ストリームは次の 3 種類のイベントを返します:
raw_model_stream_event
Section titled “raw_model_stream_event”type RunRawModelStreamEvent = { type: 'raw_model_stream_event'; data: ResponseStreamEvent;};
例:
{ "type": "raw_model_stream_event", "data": { "type": "output_text_delta", "delta": "Hello" }}
run_item_stream_event
Section titled “run_item_stream_event”type RunItemStreamEvent = { type: 'run_item_stream_event'; name: RunItemStreamEventName; item: RunItem;};
ハンドオフのペイロード例:
{ "type": "run_item_stream_event", "name": "handoff_occurred", "item": { "type": "handoff_call", "id": "h1", "status": "completed", "name": "transfer_to_refund_agent" }}
agent_updated_stream_event
Section titled “agent_updated_stream_event”type RunAgentUpdatedStreamEvent = { type: 'agent_updated_stream_event'; agent: Agent<any, any>;};
例:
{ "type": "agent_updated_stream_event", "agent": { "name": "Refund Agent" }}
ストリーミング中の Human in the loop(人間の介入)
Section titled “ストリーミング中の Human in the loop(人間の介入)”ストリーミングは、実行を一時停止するハンドオフ(たとえばツールに承認が必要な場合)と両立します。ストリームオブジェクトの interruption
フィールドで割り込みにアクセスでき、各割り込みに対して state.approve()
または state.reject()
を呼び出すことで実行を継続できます。{ stream: true }
で再実行するとストリーミング出力が再開されます。
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Storyteller', instructions: 'You are a storyteller. You will be given a topic and you will tell a story about it.',});
let stream = await run( agent, 'What is the weather in San Francisco and Oakland?', { stream: true },);stream.toTextStream({ compatibleWithNodeStreams: true }).pipe(process.stdout);await stream.completed;
while (stream.interruptions?.length) { console.log( 'Human-in-the-loop: approval required for the following tool calls:', ); const state = stream.state; for (const interruption of stream.interruptions) { const approved = confirm( `Agent ${interruption.agent.name} would like to use the tool ${interruption.rawItem.name} with "${interruption.rawItem.arguments}". Do you approve?`, ); if (approved) { state.approve(interruption); } else { state.reject(interruption); } }
// Resume execution with streaming output stream = await run(agent, state, { stream: true }); const textStream = stream.toTextStream({ compatibleWithNodeStreams: true }); textStream.pipe(process.stdout); await stream.completed;}
ユーザー と対話するより完全な例は
human-in-the-loop-stream.ts
です。
- 終了前に
stream.completed
を待機して、すべての出力がフラッシュされたことを確認する - 最初の
{ stream: true }
オプションは、その呼び出しにのみ適用されるため、RunState
で再実行する場合は再度オプションを指定する - アプリケーションがテキスト結果にだけ関心がある場合は、個々のイベントオブジェクトを扱わずに済むよう
toTextStream()
を優先する
ストリーミングとイベントシステムにより、チャットインターフェースや端末アプリケーションなど、段階的な更新が ユーザー の利点になる場所に エージェント を統合できます。