@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,398 @@
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' }, note: { type: 'string' } },
25
+ required: ['category'],
26
+ },
27
+ };
28
+ const calls = ['invoice', 'policy'].map((category, index) => ({
29
+ id: `call_${index}`,
30
+ type: 'function',
31
+ function: { name: tool.name, arguments: JSON.stringify({ category }) },
32
+ }));
33
+ const usage = { prompt_tokens: 12, completion_tokens: 6, total_tokens: 18 };
34
+ const completion = {
35
+ id: 'completion-fixture',
36
+ object: 'chat.completion',
37
+ created: 0,
38
+ model: 'fixture-model',
39
+ choices: [
40
+ {
41
+ index: 0,
42
+ message: { role: 'assistant', content: '', tool_calls: calls },
43
+ finish_reason: 'tool_calls',
44
+ },
45
+ ],
46
+ usage,
47
+ };
48
+ const response = {
49
+ id: 'response-fixture',
50
+ object: 'response',
51
+ created_at: 0,
52
+ model: 'fixture-model',
53
+ status: 'completed',
54
+ output: calls.map((call, index) => ({
55
+ type: 'function_call',
56
+ id: `item_${index}`,
57
+ call_id: call.id,
58
+ status: 'completed',
59
+ name: call.function.name,
60
+ arguments: call.function.arguments,
61
+ })),
62
+ usage: { input_tokens: 12, output_tokens: 6, total_tokens: 18 },
63
+ };
64
+ const messages: TUniversalMessage[] = [
65
+ {
66
+ id: 'user-fixture',
67
+ role: 'user',
68
+ content: 'Classify this invoice.',
69
+ state: 'complete',
70
+ timestamp: new Date(0),
71
+ },
72
+ ];
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
+ reply.setHeader('x-request-id', 'request-fixture');
88
+ if (body.stream === true) {
89
+ reply.setHeader('content-type', 'text/event-stream');
90
+ const events = responses
91
+ ? [{ type: 'response.completed', response, sequence_number: 1 }]
92
+ : [
93
+ {
94
+ id: completion.id,
95
+ object: 'chat.completion.chunk',
96
+ created: 0,
97
+ model: 'fixture-model',
98
+ choices: [
99
+ {
100
+ index: 0,
101
+ delta: {
102
+ role: 'assistant',
103
+ content: '',
104
+ tool_calls: calls.map((call, index) => ({ ...call, index })),
105
+ },
106
+ finish_reason: 'tool_calls',
107
+ },
108
+ ],
109
+ usage,
110
+ },
111
+ ];
112
+ reply.end(
113
+ events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') +
114
+ (responses ? '' : 'data: [DONE]\n\n'),
115
+ );
116
+ } else {
117
+ reply.setHeader('content-type', 'application/json');
118
+ reply.end(JSON.stringify(responses ? response : completion));
119
+ }
120
+ });
121
+
122
+ beforeAll(async () => {
123
+ server.listen(0, '127.0.0.1');
124
+ await once(server, 'listening');
125
+ const address = server.address();
126
+ if (!address || typeof address === 'string') throw new Error('Missing fixture address');
127
+ baseURL = `http://127.0.0.1:${address.port}/v1`;
128
+ });
129
+ afterEach(() => {
130
+ received.length = 0;
131
+ });
132
+ afterAll(async () => {
133
+ server.closeAllConnections();
134
+ await new Promise<void>((resolve, reject) => {
135
+ server.close((error) => (error ? reject(error) : resolve()));
136
+ });
137
+ });
138
+
139
+ function providerOptions(apiSurface: TOpenAIApiSurface): IOpenAIProviderOptions {
140
+ return { apiSurface, client: new OpenAI({ apiKey: 'fixture-key', baseURL, maxRetries: 0 }) };
141
+ }
142
+
143
+ async function invoke(
144
+ provider: OpenAIProvider,
145
+ form: 'chat' | 'callback' | 'stream',
146
+ options: IChatOptions,
147
+ ): Promise<TUniversalMessage[]> {
148
+ if (form !== 'stream') {
149
+ return [
150
+ await provider.chat(messages, {
151
+ ...options,
152
+ ...(form === 'callback' && { onTextDelta: () => undefined }),
153
+ }),
154
+ ];
155
+ }
156
+ const result: TUniversalMessage[] = [];
157
+ for await (const message of provider.chatStream(messages, options)) result.push(message);
158
+ return result;
159
+ }
160
+
161
+ describe.each<TOpenAIApiSurface>(['chat-completions', 'responses'])(
162
+ '%s parallel tool policy',
163
+ (apiSurface) => {
164
+ it.each([undefined, false, true])('serializes %s on every invocation form', async (policy) => {
165
+ const provider = new OpenAIProvider({
166
+ ...providerOptions(apiSurface),
167
+ parallelToolCalls: policy,
168
+ });
169
+ const schemaBefore = JSON.stringify(tool);
170
+ for (const form of ['chat', 'callback', 'stream'] as const) {
171
+ const observed: unknown[] = [];
172
+ const result = await invoke(provider, form, {
173
+ model: 'fixture-model',
174
+ tools: [tool],
175
+ toolChoice: 'auto',
176
+ onProviderNativeRawPayload: (event) => {
177
+ if (event.payloadKind === 'request') observed.push(event.payload);
178
+ },
179
+ });
180
+ const body = received.at(-1);
181
+ if (policy === undefined) expect(body).not.toHaveProperty('parallel_tool_calls');
182
+ else expect(body).toHaveProperty('parallel_tool_calls', policy);
183
+ expect(observed).toEqual([body]);
184
+ expect(body).toHaveProperty(
185
+ apiSurface === 'responses' ? 'tools.0.parameters' : 'tools.0.function.parameters',
186
+ tool.parameters,
187
+ );
188
+ const assistant = result.find((message) => message.role === 'assistant');
189
+ expect(assistant).toMatchObject({ toolCalls: calls });
190
+ if (form !== 'stream' || apiSurface === 'responses') {
191
+ expect(assistant).toMatchObject({
192
+ usage: {
193
+ promptTokens: 12,
194
+ completionTokens: 6,
195
+ totalTokens: 18,
196
+ },
197
+ });
198
+ }
199
+ expect(assistant?.metadata).toHaveProperty('providerRequestId', 'request-fixture');
200
+ }
201
+ expect(JSON.stringify(tool)).toBe(schemaBefore);
202
+ expect(received).toHaveLength(3);
203
+ });
204
+
205
+ it.each(['chat', 'callback', 'stream'] as const)(
206
+ 'keeps explicit false with toolChoice none and omits it without tools only on chat completions (%s)',
207
+ async (form) => {
208
+ const provider = new OpenAIProvider({
209
+ ...providerOptions(apiSurface),
210
+ parallelToolCalls: false,
211
+ });
212
+ await invoke(provider, form, { model: 'fixture-model' });
213
+ await invoke(provider, form, {
214
+ model: 'fixture-model',
215
+ tools: [tool],
216
+ toolChoice: 'none',
217
+ });
218
+ expect(received).toHaveLength(2);
219
+ expect(received[0]).not.toHaveProperty('tools');
220
+ if (apiSurface === 'responses') {
221
+ expect(received[0]).toHaveProperty('parallel_tool_calls', false);
222
+ } else {
223
+ expect(received[0]).not.toHaveProperty('parallel_tool_calls');
224
+ }
225
+ expect(received[1]).toMatchObject({ parallel_tool_calls: false, tool_choice: 'none' });
226
+ },
227
+ );
228
+
229
+ it('captures the primitive without freezing the caller options', async () => {
230
+ const options = { ...providerOptions(apiSurface), parallelToolCalls: false };
231
+ const provider = new OpenAIProvider(options);
232
+ options.parallelToolCalls = true;
233
+ options.defaultModel = 'fixture-model';
234
+ await provider.chat(messages, { tools: [tool] });
235
+ expect(received[0]).toMatchObject({ parallel_tool_calls: false, model: 'fixture-model' });
236
+ expect(Object.isFrozen(options)).toBe(false);
237
+ });
238
+
239
+ it.each([undefined, false, true])('preserves profile policy %s on the wire', async (policy) => {
240
+ const provider = createOpenAIProviderDefinition().createProvider({
241
+ name: 'openai',
242
+ model: 'fixture-model',
243
+ apiKey: 'fixture-key',
244
+ baseURL,
245
+ options: { apiSurface, ...(policy !== undefined && { parallelToolCalls: policy }) },
246
+ });
247
+ await provider.chat(messages, { tools: [tool] });
248
+ if (policy === undefined) expect(received[0]).not.toHaveProperty('parallel_tool_calls');
249
+ else expect(received[0]).toHaveProperty('parallel_tool_calls', policy);
250
+ });
251
+ },
252
+ );
253
+
254
+ describe('parallel tool policy boundary', () => {
255
+ it.each([null, 0, 'private-invalid-value', {}, []])('rejects non-boolean policy %j', (value) => {
256
+ const options = providerOptions('responses');
257
+ Object.defineProperty(options, 'parallelToolCalls', { value });
258
+ const direct = () => new OpenAIProvider(options);
259
+ const profile = () =>
260
+ createOpenAIProviderDefinition().createProvider({
261
+ name: 'openai',
262
+ model: 'fixture-model',
263
+ apiKey: 'fixture-key',
264
+ baseURL,
265
+ options: { parallelToolCalls: value },
266
+ });
267
+ for (const create of [direct, profile]) {
268
+ expect(create).toThrow('parallelToolCalls must be a boolean');
269
+ expect(create).not.toThrow('private-invalid-value');
270
+ }
271
+ expect(received).toHaveLength(0);
272
+ });
273
+
274
+ it.each([null, false, 1, 'private-unsupported-surface', {}, []])(
275
+ 'rejects original invalid surface %j before profile fallback',
276
+ (apiSurface) => {
277
+ const options = { ...providerOptions('responses'), parallelToolCalls: false };
278
+ Object.defineProperty(options, 'apiSurface', { value: apiSurface });
279
+ expect(() => new OpenAIProvider(options)).toThrow('supported OpenAI API surface');
280
+ expect(() =>
281
+ createOpenAIProviderDefinition().createProvider({
282
+ name: 'openai',
283
+ model: 'fixture-model',
284
+ apiKey: 'fixture-key',
285
+ baseURL,
286
+ options: { apiSurface, parallelToolCalls: false },
287
+ }),
288
+ ).toThrow('supported OpenAI API surface');
289
+ expect(received).toHaveLength(0);
290
+ },
291
+ );
292
+
293
+ it('retains legacy profile surface fallback when policy is omitted', async () => {
294
+ const provider = createOpenAIProviderDefinition().createProvider({
295
+ name: 'openai',
296
+ apiKey: 'fixture-key',
297
+ model: 'fixture-model',
298
+ baseURL,
299
+ options: { apiSurface: 'legacy-invalid-surface' },
300
+ });
301
+ await provider.chat(messages);
302
+ expect(received[0]).toHaveProperty('messages');
303
+ expect(received[0]).not.toHaveProperty('parallel_tool_calls');
304
+ });
305
+ });
306
+
307
+ describe('opaque executors', () => {
308
+ async function configureExecutor(provider: OpenAIProvider, executor: IExecutor) {
309
+ const config = {};
310
+ Object.defineProperty(config, 'executor', { value: executor });
311
+ await provider.configure(config);
312
+ }
313
+
314
+ function executor() {
315
+ const message: IAssistantMessage = {
316
+ id: 'executor-fixture',
317
+ role: 'assistant',
318
+ content: 'Invoice classified.',
319
+ state: 'complete',
320
+ timestamp: new Date(0),
321
+ };
322
+ const executeChat = vi.fn(async () => ({ message }));
323
+ const executeChatStream = vi.fn(async function* () {
324
+ yield { kind: 'message' as const, message };
325
+ yield { kind: 'terminal' as const };
326
+ });
327
+ const value: IExecutor = {
328
+ name: 'fixture',
329
+ version: '1',
330
+ executeChat,
331
+ executeChatStream,
332
+ supportsTools: () => true,
333
+ validateConfig: () => true,
334
+ };
335
+ return { value, executeChat, executeChatStream };
336
+ }
337
+
338
+ it.each([false, true])(
339
+ 'rejects constructor policy %s before client or executor dispatch',
340
+ (policy) => {
341
+ const fixture = executor();
342
+ const options = { executor: fixture.value, parallelToolCalls: policy };
343
+ const client = vi.fn(() => {
344
+ throw new Error('Client must not be read');
345
+ });
346
+ Object.defineProperty(options, 'client', { get: client });
347
+ expect(() => new OpenAIProvider(options)).toThrow(
348
+ 'parallelToolCalls cannot be used with an executor',
349
+ );
350
+ expect(client).not.toHaveBeenCalled();
351
+ expect(fixture.executeChat).not.toHaveBeenCalled();
352
+ expect(received).toHaveLength(0);
353
+ },
354
+ );
355
+
356
+ it.each([false, true])(
357
+ 'rejects policy %s after late configure injection before callbacks',
358
+ async (policy) => {
359
+ const fixture = executor();
360
+ const provider = new OpenAIProvider({
361
+ ...providerOptions('responses'),
362
+ parallelToolCalls: policy,
363
+ });
364
+ await configureExecutor(provider, fixture.value);
365
+ const callback = vi.fn();
366
+ for (const form of ['chat', 'callback', 'stream'] as const) {
367
+ await expect(
368
+ invoke(provider, form, {
369
+ model: 'fixture-model',
370
+ onProviderNativeRawPayload: callback,
371
+ onModelEffortOutcome: callback,
372
+ }),
373
+ ).rejects.toThrow('parallelToolCalls cannot be used with an executor');
374
+ }
375
+ expect(callback).not.toHaveBeenCalled();
376
+ expect(fixture.executeChat).not.toHaveBeenCalled();
377
+ expect(fixture.executeChatStream).not.toHaveBeenCalled();
378
+ expect(received).toHaveLength(0);
379
+ },
380
+ );
381
+
382
+ it.each(['constructor', 'configure'])(
383
+ 'preserves omitted policy with %s executor injection',
384
+ async (injection) => {
385
+ const fixture = executor();
386
+ const provider = new OpenAIProvider(
387
+ injection === 'constructor' ? { executor: fixture.value } : providerOptions('responses'),
388
+ );
389
+ if (injection === 'configure') await configureExecutor(provider, fixture.value);
390
+ for (const form of ['chat', 'callback', 'stream'] as const) {
391
+ expect(await invoke(provider, form, { model: 'fixture-model' })).toHaveLength(1);
392
+ }
393
+ expect(fixture.executeChat).toHaveBeenCalledTimes(2);
394
+ expect(fixture.executeChatStream).toHaveBeenCalledTimes(1);
395
+ expect(received).toHaveLength(0);
396
+ },
397
+ );
398
+ });
@@ -24,7 +24,12 @@ const messages: TUniversalMessage[] = [
24
24
  ];
25
25
 
26
26
  function httpError(status: number, type: string): Error {
27
- return APIError.generate(status, { error: { type, message: `${type} happened` } }, undefined, {});
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,8 +4,10 @@ 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';
10
+ import { parallelToolCallsWire } from './parallel-tool-policy';
9
11
  import {
10
12
  awaitWithProviderRequestId,
11
13
  readOpenAIRequestId,
@@ -16,7 +18,7 @@ import { assembleOpenAIStream } from './streaming/stream-assembler';
16
18
 
17
19
  import type { IPayloadLogger } from './interfaces/payload-logger';
18
20
  import type { OpenAIResponseParser } from './parsers/response-parser';
19
- import type { IOpenAIProviderOptions } from './types';
21
+ import type { IOpenAIProviderOptions, TOpenAIExtraBody } from './types';
20
22
  import type { IOpenAILogData } from './types/api-types';
21
23
  import type { IChatOptions, TTextDeltaCallback, TUniversalMessage } from '@robota-sdk/agent-core';
22
24
  import type OpenAI from 'openai';
@@ -26,6 +28,8 @@ export interface IOpenAIChatCompletionsOptions {
26
28
  messages: TUniversalMessage[];
27
29
  chatOptions?: IChatOptions;
28
30
  providerOptions: IOpenAIProviderOptions;
31
+ parallelToolCalls?: boolean;
32
+ extraBody?: TOpenAIExtraBody;
29
33
  payloadLogger?: IPayloadLogger;
30
34
  responseParser: OpenAIResponseParser;
31
35
  onTextDelta?: TTextDeltaCallback;
@@ -144,15 +148,18 @@ function buildChatRequestParams(
144
148
  mergeChatResponseFormat(input.providerOptions, input.chatOptions?.responseFormat),
145
149
  );
146
150
  return {
151
+ ...extraBodyWire(input.extraBody),
147
152
  model,
148
153
  messages: openaiMessages,
149
154
  ...(input.chatOptions?.temperature !== undefined && {
150
155
  temperature: input.chatOptions.temperature,
151
156
  }),
152
157
  ...(input.chatOptions?.maxTokens !== undefined && { max_tokens: input.chatOptions.maxTokens }),
158
+ // The policy only constrains tool calls; Chat Completions may reject it without `tools`.
153
159
  ...(input.chatOptions?.tools && {
154
160
  tools: convertToOpenAITools(input.chatOptions.tools, input.providerOptions.strictTools),
155
161
  tool_choice: toOpenAICompatibleToolChoice(input.chatOptions.toolChoice),
162
+ ...parallelToolCallsWire(input.parallelToolCalls),
156
163
  }),
157
164
  ...(responseFormat !== undefined && { response_format: responseFormat }),
158
165
  } as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming;
@@ -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
+ }
@@ -0,0 +1,25 @@
1
+ export function parseParallelToolCalls(value: unknown, apiSurface: unknown): boolean | undefined {
2
+ if (value === undefined) return undefined;
3
+ if (typeof value !== 'boolean') {
4
+ throw new Error('parallelToolCalls must be a boolean');
5
+ }
6
+ if (apiSurface !== undefined && apiSurface !== 'chat-completions' && apiSurface !== 'responses') {
7
+ throw new Error('parallelToolCalls requires a supported OpenAI API surface');
8
+ }
9
+ return value;
10
+ }
11
+
12
+ export function assertParallelToolCallsExecutor(
13
+ policy: boolean | undefined,
14
+ hasExecutor: boolean,
15
+ ): void {
16
+ if (policy !== undefined && hasExecutor) {
17
+ throw new Error('parallelToolCalls cannot be used with an executor');
18
+ }
19
+ }
20
+
21
+ export function parallelToolCallsWire(policy: boolean | undefined): {
22
+ parallel_tool_calls?: boolean;
23
+ } {
24
+ return policy === undefined ? {} : { parallel_tool_calls: policy };
25
+ }
@@ -1,6 +1,8 @@
1
1
  import { probeOpenAICompatibleProfile } from '@robota-sdk/agent-provider-openai-compatible/shared';
2
2
 
3
+ import { parseExtraBody } from './extra-body';
3
4
  import { OpenAIProvider } from './provider';
5
+ import { parseParallelToolCalls } from './parallel-tool-policy';
4
6
 
5
7
  import type { IOpenAINativeWebToolsOptions, TOpenAIApiSurface } from './types';
6
8
  import type { IProviderDefinition, TUniversalValue } from '@robota-sdk/agent-core';
@@ -59,6 +61,11 @@ export function createOpenAIProviderDefinition(): IProviderDefinition {
59
61
  // organization and project the others name.
60
62
  destinationEnvironment: ['OPENAI_BASE_URL', 'OPENAI_ORG_ID', 'OPENAI_PROJECT_ID'],
61
63
  createProvider: (config) => {
64
+ const parallelToolCalls = parseParallelToolCalls(
65
+ config.options?.parallelToolCalls,
66
+ config.options?.apiSurface,
67
+ );
68
+ const extraBody = parseExtraBody(config.options?.extraBody);
62
69
  const apiSurface = readApiSurface(config.options);
63
70
  const nativeWebTools = readNativeWebTools(config.options);
64
71
  validateOpenAINativeWebTools(config.baseURL, apiSurface, nativeWebTools);
@@ -67,6 +74,8 @@ export function createOpenAIProviderDefinition(): IProviderDefinition {
67
74
  ...(config.baseURL !== undefined && { baseURL: config.baseURL }),
68
75
  ...(config.timeout !== undefined && { timeout: config.timeout }),
69
76
  ...(apiSurface !== undefined && { apiSurface }),
77
+ ...(parallelToolCalls !== undefined && { parallelToolCalls }),
78
+ ...(extraBody !== undefined && { extraBody }),
70
79
  ...(nativeWebTools !== undefined && { nativeWebTools }),
71
80
  ...(config.options?.durableOperations === true && { durableOperations: true }),
72
81
  defaultModel: config.model,