音声エージェントの構築
オーディオ処理
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-4o-realtime-preview-2025-06-03', 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 Agent のみです。o4-mini
のような推論モデルを使用したい場合は、ツールによる委任 をご利用ください。
通常のエージェントと同様に、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 リクエストを送信してください。
ツール実行中はエージェントが新しい user からのリクエストを処理できません。エージェントに「これからツールを実行します」とアナウンスさせたり、時間稼ぎのフレーズを言わせたりすると体験を向上できます。
会話履歴へのアクセス
Section titled “会話履歴へのアクセス”エージェントがツールを呼び出す際に渡された引数に加え、Realtime Session が管理している現在の会話履歴のスナップショットにもアクセスできます。会話の状態に基づいてより複雑なアクションを行う場合や、ツールによる委任 を計画している場合に便利です。
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
イベントを発火します。
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-4o-realtime-preview-2025-06-03', config: { turnDetection: { type: 'semantic_vad', eagerness: 'medium', create_response: true, interrupt_response: 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-4o-realtime-preview-2025-06-03',});
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-4o-realtime-preview-2025-06-03',});
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 “ツールによる委任”会話履歴とツール呼び出しを組み合わせることで、より複雑な処理を別のバックエンドエージェントに委任し、その結果を user に返すことができます。
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: 'o4-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);}