@robota-sdk/agent-provider-openai 3.0.0-beta.99 → 3.0.2
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/CHANGELOG.md +340 -0
- package/README.md +36 -1
- package/dist/node/index.cjs +2 -2
- package/dist/node/index.d.cts +16 -2
- package/dist/node/index.d.cts.map +1 -1
- package/dist/node/index.d.ts +16 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -2
- package/dist/node/index.js.map +1 -1
- package/package.json +4 -4
- package/src/openai/__tests__/extra-body.test.ts +507 -0
- package/src/openai/__tests__/provider-errors.test.ts +8 -3
- package/src/openai/chat-completions-chat.ts +4 -1
- package/src/openai/extra-body.ts +120 -0
- package/src/openai/provider-definition.ts +3 -0
- package/src/openai/provider.ts +11 -1
- package/src/openai/responses-chat.ts +4 -1
- package/src/openai/types.ts +21 -0
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
|
|
4
|
+
import OpenAI from 'openai';
|
|
5
|
+
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { OpenAIProvider } from '../provider';
|
|
8
|
+
import { createOpenAIProviderDefinition } from '../provider-definition';
|
|
9
|
+
|
|
10
|
+
import type { IOpenAIProviderOptions, TOpenAIApiSurface } from '../types';
|
|
11
|
+
import type {
|
|
12
|
+
IAssistantMessage,
|
|
13
|
+
IChatOptions,
|
|
14
|
+
IExecutor,
|
|
15
|
+
IToolSchema,
|
|
16
|
+
TUniversalMessage,
|
|
17
|
+
} from '@robota-sdk/agent-core';
|
|
18
|
+
|
|
19
|
+
const tool: IToolSchema = {
|
|
20
|
+
name: 'classify_invoice',
|
|
21
|
+
description: 'Classify an invoice.',
|
|
22
|
+
parameters: {
|
|
23
|
+
type: 'object',
|
|
24
|
+
properties: { category: { type: 'string' } },
|
|
25
|
+
required: ['category'],
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
const call = {
|
|
29
|
+
id: 'call_0',
|
|
30
|
+
type: 'function',
|
|
31
|
+
function: { name: tool.name, arguments: JSON.stringify({ category: 'invoice' }) },
|
|
32
|
+
};
|
|
33
|
+
const completion = {
|
|
34
|
+
id: 'completion-fixture',
|
|
35
|
+
object: 'chat.completion',
|
|
36
|
+
created: 0,
|
|
37
|
+
model: 'fixture-model',
|
|
38
|
+
choices: [
|
|
39
|
+
{
|
|
40
|
+
index: 0,
|
|
41
|
+
message: { role: 'assistant', content: '', tool_calls: [call] },
|
|
42
|
+
finish_reason: 'tool_calls',
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
};
|
|
46
|
+
const response = {
|
|
47
|
+
id: 'response-fixture',
|
|
48
|
+
object: 'response',
|
|
49
|
+
created_at: 0,
|
|
50
|
+
model: 'fixture-model',
|
|
51
|
+
status: 'completed',
|
|
52
|
+
output: [
|
|
53
|
+
{
|
|
54
|
+
type: 'function_call',
|
|
55
|
+
id: 'item_0',
|
|
56
|
+
call_id: call.id,
|
|
57
|
+
status: 'completed',
|
|
58
|
+
name: call.function.name,
|
|
59
|
+
arguments: call.function.arguments,
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
};
|
|
63
|
+
const messages: TUniversalMessage[] = [
|
|
64
|
+
{
|
|
65
|
+
id: 'user-fixture',
|
|
66
|
+
role: 'user',
|
|
67
|
+
content: 'Classify this invoice.',
|
|
68
|
+
state: 'complete',
|
|
69
|
+
timestamp: new Date(0),
|
|
70
|
+
},
|
|
71
|
+
];
|
|
72
|
+
const gatewayOptions = { anthropic: { disableParallelToolUse: true } };
|
|
73
|
+
const received: Record<string, unknown>[] = [];
|
|
74
|
+
let baseURL: string;
|
|
75
|
+
|
|
76
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
77
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const server = createServer(async (request, reply) => {
|
|
81
|
+
let data = '';
|
|
82
|
+
for await (const chunk of request) data += String(chunk);
|
|
83
|
+
const body: unknown = JSON.parse(data);
|
|
84
|
+
if (!isRecord(body)) throw new Error('Expected fixture request object');
|
|
85
|
+
received.push(body);
|
|
86
|
+
const responses = request.url === '/v1/responses';
|
|
87
|
+
if (body.stream === true) {
|
|
88
|
+
reply.setHeader('content-type', 'text/event-stream');
|
|
89
|
+
const event = responses
|
|
90
|
+
? { type: 'response.completed', response, sequence_number: 1 }
|
|
91
|
+
: {
|
|
92
|
+
id: completion.id,
|
|
93
|
+
object: 'chat.completion.chunk',
|
|
94
|
+
created: 0,
|
|
95
|
+
model: 'fixture-model',
|
|
96
|
+
choices: [
|
|
97
|
+
{
|
|
98
|
+
index: 0,
|
|
99
|
+
delta: { role: 'assistant', content: '', tool_calls: [{ ...call, index: 0 }] },
|
|
100
|
+
finish_reason: 'tool_calls',
|
|
101
|
+
},
|
|
102
|
+
],
|
|
103
|
+
};
|
|
104
|
+
reply.end(`data: ${JSON.stringify(event)}\n\n${responses ? '' : 'data: [DONE]\n\n'}`);
|
|
105
|
+
} else {
|
|
106
|
+
reply.setHeader('content-type', 'application/json');
|
|
107
|
+
reply.end(JSON.stringify(responses ? response : completion));
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
beforeAll(async () => {
|
|
112
|
+
server.listen(0, '127.0.0.1');
|
|
113
|
+
await once(server, 'listening');
|
|
114
|
+
const address = server.address();
|
|
115
|
+
if (!address || typeof address === 'string') throw new Error('Missing fixture address');
|
|
116
|
+
baseURL = `http://127.0.0.1:${address.port}/v1`;
|
|
117
|
+
});
|
|
118
|
+
afterEach(() => {
|
|
119
|
+
received.length = 0;
|
|
120
|
+
});
|
|
121
|
+
afterAll(async () => {
|
|
122
|
+
server.closeAllConnections();
|
|
123
|
+
await new Promise<void>((resolve, reject) => {
|
|
124
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
function providerOptions(apiSurface: TOpenAIApiSurface): IOpenAIProviderOptions {
|
|
129
|
+
return { apiSurface, client: new OpenAI({ apiKey: 'fixture-key', baseURL, maxRetries: 0 }) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Bypasses the public type so the runtime boundary sees values TypeScript would reject. */
|
|
133
|
+
function withRawExtraBody(options: IOpenAIProviderOptions, value: unknown): IOpenAIProviderOptions {
|
|
134
|
+
Object.defineProperty(options, 'extraBody', { value, enumerable: true });
|
|
135
|
+
return options;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function createProfileProvider(apiSurface: TOpenAIApiSurface, extraBody: unknown) {
|
|
139
|
+
const options = { apiSurface };
|
|
140
|
+
if (extraBody !== undefined) {
|
|
141
|
+
Object.defineProperty(options, 'extraBody', { value: extraBody, enumerable: true });
|
|
142
|
+
}
|
|
143
|
+
return createOpenAIProviderDefinition().createProvider({
|
|
144
|
+
name: 'openai',
|
|
145
|
+
model: 'fixture-model',
|
|
146
|
+
apiKey: 'fixture-key',
|
|
147
|
+
baseURL,
|
|
148
|
+
options,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function invoke(
|
|
153
|
+
provider: OpenAIProvider,
|
|
154
|
+
form: 'chat' | 'callback' | 'stream',
|
|
155
|
+
options: IChatOptions,
|
|
156
|
+
): Promise<TUniversalMessage[]> {
|
|
157
|
+
if (form !== 'stream') {
|
|
158
|
+
return [
|
|
159
|
+
await provider.chat(messages, {
|
|
160
|
+
...options,
|
|
161
|
+
...(form === 'callback' && { onTextDelta: () => undefined }),
|
|
162
|
+
}),
|
|
163
|
+
];
|
|
164
|
+
}
|
|
165
|
+
const result: TUniversalMessage[] = [];
|
|
166
|
+
for await (const message of provider.chatStream(messages, options)) result.push(message);
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const forms = ['chat', 'callback', 'stream'] as const;
|
|
171
|
+
|
|
172
|
+
describe.each<TOpenAIApiSurface>(['chat-completions', 'responses'])(
|
|
173
|
+
'%s extra body',
|
|
174
|
+
(apiSurface) => {
|
|
175
|
+
it.each(forms)(
|
|
176
|
+
'sends nested fields unchanged next to the parallel policy and a forced tool (%s)',
|
|
177
|
+
async (form) => {
|
|
178
|
+
const provider = new OpenAIProvider({
|
|
179
|
+
...providerOptions(apiSurface),
|
|
180
|
+
parallelToolCalls: false,
|
|
181
|
+
extraBody: { providerOptions: gatewayOptions },
|
|
182
|
+
});
|
|
183
|
+
const observed: unknown[] = [];
|
|
184
|
+
const result = await invoke(provider, form, {
|
|
185
|
+
model: 'fixture-model',
|
|
186
|
+
tools: [tool],
|
|
187
|
+
toolChoice: { tool: tool.name },
|
|
188
|
+
onProviderNativeRawPayload: (event) => {
|
|
189
|
+
if (event.payloadKind === 'request') observed.push(event.payload);
|
|
190
|
+
},
|
|
191
|
+
});
|
|
192
|
+
expect(received).toHaveLength(1);
|
|
193
|
+
const body = received[0];
|
|
194
|
+
expect(body).toMatchObject({
|
|
195
|
+
model: 'fixture-model',
|
|
196
|
+
parallel_tool_calls: false,
|
|
197
|
+
tool_choice:
|
|
198
|
+
apiSurface === 'responses'
|
|
199
|
+
? { type: 'function', name: tool.name }
|
|
200
|
+
: { type: 'function', function: { name: tool.name } },
|
|
201
|
+
providerOptions: gatewayOptions,
|
|
202
|
+
});
|
|
203
|
+
expect(body?.providerOptions).toEqual(gatewayOptions);
|
|
204
|
+
expect(observed).toEqual([body]);
|
|
205
|
+
const assistant = result.find((message) => message.role === 'assistant');
|
|
206
|
+
expect(assistant).toMatchObject({ toolCalls: [call] });
|
|
207
|
+
},
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
it.each(forms)('sends the fields on requests without tools (%s)', async (form) => {
|
|
211
|
+
const provider = new OpenAIProvider({
|
|
212
|
+
...providerOptions(apiSurface),
|
|
213
|
+
extraBody: { providerOptions: gatewayOptions, user: 'fixture-user' },
|
|
214
|
+
});
|
|
215
|
+
await invoke(provider, form, { model: 'fixture-model' });
|
|
216
|
+
expect(received[0]).not.toHaveProperty('tools');
|
|
217
|
+
expect(received[0]).toMatchObject({ providerOptions: gatewayOptions, user: 'fixture-user' });
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it('captures a copy at construction', async () => {
|
|
221
|
+
const upstream = { disableParallelToolUse: true };
|
|
222
|
+
const tags = ['first'];
|
|
223
|
+
const extraBody: Record<string, { anthropic: typeof upstream } | string[]> = {
|
|
224
|
+
providerOptions: { anthropic: upstream },
|
|
225
|
+
tags,
|
|
226
|
+
};
|
|
227
|
+
const options = { ...providerOptions(apiSurface), extraBody };
|
|
228
|
+
const provider = new OpenAIProvider(options);
|
|
229
|
+
upstream.disableParallelToolUse = false;
|
|
230
|
+
tags.push('second');
|
|
231
|
+
extraBody['later'] = ['added'];
|
|
232
|
+
Object.assign(options, { extraBody: { model: 'private-override-model', replaced: true } });
|
|
233
|
+
await provider.chat(messages, { model: 'fixture-model' });
|
|
234
|
+
expect(received[0]).toMatchObject({
|
|
235
|
+
model: 'fixture-model',
|
|
236
|
+
providerOptions: gatewayOptions,
|
|
237
|
+
tags: ['first'],
|
|
238
|
+
});
|
|
239
|
+
expect(received[0]).not.toHaveProperty('later');
|
|
240
|
+
expect(received[0]).not.toHaveProperty('replaced');
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it('reserves every field the provider writes', async () => {
|
|
244
|
+
const provider = new OpenAIProvider({
|
|
245
|
+
...providerOptions(apiSurface),
|
|
246
|
+
parallelToolCalls: false,
|
|
247
|
+
strictTools: true,
|
|
248
|
+
responseFormat: 'json_schema',
|
|
249
|
+
jsonSchema: { name: 'classification', schema: { type: 'object' } },
|
|
250
|
+
...(apiSurface === 'responses' && {
|
|
251
|
+
reasoning: { summary: 'auto' },
|
|
252
|
+
includeEncryptedReasoning: true,
|
|
253
|
+
store: false,
|
|
254
|
+
}),
|
|
255
|
+
});
|
|
256
|
+
for (const form of forms) {
|
|
257
|
+
await invoke(provider, form, {
|
|
258
|
+
model: 'fixture-model',
|
|
259
|
+
tools: [tool],
|
|
260
|
+
toolChoice: 'required',
|
|
261
|
+
temperature: 0,
|
|
262
|
+
maxTokens: 64,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
const written = [...new Set(received.flatMap((body) => Object.keys(body)))];
|
|
266
|
+
expect(written).toEqual(
|
|
267
|
+
expect.arrayContaining(['model', 'tools', 'parallel_tool_calls', 'stream']),
|
|
268
|
+
);
|
|
269
|
+
for (const field of written) {
|
|
270
|
+
expect(
|
|
271
|
+
() =>
|
|
272
|
+
new OpenAIProvider({ ...providerOptions(apiSurface), extraBody: { [field]: null } }),
|
|
273
|
+
).toThrow(`extraBody cannot set the provider-managed field ${field}`);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it('keeps a raw-payload observer from changing later requests', async () => {
|
|
278
|
+
const provider = new OpenAIProvider({
|
|
279
|
+
...providerOptions(apiSurface),
|
|
280
|
+
extraBody: { metadata: { tag: 'captured' } },
|
|
281
|
+
});
|
|
282
|
+
await provider.chat(messages, {
|
|
283
|
+
model: 'fixture-model',
|
|
284
|
+
onProviderNativeRawPayload: (event) => {
|
|
285
|
+
const metadata = isRecord(event.payload) ? event.payload['metadata'] : undefined;
|
|
286
|
+
if (event.payloadKind === 'request' && isRecord(metadata)) metadata['tag'] = 'mutated';
|
|
287
|
+
},
|
|
288
|
+
});
|
|
289
|
+
await provider.chat(messages, { model: 'fixture-model' });
|
|
290
|
+
expect(received[1]).toHaveProperty('metadata', { tag: 'captured' });
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
it('leaves request bodies unchanged when omitted or empty', async () => {
|
|
294
|
+
for (const extraBody of [undefined, {}]) {
|
|
295
|
+
const provider = new OpenAIProvider({ ...providerOptions(apiSurface), extraBody });
|
|
296
|
+
await provider.chat(messages, { model: 'fixture-model', tools: [tool] });
|
|
297
|
+
}
|
|
298
|
+
const baseline = new OpenAIProvider(providerOptions(apiSurface));
|
|
299
|
+
await baseline.chat(messages, { model: 'fixture-model', tools: [tool] });
|
|
300
|
+
expect(received).toHaveLength(3);
|
|
301
|
+
expect(received[0]).toEqual(received[2]);
|
|
302
|
+
expect(received[1]).toEqual(received[2]);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it('forwards a profile extra body', async () => {
|
|
306
|
+
const provider = createProfileProvider(apiSurface, { providerOptions: gatewayOptions });
|
|
307
|
+
await provider.chat(messages, { tools: [tool] });
|
|
308
|
+
expect(received[0]).toHaveProperty('providerOptions', gatewayOptions);
|
|
309
|
+
});
|
|
310
|
+
},
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
describe('extra body boundary', () => {
|
|
314
|
+
const managedFields = [
|
|
315
|
+
'model',
|
|
316
|
+
'messages',
|
|
317
|
+
'input',
|
|
318
|
+
'previous_response_id',
|
|
319
|
+
'conversation',
|
|
320
|
+
'tools',
|
|
321
|
+
'tool_choice',
|
|
322
|
+
'parallel_tool_calls',
|
|
323
|
+
'functions',
|
|
324
|
+
'function_call',
|
|
325
|
+
'web_search_options',
|
|
326
|
+
'stream',
|
|
327
|
+
'stream_options',
|
|
328
|
+
'n',
|
|
329
|
+
'background',
|
|
330
|
+
'modalities',
|
|
331
|
+
'audio',
|
|
332
|
+
'response_format',
|
|
333
|
+
'text',
|
|
334
|
+
'max_tokens',
|
|
335
|
+
'max_completion_tokens',
|
|
336
|
+
'max_output_tokens',
|
|
337
|
+
'temperature',
|
|
338
|
+
'reasoning',
|
|
339
|
+
'reasoning_effort',
|
|
340
|
+
'include',
|
|
341
|
+
'store',
|
|
342
|
+
];
|
|
343
|
+
|
|
344
|
+
it.each(managedFields)('rejects the provider-managed field %s', (field) => {
|
|
345
|
+
const extraBody = { [field]: 'private-override-value' };
|
|
346
|
+
const direct = () => new OpenAIProvider({ ...providerOptions('chat-completions'), extraBody });
|
|
347
|
+
const profile = () => createProfileProvider('chat-completions', extraBody);
|
|
348
|
+
for (const create of [direct, profile]) {
|
|
349
|
+
expect(create).toThrow(`extraBody cannot set the provider-managed field ${field}`);
|
|
350
|
+
expect(create).not.toThrow('private-override-value');
|
|
351
|
+
}
|
|
352
|
+
expect(received).toHaveLength(0);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it.each([
|
|
356
|
+
['null', null],
|
|
357
|
+
['an array', []],
|
|
358
|
+
['a string', 'private-invalid-value'],
|
|
359
|
+
['a number', 1],
|
|
360
|
+
['a Date', new Date(0)],
|
|
361
|
+
['a Map', new Map()],
|
|
362
|
+
['a class instance', new (class Options {})()],
|
|
363
|
+
])('rejects %s as the extra body', (_label, value) => {
|
|
364
|
+
const direct = () => new OpenAIProvider(withRawExtraBody(providerOptions('responses'), value));
|
|
365
|
+
const profile = () => createProfileProvider('responses', value);
|
|
366
|
+
for (const create of [direct, profile]) {
|
|
367
|
+
expect(create).toThrow('extraBody must be a plain JSON object');
|
|
368
|
+
expect(create).not.toThrow('private-invalid-value');
|
|
369
|
+
}
|
|
370
|
+
expect(received).toHaveLength(0);
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
const symbolKeyed = { [Symbol('hidden')]: true };
|
|
374
|
+
const hiddenKeyed = {};
|
|
375
|
+
Object.defineProperty(hiddenKeyed, 'hidden', { value: true, enumerable: false });
|
|
376
|
+
const cyclic: Record<string, unknown> = {};
|
|
377
|
+
cyclic['self'] = cyclic;
|
|
378
|
+
const indexedWithExtra: unknown[] & { extra?: boolean } = [1];
|
|
379
|
+
indexedWithExtra.extra = true;
|
|
380
|
+
// eslint-disable-next-line no-sparse-arrays -- a hole is one of the rejected shapes
|
|
381
|
+
const sparse = [1, , 2];
|
|
382
|
+
it.each([
|
|
383
|
+
['undefined', undefined],
|
|
384
|
+
['a function', () => 'private-invalid-value'],
|
|
385
|
+
['a symbol', Symbol('private-invalid-value')],
|
|
386
|
+
['a bigint', 1n],
|
|
387
|
+
['NaN', Number.NaN],
|
|
388
|
+
['Infinity', Number.POSITIVE_INFINITY],
|
|
389
|
+
['a Date', new Date(0)],
|
|
390
|
+
['a Map', new Map()],
|
|
391
|
+
['a class instance', new (class Options {})()],
|
|
392
|
+
['a sparse array', sparse],
|
|
393
|
+
['an array with an undefined item', [undefined]],
|
|
394
|
+
['an array with extra properties', indexedWithExtra],
|
|
395
|
+
['a symbol key', symbolKeyed],
|
|
396
|
+
['a non-enumerable key', hiddenKeyed],
|
|
397
|
+
['a cycle', cyclic],
|
|
398
|
+
])('rejects nested %s', (_label, value) => {
|
|
399
|
+
const extraBody = { secret: 'private-secret-value', nested: { value } };
|
|
400
|
+
const direct = () =>
|
|
401
|
+
new OpenAIProvider(withRawExtraBody(providerOptions('chat-completions'), extraBody));
|
|
402
|
+
const profile = () => createProfileProvider('chat-completions', extraBody);
|
|
403
|
+
for (const create of [direct, profile]) {
|
|
404
|
+
expect(create).toThrow('extraBody must contain only JSON data');
|
|
405
|
+
expect(create).not.toThrow('private-secret-value');
|
|
406
|
+
expect(create).not.toThrow('private-invalid-value');
|
|
407
|
+
}
|
|
408
|
+
expect(received).toHaveLength(0);
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
it('accepts shared references that are not cycles', async () => {
|
|
412
|
+
const shared = { tag: 'shared' };
|
|
413
|
+
const provider = new OpenAIProvider({
|
|
414
|
+
...providerOptions('chat-completions'),
|
|
415
|
+
extraBody: { first: shared, second: [shared], none: null, count: -1.5 },
|
|
416
|
+
});
|
|
417
|
+
await provider.chat(messages, { model: 'fixture-model' });
|
|
418
|
+
expect(received[0]).toMatchObject({
|
|
419
|
+
first: shared,
|
|
420
|
+
second: [shared],
|
|
421
|
+
none: null,
|
|
422
|
+
count: -1.5,
|
|
423
|
+
});
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
it('sends a __proto__ key as plain data', async () => {
|
|
427
|
+
const parsed: unknown = JSON.parse('{"__proto__":{"polluted":true}}');
|
|
428
|
+
const provider = new OpenAIProvider(
|
|
429
|
+
withRawExtraBody(providerOptions('chat-completions'), parsed),
|
|
430
|
+
);
|
|
431
|
+
await provider.chat(messages, { model: 'fixture-model' });
|
|
432
|
+
expect(Object.getOwnPropertyDescriptor(received[0], '__proto__')?.value).toEqual({
|
|
433
|
+
polluted: true,
|
|
434
|
+
});
|
|
435
|
+
expect(Object.prototype).not.toHaveProperty('polluted');
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
describe('extra body with executors', () => {
|
|
440
|
+
function executor() {
|
|
441
|
+
const message: IAssistantMessage = {
|
|
442
|
+
id: 'executor-fixture',
|
|
443
|
+
role: 'assistant',
|
|
444
|
+
content: 'Invoice classified.',
|
|
445
|
+
state: 'complete',
|
|
446
|
+
timestamp: new Date(0),
|
|
447
|
+
};
|
|
448
|
+
const executeChat = vi.fn(async () => ({ message }));
|
|
449
|
+
const executeChatStream = vi.fn(async function* () {
|
|
450
|
+
yield { kind: 'message' as const, message };
|
|
451
|
+
yield { kind: 'terminal' as const };
|
|
452
|
+
});
|
|
453
|
+
const value: IExecutor = {
|
|
454
|
+
name: 'fixture',
|
|
455
|
+
version: '1',
|
|
456
|
+
executeChat,
|
|
457
|
+
executeChatStream,
|
|
458
|
+
supportsTools: () => true,
|
|
459
|
+
validateConfig: () => true,
|
|
460
|
+
};
|
|
461
|
+
return { value, executeChat, executeChatStream };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
it('rejects constructor injection before the client is read', () => {
|
|
465
|
+
const fixture = executor();
|
|
466
|
+
const options = { executor: fixture.value, extraBody: { providerOptions: gatewayOptions } };
|
|
467
|
+
const client = vi.fn(() => {
|
|
468
|
+
throw new Error('Client must not be read');
|
|
469
|
+
});
|
|
470
|
+
Object.defineProperty(options, 'client', { get: client });
|
|
471
|
+
expect(() => new OpenAIProvider(options)).toThrow('extraBody cannot be used with an executor');
|
|
472
|
+
expect(client).not.toHaveBeenCalled();
|
|
473
|
+
expect(fixture.executeChat).not.toHaveBeenCalled();
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
it('rejects a later configure injection before callbacks or dispatch', async () => {
|
|
477
|
+
const fixture = executor();
|
|
478
|
+
const provider = new OpenAIProvider({
|
|
479
|
+
...providerOptions('chat-completions'),
|
|
480
|
+
extraBody: { providerOptions: gatewayOptions },
|
|
481
|
+
});
|
|
482
|
+
const config = {};
|
|
483
|
+
Object.defineProperty(config, 'executor', { value: fixture.value });
|
|
484
|
+
await provider.configure(config);
|
|
485
|
+
const callback = vi.fn();
|
|
486
|
+
for (const form of forms) {
|
|
487
|
+
await expect(
|
|
488
|
+
invoke(provider, form, {
|
|
489
|
+
model: 'fixture-model',
|
|
490
|
+
onProviderNativeRawPayload: callback,
|
|
491
|
+
onModelEffortOutcome: callback,
|
|
492
|
+
}),
|
|
493
|
+
).rejects.toThrow('extraBody cannot be used with an executor');
|
|
494
|
+
}
|
|
495
|
+
expect(callback).not.toHaveBeenCalled();
|
|
496
|
+
expect(fixture.executeChat).not.toHaveBeenCalled();
|
|
497
|
+
expect(fixture.executeChatStream).not.toHaveBeenCalled();
|
|
498
|
+
expect(received).toHaveLength(0);
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
it('treats an empty extra body as omitted', async () => {
|
|
502
|
+
const fixture = executor();
|
|
503
|
+
const provider = new OpenAIProvider({ executor: fixture.value, extraBody: {} });
|
|
504
|
+
expect(await invoke(provider, 'chat', { model: 'fixture-model' })).toHaveLength(1);
|
|
505
|
+
expect(fixture.executeChat).toHaveBeenCalledTimes(1);
|
|
506
|
+
});
|
|
507
|
+
});
|
|
@@ -24,7 +24,12 @@ const messages: TUniversalMessage[] = [
|
|
|
24
24
|
];
|
|
25
25
|
|
|
26
26
|
function httpError(status: number, type: string): Error {
|
|
27
|
-
return APIError.generate(
|
|
27
|
+
return APIError.generate(
|
|
28
|
+
status,
|
|
29
|
+
{ error: { type, message: `${type} happened` } },
|
|
30
|
+
undefined,
|
|
31
|
+
new Headers(),
|
|
32
|
+
);
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
function providerWith(apiSurface: 'chat-completions' | 'responses', error: Error): OpenAIProvider {
|
|
@@ -101,7 +106,7 @@ describe('OpenAI provider errors', () => {
|
|
|
101
106
|
error: { type: 'invalid_request_error', code: 'model_not_found', message: 'no model' },
|
|
102
107
|
},
|
|
103
108
|
undefined,
|
|
104
|
-
|
|
109
|
+
new Headers(),
|
|
105
110
|
),
|
|
106
111
|
);
|
|
107
112
|
const error = await failure(() => provider.chat(messages, { model: 'gpt-4o' }));
|
|
@@ -132,7 +137,7 @@ describe('OpenAI provider errors', () => {
|
|
|
132
137
|
429,
|
|
133
138
|
{ error: { type: 'rate_limit_exceeded', message: 'slow down' } },
|
|
134
139
|
undefined,
|
|
135
|
-
{ 'retry-after': '12' },
|
|
140
|
+
new Headers({ 'retry-after': '12' }),
|
|
136
141
|
),
|
|
137
142
|
);
|
|
138
143
|
const error = await failure(() => provider.chat(messages, { model: 'gpt-4o' }));
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
toOpenAICompatibleToolChoice,
|
|
5
5
|
} from '@robota-sdk/agent-provider-openai-compatible/shared';
|
|
6
6
|
|
|
7
|
+
import { extraBodyWire } from './extra-body';
|
|
7
8
|
import { convertToOpenAIMessages, convertToOpenAITools } from './message-converter';
|
|
8
9
|
import { buildOpenAIChatResponseFormat, mergeChatResponseFormat } from './openai-request-format';
|
|
9
10
|
import { parallelToolCallsWire } from './parallel-tool-policy';
|
|
@@ -17,7 +18,7 @@ import { assembleOpenAIStream } from './streaming/stream-assembler';
|
|
|
17
18
|
|
|
18
19
|
import type { IPayloadLogger } from './interfaces/payload-logger';
|
|
19
20
|
import type { OpenAIResponseParser } from './parsers/response-parser';
|
|
20
|
-
import type { IOpenAIProviderOptions } from './types';
|
|
21
|
+
import type { IOpenAIProviderOptions, TOpenAIExtraBody } from './types';
|
|
21
22
|
import type { IOpenAILogData } from './types/api-types';
|
|
22
23
|
import type { IChatOptions, TTextDeltaCallback, TUniversalMessage } from '@robota-sdk/agent-core';
|
|
23
24
|
import type OpenAI from 'openai';
|
|
@@ -28,6 +29,7 @@ export interface IOpenAIChatCompletionsOptions {
|
|
|
28
29
|
chatOptions?: IChatOptions;
|
|
29
30
|
providerOptions: IOpenAIProviderOptions;
|
|
30
31
|
parallelToolCalls?: boolean;
|
|
32
|
+
extraBody?: TOpenAIExtraBody;
|
|
31
33
|
payloadLogger?: IPayloadLogger;
|
|
32
34
|
responseParser: OpenAIResponseParser;
|
|
33
35
|
onTextDelta?: TTextDeltaCallback;
|
|
@@ -146,6 +148,7 @@ function buildChatRequestParams(
|
|
|
146
148
|
mergeChatResponseFormat(input.providerOptions, input.chatOptions?.responseFormat),
|
|
147
149
|
);
|
|
148
150
|
return {
|
|
151
|
+
...extraBodyWire(input.extraBody),
|
|
149
152
|
model,
|
|
150
153
|
messages: openaiMessages,
|
|
151
154
|
...(input.chatOptions?.temperature !== undefined && {
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { TOpenAIExtraBody, TOpenAIExtraBodyValue } from './types';
|
|
2
|
+
|
|
3
|
+
// Fields either request builder writes, plus other spellings of the same concerns: overriding one
|
|
4
|
+
// would bypass tool projection, the parallel policy, stream assembly, or the effort-outcome and
|
|
5
|
+
// native-web reports. Also fields that change the response shape the parsers read (one choice, a
|
|
6
|
+
// completed text response) or add server-side history to the full history already sent.
|
|
7
|
+
const PROVIDER_MANAGED_FIELDS: ReadonlySet<string> = new Set([
|
|
8
|
+
'model',
|
|
9
|
+
'messages',
|
|
10
|
+
'input',
|
|
11
|
+
'previous_response_id',
|
|
12
|
+
'conversation',
|
|
13
|
+
'tools',
|
|
14
|
+
'tool_choice',
|
|
15
|
+
'parallel_tool_calls',
|
|
16
|
+
'functions',
|
|
17
|
+
'function_call',
|
|
18
|
+
'web_search_options',
|
|
19
|
+
'stream',
|
|
20
|
+
'stream_options',
|
|
21
|
+
'n',
|
|
22
|
+
'background',
|
|
23
|
+
'modalities',
|
|
24
|
+
'audio',
|
|
25
|
+
'response_format',
|
|
26
|
+
'text',
|
|
27
|
+
'max_tokens',
|
|
28
|
+
'max_completion_tokens',
|
|
29
|
+
'max_output_tokens',
|
|
30
|
+
'temperature',
|
|
31
|
+
'reasoning',
|
|
32
|
+
'reasoning_effort',
|
|
33
|
+
'include',
|
|
34
|
+
'store',
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
export function parseExtraBody(value: unknown): TOpenAIExtraBody | undefined {
|
|
38
|
+
if (value === undefined) return undefined;
|
|
39
|
+
if (!isPlainObject(value)) {
|
|
40
|
+
throw new Error('extraBody must be a plain JSON object');
|
|
41
|
+
}
|
|
42
|
+
const extraBody = copyJsonObject(value, new Set());
|
|
43
|
+
for (const field of Object.keys(extraBody)) {
|
|
44
|
+
if (PROVIDER_MANAGED_FIELDS.has(field)) {
|
|
45
|
+
throw new Error(`extraBody cannot set the provider-managed field ${field}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return Object.keys(extraBody).length === 0 ? undefined : extraBody;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function assertExtraBodyExecutor(
|
|
52
|
+
extraBody: TOpenAIExtraBody | undefined,
|
|
53
|
+
hasExecutor: boolean,
|
|
54
|
+
): void {
|
|
55
|
+
if (extraBody !== undefined && hasExecutor) {
|
|
56
|
+
throw new Error('extraBody cannot be used with an executor');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A fresh copy per request, so a raw-payload observer cannot change later requests. */
|
|
61
|
+
export function extraBodyWire(
|
|
62
|
+
extraBody: TOpenAIExtraBody | undefined,
|
|
63
|
+
): Record<string, TOpenAIExtraBodyValue> {
|
|
64
|
+
return extraBody === undefined ? {} : copyJsonObject(extraBody, new Set());
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isPlainObject(value: unknown): value is object {
|
|
68
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
69
|
+
const prototype: unknown = Object.getPrototypeOf(value);
|
|
70
|
+
return prototype === Object.prototype || prototype === null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Accepts exactly what JSON serialization keeps unchanged; anything it would drop, alter or throw
|
|
74
|
+
// on is rejected instead.
|
|
75
|
+
function copyJsonValue(value: unknown, ancestors: Set<object>): TOpenAIExtraBodyValue {
|
|
76
|
+
if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;
|
|
77
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
78
|
+
if (Array.isArray(value)) return copyJsonArray(value, ancestors);
|
|
79
|
+
if (isPlainObject(value)) return copyJsonObject(value, ancestors);
|
|
80
|
+
throw invalidJsonData();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function copyJsonArray(value: unknown[], ancestors: Set<object>): TOpenAIExtraBodyValue[] {
|
|
84
|
+
enter(value, ancestors);
|
|
85
|
+
if (Object.keys(value).length !== value.length) throw invalidJsonData();
|
|
86
|
+
const copy: TOpenAIExtraBodyValue[] = [];
|
|
87
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
88
|
+
if (!(index in value)) throw invalidJsonData();
|
|
89
|
+
copy.push(copyJsonValue(value[index], ancestors));
|
|
90
|
+
}
|
|
91
|
+
ancestors.delete(value);
|
|
92
|
+
return copy;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function copyJsonObject(
|
|
96
|
+
value: object,
|
|
97
|
+
ancestors: Set<object>,
|
|
98
|
+
): Record<string, TOpenAIExtraBodyValue> {
|
|
99
|
+
enter(value, ancestors);
|
|
100
|
+
const entries = Reflect.ownKeys(value).map((key): [string, TOpenAIExtraBodyValue] => {
|
|
101
|
+
if (typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key)) {
|
|
102
|
+
throw invalidJsonData();
|
|
103
|
+
}
|
|
104
|
+
return [key, copyJsonValue(Reflect.get(value, key), ancestors)];
|
|
105
|
+
});
|
|
106
|
+
ancestors.delete(value);
|
|
107
|
+
// `Object.fromEntries` defines own data properties, so a `__proto__` key stays plain data.
|
|
108
|
+
return Object.fromEntries(entries);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function enter(value: object, ancestors: Set<object>): void {
|
|
112
|
+
if (ancestors.has(value)) throw invalidJsonData();
|
|
113
|
+
ancestors.add(value);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function invalidJsonData(): Error {
|
|
117
|
+
return new Error(
|
|
118
|
+
'extraBody must contain only JSON data: null, booleans, strings, finite numbers, arrays and plain objects',
|
|
119
|
+
);
|
|
120
|
+
}
|