コンテンツにスキップ

音声エージェントの構築

デフォルトの 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 agent
session.sendAudio(newlyRecordedAudio);

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 Agent では、ハンドオフの動作が少し異なります。ハンドオフが行われると、進行中のセッションは新しいエージェント設定で更新されます。このため、エージェントは自動的に現在の会話履歴へアクセスでき、入力フィルターは適用されません。

また、voicemodel はハンドオフの一環として変更できません。接続できるのは他の Realtime Agent のみです。たとえば推論用モデル o4-mini など別モデルを使う必要がある場合は、ツールによる委任 をご利用ください。

通常のエージェントと同じく、Realtime Agent でもツールを呼び出してアクションを実行できます。ツールは通常のエージェントと同じ 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 Agent で使用できるのは関数ツールのみで、これらのツールは Realtime Session と同じ場所で実行されます。そのため、ブラウザで Realtime Session を実行している場合、ツールもブラウザで実行されます。よりセンシティブな処理が必要な場合は、ツール内からバックエンドサーバーへ HTTP リクエストを送ってください。

ツールが実行されている間、エージェントは新しいユーザーリクエストを処理できません。体験を向上させる方法として、ツール実行前にエージェントにアナウンスさせたり、処理時間を稼ぐために特定のフレーズを話させたりできます。

エージェントが特定のツールを呼び出した際の引数に加え、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
},
});

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);
});

ガードレールは、エージェントが発話した内容がルールに違反していないか監視し、違反時に即座に応答を打ち切る仕組みです。これらのチェックはエージェントの応答の文字起こしに基づいて行われるため、モデルのテキスト出力が有効になっている必要があります(デフォルトで有効)。

提供したガードレールは、モデルの応答が返されると同時に非同期で実行され、たとえば「特定の禁止ワードを含む」などの分類トリガーに基づいて応答を打ち切れます。

ガードレールが作動すると、セッションは 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
},
});

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',
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 を使用している場合は、再生キューにある音声の停止を自分で処理する必要があります。

エージェントへテキスト入力を送信したい場合は、RealtimeSessionsendMessage メソッドを使用します。

これは、ユーザーがエージェントと音声・テキストの両モダリティでやり取りできるようにしたり、追加のコンテキストを提供したりする場合に便利です。

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

RealtimeSessionhistory プロパティで会話履歴を自動的に管理します。

これを利用して履歴をユーザーに表示したり、追加の処理を行ったりできます。履歴は会話中に絶えず変化するため、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 event
session.on('history_updated', (history) => {
// returns the full history of the session
console.log(history);
});
// Option 1: explicit setting
session.updateHistory([
/* specific history */
]);
// Option 2: override based on current state like removing all agent messages
session.updateHistory((currentHistory) => {
return currentHistory.filter(
(item) => !(item.type === 'message' && item.role === 'assistant'),
);
});
  1. 現時点では、実行済みの関数ツール呼び出しを後から更新・変更できません
  2. 履歴でテキストを表示するには、文字起こしおよびテキストモダリティを有効にする必要があります
  3. 割り込みで切り捨てられた応答には文字起こしがありません

ツールによる委任

会話履歴とツール呼び出しを組み合わせることで、より複雑な処理を別のバックエンドエージェントに委任し、その結果をユーザーへ返すことができます。

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 server
import '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);
}