コンテンツにスキップ

エージェントの実行結果

エージェントを実行 すると、次のいずれかを受け取ります:

どちらの結果型でも、finalOutputnewItemsinterruptionsstate など同じ中核的な結果サーフェスが公開されます。StreamedRunResult には、completedtoStream()toTextStream()currentAgent などのストリーミング制御が追加されます。

ほとんどのアプリケーションでは、必要なのは数個のプロパティだけです:

必要なもの使用先
ユーザーに表示する最終回答finalOutput
完全なローカル transcript を含む、再生可能な次ターン入力history
この実行で新たに生成された model 形状の item のみoutput
agent/tool/handoff の metadata を含むリッチな実行 itemnewItems
通常、次のユーザーターンを担当すべきエージェントlastAgent または activeAgent
OpenAI Responses API 連鎖での previousResponseIdlastResponseId
保留中の承認と再開可能なスナップショットinterruptionsstate
アプリコンテキスト、承認、使用量、ネストされた agent-tool 入力runContext
現在のネストされた Agent.asTool() 呼び出しに関する metadata(例: customOutputExtractor 内)agentToolInvocation
元の model 呼び出しまたはガードレール診断rawResponses とガードレール結果配列

finalOutput プロパティには、最後に実行されたエージェントの最終出力が含まれます。この結果は次のいずれかです:

  • stringoutputType が未定義のエージェントの既定
  • unknown — エージェントの出力型が JSON schema で定義されている場合。この場合 JSON は parse 済みですが、型の検証は手動で必要です
  • z.infer<outputType> — エージェントの出力型が Zod schema で定義されている場合。出力はこの schema に対して自動的に parse されます
  • undefined — エージェントが出力を生成しなかった場合(例: 出力生成前に停止)

ストリーミング実行が進行中の間、または最終出力に到達する前に承認の interruption で一時停止した場合も、finalOutputundefined です。

異なる出力型を持つハンドオフを使用する場合、エージェントの作成には new Agent() コンストラクターではなく Agent.create() メソッドを使用してください。

これにより、SDK が取りうるすべてのハンドオフにわたる出力型を推論し、finalOutput プロパティに union type を提供できるようになります。

例:

Handoff final output types
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

これらのプロパティは、それぞれ異なる問いに答えます:

プロパティ含まれる内容最適な用途
inputこの実行のベース入力。handoff input filter が履歴を書き換えた場合は、実行継続に使われた filter 後の入力を反映しますこの実行が実際に入力として使った内容の監査
outputこの実行で生成された model 形状の item のみ(agent metadata なし)新しい model 差分のみの保存または再生
newItemsagent/tool/handoff metadata を持つリッチな RunItem wrapperログ、UI、監査、デバッグ
historyinput + newItems から構築された、再生可能な次ターン入力手動チャットループとクライアント管理の会話状態

実運用では:

  • アプリケーション側で会話全体を手動で保持する場合は history を使います
  • 既存の履歴を別途保存しており、この実行で新規生成された item のみ欲しい場合は output を使います
  • agent との関連付け、tool 出力、handoff 境界、承認 item が必要な場合は newItems を使います
  • conversationId または previousResponseId を使う場合、通常は historyrun() に戻しません。代わりに新しいユーザー入力のみを渡し、サーバー管理 ID を再利用します。比較の全体像は エージェントの実行 を参照してください

history は、チャットライクなユースケースで完全な履歴を維持するための便利な方法です:

History loop
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?'));
}

newItems は、実行中に何が起きたかを最もリッチに示します。一般的な item type は次のとおりです:

どのエージェントが item を生成したか、またそれが tool、tool-search、handoff、承認境界かを知る必要がある場合は、output より newItems を選んでください。toolSearchTool() を使う場合、通常の tool 呼び出しの前にどの deferred tools や namespace が読み込まれたかを確認する最も簡単な方法が、これらの tool-search item です。

lastAgent プロパティには最後に実行されたエージェントが入ります。これは、ハンドオフ後の次のユーザーターンで再利用するエージェントとして最適なことが多いです。activeAgent は同じ値の alias です。

ストリーミングモードでは、実行進行中に現在アクティブなエージェントを currentAgent で確認できます。

tool が承認を必要とする場合、実行は一時停止し、interruptions には保留中の RunToolApprovalItem が入ります。これには、直接の tool、handoff 後に到達した tool、ネストされた agent.asTool() 実行による承認が含まれる場合があります。

result.state.approve(...) / result.state.reject(...) で承認を処理し、同じ staterun() に戻して再開します。すべての interruption を一度に解決する必要はありません。一部の item だけ処理して再実行した場合、解決済みの呼び出しは継続し、未解決のものは保留のままで再度一時停止します。

state プロパティは、結果の背後にある serialize 可能な snapshot です。人間の介入(HITL)、retry フロー、または後で一時停止した実行を再開する必要があるケースで使用します。

lastResponseId は、OpenAI Responses API 連鎖を使う際に、次ターンで previousResponseId として渡す値です。

すでに historysessionconversationId で会話を継続している場合、通常 lastResponseId は不要です。マルチステップ実行のすべての元の model 応答が必要な場合は、代わりに rawResponses を確認してください。

agentToolInvocation は、ネストされた Agent.asTool() の結果向けで、特に customOutputExtractor 内で現在の tool invocation の metadata が必要な場合に使います。これは「実行全体が完了したこと」を示す一般的な summary フィールドではありません。

このネストされたコンテキストでは、agentToolInvocation は次を公開します:

  • toolName
  • toolCallId
  • toolArguments

ネストされた agent-tool 実行に渡された構造化入力も必要な場合は、result.runContext.toolInput と組み合わせてください。

通常のトップレベル run() 結果では、これは通常 undefined です。この metadata は runtime のみで、RunState には serialize されません。周辺パターンは Agents as tools を参照してください。

StreamedRunResult は上記と同じ結果サーフェスを継承しますが、ストリーミング固有の制御が追加されます:

  • assistant テキストのみの toTextStream()
  • 完全なイベントストリーム用の toStream() または for await ... of stream
  • 実行とすべての後処理 callback の完了を待つ completed
  • ストリーミング終端状態を確認する errorcancelled
  • 実行途中のアクティブエージェントを追跡する currentAgent

ストリーミング実行の確定した最終状態が必要な場合は、finalOutputhistoryinterruptions、その他の要約プロパティを読む前に completed を待ってください。イベント単位の処理は ストリーミング ガイド を参照してください。

runContext プロパティは、結果上の run context のサポートされた公開ビューです。result.runContext.context はアプリコンテキストで、同じオブジェクトには承認、使用量、ネストされた toolInput など SDK 管理の runtime metadata も含まれます。完全な形状は コンテキスト管理 を参照してください。

rawResponses には、実行中に収集された元の model 応答が含まれます。マルチステップ実行では、たとえば handoff や反復的な tool/model サイクルをまたいで複数の応答が生成されることがあります。

inputGuardrailResultsoutputGuardrailResults プロパティには、エージェントレベルのガードレール結果が含まれます。tool のガードレール結果は、toolInputGuardrailResultstoolOutputGuardrailResults で別途公開されます。

ガードレールの判定をログ化したい場合、ガードレール関数が返した追加 metadata を確認したい場合、または実行がブロックされた理由をデバッグしたい場合に、これらの配列を使います。

token 使用量は result.state.usage に集約され、実行のリクエスト数と token 合計を追跡します。同じ usage オブジェクトは result.runContext.usage からも利用できます。ストリーミング実行では、このデータは応答到着に応じて更新されます。

RunState から使用量を読む
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,
});
}
}