@robota-sdk/agent-provider-openai 3.0.0-beta.97 → 3.0.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.
@@ -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
+ });