音声エージェントの構築
音声の取り扱い
Section titled “音声の取り扱い”デフォルトの 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 オブジェクトの一部としてそのまま渡されます。
通常の エージェント と同様に、ハンドオフを使って エージェント を複数に分割し、それらをオーケストレーションすることで、エージェント のパフォーマンスを向上させ、問題の範囲をより適切に絞り込むことができます。
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],});通常の エージェント と異なり、Realtime Agents ではハンドオフの動作が少し異なります。ハンドオフが実行されると、進行中のセッションは新しい エージェント 設定で更新されます。このため、エージェント は進行中の会話履歴に自動的にアクセスでき、入力フィルターは現在適用されません。
加えて、ハンドオフの一部として voice や model を変更することはできません。また、接続できるのは他の Realtime Agents のみです。別のモデル、たとえば gpt-5-mini のような推論モデルを使う必要がある場合は、delegation through tools を使用できます。
通常の エージェント と同様に、Realtime Agents はアクションを実行するためにツールを呼び出せます。通常の エージェント で使うのと同じ 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],});Realtime Agents で使用できるのは 関数ツール のみで、これらのツールは Realtime Session と同じ場所で実行されます。つまり、ブラウザで Realtime Session を実行している場合、ツールもブラウザで実行されます。より機微な操作を行う必要がある場合は、ツール内でバックエンド サーバー への HTTP リクエストを実行できます。
ツールの実行中、エージェント は ユーザー からの新しいリクエストを処理できません。体験を向上させる方法の 1 つは、エージェント に対してツールを実行しようとしていることを告知させたり、ツール実行のための時間を稼ぐ特定のフレーズを話させたりするように指示することです。
会話履歴へのアクセス
Section titled “会話履歴へのアクセス”エージェント が特定のツールを呼び出す際に渡した引数に加えて、Realtime Session によって追跡されている現在の会話履歴のスナップショットにもアクセスできます。これは、会話の現在の状態に基づいてより複雑なアクションを実行する必要がある場合や、tools for delegation を使用する予定がある場合に役立ちます。
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 Session は、ユーザーが話しているタイミングを自動的に検出し、組み込みの 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いずれの場合も、Realtime Session はエージェントの生成を中断し、ユーザーに話した内容に関する認識を切り詰め、履歴を更新します。
エージェントへの接続に 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'), );});- 事後に 関数ツール の呼び出しを更新・変更することは現在できません
- 履歴内のテキスト出力には、書き起こしとテキストモダリティが有効である必要があります
- 割り込みにより切り詰められた応答には書き起こしがありません
Delegation through tools
Section titled “Delegation through tools”
会話履歴とツール呼び出しを組み合わせることで、より複雑なアクションを実行するために会話を別のバックエンド エージェント に委譲し、その結果を ユーザー に返すことができます。
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);}