音声エージェントの構築
デフォルトの OpenAIRealtimeWebRTC のようないくつかのトランスポート層は、音声の入力と出力を自動的に処理します。OpenAIRealtimeWebSocket のようなその他のトランスポートでは、セッションの音声を自分で処理する必要があります:
import { RealtimeAgent, RealtimeSession, TransportLayerAudio,} from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'My agent' });const session = new RealtimeSession(agent);const newlyRecordedAudio = new ArrayBuffer(0);
session.on('audio', (event: TransportLayerAudio) => { // play your audio});
// send new audio to the agentsession.sendAudio(newlyRecordedAudio);セッション設定
Section titled “セッション設定”RealtimeSession のコンストラクターに追加オプションを渡すか、connect(...) を呼び出すときに渡すことで、セッションを設定できます。
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
const session = new RealtimeSession(agent, { model: 'gpt-realtime', config: { inputAudioFormat: 'pcm16', outputAudioFormat: 'pcm16', inputAudioTranscription: { model: 'gpt-4o-mini-transcribe', }, },});これらのトランスポート層では、session に一致する任意のパラメーターを渡せます。
RealtimeSessionConfig にまだ存在しない新しいパラメーターについては、providerData を使用できます。providerData に渡したものは session オブジェクトの一部としてそのまま渡されます。
構築時に設定できる追加の RealtimeSession オプション:
| Option | Type | Purpose |
|---|---|---|
context | TContext | セッションコンテキストにマージされる追加のローカルコンテキスト |
historyStoreAudio | boolean | ローカルの履歴スナップショットに音声データを保存するかどうか(デフォルトは無効) |
outputGuardrails | RealtimeOutputGuardrail[] | セッションの出力ガードレール(ガードレール を参照) |
outputGuardrailSettings | RealtimeOutputGuardrailSettings | ガードレールチェックの頻度と動作 |
tracingDisabled | boolean | セッションのトレーシングを無効化 |
groupId | string | セッションやバックエンド実行をまたいでトレースをグループ化 |
traceMetadata | Record<string, any> | セッショントレースに付与するカスタムメタデータ |
workflowName | string | トレースワークフローのわかりやすい名前 |
automaticallyTriggerResponseForMcpToolCalls | boolean | MCP ツール呼び出し完了時にモデル応答を自動トリガー(デフォルト: true) |
toolErrorFormatter | ToolErrorFormatter | モデルに返すツール承認拒否メッセージのカスタマイズ |
通常のエージェントと同様に、ハンドオフを使ってエージェントを複数のエージェントに分割し、それらをオーケストレーションしてエージェントのパフォーマンスを向上させ、問題の範囲を適切に絞り込めます。
import { RealtimeAgent } from '@openai/agents/realtime';
const mathTutorAgent = new RealtimeAgent({ name: 'Math Tutor', handoffDescription: 'Specialist agent for math questions', instructions: 'You provide help with math problems. Explain your reasoning at each step and include examples',});
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.', handoffs: [mathTutorAgent],});通常のエージェントとは異なり、リアルタイムエージェントではハンドオフの挙動が少し異なります。ハンドオフが実行されると、進行中のセッションは新しいエージェント設定で更新されます。このため、エージェントは自動的に進行中の会話履歴にアクセスでき、入力フィルターは現在適用されません。
また、ハンドオフの一部として voice や model を変更することはできません。接続できるのは他のリアルタイムエージェントのみです。別のモデル、例えば gpt-5-mini のような推論モデルを使用する必要がある場合は、ツールによる委譲 を使用できます。
通常のエージェントと同様に、リアルタイムエージェントはツールを呼び出して処理を実行できます。Realtime は 関数ツール(ローカルで実行)と リモート MCP サーバーツール(Realtime API によってリモート実行)をサポートします。通常のエージェントで使用するのと同じ tool() ヘルパーで関数ツールを定義できます。
import { tool, RealtimeAgent } from '@openai/agents/realtime';import { z } from 'zod';
const getWeather = tool({ name: 'get_weather', description: 'Return the weather for a city.', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});
const weatherAgent = new RealtimeAgent({ name: 'Weather assistant', instructions: 'Answer weather questions.', tools: [getWeather],});関数ツールは RealtimeSession と同じ環境で実行されます。つまり、セッションをブラウザで実行している場合はツールもブラウザで実行されます。機密性の高い処理が必要な場合は、ツール内でバックエンドへの HTTP リクエストを実行してください。
リモート MCP サーバーツールは hostedMcpTool で設定でき、リモートで実行されます。MCP ツールの可用性が変化すると、セッションは mcp_tools_changed を発行します。MCP ツール呼び出し完了後にセッションがモデル応答を自動トリガーしないようにするには、automaticallyTriggerResponseForMcpToolCalls: false を設定します。
ツールの実行中、エージェントはユーザーからの新しいリクエストを処理できません。体験を向上させる 1 つの方法は、ツールの実行直前にそれをアナウンスする、または特定のフレーズを話してツール実行のための時間を稼ぐようエージェントに指示することです。
会話履歴へのアクセス
Section titled “会話履歴へのアクセス”エージェントが特定のツールを呼び出した引数に加えて、リアルタイムセッションが追跡している現在の会話履歴のスナップショットにもアクセスできます。これは、現在の会話状態に基づいてより複雑なアクションを実行する必要がある場合や、委譲のためのツール を使用する予定がある場合に役立ちます。
import { tool, RealtimeContextData, RealtimeItem,} from '@openai/agents/realtime';import { z } from 'zod';
const parameters = z.object({ request: z.string(),});
const refundTool = tool<typeof parameters, RealtimeContextData>({ name: 'Refund Expert', description: 'Evaluate a refund', parameters, execute: async ({ request }, details) => { // The history might not be available const history: RealtimeItem[] = details?.context?.history ?? []; // making your call to process the refund request },});ツール実行前の承認
Section titled “ツール実行前の承認”needsApproval: true でツールを定義すると、エージェントはツールを実行する前に tool_approval_requested イベントを発行します。
このイベントを監視して、ツール呼び出しを承認または拒否するための UI をユーザーに表示できます。
import { session } from './agent';
session.on('tool_approval_requested', (_context, _agent, request) => { // show a UI to the user to approve or reject the tool call // you can use the `session.approve(...)` or `session.reject(...)` methods to approve or reject the tool call
session.approve(request.approvalItem); // or session.reject(request.rawItem);});ガードレール
Section titled “ガードレール”ガードレールは、エージェントが話した内容が一連のルールに違反していないかを監視し、即座に応答を遮断する手段を提供します。これらのガードレールチェックはエージェントの応答の書き起こしに基づいて実行されるため、モデルのテキスト出力が有効である必要があります(デフォルトで有効)。
提供したガードレールは、モデル応答の返却と並行して非同期に実行され、例えば「特定の禁止ワードに言及した」といった、事前定義の分類トリガーに基づいて応答を打ち切れます。
ガードレールが作動すると、セッションは guardrail_tripped イベントを発行します。イベントには、ガードレールをトリガーした itemId を含む details オブジェクトも含まれます。
import { RealtimeOutputGuardrail, RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
const guardrails: RealtimeOutputGuardrail[] = [ { name: 'No mention of Dom', async execute({ agentOutput }) { const domInOutput = agentOutput.includes('Dom'); return { tripwireTriggered: domInOutput, outputInfo: { domInOutput }, }; }, },];
const guardedSession = new RealtimeSession(agent, { outputGuardrails: guardrails,});デフォルトでは、ガードレールは 100 文字ごと、または応答テキスト生成の終わりに実行されます。音声での読み上げは通常時間がかかるため、ほとんどの場合、ユーザーが聞く前にガードレールが違反を検出できます。
この動作を変更したい場合は、outputGuardrailSettings オブジェクトをセッションに渡してください。
import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Greeter', instructions: 'Greet the user with cheer and answer questions.',});
const guardedSession = new RealtimeSession(agent, { outputGuardrails: [ /*...*/ ], outputGuardrailSettings: { debounceTextLength: 500, // run guardrail every 500 characters or set it to -1 to run it only at the end },});ターン検出 / 音声活動検出
Section titled “ターン検出 / 音声活動検出”リアルタイムセッションは、ユーザーが話しているタイミングを自動的に検出し、内蔵の Realtime API の音声活動検出モード を使用して新しいターンをトリガーします。
turnDetection オブジェクトをセッションに渡すことで、音声活動検出モードを変更できます。
import { RealtimeSession } from '@openai/agents/realtime';import { agent } from './agent';
const session = new RealtimeSession(agent, { model: 'gpt-realtime', config: { turnDetection: { type: 'semantic_vad', eagerness: 'medium', createResponse: true, interruptResponse: true, }, },});ターン検出の設定を調整すると、望ましくない割り込みや無音への対処を校正できます。さまざまな設定の詳細は Realtime API のドキュメント を参照してください
内蔵の音声活動検出を使用している場合、エージェントの発話に被せて話すと、自動的にエージェントがそれを検出して、話された内容に基づいてコンテキストを更新します。また、audio_interrupted イベントも発行します。これはすべての音声再生を即時停止するために利用できます(WebSocket 接続の場合のみ適用)。
import { session } from './agent';
session.on('audio_interrupted', () => { // handle local playback interruption});UI に「停止」ボタンを用意するなど、手動で割り込みを行いたい場合は、interrupt() を手動で呼び出せます:
import { session } from './agent';
session.interrupt();// this will still trigger the `audio_interrupted` event for you// to cut off the audio playback when using WebSocketsいずれの場合も、リアルタイムセッションはエージェントの生成を中断し、ユーザーに対して何が話されたかの認識を切り詰め、履歴を更新します。
エージェントに接続するのに WebRTC を使用している場合は、音声出力もクリアされます。WebSocket を使用している場合は、再生キューにある音声の再生停止を自分で処理する必要があります。
テキスト入力
Section titled “テキスト入力”エージェントにテキスト入力を送信したい場合は、RealtimeSession の sendMessage メソッドを使用できます。
ユーザーがエージェントと両方のモダリティでやり取りできるようにしたい場合や、会話に追加のコンテキストを提供したい場合に便利です。
import { RealtimeSession, RealtimeAgent } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Assistant',});
const session = new RealtimeSession(agent, { model: 'gpt-realtime',});
session.sendMessage('Hello, how are you?');会話履歴の管理
Section titled “会話履歴の管理”RealtimeSession は history プロパティで会話履歴を自動的に管理します:
この履歴を使用して、顧客に履歴を表示したり、追加のアクションを実行したりできます。会話の進行中はこの履歴が継続的に変化するため、history_updated イベントを監視できます。
履歴を変更したい場合、例えばメッセージを完全に削除したり、その書き起こしを更新したりするには、updateHistory メソッドを使用できます。
import { RealtimeSession, RealtimeAgent } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Assistant',});
const session = new RealtimeSession(agent, { model: 'gpt-realtime',});
await session.connect({ apiKey: '<client-api-key>' });
// listening to the history_updated eventsession.on('history_updated', (history) => { // returns the full history of the session console.log(history);});
// Option 1: explicit settingsession.updateHistory([ /* specific history */]);
// Option 2: override based on current state like removing all agent messagessession.updateHistory((currentHistory) => { return currentHistory.filter( (item) => !(item.type === 'message' && item.role === 'assistant'), );});- 現時点では、関数ツール呼び出しを後から更新/変更することはできません
- 履歴内のテキスト出力には、書き起こしとテキストモダリティを有効にする必要があります
- 割り込みにより切り詰められた応答には書き起こしがありません
ツールによる委譲
Section titled “ツールによる委譲”
会話履歴とツール呼び出しを組み合わせることで、より複雑な処理を実行するために別のバックエンドエージェントへ会話を委譲し、その結果をユーザーに返すことができます。
import { RealtimeAgent, RealtimeContextData, tool,} from '@openai/agents/realtime';import { handleRefundRequest } from './serverAgent';import z from 'zod';
const refundSupervisorParameters = z.object({ request: z.string(),});
const refundSupervisor = tool< typeof refundSupervisorParameters, RealtimeContextData>({ name: 'escalateToRefundSupervisor', description: 'Escalate a refund request to the refund supervisor', parameters: refundSupervisorParameters, execute: async ({ request }, details) => { // This will execute on the server return handleRefundRequest(request, details?.context?.history ?? []); },});
const agent = new RealtimeAgent({ name: 'Customer Support', instructions: 'You are a customer support agent. If you receive any requests for refunds, you need to delegate to your supervisor.', tools: [refundSupervisor],});以下のコードはサーバー上で実行されます。この例では Next.js の server actions を使用します。
// This runs on the serverimport 'server-only';
import { Agent, run } from '@openai/agents';import type { RealtimeItem } from '@openai/agents/realtime';import z from 'zod';
const agent = new Agent({ name: 'Refund Expert', instructions: 'You are a refund expert. You are given a request to process a refund and you need to determine if the request is valid.', model: 'gpt-5-mini', outputType: z.object({ reasong: z.string(), refundApproved: z.boolean(), }),});
export async function handleRefundRequest( request: string, history: RealtimeItem[],) { const input = `The user has requested a refund.
The request is: ${request}
Current conversation history:${JSON.stringify(history, null, 2)}`.trim();
const result = await run(agent, input);
return JSON.stringify(result.finalOutput, null, 2);}