エージェントの実行結果
エージェントを実行 すると、次のいずれかを受け取ります:
stream: trueなしでrunを呼び出した場合はRunResultstream: trueありでrunを呼び出した場合はStreamedRunResult。ストリーミングの詳細は ストリーミング ガイド も参照してください
どちらの結果型でも、finalOutput、newItems、interruptions、state など同じ中核的な結果サーフェスが公開されます。StreamedRunResult には、completed、toStream()、toTextStream()、currentAgent などのストリーミング制御が追加されます。
適切な結果サーフェスの選択
Section titled “適切な結果サーフェスの選択”ほとんどのアプリケーションでは、必要なのは数個のプロパティだけです:
| 必要なもの | 使用先 |
|---|---|
| ユーザーに表示する最終回答 | finalOutput |
| 完全なローカル transcript を含む、再生可能な次ターン入力 | history |
| この実行で新たに生成された model 形状の item のみ | output |
| agent/tool/handoff の metadata を含むリッチな実行 item | newItems |
| 通常、次のユーザーターンを担当すべきエージェント | lastAgent または activeAgent |
OpenAI Responses API 連鎖での previousResponseId | lastResponseId |
| 保留中の承認と再開可能なスナップショット | interruptions と state |
| アプリコンテキスト、承認、使用量、ネストされた agent-tool 入力 | runContext |
現在のネストされた Agent.asTool() 呼び出しに関する metadata(例: customOutputExtractor 内) | agentToolInvocation |
| 元の model 呼び出しまたはガードレール診断 | rawResponses とガードレール結果配列 |
finalOutput プロパティには、最後に実行されたエージェントの最終出力が含まれます。この結果は次のいずれかです:
string—outputTypeが未定義のエージェントの既定unknown— エージェントの出力型が JSON schema で定義されている場合。この場合 JSON は parse 済みですが、型の検証は手動で必要ですz.infer<outputType>— エージェントの出力型が Zod schema で定義されている場合。出力はこの schema に対して自動的に parse されますundefined— エージェントが出力を生成しなかった場合(例: 出力生成前に停止)
ストリーミング実行が進行中の間、または最終出力に到達する前に承認の interruption で一時停止した場合も、finalOutput は undefined です。
異なる出力型を持つハンドオフを使用する場合、エージェントの作成には new Agent() コンストラクターではなく Agent.create() メソッドを使用してください。
これにより、SDK が取りうるすべてのハンドオフにわたる出力型を推論し、finalOutput プロパティに union type を提供できるようになります。
例:
import { Agent, run } from '@openai/agents';import { z } from 'zod';
const refundAgent = new Agent({ name: 'Refund Agent', instructions: 'You are a refund agent. You are responsible for refunding customers.', outputType: z.object({ refundApproved: z.boolean(), }),});
const orderAgent = new Agent({ name: 'Order Agent', instructions: 'You are an order agent. You are responsible for processing orders.', outputType: z.object({ orderId: z.string(), }),});
const triageAgent = Agent.create({ name: 'Triage Agent', instructions: 'You are a triage agent. You are responsible for triaging customer issues.', handoffs: [refundAgent, orderAgent],});
const result = await run(triageAgent, 'I need to a refund for my order');
const output = result.finalOutput;// ^? { refundApproved: boolean } | { orderId: string } | string | undefined入出力サーフェス
Section titled “入出力サーフェス”これらのプロパティは、それぞれ異なる問いに答えます:
| プロパティ | 含まれる内容 | 最適な用途 |
|---|---|---|
input | この実行のベース入力。handoff input filter が履歴を書き換えた場合は、実行継続に使われた filter 後の入力を反映します | この実行が実際に入力として使った内容の監査 |
output | この実行で生成された model 形状の item のみ(agent metadata なし) | 新しい model 差分のみの保存または再生 |
newItems | agent/tool/handoff metadata を持つリッチな RunItem wrapper | ログ、UI、監査、デバッグ |
history | input + newItems から構築された、再生可能な次ターン入力 | 手動チャットループとクライアント管理の会話状態 |
実運用では:
- アプリケーション側で会話全体を手動で保持する場合は
historyを使います - 既存の履歴を別途保存しており、この実行で新規生成された item のみ欲しい場合は
outputを使います - agent との関連付け、tool 出力、handoff 境界、承認 item が必要な場合は
newItemsを使います conversationIdまたはpreviousResponseIdを使う場合、通常はhistoryをrun()に戻しません。代わりに新しいユーザー入力のみを渡し、サーバー管理 ID を再利用します。比較の全体像は エージェントの実行 を参照してください
history は、チャットライクなユースケースで完全な履歴を維持するための便利な方法です:
import { Agent, user, run } from '@openai/agents';import type { AgentInputItem } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant knowledgeable about recent AGI research.',});
let history: AgentInputItem[] = [ // initial message user('Are we there yet?'),];
for (let i = 0; i < 10; i++) { // run 10 times const result = await run(agent, history);
// update the history to the new output history = result.history;
history.push(user('How about now?'));}新規 item
Section titled “新規 item”newItems は、実行中に何が起きたかを最もリッチに示します。一般的な item type は次のとおりです:
- assistant メッセージ用の
RunMessageOutputItem - reasoning item 用の
RunReasoningItem - Responses の tool-search リクエストと、返される読み込み済み tool 定義用の
RunToolSearchCallItemとRunToolSearchOutputItem - tool 呼び出しとその結果用の
RunToolCallItemとRunToolCallOutputItem - 承認待ちで一時停止した tool 呼び出し用の
RunToolApprovalItem - handoff リクエストと完了した転送用の
RunHandoffCallItemとRunHandoffOutputItem
どのエージェントが item を生成したか、またそれが tool、tool-search、handoff、承認境界かを知る必要がある場合は、output より newItems を選んでください。toolSearchTool() を使う場合、通常の tool 呼び出しの前にどの deferred tools や namespace が読み込まれたかを確認する最も簡単な方法が、これらの tool-search item です。
会話の継続または再開
Section titled “会話の継続または再開”アクティブエージェント
Section titled “アクティブエージェント”lastAgent プロパティには最後に実行されたエージェントが入ります。これは、ハンドオフ後の次のユーザーターンで再利用するエージェントとして最適なことが多いです。activeAgent は同じ値の alias です。
ストリーミングモードでは、実行進行中に現在アクティブなエージェントを currentAgent で確認できます。
割り込みと再開可能な状態
Section titled “割り込みと再開可能な状態”tool が承認を必要とする場合、実行は一時停止し、interruptions には保留中の RunToolApprovalItem が入ります。これには、直接の tool、handoff 後に到達した tool、ネストされた agent.asTool() 実行による承認が含まれる場合があります。
result.state.approve(...) / result.state.reject(...) で承認を処理し、同じ state を run() に戻して再開します。すべての interruption を一度に解決する必要はありません。一部の item だけ処理して再実行した場合、解決済みの呼び出しは継続し、未解決のものは保留のままで再度一時停止します。
state プロパティは、結果の背後にある serialize 可能な snapshot です。人間の介入(HITL)、retry フロー、または後で一時停止した実行を再開する必要があるケースで使用します。
サーバー管理の継続
Section titled “サーバー管理の継続”lastResponseId は、OpenAI Responses API 連鎖を使う際に、次ターンで previousResponseId として渡す値です。
すでに history、session、conversationId で会話を継続している場合、通常 lastResponseId は不要です。マルチステップ実行のすべての元の model 応答が必要な場合は、代わりに rawResponses を確認してください。
ネストされた agent-tool metadata
Section titled “ネストされた agent-tool metadata”agentToolInvocation は、ネストされた Agent.asTool() の結果向けで、特に customOutputExtractor 内で現在の tool invocation の metadata が必要な場合に使います。これは「実行全体が完了したこと」を示す一般的な summary フィールドではありません。
このネストされたコンテキストでは、agentToolInvocation は次を公開します:
toolNametoolCallIdtoolArguments
ネストされた agent-tool 実行に渡された構造化入力も必要な場合は、result.runContext.toolInput と組み合わせてください。
通常のトップレベル run() 結果では、これは通常 undefined です。この metadata は runtime のみで、RunState には serialize されません。周辺パターンは Agents as tools を参照してください。
ストリーミング結果
Section titled “ストリーミング結果”StreamedRunResult は上記と同じ結果サーフェスを継承しますが、ストリーミング固有の制御が追加されます:
- assistant テキストのみの
toTextStream() - 完全なイベントストリーム用の
toStream()またはfor await ... of stream - 実行とすべての後処理 callback の完了を待つ
completed - ストリーミング終端状態を確認する
errorとcancelled - 実行途中のアクティブエージェントを追跡する
currentAgent
ストリーミング実行の確定した最終状態が必要な場合は、finalOutput、history、interruptions、その他の要約プロパティを読む前に completed を待ってください。イベント単位の処理は ストリーミング ガイド を参照してください。
診断と高度なフィールド
Section titled “診断と高度なフィールド”実行コンテキスト
Section titled “実行コンテキスト”runContext プロパティは、結果上の run context のサポートされた公開ビューです。result.runContext.context はアプリコンテキストで、同じオブジェクトには承認、使用量、ネストされた toolInput など SDK 管理の runtime metadata も含まれます。完全な形状は コンテキスト管理 を参照してください。
rawResponses には、実行中に収集された元の model 応答が含まれます。マルチステップ実行では、たとえば handoff や反復的な tool/model サイクルをまたいで複数の応答が生成されることがあります。
ガードレール結果
Section titled “ガードレール結果”inputGuardrailResults と outputGuardrailResults プロパティには、エージェントレベルのガードレール結果が含まれます。tool のガードレール結果は、toolInputGuardrailResults と toolOutputGuardrailResults で別途公開されます。
ガードレールの判定をログ化したい場合、ガードレール関数が返した追加 metadata を確認したい場合、または実行がブロックされた理由をデバッグしたい場合に、これらの配列を使います。
token 使用量は result.state.usage に集約され、実行のリクエスト数と token 合計を追跡します。同じ usage オブジェクトは result.runContext.usage からも利用できます。ストリーミング実行では、このデータは応答到着に応じて更新されます。
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Usage Tracker', instructions: 'Summarize the latest project update in one sentence.',});
const result = await run( agent, 'Summarize this: key customer feedback themes and the next product iteration.',);
const usage = result.state.usage;console.log({ requests: usage.requests, inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, totalTokens: usage.totalTokens,});
if (usage.requestUsageEntries) { for (const entry of usage.requestUsageEntries) { console.log('request', { endpoint: entry.endpoint, inputTokens: entry.inputTokens, outputTokens: entry.outputTokens, totalTokens: entry.totalTokens, }); }}