@openai/agents-realtime
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. This package contains the logic for building realtime voice agents on the server or in the browser.
861 lines • 37 kB
JavaScript
import { RuntimeEventEmitter, UserError, Usage } from '@openai/agents-core';
import { normalizeHostedMcpRequireApproval } from '@openai/agents-core/utils';
import { logModelActionError, logToolActionError, } from '@openai/agents-core/utils/internal';
import { toNewSessionConfig, } from "./clientMessages.mjs";
import { realtimeMcpCallApprovalRequestItem, realtimeMcpCallItem, realtimeMessageItemSchema, realtimeToolCallItem, } from "./items.mjs";
import logger from "./logger.mjs";
import { parseRealtimeEvent, responseDoneEventSchema, } from "./openaiRealtimeEvents.mjs";
import { arrayBufferToBase64, diffRealtimeHistory } from "./utils.mjs";
import { EventEmitterDelegate } from '@openai/agents-core/utils';
/**
* The default model that is used during the connection if no model is provided.
*/
export const DEFAULT_OPENAI_REALTIME_MODEL = 'gpt-realtime-2.1';
/**
* The default session config that gets send over during session connection unless overridden
* by the user.
*/
export const DEFAULT_OPENAI_REALTIME_SESSION_CONFIG = {
outputModalities: ['audio'],
audio: {
input: {
format: { type: 'audio/pcm', rate: 24000 },
transcription: { model: 'gpt-4o-mini-transcribe' },
turnDetection: { type: 'semantic_vad' },
noiseReduction: null,
},
output: {
format: { type: 'audio/pcm', rate: 24000 },
speed: 1,
},
},
};
function normalizeRealtimeMessageContent(role, content) {
if (!Array.isArray(content)) {
return content;
}
return content.map((part) => {
if (part &&
typeof part === 'object' &&
'type' in part &&
role === 'assistant' &&
part.type === 'audio') {
return {
...part,
type: 'output_audio',
};
}
if (role === 'user' &&
part &&
typeof part === 'object' &&
part.type === 'input_audio') {
return { ...part, transcript: part.transcript ?? null };
}
return part;
});
}
function cloneRealtimeEvent(event) {
if (typeof globalThis.structuredClone === 'function') {
return globalThis.structuredClone(event);
}
return JSON.parse(JSON.stringify(event));
}
/**
* Sentinel accepted by `conversation.item.create` that places the item at the
* beginning of the conversation. Omitting `previous_item_id` appends instead.
*/
const CONVERSATION_ROOT = 'root';
export class OpenAIRealtimeBase extends EventEmitterDelegate {
#model;
#apiKey;
#tracingConfig = null;
#rawSessionConfig = null;
// Requests stay in wire order so placement can project both removals and
// recreations while the session still exposes server-confirmed history.
#pendingHistoryRequests = new Map();
#historyRequestSeq = 0;
eventEmitter = new RuntimeEventEmitter();
constructor(options = {}) {
super();
this.#model = options.model ?? DEFAULT_OPENAI_REALTIME_MODEL;
this.#apiKey = options.apiKey;
}
/**
* The current model that is being used by the transport layer.
*/
get currentModel() {
return this.#model;
}
/**
* The current model that is being used by the transport layer.
* **Note**: The model cannot be changed mid conversation.
*/
set currentModel(model) {
this.#model = model;
}
/**
* Hook for subclasses to clean up transport-specific state when audio
* playback finishes. Defaults to a no-op.
*/
_afterAudioDoneEvent() {
// Intentionally empty.
}
get _rawSessionConfig() {
return this.#rawSessionConfig ?? null;
}
async _getApiKey(options) {
const apiKey = options.apiKey ?? this.#apiKey;
if (typeof apiKey === 'function') {
return await apiKey();
}
return apiKey;
}
_onMessage(event) {
const result = parseRealtimeEvent(event);
const { data: parsed, raw } = result;
if (raw === null)
return;
this.emit('*', cloneRealtimeEvent(raw));
if (parsed === null)
return;
if (parsed.type === 'conversation.item.added' && parsed.item.id) {
this.#settleHistoryRequest(parsed.item.id, 'create');
}
if (parsed.type === 'error') {
// The Realtime API reports the offending client event under `error.event_id`.
const causedBy = parsed.error
?.event_id;
if (typeof causedBy === 'string') {
this.#pendingHistoryRequests.delete(causedBy);
}
this.emit('error', { type: 'error', error: parsed });
}
else if (parsed.type.includes('.')) {
// Wire notifications use dotted names. Undotted names belong to SDK
// action/lifecycle channels; unknown ones remain observable through '*'.
this.emit(parsed.type, parsed);
}
if (parsed.type === 'response.created') {
this.emit('turn_started', {
type: 'response_started',
providerData: {
...parsed,
},
});
return;
}
if (parsed.type === 'session.updated') {
this.#rawSessionConfig = parsed.session;
}
if (parsed.type === 'response.done') {
const response = responseDoneEventSchema.safeParse(parsed);
if (!response.success) {
logModelActionError(logger, 'Error parsing response done event', response.error);
return;
}
const inputTokens = response.data.response.usage?.input_tokens ?? 0;
const outputTokens = response.data.response.usage?.output_tokens ?? 0;
const totalTokens = inputTokens + outputTokens;
const usage = new Usage({
inputTokens,
inputTokensDetails: response.data.response.usage?.input_token_details ?? {},
outputTokens,
outputTokensDetails: response.data.response.usage?.output_token_details ?? {},
totalTokens,
});
this.emit('usage_update', usage);
this.emit('turn_done', {
type: 'response_done',
response: {
id: response.data.response.id ?? '',
output: response.data.response.output ?? [],
usage: {
inputTokens,
inputTokensDetails: response.data.response.usage?.input_token_details ?? {},
outputTokens,
outputTokensDetails: response.data.response.usage?.output_token_details ?? {},
totalTokens,
},
},
});
return;
}
if (parsed.type === 'response.output_audio.done') {
this.emit('audio_done');
this._afterAudioDoneEvent();
return;
}
if (parsed.type === 'conversation.item.deleted') {
this.#settleHistoryRequest(parsed.item_id, 'delete');
this.emit('item_deleted', {
itemId: parsed.item_id,
});
return;
}
if (parsed.type === 'conversation.item.input_audio_transcription.completed' ||
parsed.type === 'conversation.item.truncated') {
// right now rather than keeping track of partials and rebuilding the item we
// will retrieve it instead which triggers the `conversation.item.retrieved` event below
this.sendEvent({
type: 'conversation.item.retrieve',
item_id: parsed.item_id,
});
return;
}
if (parsed.type === 'conversation.item.input_audio_transcription.delta' ||
parsed.type === 'response.output_text.delta' ||
parsed.type === 'response.output_audio_transcript.delta' ||
parsed.type === 'response.function_call_arguments.delta') {
if (parsed.type === 'response.output_audio_transcript.delta') {
this.emit('audio_transcript_delta', {
type: 'transcript_delta',
delta: parsed.delta,
itemId: parsed.item_id,
responseId: parsed.response_id,
});
}
else if (parsed.type === 'response.output_text.delta') {
this.emit('output_text_delta', {
type: 'output_text_delta',
delta: parsed.delta,
itemId: parsed.item_id,
responseId: parsed.response_id,
});
}
// no support for partial transcripts yet.
return;
}
if (parsed.type === 'conversation.item.added' ||
parsed.type === 'conversation.item.done' ||
parsed.type === 'conversation.item.retrieved') {
// Handle MCP list tools items (only act when done to ensure tools are present)
if (parsed.item.type === 'mcp_list_tools' &&
parsed.type === 'conversation.item.done') {
const serverLabel = parsed.item.server_label ?? '';
const tools = parsed.item.tools ?? [];
if (typeof serverLabel !== 'string' ||
!Array.isArray(tools) ||
tools.some((tool) => !tool || typeof tool.name !== 'string')) {
return;
}
try {
this.emit('mcp_tools_listed', {
serverLabel,
tools,
});
}
catch (err) {
logToolActionError(logger, 'Error emitting mcp_tools_listed', err, parsed.item);
}
// We do not add this item to history; it's a transport-level side-channel.
return;
}
if (parsed.item.type === 'message') {
// `null` here is the server saying the item has nothing before it, which
// is what decides where local history puts it. An event that does not
// carry the field says nothing about placement, so it stays undefined
// rather than claiming the front.
const previousItemId = parsed.type === 'conversation.item.added' ||
parsed.type === 'conversation.item.done'
? parsed.previous_item_id
: undefined;
const item = realtimeMessageItemSchema.safeParse({
itemId: parsed.item.id,
previousItemId,
type: parsed.item.type,
role: parsed.item.role,
content: normalizeRealtimeMessageContent(parsed.item.role, parsed.item.content),
status: parsed.item.status ??
(parsed.type === 'conversation.item.added'
? 'in_progress'
: 'completed'),
});
if (item.success) {
this.emit('item_update', item.data);
}
return;
}
if (parsed.item.type === 'mcp_approval_request' &&
parsed.type === 'conversation.item.done') {
const item = parsed.item;
if (item.arguments !== undefined &&
typeof item.arguments !== 'string') {
return;
}
const mcpApprovalRequest = realtimeMcpCallApprovalRequestItem.safeParse({
itemId: item.id,
type: item.type,
serverLabel: item.server_label,
name: item.name,
arguments: JSON.parse(item.arguments || '{}'),
approved: item.approved,
});
if (mcpApprovalRequest.success) {
this.emit('item_update', mcpApprovalRequest.data);
this.emit('mcp_approval_request', mcpApprovalRequest.data);
}
return;
}
if (parsed.item.type === 'mcp_tool_call' ||
parsed.item.type === 'mcp_call') {
const status = parsed.type === 'conversation.item.done'
? 'completed'
: 'in_progress';
const mcpCall = realtimeMcpCallItem.safeParse({
itemId: parsed.item.id,
type: parsed.item.type,
status,
arguments: parsed.item.arguments,
name: parsed.item.name,
output: parsed.item.output ?? null,
});
if (!mcpCall.success) {
return;
}
this.emit('item_update', mcpCall.data);
if (parsed.type === 'conversation.item.done') {
this.emit('mcp_tool_call_completed', mcpCall.data);
}
return;
}
}
if (parsed.type === 'response.mcp_call.in_progress') {
const item = parsed;
this.sendEvent({
type: 'conversation.item.retrieve',
item_id: item.item_id,
});
return;
}
if (parsed.type === 'mcp_list_tools.in_progress') {
const item = parsed;
if (item.item_id) {
this.sendEvent({
type: 'conversation.item.retrieve',
item_id: item.item_id,
});
}
return;
}
if (parsed.type === 'response.output_item.done' ||
parsed.type === 'response.output_item.added') {
const item = parsed.item;
if (item.type === 'function_call' && item.status === 'completed') {
const toolCall = realtimeToolCallItem.safeParse({
itemId: item.id,
type: item.type,
status: 'in_progress', // we set it to in_progress for the UI as it will only be completed with the output
arguments: item.arguments,
name: item.name,
output: null,
});
if (!toolCall.success ||
(item.call_id !== undefined && typeof item.call_id !== 'string')) {
return;
}
this.emit('item_update', toolCall.data);
this.emit('function_call', {
id: item.id,
type: 'function_call',
callId: item.call_id ?? '',
arguments: item.arguments ?? '',
name: item.name ?? '',
responseId: parsed.response_id,
});
return;
}
if (item.type === 'mcp_tool_call' || item.type === 'mcp_call') {
const mcpCall = realtimeMcpCallItem.safeParse({
itemId: item.id,
type: item.type,
status: parsed.type === 'response.output_item.done'
? 'completed'
: 'in_progress', // we set it to in_progress for the UI as it will only be completed with the output
arguments: item.arguments,
name: item.name,
output: item.output ?? null,
});
if (!mcpCall.success) {
return;
}
this.emit('item_update', mcpCall.data);
return;
}
if (item.type === 'message') {
const realtimeItem = realtimeMessageItemSchema.safeParse({
itemId: item.id,
type: item.type,
role: item.role,
content: normalizeRealtimeMessageContent(item.role, item.content),
status: parsed.type === 'response.output_item.done'
? (item.status ?? 'completed')
: (item.status ?? 'in_progress'),
});
if (realtimeItem.success) {
this.emit('item_update', realtimeItem.data);
}
return;
}
}
}
_onError(error) {
this.emit('error', {
type: 'error',
error,
});
}
_onOpen() {
this.emit('connected');
}
// Successful replies identify the item, so retire its oldest matching request.
// `done` finalizes content and must not settle another create of the same ID.
#settleHistoryRequest(itemId, kind) {
for (const [eventId, request] of this.#pendingHistoryRequests) {
if (request.itemId === itemId && request.kind === kind) {
this.#pendingHistoryRequests.delete(eventId);
return;
}
}
}
#sendHistoryRequest(itemId, kind, event) {
const eventId = `agents_${kind}_${++this.#historyRequestSeq}`;
this.#pendingHistoryRequests.set(eventId, { itemId, kind });
try {
this.sendEvent({ ...event, event_id: eventId });
}
catch (error) {
this.#pendingHistoryRequests.delete(eventId);
throw error;
}
}
_onClose() {
// Unacknowledged requests belong only to the connection that sent them.
this.#pendingHistoryRequests.clear();
this.emit('disconnected');
}
requestResponse(response) {
this.sendEvent({
type: 'response.create',
...(response ? { response } : {}),
});
}
/**
* Send a message to the Realtime API. This will create a new item in the conversation and
* trigger a response.
*
* @param message - The message to send.
* @param otherEventData - Additional event data to send.
*/
sendMessage(message, otherEventData, { triggerResponse = true } = {}) {
const content = typeof message === 'string'
? [
{
type: 'input_text',
text: message,
},
]
: message.content.map((content) => {
if (content.type === 'input_image') {
return {
type: 'input_image',
image_url: content.image,
...(content.providerData ?? {}),
};
}
return content;
});
this.sendEvent({
type: 'conversation.item.create',
item: {
type: 'message',
role: 'user',
content,
},
...otherEventData,
});
if (triggerResponse) {
this.requestResponse();
}
}
addImage(image, { triggerResponse = true } = {}) {
this.sendMessage({
type: 'message',
role: 'user',
content: [{ type: 'input_image', image }],
}, {}, { triggerResponse });
}
_getMergedSessionConfig(config) {
const newConfig = toNewSessionConfig(config);
const noiseReductionOverride = newConfig.audio?.input?.noiseReduction;
const transcriptionOverride = newConfig.audio?.input?.transcription;
const turnDetectionOverride = OpenAIRealtimeBase.buildTurnDetectionConfig(newConfig.audio?.input?.turnDetection);
const sessionData = {
type: 'realtime',
instructions: newConfig.instructions,
model: newConfig.model ?? this.#model,
output_modalities: newConfig.outputModalities ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.outputModalities,
audio: {
input: {
format: newConfig.audio?.input?.format ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.input?.format,
noise_reduction: noiseReductionOverride === undefined
? DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.input
?.noiseReduction
: noiseReductionOverride,
transcription: transcriptionOverride === undefined
? DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.input
?.transcription
: transcriptionOverride,
turn_detection: turnDetectionOverride === undefined
? DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.input
?.turnDetection
: turnDetectionOverride,
},
output: {
format: newConfig.audio?.output?.format ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.output?.format,
voice: newConfig.audio?.output?.voice ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.output?.voice,
speed: newConfig.audio?.output?.speed ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.audio?.output?.speed,
},
},
tool_choice: newConfig.toolChoice ??
DEFAULT_OPENAI_REALTIME_SESSION_CONFIG.toolChoice,
...(typeof newConfig.parallelToolCalls === 'undefined'
? {}
: { parallel_tool_calls: newConfig.parallelToolCalls }),
...(newConfig.reasoning ? { reasoning: newConfig.reasoning } : {}),
// We don't set tracing here to make sure that we don't try to override it on every
// session.update as it might lead to errors
...(newConfig.providerData ?? {}),
};
if (newConfig.prompt) {
sessionData.prompt = {
id: newConfig.prompt.promptId,
version: newConfig.prompt.version,
variables: newConfig.prompt.variables,
};
}
if (newConfig.tools && newConfig.tools.length > 0) {
sessionData.tools = newConfig.tools.map((tool) => {
const pickDefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([, value]) => typeof value !== 'undefined'));
if (tool.type === 'mcp') {
// Realtime API MCP tool shape: session.update properties and MCP tool headers
return pickDefined({
type: 'mcp',
server_label: tool.server_label,
server_url: tool.server_url,
server_description: tool.server_description,
connector_id: tool.connector_id,
authorization: tool.authorization,
headers: tool.headers,
allowed_tools: tool.allowed_tools,
require_approval: typeof tool.require_approval === 'undefined'
? undefined
: normalizeHostedMcpRequireApproval(tool.require_approval),
});
}
// Realtime API function tool shape: keep only documented fields for session.update.
return pickDefined({
type: tool.type,
name: tool.name,
description: tool.description,
parameters: tool.parameters,
});
});
}
return sessionData;
}
/**
* Build the payload object expected by the Realtime API when creating or updating a session.
*
* The helper centralises the conversion from camelCase runtime config to the snake_case payload
* required by the Realtime API so transports that need a one-off payload (for example SIP call
* acceptance) can reuse the same logic without duplicating private state.
*
* @param config - The session config to merge with defaults.
*/
buildSessionPayload(config) {
return this._getMergedSessionConfig(config);
}
static buildTurnDetectionConfig(c) {
if (typeof c === 'undefined') {
return undefined;
}
if (c === null) {
return null;
}
const { type, createResponse, create_response, eagerness, interruptResponse, interrupt_response, prefixPaddingMs, prefix_padding_ms, silenceDurationMs, silence_duration_ms, threshold, idleTimeoutMs, idle_timeout_ms, modelVersion, model_version, ...rest } = c;
const config = {
type,
create_response: createResponse ?? create_response,
eagerness,
interrupt_response: interruptResponse ?? interrupt_response,
prefix_padding_ms: prefixPaddingMs ?? prefix_padding_ms,
silence_duration_ms: silenceDurationMs ?? silence_duration_ms,
idle_timeout_ms: idleTimeoutMs ?? idle_timeout_ms,
model_version: modelVersion ?? model_version,
threshold,
...rest,
};
// Remove undefined values from the config
Object.keys(config).forEach((key) => {
if (config[key] === undefined)
delete config[key];
});
return Object.keys(config).length > 0 ? config : undefined;
}
/**
* Sets the internal tracing config. This is used to track the tracing config that has been set
* during the session.create event.
*/
set _tracingConfig(tracingConfig) {
this.#tracingConfig = tracingConfig;
}
/**
* Sets the tracing config for the session. This will send the tracing config to the Realtime API.
*
* @param tracingConfig - The tracing config to set. We don't support 'auto' here as the SDK will always configure a Workflow Name unless it exists
*/
_updateTracingConfig(tracingConfig) {
if (typeof this.#tracingConfig === 'undefined') {
// treating it as default value
this.#tracingConfig = null;
}
if (tracingConfig === 'auto') {
// turn on tracing in auto mode
this.sendEvent({
type: 'session.update',
session: {
type: 'realtime',
tracing: 'auto',
},
});
return;
}
if (this.#tracingConfig !== null &&
typeof this.#tracingConfig !== 'string' &&
typeof tracingConfig !== 'string') {
// tracing is already set, we can't change it
logger.warn('Tracing config is already set, skipping setting it again. This likely happens when you already set a tracing config on session creation.');
return;
}
if (tracingConfig === null) {
logger.debug('Disabling tracing for this session. It cannot be turned on for this session from this point on.');
this.sendEvent({
type: 'session.update',
session: {
type: 'realtime',
tracing: null,
},
});
return;
}
if (this.#tracingConfig === null ||
typeof this.#tracingConfig === 'string') {
// tracing is currently not set so we can set it to the new value
this.sendEvent({
type: 'session.update',
session: {
type: 'realtime',
tracing: tracingConfig,
},
});
return;
}
if (tracingConfig?.group_id !== this.#tracingConfig?.group_id ||
tracingConfig?.metadata !== this.#tracingConfig?.metadata ||
tracingConfig?.workflow_name !== this.#tracingConfig?.workflow_name) {
logger.warn('Mismatch in tracing config. Ignoring the new tracing config. This likely happens when you already set a tracing config on session creation. Current tracing config: %s, new tracing config: %s', JSON.stringify(this.#tracingConfig), JSON.stringify(tracingConfig));
return;
}
this.sendEvent({
type: 'session.update',
session: {
type: 'realtime',
tracing: tracingConfig,
},
});
}
/**
* Updates the session config. This will merge it with the current session config with the default
* values and send it to the Realtime API.
*
* @param config - The session config to update.
*/
updateSessionConfig(config) {
const sessionData = this.buildSessionPayload(config);
this.sendEvent({
type: 'session.update',
session: sessionData,
});
}
/**
* Send the output of a function call to the Realtime API.
*
* @param toolCall - The tool call to send the output for.
* @param output - The output of the function call.
* @param startResponse - Whether to start a new response after sending the output.
*/
sendFunctionCallOutput(toolCall, output, startResponse = true) {
this.sendEvent({
type: 'conversation.item.create',
item: {
type: 'function_call_output',
output,
call_id: toolCall.callId,
},
});
try {
const item = realtimeToolCallItem.parse({
itemId: toolCall.id,
previousItemId: toolCall.previousItemId,
type: 'function_call',
status: 'completed',
arguments: toolCall.arguments,
name: toolCall.name,
output,
});
this.emit('item_update', item);
}
catch (error) {
logToolActionError(logger, 'Error parsing tool call item', error, toolCall);
}
if (startResponse) {
this.requestResponse();
}
}
/**
* Send an audio buffer to the Realtime API. If `{ commit: true }` is passed, the audio buffer
* will be committed and the model will start processing it. This is necessary if you have
* disabled turn detection / voice activity detection (VAD).
*
* @param audio - The audio buffer to send.
* @param options - The options for the audio buffer.
*/
sendAudio(audio, { commit = false } = {}) {
this.sendEvent({
type: 'input_audio_buffer.append',
audio: arrayBufferToBase64(audio),
});
if (commit) {
this.sendEvent({
type: 'input_audio_buffer.commit',
});
}
}
/**
* Reset the history of the conversation. This will create a diff between the old and new history
* and send the necessary events to the Realtime API to update the history.
*
* @param oldHistory - The old history of the conversation.
* @param newHistory - The new history of the conversation.
*/
resetHistory(oldHistory, newHistory) {
const { removals, additions, updates } = diffRealtimeHistory(oldHistory, newHistory);
// MCP items cannot be recreated once their conversation entry is deleted, so
// reject additions/updates before sending a single client event. A same-ID
// cross-type replacement surfaces in `updates` as the new non-MCP item, so
// classify by the old item's type as well. Explicit removals (item present
// in oldHistory but absent from newHistory) and unchanged items are
// unaffected and continue to work.
const isMcpItem = (item) => item.type === 'mcp_call' ||
item.type === 'mcp_tool_call' ||
item.type === 'mcp_approval_request';
const oldMcpItemIds = new Set(oldHistory.filter(isMcpItem).map((item) => item.itemId));
const rejectedMcpItem = [...additions, ...updates].find((item) => isMcpItem(item) || oldMcpItemIds.has(item.itemId));
if (rejectedMcpItem) {
const replaced = oldHistory.find((item) => item.itemId === rejectedMcpItem.itemId);
const detail = replaced && isMcpItem(replaced)
? `itemId ${rejectedMcpItem.itemId} replaces an existing '${replaced.type}' item with a '${rejectedMcpItem.type}' item`
: `a '${rejectedMcpItem.type}' item (itemId: ${rejectedMcpItem.itemId}) would be added or updated`;
throw new UserError(`MCP items cannot be added or updated via updateHistory(). Found ${detail}. Leave existing MCP items unchanged, or remove them from history entirely, before calling updateHistory().`);
}
const removalIds = new Set(removals.map((item) => item.itemId));
// we don't have an update event for items so we will remove and re-add what's there
for (const update of updates) {
removalIds.add(update.itemId);
}
if (removalIds.size > 0) {
for (const itemId of removalIds) {
this.#sendHistoryRequest(itemId, 'delete', {
type: 'conversation.item.delete',
item_id: itemId,
});
}
}
// Walk the new history in order so each created item can name the item it
// follows. `conversation.item.create` appends to the end of the
// conversation when `previous_item_id` is omitted, which would move a
// corrected or inserted item behind everything after it.
const pendingIds = new Set([...additions, ...updates].map((item) => item.itemId));
// Apply outstanding operations in send order. A recreation restores an
// anchor even before its earlier deletion is acknowledged; a later delete
// removes it again. Keep this projection separate from confirmed history.
const projectedPresence = new Map();
for (const request of this.#pendingHistoryRequests.values()) {
projectedPresence.set(request.itemId, request.kind === 'create');
}
const survives = (item) => !pendingIds.has(item.itemId) &&
projectedPresence.get(item.itemId) !== false;
// Only a create that has to land before something the server keeps needs to
// name an anchor. Past the last such item there is nothing to sit in front
// of, so those stay plain appends.
let lastAnchoredIndex = -1;
for (const [index, item] of newHistory.entries()) {
if (survives(item)) {
lastAnchoredIndex = index;
}
}
// `root` places the item at the beginning; omitting the field appends it.
let previousItemId = CONVERSATION_ROOT;
for (const [index, item] of newHistory.entries()) {
if (!pendingIds.has(item.itemId)) {
// An item on its way out cannot anchor anything: the anchor stays on
// the last one that will still be there when the create arrives.
if (survives(item)) {
previousItemId = item.itemId;
}
continue;
}
if (item.type === 'message') {
const itemEntry = {
type: 'message',
role: item.role,
content: item.content,
id: item.itemId,
};
if (item.role !== 'system' && item.status) {
itemEntry.status = item.status;
}
this.#sendHistoryRequest(item.itemId, 'create', {
type: 'conversation.item.create',
...(index < lastAnchoredIndex
? { previous_item_id: previousItemId }
: {}),
item: itemEntry,
});
previousItemId = item.itemId;
}
else if (item.type === 'function_call') {
logger.warn('Function calls cannot be manually added or updated at the moment. Ignoring.');
// Not created, so it cannot anchor the next insert.
}
}
}
sendMcpResponse(approvalRequest, approved, reason) {
this.sendEvent({
type: 'conversation.item.create',
previous_item_id: approvalRequest.itemId,
item: {
type: 'mcp_approval_response',
approval_request_id: approvalRequest.itemId,
approve: approved,
...(reason !== undefined ? { reason } : {}),
},
});
}
}
//# sourceMappingURL=openaiRealtimeBase.mjs.map