コンテンツにスキップ

音声エージェントの構築

デフォルトの 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-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],
});

通常のエージェントと異なり、リアルタイムエージェントではハンドオフの挙動がやや異なります。ハンドオフが実行されると、進行中のセッションは新しいエージェント設定で更新されます。このため、エージェントは進行中の会話履歴に自動的にアクセスでき、入力フィルターは現在適用されません。

また、これによりハンドオフの一環として voicemodel を変更することはできません。接続できるのは他の リアルタイムエージェント のみです。別のモデル、例えば o4-mini のような推論モデルを使う必要がある場合は、ツールによる委譲 を使用できます。

通常のエージェントと同様に、リアルタイムエージェントはツールを呼び出してアクションを実行できます。通常のエージェントで使用するのと同じ 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 Session と同じ場所で実行されます。つまり、Realtime Session をブラウザで実行している場合、ツールもブラウザで実行されます。より機微なアクションを実行する必要がある場合は、ツール内でバックエンド サーバーへの HTTP リクエストを行ってください。

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

エージェントが特定のツールを呼び出す際の引数に加えて、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-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 を使用している場合は、再生キューに入っている音声の再生を停止する処理を自分で行う必要があります。

エージェントにテキスト入力を送るには、RealtimeSessionsendMessage メソッドを使用します。

ユーザーがエージェントと複数のモダリティでやり取りできるようにしたい場合や、会話に追加のコンテキストを提供したい場合に便利です。

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

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

これを使って顧客向けに履歴をレンダリングしたり、追加の処理を行ったりできます。会話の進行に伴って履歴は継続的に変化するため、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 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);
}