@livekit/agents-plugin-openai 1.7.1 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/realtime/gpt_live_model.cjs +883 -0
- package/dist/realtime/gpt_live_model.cjs.map +1 -0
- package/dist/realtime/gpt_live_model.d.cts +183 -0
- package/dist/realtime/gpt_live_model.d.ts +183 -0
- package/dist/realtime/gpt_live_model.d.ts.map +1 -0
- package/dist/realtime/gpt_live_model.js +859 -0
- package/dist/realtime/gpt_live_model.js.map +1 -0
- package/dist/realtime/gpt_live_model.test.cjs +1397 -0
- package/dist/realtime/gpt_live_model.test.cjs.map +1 -0
- package/dist/realtime/gpt_live_model.test.d.cts +2 -0
- package/dist/realtime/gpt_live_model.test.d.ts +2 -0
- package/dist/realtime/gpt_live_model.test.d.ts.map +1 -0
- package/dist/realtime/gpt_live_model.test.js +1398 -0
- package/dist/realtime/gpt_live_model.test.js.map +1 -0
- package/dist/realtime/gpt_live_types.cjs +17 -0
- package/dist/realtime/gpt_live_types.cjs.map +1 -0
- package/dist/realtime/gpt_live_types.d.cts +170 -0
- package/dist/realtime/gpt_live_types.d.ts +170 -0
- package/dist/realtime/gpt_live_types.d.ts.map +1 -0
- package/dist/realtime/gpt_live_types.js +1 -0
- package/dist/realtime/gpt_live_types.js.map +1 -0
- package/dist/realtime/index.cjs +22 -1
- package/dist/realtime/index.cjs.map +1 -1
- package/dist/realtime/index.d.cts +2 -0
- package/dist/realtime/index.d.ts +2 -0
- package/dist/realtime/index.d.ts.map +1 -1
- package/dist/realtime/index.js +5 -0
- package/dist/realtime/index.js.map +1 -1
- package/dist/realtime/realtime_model.cjs +4 -1
- package/dist/realtime/realtime_model.cjs.map +1 -1
- package/dist/realtime/realtime_model.d.ts.map +1 -1
- package/dist/realtime/realtime_model.js +4 -1
- package/dist/realtime/realtime_model.js.map +1 -1
- package/dist/realtime/realtime_model.test.cjs +29 -0
- package/dist/realtime/realtime_model.test.cjs.map +1 -1
- package/dist/realtime/realtime_model.test.js +29 -0
- package/dist/realtime/realtime_model.test.js.map +1 -1
- package/dist/responses/llm.cjs +10 -0
- package/dist/responses/llm.cjs.map +1 -1
- package/dist/responses/llm.d.ts.map +1 -1
- package/dist/responses/llm.js +10 -0
- package/dist/responses/llm.js.map +1 -1
- package/dist/responses/llm.test.cjs +51 -0
- package/dist/responses/llm.test.cjs.map +1 -1
- package/dist/responses/llm.test.js +52 -1
- package/dist/responses/llm.test.js.map +1 -1
- package/dist/tool_utils.cjs +12 -8
- package/dist/tool_utils.cjs.map +1 -1
- package/dist/tool_utils.d.cts +1 -0
- package/dist/tool_utils.d.ts +1 -0
- package/dist/tool_utils.d.ts.map +1 -1
- package/dist/tool_utils.js +11 -8
- package/dist/tool_utils.js.map +1 -1
- package/dist/tool_utils.test.cjs +27 -0
- package/dist/tool_utils.test.cjs.map +1 -1
- package/dist/tool_utils.test.js +27 -0
- package/dist/tool_utils.test.js.map +1 -1
- package/dist/ws/llm.cjs +25 -7
- package/dist/ws/llm.cjs.map +1 -1
- package/dist/ws/llm.d.cts +2 -2
- package/dist/ws/llm.d.ts +2 -2
- package/dist/ws/llm.d.ts.map +1 -1
- package/dist/ws/llm.js +25 -7
- package/dist/ws/llm.js.map +1 -1
- package/dist/ws/llm.test.cjs +117 -0
- package/dist/ws/llm.test.cjs.map +1 -1
- package/dist/ws/llm.test.js +126 -3
- package/dist/ws/llm.test.js.map +1 -1
- package/dist/ws/types.cjs +12 -0
- package/dist/ws/types.cjs.map +1 -1
- package/dist/ws/types.d.cts +18 -0
- package/dist/ws/types.d.ts +18 -0
- package/dist/ws/types.d.ts.map +1 -1
- package/dist/ws/types.js +11 -0
- package/dist/ws/types.js.map +1 -1
- package/package.json +5 -5
- package/src/realtime/gpt_live_model.test.ts +1458 -0
- package/src/realtime/gpt_live_model.ts +1032 -0
- package/src/realtime/gpt_live_types.ts +140 -0
- package/src/realtime/index.ts +2 -0
- package/src/realtime/realtime_model.test.ts +32 -0
- package/src/realtime/realtime_model.ts +4 -1
- package/src/responses/llm.test.ts +55 -1
- package/src/responses/llm.ts +10 -0
- package/src/tool_utils.test.ts +30 -0
- package/src/tool_utils.ts +21 -18
- package/src/ws/llm.test.ts +141 -5
- package/src/ws/llm.ts +29 -8
- package/src/ws/types.ts +17 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import type OpenAI from 'openai';
|
|
5
|
+
import type { Reasoning } from 'openai/resources/shared.js';
|
|
6
|
+
|
|
7
|
+
/** GPT-Live wire types. Field names follow the service protocol. @public */
|
|
8
|
+
export type DelegationTarget = 'responses' | 'client';
|
|
9
|
+
/** Roles accepted in initial session history. @public */
|
|
10
|
+
export type InputRole = 'developer' | 'user' | 'assistant';
|
|
11
|
+
/** A text message used to seed session history. @public */
|
|
12
|
+
export interface InputItem {
|
|
13
|
+
type: 'message';
|
|
14
|
+
role: InputRole;
|
|
15
|
+
content: { type: 'input_text' | 'output_text'; text: string }[];
|
|
16
|
+
}
|
|
17
|
+
/** Backend Responses API options, using wire field names. @public */
|
|
18
|
+
export interface ResponsesConfig {
|
|
19
|
+
model?: string;
|
|
20
|
+
instructions?: string;
|
|
21
|
+
tools?: OpenAI.Responses.Tool[];
|
|
22
|
+
tool_choice?: string | { type: 'function'; name: string };
|
|
23
|
+
parallel_tool_calls?: boolean;
|
|
24
|
+
reasoning?: Reasoning;
|
|
25
|
+
text?: OpenAI.Responses.ResponseTextConfig;
|
|
26
|
+
service_tier?: 'auto' | 'default' | 'flex' | 'priority';
|
|
27
|
+
max_output_tokens?: number;
|
|
28
|
+
}
|
|
29
|
+
/** Choose the backend Responses model or application callbacks. @public */
|
|
30
|
+
export type Delegation = { type: 'client' } | { type: 'responses'; responses: ResponsesConfig };
|
|
31
|
+
/** Initial voice, audio, context, and delegation configuration. @public */
|
|
32
|
+
export interface SessionConfig {
|
|
33
|
+
model: string;
|
|
34
|
+
instructions?: string;
|
|
35
|
+
input?: InputItem[];
|
|
36
|
+
audio?: {
|
|
37
|
+
format?: { type: 'audio/pcm' | 'audio/pcmu' | 'audio/pcma'; rate: number };
|
|
38
|
+
output?: { voice?: string | Record<string, unknown> };
|
|
39
|
+
};
|
|
40
|
+
delegation?: Delegation;
|
|
41
|
+
}
|
|
42
|
+
/** Commands sent to the GPT-Live WebSocket. @public */
|
|
43
|
+
export type ClientEvent = { event_id?: string } & (
|
|
44
|
+
| { type: 'session.start'; session: SessionConfig }
|
|
45
|
+
| { type: 'session.update'; session: { delegation: Delegation } }
|
|
46
|
+
| { type: 'session.input_audio.append'; audio: string }
|
|
47
|
+
| {
|
|
48
|
+
type:
|
|
49
|
+
| 'session.input_audio.mute'
|
|
50
|
+
| 'session.input_audio.unmute'
|
|
51
|
+
| 'session.close'
|
|
52
|
+
| 'response.create';
|
|
53
|
+
}
|
|
54
|
+
| {
|
|
55
|
+
type: 'session.instructions.append' | 'session.thinking.append' | 'session.commentary.append';
|
|
56
|
+
/** Required on every append, including when no delegation is being answered. */
|
|
57
|
+
delegation_id: string | null;
|
|
58
|
+
content: string;
|
|
59
|
+
}
|
|
60
|
+
| { type: 'response.item.create'; item: OpenAI.Responses.ResponseInputItem }
|
|
61
|
+
);
|
|
62
|
+
/** Backend response token usage, separate from voice session duration. @public */
|
|
63
|
+
export interface ResponseUsage {
|
|
64
|
+
input_tokens?: number;
|
|
65
|
+
input_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number };
|
|
66
|
+
output_tokens?: number;
|
|
67
|
+
output_tokens_details?: { reasoning_tokens?: number };
|
|
68
|
+
total_tokens?: number;
|
|
69
|
+
}
|
|
70
|
+
/** Responses API events nested inside a GPT-Live response.event. @public */
|
|
71
|
+
export interface ResponsesEvent {
|
|
72
|
+
type: string;
|
|
73
|
+
response?: {
|
|
74
|
+
id?: string | null;
|
|
75
|
+
model?: string | null;
|
|
76
|
+
usage?: ResponseUsage | null;
|
|
77
|
+
error?: Record<string, unknown> | null;
|
|
78
|
+
incomplete_details?: Record<string, unknown> | null;
|
|
79
|
+
} | null;
|
|
80
|
+
item?: {
|
|
81
|
+
id?: string | null;
|
|
82
|
+
type?: string | null;
|
|
83
|
+
call_id?: string | null;
|
|
84
|
+
name?: string | null;
|
|
85
|
+
arguments?: string | null;
|
|
86
|
+
} | null;
|
|
87
|
+
}
|
|
88
|
+
/** Provider error details. Messages can contain customer content. @public */
|
|
89
|
+
export interface ErrorBody {
|
|
90
|
+
type?: string | null;
|
|
91
|
+
code?: string | null;
|
|
92
|
+
message?: string;
|
|
93
|
+
param?: string | null;
|
|
94
|
+
client_event_id?: string | null;
|
|
95
|
+
}
|
|
96
|
+
/** Server fields are optional so missing fields do not end a session. @public */
|
|
97
|
+
export type ServerEvent =
|
|
98
|
+
| { type: 'session.started'; session?: { id?: string | null } }
|
|
99
|
+
| { type: 'session.output_audio.delta'; delta?: string }
|
|
100
|
+
| {
|
|
101
|
+
type: 'session.output_transcript.delta' | 'session.input_transcript.delta';
|
|
102
|
+
delta?: string;
|
|
103
|
+
start_ms?: number | null;
|
|
104
|
+
end_ms?: number | null;
|
|
105
|
+
}
|
|
106
|
+
| {
|
|
107
|
+
type: 'session.delegation.created';
|
|
108
|
+
delegation?: { id?: string | null; target?: DelegationTarget | null };
|
|
109
|
+
}
|
|
110
|
+
| { type: 'response.event'; delegation_id?: string | null; event?: ResponsesEvent }
|
|
111
|
+
| {
|
|
112
|
+
type: 'session.usage.updated';
|
|
113
|
+
usage?: { seconds?: number };
|
|
114
|
+
context_window?: { usage_ratio?: number | null } | null;
|
|
115
|
+
}
|
|
116
|
+
| {
|
|
117
|
+
type: 'session.closed';
|
|
118
|
+
reason?:
|
|
119
|
+
| 'close_requested'
|
|
120
|
+
| 'expired'
|
|
121
|
+
| 'content'
|
|
122
|
+
| 'remote_hangup'
|
|
123
|
+
| 'connection_lost'
|
|
124
|
+
| null;
|
|
125
|
+
usage?: { seconds?: number };
|
|
126
|
+
context_window?: { usage_ratio?: number | null } | null;
|
|
127
|
+
}
|
|
128
|
+
| { type: 'error'; error?: ErrorBody }
|
|
129
|
+
| {
|
|
130
|
+
type: 'session.updated' | 'session.input_audio.muted' | 'session.input_audio.unmuted';
|
|
131
|
+
client_event_id?: string;
|
|
132
|
+
}
|
|
133
|
+
| {
|
|
134
|
+
/** Sent at the estimated context-injection end; does not indicate speech completion. */
|
|
135
|
+
type:
|
|
136
|
+
| 'session.instructions.appended'
|
|
137
|
+
| 'session.thinking.appended'
|
|
138
|
+
| 'session.commentary.appended';
|
|
139
|
+
client_event_id?: string;
|
|
140
|
+
};
|
package/src/realtime/index.ts
CHANGED
|
@@ -1096,6 +1096,38 @@ describe('RealtimeSession chat context update events', () => {
|
|
|
1096
1096
|
expect((events[0] as api_proto.ConversationItemDeleteEvent).item_id).toBe('item_1');
|
|
1097
1097
|
expect((events[1] as api_proto.ConversationItemCreateEvent).item.id).toBe('item_1');
|
|
1098
1098
|
});
|
|
1099
|
+
|
|
1100
|
+
it('ignores session metadata when creating provider events', async () => {
|
|
1101
|
+
const existingMessage = llm.ChatMessage.create({
|
|
1102
|
+
id: 'item_1',
|
|
1103
|
+
role: 'assistant',
|
|
1104
|
+
content: ['What is two plus two?'],
|
|
1105
|
+
});
|
|
1106
|
+
const session = createChatCtxUpdateSession(existingMessage);
|
|
1107
|
+
|
|
1108
|
+
const events = await session.createChatCtxUpdateEvents(
|
|
1109
|
+
new llm.ChatContext([
|
|
1110
|
+
existingMessage,
|
|
1111
|
+
new llm.AgentConfigUpdate({
|
|
1112
|
+
id: 'item_config',
|
|
1113
|
+
instructions: 'Ask the next math question.',
|
|
1114
|
+
}),
|
|
1115
|
+
new llm.AgentHandoffItem({
|
|
1116
|
+
id: 'item_handoff',
|
|
1117
|
+
oldAgentId: 'agent_1',
|
|
1118
|
+
newAgentId: 'agent_2',
|
|
1119
|
+
}),
|
|
1120
|
+
llm.ChatMessage.create({ id: 'item_2', role: 'user', content: ['four'] }),
|
|
1121
|
+
]),
|
|
1122
|
+
);
|
|
1123
|
+
|
|
1124
|
+
expect(events).toHaveLength(1);
|
|
1125
|
+
expect(events[0]).toMatchObject({
|
|
1126
|
+
type: 'conversation.item.create',
|
|
1127
|
+
previous_item_id: 'item_1',
|
|
1128
|
+
item: { id: 'item_2' },
|
|
1129
|
+
});
|
|
1130
|
+
});
|
|
1099
1131
|
});
|
|
1100
1132
|
|
|
1101
1133
|
describe('RealtimeSession.updateOptions', () => {
|
|
@@ -710,7 +710,10 @@ export class RealtimeSession extends llm.RealtimeSession {
|
|
|
710
710
|
chatCtx: llm.ChatContext,
|
|
711
711
|
addMockAudio: boolean = false,
|
|
712
712
|
): Promise<(api_proto.ConversationItemCreateEvent | api_proto.ConversationItemDeleteEvent)[]> {
|
|
713
|
-
const newChatCtx = chatCtx.copy(
|
|
713
|
+
const newChatCtx = chatCtx.copy({
|
|
714
|
+
excludeHandoff: true,
|
|
715
|
+
excludeConfigUpdate: true,
|
|
716
|
+
});
|
|
714
717
|
if (addMockAudio) {
|
|
715
718
|
newChatCtx.items.push(createMockAudioItem());
|
|
716
719
|
} else {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import { ChatContext, initializeLogger } from '@livekit/agents';
|
|
4
|
+
import { APIStatusError, ChatContext, initializeLogger } from '@livekit/agents';
|
|
5
5
|
import { llm, llmStrict } from '@livekit/agents-plugins-test';
|
|
6
6
|
import type OpenAI from 'openai';
|
|
7
7
|
import { describe, expect, it } from 'vitest';
|
|
@@ -116,6 +116,60 @@ describe('OpenAI Responses HTTP retry eligibility', () => {
|
|
|
116
116
|
});
|
|
117
117
|
});
|
|
118
118
|
|
|
119
|
+
describe('OpenAI Responses HTTP incomplete handling', () => {
|
|
120
|
+
it.each([
|
|
121
|
+
['max_output_tokens', 'max_output_tokens'],
|
|
122
|
+
[undefined, 'reason unavailable'],
|
|
123
|
+
] as const)('surfaces %s as non-retryable', async (reason, expectedMessage) => {
|
|
124
|
+
let attempts = 0;
|
|
125
|
+
const incomplete = {
|
|
126
|
+
type: 'response.incomplete',
|
|
127
|
+
response: {
|
|
128
|
+
id: 'resp_1',
|
|
129
|
+
...(reason === undefined ? {} : { incomplete_details: { reason } }),
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
const client = {
|
|
133
|
+
responses: {
|
|
134
|
+
create: async () => {
|
|
135
|
+
attempts++;
|
|
136
|
+
return {
|
|
137
|
+
async *[Symbol.asyncIterator]() {
|
|
138
|
+
yield RESPONSE_CREATED;
|
|
139
|
+
yield incomplete;
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
const model = new LLM({
|
|
146
|
+
model: 'gpt-4.1',
|
|
147
|
+
apiKey: 'test-key',
|
|
148
|
+
useWebSocket: false,
|
|
149
|
+
client: client as unknown as OpenAI,
|
|
150
|
+
});
|
|
151
|
+
const errorEvent = new Promise<Error>((resolve) => {
|
|
152
|
+
model.once('error', (event) => resolve(event.error));
|
|
153
|
+
});
|
|
154
|
+
const chatCtx = ChatContext.empty();
|
|
155
|
+
chatCtx.addMessage({ role: 'user', content: 'hi' });
|
|
156
|
+
|
|
157
|
+
const stream = model.chat({
|
|
158
|
+
chatCtx,
|
|
159
|
+
connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5000 },
|
|
160
|
+
});
|
|
161
|
+
for await (const _chunk of stream) void _chunk;
|
|
162
|
+
const error = await errorEvent;
|
|
163
|
+
|
|
164
|
+
expect(error).toBeInstanceOf(APIStatusError);
|
|
165
|
+
expect(error.message).toContain(expectedMessage);
|
|
166
|
+
expect((error as APIStatusError).statusCode).toBe(-1);
|
|
167
|
+
expect((error as APIStatusError).retryable).toBe(false);
|
|
168
|
+
expect(attempts).toBe(1);
|
|
169
|
+
await model.aclose();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
|
|
119
173
|
if (hasOpenAIApiKey) {
|
|
120
174
|
describe('OpenAI Responses', async () => {
|
|
121
175
|
await llm(
|
package/src/responses/llm.ts
CHANGED
|
@@ -247,6 +247,9 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
|
|
|
247
247
|
case 'response.failed':
|
|
248
248
|
this.handleResponseFailed(event);
|
|
249
249
|
break;
|
|
250
|
+
case 'response.incomplete':
|
|
251
|
+
this.handleResponseIncomplete(event);
|
|
252
|
+
break;
|
|
250
253
|
}
|
|
251
254
|
|
|
252
255
|
if (chunk) {
|
|
@@ -303,6 +306,13 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
|
|
|
303
306
|
});
|
|
304
307
|
}
|
|
305
308
|
|
|
309
|
+
private handleResponseIncomplete(event: OpenAI.Responses.ResponseIncompleteEvent): void {
|
|
310
|
+
throw new APIStatusError({
|
|
311
|
+
message: `response incomplete: ${event.response.incomplete_details?.reason ?? 'reason unavailable'}`,
|
|
312
|
+
options: { statusCode: -1, retryable: false },
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
306
316
|
private handleResponseCreated(event: OpenAI.Responses.ResponseCreatedEvent): void {
|
|
307
317
|
this.responseId = event.response.id;
|
|
308
318
|
}
|
package/src/tool_utils.test.ts
CHANGED
|
@@ -8,6 +8,36 @@ import { toResponsesTools } from './tool_utils.js';
|
|
|
8
8
|
import { CodeInterpreter, FileSearch, WebSearch } from './tools.js';
|
|
9
9
|
|
|
10
10
|
describe('toResponsesTools', () => {
|
|
11
|
+
it('sorts function tools before provider tools without making optional parameters strict', () => {
|
|
12
|
+
const makeTool = (name: string) =>
|
|
13
|
+
llm.tool({
|
|
14
|
+
name,
|
|
15
|
+
description: 'Look up weather',
|
|
16
|
+
parameters: z.object({ city: z.string().optional() }),
|
|
17
|
+
execute: async () => 'sunny',
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
expect(
|
|
21
|
+
toResponsesTools(
|
|
22
|
+
new llm.ToolContext([makeTool('zulu'), new WebSearch(), makeTool('alpha')]),
|
|
23
|
+
false,
|
|
24
|
+
),
|
|
25
|
+
).toEqual([
|
|
26
|
+
...['alpha', 'zulu'].map((name) => ({
|
|
27
|
+
type: 'function',
|
|
28
|
+
name,
|
|
29
|
+
description: 'Look up weather',
|
|
30
|
+
parameters: {
|
|
31
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: { city: { type: 'string' } },
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
},
|
|
36
|
+
})),
|
|
37
|
+
{ type: 'web_search', search_context_size: 'medium' },
|
|
38
|
+
]);
|
|
39
|
+
});
|
|
40
|
+
|
|
11
41
|
it('serializes function tools', () => {
|
|
12
42
|
const fn = llm.tool({
|
|
13
43
|
name: 'lookup_weather',
|
package/src/tool_utils.ts
CHANGED
|
@@ -5,16 +5,14 @@ import { llm } from '@livekit/agents';
|
|
|
5
5
|
import type OpenAI from 'openai';
|
|
6
6
|
import { OpenAITool } from './tools.js';
|
|
7
7
|
|
|
8
|
-
export function
|
|
9
|
-
|
|
8
|
+
export function toResponsesTool(
|
|
9
|
+
tool: llm.Tool,
|
|
10
10
|
strictToolSchema: boolean,
|
|
11
|
-
): OpenAI.Responses.Tool
|
|
12
|
-
|
|
13
|
-
// tools follow in registration order.
|
|
14
|
-
const functionTools = llm.sortedToolEntries(toolCtx).map(([name, tool]) => {
|
|
11
|
+
): OpenAI.Responses.Tool | undefined {
|
|
12
|
+
if (llm.isFunctionTool(tool)) {
|
|
15
13
|
const oaiParams = {
|
|
16
14
|
type: 'function' as const,
|
|
17
|
-
name,
|
|
15
|
+
name: tool.name,
|
|
18
16
|
description: tool.description,
|
|
19
17
|
parameters: llm.toJsonSchema(
|
|
20
18
|
tool.parameters,
|
|
@@ -28,19 +26,24 @@ export function toResponsesTools(
|
|
|
28
26
|
}
|
|
29
27
|
|
|
30
28
|
return oaiParams;
|
|
31
|
-
}
|
|
29
|
+
}
|
|
32
30
|
|
|
33
|
-
|
|
34
|
-
.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
tool instanceof OpenAITool
|
|
38
|
-
? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)
|
|
39
|
-
: undefined,
|
|
40
|
-
)
|
|
41
|
-
.filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);
|
|
31
|
+
return tool instanceof OpenAITool
|
|
32
|
+
? (tool.toToolConfig() as unknown as OpenAI.Responses.Tool)
|
|
33
|
+
: undefined;
|
|
34
|
+
}
|
|
42
35
|
|
|
43
|
-
|
|
36
|
+
export function toResponsesTools(
|
|
37
|
+
toolCtx: llm.ToolContext,
|
|
38
|
+
strictToolSchema: boolean,
|
|
39
|
+
): OpenAI.Responses.Tool[] | undefined {
|
|
40
|
+
// Function tools are emitted first, sorted by name for deterministic payloads; provider
|
|
41
|
+
// tools follow in registration order.
|
|
42
|
+
const functionTools = llm.sortedToolEntries(toolCtx).map(([, tool]) => tool);
|
|
43
|
+
const providerTools = toolCtx.flatten().filter((tool) => !llm.isFunctionTool(tool));
|
|
44
|
+
const tools = [...functionTools, ...providerTools]
|
|
45
|
+
.map((tool) => toResponsesTool(tool, strictToolSchema))
|
|
46
|
+
.filter((tool): tool is OpenAI.Responses.Tool => tool !== undefined);
|
|
44
47
|
|
|
45
48
|
return tools.length > 0 ? tools : undefined;
|
|
46
49
|
}
|
package/src/ws/llm.test.ts
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
APIStatusError,
|
|
6
|
+
ChatContext,
|
|
7
|
+
ConnectionPool,
|
|
8
|
+
initializeLogger,
|
|
9
|
+
stream,
|
|
10
|
+
} from '@livekit/agents';
|
|
5
11
|
import { llm, llmStrict } from '@livekit/agents-plugins-test';
|
|
6
|
-
import {
|
|
12
|
+
import { EventEmitter } from 'node:events';
|
|
13
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
7
14
|
import { LLM } from '../responses/llm.js';
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
15
|
+
import { ResponsesWebSocket, WSLLM, WSLLMStream, buildResponsesWsUrl } from './llm.js';
|
|
16
|
+
import type { WsResponseCreateEvent, WsServerEvent } from './types.js';
|
|
17
|
+
import { wsServerEventSchema } from './types.js';
|
|
11
18
|
|
|
12
19
|
initializeLogger({ level: 'silent', pretty: false });
|
|
13
20
|
|
|
@@ -100,6 +107,65 @@ const TEXT_DELTA: WsServerEvent = {
|
|
|
100
107
|
delta: 'hello',
|
|
101
108
|
};
|
|
102
109
|
|
|
110
|
+
function responseIncomplete(reason?: string): WsServerEvent {
|
|
111
|
+
return {
|
|
112
|
+
type: 'response.incomplete',
|
|
113
|
+
response: {
|
|
114
|
+
id: 'resp_1',
|
|
115
|
+
incomplete_details: reason === undefined ? {} : { reason },
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
describe('OpenAI Responses WS incomplete events', () => {
|
|
121
|
+
it.each(['max_output_tokens', 'content_filter'])('parses the provider reason %s', (reason) => {
|
|
122
|
+
const parsed = wsServerEventSchema.parse(responseIncomplete(reason));
|
|
123
|
+
|
|
124
|
+
expect(parsed.type).toBe('response.incomplete');
|
|
125
|
+
if (parsed.type !== 'response.incomplete') throw new Error('expected incomplete event');
|
|
126
|
+
expect(parsed.response.incomplete_details?.reason).toBe(reason);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('accepts incomplete details without a reason', () => {
|
|
130
|
+
const parsed = wsServerEventSchema.parse({
|
|
131
|
+
type: 'response.incomplete',
|
|
132
|
+
response: { id: 'resp_1', incomplete_details: {} },
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
expect(parsed.type).toBe('response.incomplete');
|
|
136
|
+
if (parsed.type !== 'response.incomplete') throw new Error('expected incomplete event');
|
|
137
|
+
expect(parsed.response.incomplete_details?.reason).toBeUndefined();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('closes the request channel after the terminal frame', async () => {
|
|
141
|
+
class RecordingSocket extends EventEmitter {
|
|
142
|
+
readyState = 1;
|
|
143
|
+
sent: string[] = [];
|
|
144
|
+
|
|
145
|
+
send(data: string): void {
|
|
146
|
+
this.sent.push(data);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
close(): void {}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const socket = new RecordingSocket();
|
|
153
|
+
const transport = new ResponsesWebSocket(socket as never);
|
|
154
|
+
const channel = transport.sendRequest({
|
|
155
|
+
type: 'response.create',
|
|
156
|
+
model: 'gpt-4.1',
|
|
157
|
+
input: [],
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
socket.emit('message', Buffer.from(JSON.stringify(responseIncomplete())));
|
|
161
|
+
const events = [];
|
|
162
|
+
for await (const event of channel.stream()) events.push(event);
|
|
163
|
+
|
|
164
|
+
expect(events).toEqual([responseIncomplete()]);
|
|
165
|
+
expect(socket.sent).toHaveLength(1);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
103
169
|
/** Replays the given frames, then dies the way a socket going quiet does. */
|
|
104
170
|
class StallingConnection {
|
|
105
171
|
attempts = 0;
|
|
@@ -173,6 +239,76 @@ describe('OpenAI Responses WS retry eligibility', () => {
|
|
|
173
239
|
});
|
|
174
240
|
});
|
|
175
241
|
|
|
242
|
+
describe('OpenAI Responses WS incomplete handling', () => {
|
|
243
|
+
it.each([
|
|
244
|
+
['max_output_tokens', 'max_output_tokens'],
|
|
245
|
+
[undefined, 'reason unavailable'],
|
|
246
|
+
] as const)(
|
|
247
|
+
'surfaces %s as non-retryable without updating context',
|
|
248
|
+
async (reason, expectedMessage) => {
|
|
249
|
+
class ReplayConnection {
|
|
250
|
+
attempts = 0;
|
|
251
|
+
payloads: WsResponseCreateEvent[] = [];
|
|
252
|
+
|
|
253
|
+
sendRequest(payload: WsResponseCreateEvent): stream.StreamChannel<WsServerEvent> {
|
|
254
|
+
this.attempts++;
|
|
255
|
+
this.payloads.push(payload);
|
|
256
|
+
const channel = stream.createStreamChannel<WsServerEvent>();
|
|
257
|
+
void (async () => {
|
|
258
|
+
await channel.write(RESPONSE_CREATED);
|
|
259
|
+
await channel.write(responseIncomplete(reason));
|
|
260
|
+
await channel.close();
|
|
261
|
+
})();
|
|
262
|
+
return channel;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
close(): void {}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const model = new WSLLM({ model: 'gpt-4.1', apiKey: 'test-key' });
|
|
269
|
+
const onCompleted = vi.spyOn(model, '_onResponseCompleted');
|
|
270
|
+
const errorEvent = new Promise<Error>((resolve) => {
|
|
271
|
+
model.once('error', (event) => resolve(event.error));
|
|
272
|
+
});
|
|
273
|
+
const conn = new ReplayConnection();
|
|
274
|
+
let connectCalls = 0;
|
|
275
|
+
const pool = new ConnectionPool<ResponsesWebSocket>({
|
|
276
|
+
connectCb: async () => {
|
|
277
|
+
connectCalls++;
|
|
278
|
+
return conn as unknown as ResponsesWebSocket;
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
const chatCtx = ChatContext.empty();
|
|
282
|
+
chatCtx.addMessage({ role: 'user', content: 'hi' });
|
|
283
|
+
const llmStream = new WSLLMStream(model, {
|
|
284
|
+
pool,
|
|
285
|
+
model: 'gpt-4.1',
|
|
286
|
+
chatCtx,
|
|
287
|
+
fullChatCtx: chatCtx,
|
|
288
|
+
connOptions: { maxRetry: 2, retryIntervalMs: 0, timeoutMs: 5000 },
|
|
289
|
+
modelOptions: {},
|
|
290
|
+
strictToolSchema: true,
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
for await (const _chunk of llmStream) void _chunk;
|
|
294
|
+
const error = await errorEvent;
|
|
295
|
+
|
|
296
|
+
expect(error).toBeInstanceOf(APIStatusError);
|
|
297
|
+
expect(error.message).toContain(expectedMessage);
|
|
298
|
+
expect((error as APIStatusError).statusCode).toBe(-1);
|
|
299
|
+
expect((error as APIStatusError).retryable).toBe(false);
|
|
300
|
+
expect(conn.attempts).toBe(1);
|
|
301
|
+
expect(onCompleted).not.toHaveBeenCalled();
|
|
302
|
+
|
|
303
|
+
await pool.withConnection(async (pooled) => expect(pooled).toBe(conn));
|
|
304
|
+
expect(connectCalls).toBe(1);
|
|
305
|
+
expect(conn.payloads[0]).not.toHaveProperty('previous_response_id');
|
|
306
|
+
await pool.close();
|
|
307
|
+
await model.aclose();
|
|
308
|
+
},
|
|
309
|
+
);
|
|
310
|
+
});
|
|
311
|
+
|
|
176
312
|
if (hasOpenAIApiKey) {
|
|
177
313
|
describe('OpenAI Responses WS wrapper', async () => {
|
|
178
314
|
await llm(
|
package/src/ws/llm.ts
CHANGED
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
WsResponseCreateEvent,
|
|
25
25
|
WsResponseCreatedEvent,
|
|
26
26
|
WsResponseFailedEvent,
|
|
27
|
+
WsResponseIncompleteEvent,
|
|
27
28
|
WsServerEvent,
|
|
28
29
|
} from './types.js';
|
|
29
30
|
import { wsServerEventSchema } from './types.js';
|
|
@@ -68,7 +69,7 @@ export function buildResponsesWsUrl(baseURL: string | undefined, model: string):
|
|
|
68
69
|
// StreamChannels — one per outstanding response.create request — and
|
|
69
70
|
// dispatches every incoming server-event to the front of the queue.
|
|
70
71
|
// A response is terminated (and its channel closed) when the service sends
|
|
71
|
-
// response.completed, response.failed, or error.
|
|
72
|
+
// response.completed, response.failed, response.incomplete, or error.
|
|
72
73
|
//
|
|
73
74
|
// ============================================================================
|
|
74
75
|
|
|
@@ -103,6 +104,7 @@ export class ResponsesWebSocket {
|
|
|
103
104
|
if (
|
|
104
105
|
event.type === 'response.completed' ||
|
|
105
106
|
event.type === 'response.failed' ||
|
|
107
|
+
event.type === 'response.incomplete' ||
|
|
106
108
|
event.type === 'error'
|
|
107
109
|
) {
|
|
108
110
|
void current.close();
|
|
@@ -255,9 +257,9 @@ export class WSLLM extends llm.LLM {
|
|
|
255
257
|
await this.close();
|
|
256
258
|
}
|
|
257
259
|
|
|
258
|
-
/** Called by LLMStream once response.
|
|
260
|
+
/** Called by LLMStream once response.completed fires to atomically persist both the
|
|
259
261
|
* response ID and its corresponding chat context for the next turn's diff. */
|
|
260
|
-
|
|
262
|
+
_onResponseCompleted(responseId: string, chatCtx: llm.ChatContext): void {
|
|
261
263
|
this.#prevResponseId = responseId;
|
|
262
264
|
this.#prevChatCtx = chatCtx;
|
|
263
265
|
}
|
|
@@ -436,18 +438,28 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
436
438
|
|
|
437
439
|
protected async run(): Promise<void> {
|
|
438
440
|
this.#retryable = true;
|
|
441
|
+
let responseError: APIStatusError | undefined;
|
|
439
442
|
|
|
440
443
|
try {
|
|
441
444
|
await this.#pool.withConnection(async (conn: ResponsesWebSocket) => {
|
|
442
|
-
const
|
|
445
|
+
const result = await this.#runWithConn(conn, this.chatCtx, this.#prevResponseId);
|
|
443
446
|
|
|
444
|
-
if (
|
|
447
|
+
if (result instanceof APIStatusError) {
|
|
448
|
+
responseError = result;
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (result) {
|
|
445
453
|
// previous_response_id was evicted from the server-side cache.
|
|
446
454
|
// Retry once on the same connection with the full context and no ID.
|
|
447
455
|
this.#retryable = true;
|
|
448
|
-
await this.#runWithConn(conn, this.#fullChatCtx, undefined);
|
|
456
|
+
const retryResult = await this.#runWithConn(conn, this.#fullChatCtx, undefined);
|
|
457
|
+
if (retryResult instanceof APIStatusError) {
|
|
458
|
+
responseError = retryResult;
|
|
459
|
+
}
|
|
449
460
|
}
|
|
450
461
|
});
|
|
462
|
+
if (responseError) throw responseError;
|
|
451
463
|
} catch (error) {
|
|
452
464
|
if (
|
|
453
465
|
error instanceof APIStatusError ||
|
|
@@ -472,7 +484,7 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
472
484
|
conn: ResponsesWebSocket,
|
|
473
485
|
chatCtx: llm.ChatContext,
|
|
474
486
|
prevResponseId: string | undefined,
|
|
475
|
-
): Promise<boolean> {
|
|
487
|
+
): Promise<boolean | APIStatusError> {
|
|
476
488
|
const messages = (await chatCtx.toProviderFormat(
|
|
477
489
|
'openai.responses',
|
|
478
490
|
)) as OpenAI.Responses.ResponseInputItem[];
|
|
@@ -535,6 +547,8 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
535
547
|
case 'response.failed':
|
|
536
548
|
this.#handleResponseFailed(event);
|
|
537
549
|
break;
|
|
550
|
+
case 'response.incomplete':
|
|
551
|
+
return this.#handleResponseIncomplete(event);
|
|
538
552
|
default:
|
|
539
553
|
break;
|
|
540
554
|
}
|
|
@@ -588,7 +602,6 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
588
602
|
|
|
589
603
|
#handleResponseCreated(event: WsResponseCreatedEvent): void {
|
|
590
604
|
this.#responseId = event.response.id;
|
|
591
|
-
this.#llm._onResponseCreated(event.response.id, this.#fullChatCtx);
|
|
592
605
|
}
|
|
593
606
|
|
|
594
607
|
#handleOutputItemDone(event: WsOutputItemDoneEvent): llm.ChatChunk | undefined {
|
|
@@ -632,6 +645,7 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
632
645
|
}
|
|
633
646
|
|
|
634
647
|
#handleResponseCompleted(event: WsResponseCompletedEvent): llm.ChatChunk | undefined {
|
|
648
|
+
this.#llm._onResponseCompleted(event.response.id, this.#fullChatCtx);
|
|
635
649
|
this.#llm._setPendingToolCalls(this.#pendingToolCalls);
|
|
636
650
|
|
|
637
651
|
if (event.response.usage) {
|
|
@@ -655,6 +669,13 @@ export class WSLLMStream extends llm.LLMStream {
|
|
|
655
669
|
options: { statusCode: -1, retryable: false },
|
|
656
670
|
});
|
|
657
671
|
}
|
|
672
|
+
|
|
673
|
+
#handleResponseIncomplete(event: WsResponseIncompleteEvent): APIStatusError {
|
|
674
|
+
return new APIStatusError({
|
|
675
|
+
message: `response incomplete: ${event.response.incomplete_details?.reason ?? 'reason unavailable'}`,
|
|
676
|
+
options: { statusCode: -1, retryable: false },
|
|
677
|
+
});
|
|
678
|
+
}
|
|
658
679
|
}
|
|
659
680
|
|
|
660
681
|
// ============================================================================
|