@theia/ai-openai 1.77.0-next.95 → 1.77.0

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.
Files changed (108) hide show
  1. package/lib/browser/openai-frontend-application-contribution.d.ts +1 -1
  2. package/lib/browser/openai-frontend-application-contribution.d.ts.map +1 -1
  3. package/lib/browser/openai-frontend-application-contribution.js +55 -60
  4. package/lib/browser/openai-frontend-application-contribution.js.map +1 -1
  5. package/lib/browser/openai-frontend-application-contribution.spec.js +13 -15
  6. package/lib/browser/openai-frontend-application-contribution.spec.js.map +1 -1
  7. package/lib/browser/openai-frontend-module.js +13 -15
  8. package/lib/browser/openai-frontend-module.js.map +1 -1
  9. package/lib/common/index.d.ts +1 -1
  10. package/lib/common/index.d.ts.map +1 -1
  11. package/lib/common/index.js +1 -4
  12. package/lib/common/index.js.map +1 -1
  13. package/lib/common/openai-language-models-manager.js +3 -6
  14. package/lib/common/openai-language-models-manager.js.map +1 -1
  15. package/lib/common/openai-preferences.js +52 -55
  16. package/lib/common/openai-preferences.js.map +1 -1
  17. package/lib/node/openai-backend-module.d.ts.map +1 -1
  18. package/lib/node/openai-backend-module.js +31 -31
  19. package/lib/node/openai-backend-module.js.map +1 -1
  20. package/lib/node/openai-chat-completion-stream.d.ts +6 -9
  21. package/lib/node/openai-chat-completion-stream.d.ts.map +1 -1
  22. package/lib/node/openai-chat-completion-stream.js +34 -43
  23. package/lib/node/openai-chat-completion-stream.js.map +1 -1
  24. package/lib/node/openai-chat-completion-stream.spec.js +159 -76
  25. package/lib/node/openai-chat-completion-stream.spec.js.map +1 -1
  26. package/lib/node/openai-language-model.d.ts +4 -3
  27. package/lib/node/openai-language-model.d.ts.map +1 -1
  28. package/lib/node/openai-language-model.js +68 -76
  29. package/lib/node/openai-language-model.js.map +1 -1
  30. package/lib/node/openai-language-model.spec.js +137 -75
  31. package/lib/node/openai-language-model.spec.js.map +1 -1
  32. package/lib/node/openai-language-models-manager-impl.d.ts +3 -3
  33. package/lib/node/openai-language-models-manager-impl.d.ts.map +1 -1
  34. package/lib/node/openai-language-models-manager-impl.js +29 -36
  35. package/lib/node/openai-language-models-manager-impl.js.map +1 -1
  36. package/lib/node/openai-language-models-manager-impl.spec.js +34 -36
  37. package/lib/node/openai-language-models-manager-impl.spec.js.map +1 -1
  38. package/lib/node/openai-model-defaults.d.ts +1 -1
  39. package/lib/node/openai-model-defaults.d.ts.map +1 -1
  40. package/lib/node/openai-model-defaults.js +1 -4
  41. package/lib/node/openai-model-defaults.js.map +1 -1
  42. package/lib/node/openai-model-defaults.spec.js +52 -54
  43. package/lib/node/openai-model-defaults.spec.js.map +1 -1
  44. package/lib/node/openai-model-utils.d.ts +1 -1
  45. package/lib/node/openai-model-utils.d.ts.map +1 -1
  46. package/lib/node/openai-model-utils.js +14 -17
  47. package/lib/node/openai-model-utils.js.map +1 -1
  48. package/lib/node/openai-model-utils.spec.js +45 -47
  49. package/lib/node/openai-model-utils.spec.js.map +1 -1
  50. package/lib/node/openai-reasoning.js +1 -4
  51. package/lib/node/openai-reasoning.js.map +1 -1
  52. package/lib/node/openai-request-settings.js +9 -13
  53. package/lib/node/openai-request-settings.js.map +1 -1
  54. package/lib/node/openai-response-api-utils.d.ts +5 -3
  55. package/lib/node/openai-response-api-utils.d.ts.map +1 -1
  56. package/lib/node/openai-response-api-utils.js +84 -70
  57. package/lib/node/openai-response-api-utils.js.map +1 -1
  58. package/lib/node/openai-response-api-utils.spec.js +320 -166
  59. package/lib/node/openai-response-api-utils.spec.js.map +1 -1
  60. package/lib/node/openai-server-tools.js +4 -7
  61. package/lib/node/openai-server-tools.js.map +1 -1
  62. package/lib/node/openai-streaming-iterator.d.ts +2 -1
  63. package/lib/node/openai-streaming-iterator.d.ts.map +1 -1
  64. package/lib/node/openai-streaming-iterator.js +5 -8
  65. package/lib/node/openai-streaming-iterator.js.map +1 -1
  66. package/lib/node/openai-streaming-iterator.spec.js +37 -40
  67. package/lib/node/openai-streaming-iterator.spec.js.map +1 -1
  68. package/lib/node/openai-streaming-retry.d.ts +8 -0
  69. package/lib/node/openai-streaming-retry.d.ts.map +1 -0
  70. package/lib/node/openai-streaming-retry.js +108 -0
  71. package/lib/node/openai-streaming-retry.js.map +1 -0
  72. package/lib/node/openai-streaming-retry.spec.d.ts +2 -0
  73. package/lib/node/openai-streaming-retry.spec.d.ts.map +1 -0
  74. package/lib/node/openai-streaming-retry.spec.js +182 -0
  75. package/lib/node/openai-streaming-retry.spec.js.map +1 -0
  76. package/lib/node/streaming-response-iterator.js +5 -9
  77. package/lib/node/streaming-response-iterator.js.map +1 -1
  78. package/lib/node/streaming-response-iterator.spec.js +6 -8
  79. package/lib/node/streaming-response-iterator.spec.js.map +1 -1
  80. package/package.json +16 -7
  81. package/src/browser/openai-frontend-application-contribution.spec.ts +3 -3
  82. package/src/browser/openai-frontend-application-contribution.ts +2 -2
  83. package/src/browser/openai-frontend-module.ts +3 -3
  84. package/src/common/index.ts +1 -1
  85. package/src/node/openai-backend-module.ts +9 -7
  86. package/src/node/openai-chat-completion-stream.spec.ts +88 -3
  87. package/src/node/openai-chat-completion-stream.ts +20 -15
  88. package/src/node/openai-language-model.spec.ts +84 -7
  89. package/src/node/openai-language-model.ts +37 -32
  90. package/src/node/openai-language-models-manager-impl.spec.ts +3 -3
  91. package/src/node/openai-language-models-manager-impl.ts +4 -4
  92. package/src/node/openai-model-defaults.spec.ts +1 -1
  93. package/src/node/openai-model-defaults.ts +1 -1
  94. package/src/node/openai-model-utils.spec.ts +2 -2
  95. package/src/node/openai-model-utils.ts +2 -2
  96. package/src/node/openai-request-settings.ts +1 -1
  97. package/src/node/openai-response-api-utils.spec.ts +180 -27
  98. package/src/node/openai-response-api-utils.ts +45 -21
  99. package/src/node/openai-streaming-iterator.spec.ts +1 -1
  100. package/src/node/openai-streaming-iterator.ts +2 -1
  101. package/src/node/openai-streaming-retry.spec.ts +195 -0
  102. package/src/node/openai-streaming-retry.ts +110 -0
  103. package/src/node/streaming-response-iterator.spec.ts +1 -1
  104. package/lib/node/openai-request-api-context.d.ts +0 -4
  105. package/lib/node/openai-request-api-context.d.ts.map +0 -1
  106. package/lib/node/openai-request-api-context.js +0 -19
  107. package/lib/node/openai-request-api-context.js.map +0 -1
  108. package/src/node/openai-request-api-context.ts +0 -23
@@ -35,14 +35,15 @@ import {
35
35
  ToolRequest,
36
36
  UserRequest
37
37
  } from '@theia/ai-core';
38
- import { ChatCompletionStreamingAsyncIterator, ChatCompletionToolLoopOptions } from './openai-chat-completion-stream';
38
+ import { ChatCompletionStreamingAsyncIterator, ChatCompletionToolLoopOptions } from './openai-chat-completion-stream.js';
39
+ import { OpenAiStreamingRetry } from './openai-streaming-retry.js';
39
40
 
40
41
  /* eslint-disable @typescript-eslint/no-explicit-any */
41
42
 
42
43
  /** A fake of the OpenAI chat-completion stream: async-iterable over chunks and an abortable controller. */
43
44
  class FakeStream {
44
45
  readonly controller = { abort: sinon.spy() } as unknown as AbortController;
45
- constructor(protected readonly chunks: any[], protected readonly gate?: Promise<void>) { }
46
+ constructor(protected readonly chunks: any[], protected readonly gate?: Promise<void>, protected readonly error?: Error) { }
46
47
  async *[Symbol.asyncIterator](): AsyncIterator<any> {
47
48
  if (this.gate) {
48
49
  await this.gate;
@@ -50,6 +51,9 @@ class FakeStream {
50
51
  for (const chunk of this.chunks) {
51
52
  yield chunk;
52
53
  }
54
+ if (this.error) {
55
+ throw this.error;
56
+ }
53
57
  }
54
58
  }
55
59
 
@@ -136,7 +140,7 @@ function makeIterator(
136
140
  request: overrides.request ?? defaultRequest,
137
141
  messages: overrides.messages ?? [{ role: 'user', content: 'hi' }],
138
142
  settings: overrides.settings ?? {},
139
- tools: overrides.tools ?? [{ type: 'function', function: { name: 'a' } } as any],
143
+ tools: 'tools' in overrides ? overrides.tools : [{ type: 'function', function: { name: 'a' } } as any],
140
144
  maxRetries: overrides.maxRetries ?? 0,
141
145
  cancellationToken: overrides.cancellationToken
142
146
  };
@@ -144,6 +148,7 @@ function makeIterator(
144
148
  container.bind(ILogger).to(MockLogger);
145
149
  container.bind(ToolCallExecutor).toConstantValue(toolCallExecutor);
146
150
  container.bind(ChatCompletionToolLoopOptions).toConstantValue(options);
151
+ container.bind(OpenAiStreamingRetry).toSelf();
147
152
  container.bind(ChatCompletionStreamingAsyncIterator).toSelf();
148
153
  return container.get(ChatCompletionStreamingAsyncIterator);
149
154
  }
@@ -201,6 +206,86 @@ describe('ChatCompletionStreamingAsyncIterator', () => {
201
206
  expect(openai.calls).to.have.lengthOf(1);
202
207
  });
203
208
 
209
+ for (const withTools of [false, true]) {
210
+ it(`quietly retries a busy stream after an empty initial chunk ${withTools ? 'with tools' : 'without tools'}`, async () => {
211
+ const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
212
+ try {
213
+ const busy = Object.assign(new Error('Model too busy'), { code: 'server_error' });
214
+ const openai = fakeOpenAi([
215
+ new FakeStream([{ choices: [{ delta: JSON.parse('{"role":"assistant","content":"","refusal":null}') }] }], undefined, busy),
216
+ new FakeStream([textChunk('success')])
217
+ ]);
218
+ const settled = collectUntilSettled(makeIterator(openai, {
219
+ maxRetries: 1,
220
+ tools: withTools ? [{ type: 'function', function: { name: 'a' } } as any] : undefined
221
+ }));
222
+ await clock.tickAsync(1000);
223
+ const { parts, error } = await settled;
224
+ expect(error).to.equal(undefined);
225
+ expect(parts).to.deep.equal([{ content: 'success' }]);
226
+ expect(openai.calls).to.have.lengthOf(2);
227
+ if (!withTools) {
228
+ for (const body of openai.calls) {
229
+ const wireBody = JSON.parse(JSON.stringify(body));
230
+ expect(wireBody).not.to.have.property('tools');
231
+ expect(wireBody).not.to.have.property('tool_choice');
232
+ }
233
+ }
234
+ } finally {
235
+ clock.restore();
236
+ }
237
+ });
238
+ }
239
+
240
+ for (const [name, chunk] of [
241
+ ['text', textChunk('partial')],
242
+ ['reasoning', { choices: [{ delta: { reasoning_content: 'thinking' } }] }],
243
+ ['refusal', { choices: [{ delta: { refusal: 'Cannot comply' } }] }],
244
+ ['tool ID', toolIdOnlyChunk(0, 'call-a')],
245
+ ['tool arguments', toolChunk(0, 'call-a', 'a', '{')]
246
+ ] as const) {
247
+ it(`does not retry a busy stream after a ${name} delta`, async () => {
248
+ const busy = Object.assign(new Error('Model too busy'), { code: 'server_error' });
249
+ const openai = fakeOpenAi([new FakeStream([chunk], undefined, busy), new FakeStream([textChunk('unexpected')])]);
250
+ const handler = sinon.stub().resolves('a-result');
251
+ const request: UserRequest = {
252
+ sessionId: 'session', requestId: 'request', messages: [], tools: [toolRequest('a', handler)]
253
+ };
254
+ const { error } = await collectUntilSettled(makeIterator(openai, { request, maxRetries: 1 }));
255
+ expect(error).to.equal(busy);
256
+ expect(openai.calls).to.have.lengthOf(1);
257
+ expect(handler.called).to.equal(false);
258
+ });
259
+ }
260
+
261
+ it('does not execute completed tools again when retrying a later busy turn', async () => {
262
+ const clock = sinon.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
263
+ try {
264
+ const handler = sinon.stub().resolves('a-result');
265
+ const request: UserRequest = {
266
+ sessionId: 'session', requestId: 'request', messages: [], tools: [toolRequest('a', handler)]
267
+ };
268
+ const busy = Object.assign(new Error('Model too busy'), { code: 'server_error' });
269
+ const openai = fakeOpenAi([
270
+ new FakeStream([toolChunk(0, 'call-a', 'a', '{}')]),
271
+ new FakeStream([{ choices: [{ delta: JSON.parse('{"role":"assistant","content":"","refusal":null}') }] }], undefined, busy),
272
+ new FakeStream([textChunk('done')])
273
+ ]);
274
+ const settled = collectUntilSettled(makeIterator(openai, { request, maxRetries: 1 }));
275
+ await clock.tickAsync(1000);
276
+ const { parts, error } = await settled;
277
+ expect(error).to.equal(undefined);
278
+ expect(handler.callCount).to.equal(1);
279
+ expect(openai.calls).to.have.lengthOf(3);
280
+ expect(openai.calls[2].messages.filter((message: any) => message.role === 'tool'))
281
+ .to.deep.equal([{ role: 'tool', tool_call_id: 'call-a', content: 'a-result' }]);
282
+ expect(parts.filter(isToolCallResponsePart).flatMap(part => part.tool_calls).filter(call => call.finished)).to.have.lengthOf(1);
283
+ expect(parts.filter(isTextResponsePart)).to.deep.equal([{ content: 'done' }]);
284
+ } finally {
285
+ clock.restore();
286
+ }
287
+ });
288
+
204
289
  it('emits token usage parts', async () => {
205
290
  const openai = fakeOpenAi([new FakeStream([textChunk('hi'), usageChunk(10, 4)])]);
206
291
  const parts = await drain(makeIterator(openai));
@@ -15,10 +15,11 @@
15
15
  // *****************************************************************************
16
16
 
17
17
  import { formatToolCallContentForModel, ToolCallExecutor, ToolCallResult, UserRequest } from '@theia/ai-core';
18
- import { CancellationError, CancellationToken, Disposable, ILogger } from '@theia/core';
18
+ import { CancellationError, CancellationToken, CancellationTokenSource, ILogger } from '@theia/core';
19
19
  import { inject, injectable, named, postConstruct } from '@theia/core/shared/inversify';
20
20
  import { OpenAI } from 'openai';
21
- import { AbstractStreamingResponseIterator } from './streaming-response-iterator';
21
+ import { AbstractStreamingResponseIterator } from './streaming-response-iterator.js';
22
+ import { OpenAiStreamingRetry } from './openai-streaming-retry.js';
22
23
  import {
23
24
  ChatCompletionAssistantMessageParam,
24
25
  ChatCompletionChunk,
@@ -51,7 +52,7 @@ export interface ChatCompletionToolLoopOptions {
51
52
  readonly messages: ChatCompletionMessageParam[];
52
53
  /** Additional request settings (may include `stream_options`, temperature, etc.). */
53
54
  readonly settings: Record<string, unknown>;
54
- readonly tools: ChatCompletionTool[];
55
+ readonly tools?: ChatCompletionTool[];
55
56
  readonly maxRetries: number;
56
57
  readonly cancellationToken?: CancellationToken;
57
58
  }
@@ -70,12 +71,7 @@ export class ChatCompletionStreamingAsyncIterator extends AbstractStreamingRespo
70
71
 
71
72
  protected messages: ChatCompletionMessageParam[];
72
73
 
73
- /**
74
- * Aborts the provider request. Its signal is handed to every `create()` call, so that it covers the
75
- * request while it is still in flight just as well as the chunk stream that it eventually yields.
76
- * The OpenAI SDK forwards the abort to the stream's own controller.
77
- */
78
- protected readonly abortController = new AbortController();
74
+ protected readonly streamCancellation = new CancellationTokenSource();
79
75
 
80
76
  @inject(ChatCompletionToolLoopOptions)
81
77
  protected readonly options: ChatCompletionToolLoopOptions;
@@ -83,6 +79,9 @@ export class ChatCompletionStreamingAsyncIterator extends AbstractStreamingRespo
83
79
  @inject(ToolCallExecutor)
84
80
  protected readonly toolCallExecutor: ToolCallExecutor;
85
81
 
82
+ @inject(OpenAiStreamingRetry)
83
+ protected readonly streamingRetry: OpenAiStreamingRetry;
84
+
86
85
  @inject(ILogger) @named('ai-openai:ChatCompletionStreamingAsyncIterator')
87
86
  protected readonly logger: ILogger;
88
87
 
@@ -91,7 +90,7 @@ export class ChatCompletionStreamingAsyncIterator extends AbstractStreamingRespo
91
90
  this.messages = [...this.options.messages];
92
91
  // Abort the provider request whenever the iterator terminates, including when the consumer
93
92
  // abandons it (`return()`), so that we never leave a request running for nobody.
94
- this.toDispose.push(Disposable.create(() => this.abortController.abort()));
93
+ this.toDispose.push(this.streamCancellation);
95
94
  if (this.options.cancellationToken) {
96
95
  this.toDispose.push(this.options.cancellationToken.onCancellationRequested(() => this.cancel()));
97
96
  }
@@ -159,13 +158,19 @@ export class ChatCompletionStreamingAsyncIterator extends AbstractStreamingRespo
159
158
  messages: this.messages,
160
159
  stream: true,
161
160
  tools: this.options.tools,
162
- tool_choice: 'auto',
161
+ tool_choice: this.options.tools?.length ? 'auto' : undefined,
163
162
  ...this.options.settings
164
163
  } as ChatCompletionCreateParamsStreaming;
165
- const stream = await this.options.openai.chat.completions.create(body, {
166
- maxRetries: this.options.maxRetries,
167
- signal: this.abortController.signal
168
- }) as unknown as ChatCompletionChunkStream;
164
+ const stream = this.streamingRetry.retry(
165
+ async signal => await this.options.openai.chat.completions.create(body, {
166
+ maxRetries: this.options.maxRetries,
167
+ signal
168
+ }) as unknown as ChatCompletionChunkStream,
169
+ this.options.maxRetries,
170
+ chunk => !chunk.usage && chunk.choices.every(choice => !choice.finish_reason
171
+ && Object.entries(choice.delta ?? {}).every(([key, value]) => key === 'role' || (value ?? '') === '')),
172
+ this.streamCancellation.token
173
+ );
169
174
 
170
175
  for await (const chunk of stream) {
171
176
  if (this.done || this.cancellationRequested) {
@@ -19,13 +19,14 @@ import { Container, injectable } from '@theia/core/shared/inversify';
19
19
  import { ILogger } from '@theia/core';
20
20
  import { MockLogger } from '@theia/core/lib/common/test/mock-logger';
21
21
  import { LanguageModelRequest, LanguageModelResponse, ReasoningSupport, ToolCallExecutor, ToolCallExecutorImpl, UserRequest } from '@theia/ai-core';
22
- import { OpenAI } from 'openai';
23
- import { MistralFixedOpenAI, OpenAiModel, OpenAiModelParams } from './openai-language-model';
24
- import { OpenAiModelUtils } from './openai-model-utils';
25
- import { OpenAiResponseApiUtils } from './openai-response-api-utils';
26
- import { ChatCompletionStreamingAsyncIteratorFactory } from './openai-chat-completion-stream';
27
- import { getOpenAiModelDefaults } from './openai-model-defaults';
28
- import { OPENAI_WEB_SEARCH } from './openai-server-tools';
22
+ import { AzureOpenAI, OpenAI } from 'openai';
23
+ import { createOpenAiClient, MistralFixedOpenAI, OpenAiClientOptions, OpenAiModel, OpenAiModelParams } from './openai-language-model.js';
24
+ import { OpenAiModelUtils } from './openai-model-utils.js';
25
+ import { OpenAiResponseApiUtils } from './openai-response-api-utils.js';
26
+ import { OpenAiStreamingRetry } from './openai-streaming-retry.js';
27
+ import { ChatCompletionStreamingAsyncIteratorFactory } from './openai-chat-completion-stream.js';
28
+ import { getOpenAiModelDefaults } from './openai-model-defaults.js';
29
+ import { OPENAI_WEB_SEARCH } from './openai-server-tools.js';
29
30
 
30
31
  const LEGACY_GPT5_REASONING_SUPPORT: ReasoningSupport = {
31
32
  supportedLevels: ['off', 'minimal', 'low', 'medium', 'high', 'auto'],
@@ -41,6 +42,10 @@ const O_SERIES_REASONING_SUPPORT: ReasoningSupport = {
41
42
  class TestableOpenAiModel extends OpenAiModel {
42
43
  chatCompletionsRequests = 0;
43
44
 
45
+ public callInitializeOpenAi(): OpenAI {
46
+ return this.initializeOpenAi();
47
+ }
48
+
44
49
  public callGetSettings(request: LanguageModelRequest, forResponseApi: boolean = false): Record<string, unknown> {
45
50
  return this.getSettings(request, forResponseApi);
46
51
  }
@@ -66,6 +71,7 @@ function buildModel<T extends OpenAiModel>(
66
71
  ): T {
67
72
  const parent = new Container();
68
73
  parent.bind(OpenAiModelUtils).toSelf();
74
+ parent.bind(OpenAiStreamingRetry).toSelf();
69
75
  if (responseApiUtils) {
70
76
  parent.bind(OpenAiResponseApiUtils).toConstantValue(responseApiUtils);
71
77
  } else {
@@ -112,6 +118,30 @@ function createCompactionModel(
112
118
  });
113
119
  }
114
120
 
121
+ describe('OpenAI client retry configuration', () => {
122
+ for (const azure of [false, true]) {
123
+ const apiVersion = azure ? '2024-10-21' : undefined;
124
+ const baseURL = azure ? 'https://test.openai.azure.com' : undefined;
125
+
126
+ for (const maxRetries of [undefined, 0, 5]) {
127
+ it(`keeps ${maxRetries ?? 'SDK default'} retries for ${azure ? 'Azure' : 'OpenAI'} clients`, () => {
128
+ const client = createOpenAiClient({ apiKey: 'test-key', apiVersion, baseURL, maxRetries });
129
+ expect(client).to.be.instanceOf(azure ? AzureOpenAI : MistralFixedOpenAI);
130
+ expect(client.maxRetries).to.equal(maxRetries ?? new OpenAI({ apiKey: 'test-key' }).maxRetries);
131
+ });
132
+
133
+ it(`passes ${maxRetries ?? 'default model'} retries from the model to its ${azure ? 'Azure' : 'OpenAI'} client`, () => {
134
+ const model = buildModel(TestableOpenAiModel, {
135
+ model: 'gpt-5', apiVersion: () => apiVersion, url: baseURL, maxRetries
136
+ });
137
+ const client = model.callInitializeOpenAi();
138
+ expect(client).to.be.instanceOf(azure ? AzureOpenAI : MistralFixedOpenAI);
139
+ expect(client.maxRetries).to.equal(maxRetries ?? 3);
140
+ });
141
+ }
142
+ }
143
+ });
144
+
115
145
  describe('OpenAiModel reasoning translation', () => {
116
146
 
117
147
  for (const forResponseApi of [false, true]) {
@@ -383,3 +413,50 @@ describe('OpenAiModel server-side compaction (Response API)', () => {
383
413
  expect(result).to.deep.equal({ stream: true });
384
414
  });
385
415
  });
416
+
417
+ describe('createOpenAiClient', () => {
418
+
419
+ const AZURE: OpenAiClientOptions = { apiKey: undefined, baseURL: 'https://gateway.example.com/openai', apiVersion: '2024-10-21', deployment: 'gpt-test' };
420
+
421
+ async function sentHeaders(options: OpenAiClientOptions): Promise<{ url: string, headers: Headers }> {
422
+ const { url, req } = await createOpenAiClient(options).buildRequest({
423
+ method: 'post', path: '/chat/completions', body: { model: 'gpt-test', messages: [] }
424
+ });
425
+ return { url, headers: new Headers(req.headers) };
426
+ }
427
+
428
+ it('sends no placeholder api-key to Azure when the headers authenticate the request', async () => {
429
+ const { url, headers } = await sentHeaders({ ...AZURE, headers: { Authorization: 'Bearer entra-token' } });
430
+ expect(url).to.equal('https://gateway.example.com/openai/deployments/gpt-test/chat/completions?api-version=2024-10-21');
431
+ expect(headers.get('authorization')).to.equal('Bearer entra-token');
432
+ expect(headers.has('api-key')).to.equal(false);
433
+ });
434
+
435
+ it('sends no placeholder api-key to an Azure endpoint that authenticates with another header', async () => {
436
+ const { headers } = await sentHeaders({ ...AZURE, headers: { 'Ocp-Apim-Subscription-Key': 'subscription-key' } });
437
+ expect(headers.get('ocp-apim-subscription-key')).to.equal('subscription-key');
438
+ expect(headers.has('api-key')).to.equal(false);
439
+ });
440
+
441
+ it('sends no placeholder api-key to a keyless Azure endpoint without headers', async () => {
442
+ const { headers } = await sentHeaders(AZURE);
443
+ expect(headers.has('api-key')).to.equal(false);
444
+ });
445
+
446
+ it('sends a configured Azure key next to an Authorization header', async () => {
447
+ const { headers } = await sentHeaders({ ...AZURE, apiKey: 'azure-key', headers: { Authorization: 'Bearer entra-token' } });
448
+ expect(headers.get('api-key')).to.equal('azure-key');
449
+ expect(headers.get('authorization')).to.equal('Bearer entra-token');
450
+ });
451
+
452
+ it('keeps an api-key header the configuration sets explicitly', async () => {
453
+ const { headers } = await sentHeaders({ ...AZURE, headers: { authorization: 'Bearer entra-token', 'Api-Key': 'from-headers' } });
454
+ expect(headers.get('api-key')).to.equal('from-headers');
455
+ });
456
+
457
+ it('lets the headers replace the key-based Authorization of a non-Azure endpoint', async () => {
458
+ const { headers } = await sentHeaders({ apiKey: undefined, baseURL: 'https://gateway.example.com/v1', headers: { Authorization: 'Bearer gateway-token' } });
459
+ expect(headers.get('authorization')).to.equal('Bearer gateway-token');
460
+ expect(headers.has('api-key')).to.equal(false);
461
+ });
462
+ });
@@ -26,16 +26,15 @@ import {
26
26
  ReasoningSupport,
27
27
  ServerToolDescriptor
28
28
  } from '@theia/ai-core';
29
- import { OpenAiModelUtils } from './openai-model-utils';
29
+ import { OpenAiModelUtils } from './openai-model-utils.js';
30
30
  import { CancellationToken, ILogger } from '@theia/core';
31
31
  import { inject, injectable, named, postConstruct } from '@theia/core/shared/inversify';
32
32
  import { OpenAI, AzureOpenAI } from 'openai';
33
33
  import { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources';
34
- import { StreamingAsyncIterator } from './openai-streaming-iterator';
35
- import { ChatCompletionStreamingAsyncIteratorFactory } from './openai-chat-completion-stream';
36
- import { OPENAI_PROVIDER_ID } from '../common';
37
- import { OpenAiResponseApiUtils } from './openai-response-api-utils';
38
- import { applyResponseApiCompaction, getOpenAiRequestSettings } from './openai-request-settings';
34
+ import { ChatCompletionStreamingAsyncIteratorFactory } from './openai-chat-completion-stream.js';
35
+ import { OPENAI_PROVIDER_ID } from '../common/index.js';
36
+ import { OpenAiResponseApiUtils } from './openai-response-api-utils.js';
37
+ import { applyResponseApiCompaction, getOpenAiRequestSettings } from './openai-request-settings.js';
39
38
  import { createProxyFetch } from '@theia/ai-core/lib/node';
40
39
 
41
40
  // The SDK finalizes method and path before this hook; its equivalent internal type is not exported.
@@ -83,6 +82,7 @@ export interface OpenAiClientOptions {
83
82
  readonly apiVersion?: string;
84
83
  readonly deployment?: string;
85
84
  readonly proxyUrl?: string;
85
+ readonly maxRetries?: number;
86
86
  /** Additional HTTP headers sent with every request, e.g. headers required by a gateway in front of the API. */
87
87
  readonly headers?: Record<string, string>;
88
88
  }
@@ -98,9 +98,25 @@ export function createOpenAiClient(options: OpenAiClientOptions): OpenAI {
98
98
  const proxyFetch = createProxyFetch(options.proxyUrl);
99
99
  return options.apiVersion
100
100
  ? new AzureOpenAI({
101
- apiKey, baseURL: options.baseURL, apiVersion: options.apiVersion, deployment: options.deployment, fetch: proxyFetch, defaultHeaders: options.headers
101
+ apiKey, baseURL: options.baseURL, apiVersion: options.apiVersion, deployment: options.deployment,
102
+ fetch: proxyFetch, defaultHeaders: azureDefaultHeaders(options), maxRetries: options.maxRetries
102
103
  })
103
- : new MistralFixedOpenAI({ apiKey, baseURL: options.baseURL, fetch: proxyFetch, defaultHeaders: options.headers });
104
+ : new MistralFixedOpenAI({ apiKey, baseURL: options.baseURL, fetch: proxyFetch, defaultHeaders: options.headers, maxRetries: options.maxRetries });
105
+ }
106
+
107
+ /**
108
+ * The Azure client sends its key in the `api-key` header, so without a key it would send the `no-key` placeholder.
109
+ * When no key is configured the placeholder is removed: it only satisfies the SDK constructor and is never a valid
110
+ * credential, gateways may reject a request with an invalid `api-key` (whether they authenticate with a Microsoft
111
+ * Entra ID token in `Authorization`, a subscription-key header or not at all), and the SDK stops following redirects
112
+ * for requests that carry one. An `api-key` header set explicitly in the configured headers is kept.
113
+ */
114
+ function azureDefaultHeaders(options: OpenAiClientOptions): Record<string, string | null> | undefined {
115
+ const names = Object.keys(options.headers ?? {}).map(name => name.toLowerCase());
116
+ if (options.apiKey || names.includes('api-key')) {
117
+ return options.headers;
118
+ }
119
+ return { ...options.headers, 'api-key': null }; // eslint-disable-line no-null/no-null
104
120
  }
105
121
 
106
122
  export interface OpenAiModelParams {
@@ -238,30 +254,18 @@ export class OpenAiModel implements LanguageModel {
238
254
  if (cancellationToken?.isCancellationRequested) {
239
255
  return { text: '' };
240
256
  }
241
- const tools = this.createTools(request);
242
-
243
- if (tools) {
244
- return {
245
- stream: this.chatCompletionStreamFactory({
246
- openai,
247
- model: this.model,
248
- request,
249
- messages: this.processMessages(request.messages),
250
- settings,
251
- tools,
252
- maxRetries: this.maxRetries,
253
- cancellationToken
254
- })
255
- };
256
- }
257
-
258
- const runner = openai.chat.completions.stream({
259
- model: this.model,
260
- messages: this.processMessages(request.messages),
261
- stream: true,
262
- ...settings
263
- });
264
- return { stream: new StreamingAsyncIterator(runner, cancellationToken) };
257
+ return {
258
+ stream: this.chatCompletionStreamFactory({
259
+ openai,
260
+ model: this.model,
261
+ request,
262
+ messages: this.processMessages(request.messages),
263
+ settings,
264
+ tools: this.createTools(request),
265
+ maxRetries: this.maxRetries,
266
+ cancellationToken
267
+ })
268
+ };
265
269
  }
266
270
 
267
271
  protected async handleNonStreamingRequest(openai: OpenAI, request: UserRequest): Promise<LanguageModelTextResponse> {
@@ -334,6 +338,7 @@ export class OpenAiModel implements LanguageModel {
334
338
  apiVersion: this.apiVersion(),
335
339
  deployment: this.deployment,
336
340
  proxyUrl: this.proxy,
341
+ maxRetries: this.maxRetries,
337
342
  headers: this.headers
338
343
  });
339
344
  }
@@ -15,9 +15,9 @@
15
15
  // *****************************************************************************
16
16
 
17
17
  import { expect } from 'chai';
18
- import { OpenAiModelDescription } from '../common';
19
- import { OpenAiLanguageModelsManagerImpl } from './openai-language-models-manager-impl';
20
- import { OPENAI_SERVER_TOOLS, OPENAI_WEB_SEARCH } from './openai-server-tools';
18
+ import { OpenAiModelDescription } from '../common/index.js';
19
+ import { OpenAiLanguageModelsManagerImpl } from './openai-language-models-manager-impl.js';
20
+ import { OPENAI_SERVER_TOOLS, OPENAI_WEB_SEARCH } from './openai-server-tools.js';
21
21
  import { APIConnectionError } from 'openai';
22
22
  import { MockLogger } from '@theia/core/lib/common/test/mock-logger';
23
23
  import { DiscoveredModel } from '@theia/ai-core';
@@ -20,11 +20,11 @@ import {
20
20
  import { getProxyUrl, ModelDiscoveryFetcher } from '@theia/ai-core/lib/node';
21
21
  import { inject, injectable, named } from '@theia/core/shared/inversify';
22
22
  import { APIConnectionError } from 'openai';
23
- import { createOpenAiClient, DeveloperMessageSettings, OpenAiLanguageModelFactory, OpenAiModel } from './openai-language-model';
24
- import { getOpenAiModelDefaults } from './openai-model-defaults';
25
- import { OpenAiLanguageModelsManager, OpenAiModelDescription } from '../common';
23
+ import { createOpenAiClient, DeveloperMessageSettings, OpenAiLanguageModelFactory, OpenAiModel } from './openai-language-model.js';
24
+ import { getOpenAiModelDefaults } from './openai-model-defaults.js';
25
+ import { OpenAiLanguageModelsManager, OpenAiModelDescription } from '../common/index.js';
26
26
  import { ILogger } from '@theia/core';
27
- import { OPENAI_SERVER_TOOLS } from './openai-server-tools';
27
+ import { OPENAI_SERVER_TOOLS } from './openai-server-tools.js';
28
28
 
29
29
  const OPENAI_SNAPSHOT_FILE = 'openai-models.json';
30
30
 
@@ -15,7 +15,7 @@
15
15
  // *****************************************************************************
16
16
 
17
17
  import { expect } from 'chai';
18
- import { getOpenAiModelDefaults } from './openai-model-defaults';
18
+ import { getOpenAiModelDefaults } from './openai-model-defaults.js';
19
19
 
20
20
  describe('getOpenAiModelDefaults', () => {
21
21
  it('returns empty defaults for unknown models', () => {
@@ -15,7 +15,7 @@
15
15
  // *****************************************************************************
16
16
 
17
17
  import { ReasoningSupport } from '@theia/ai-core';
18
- import { DeveloperMessageSettings } from './openai-language-model';
18
+ import { DeveloperMessageSettings } from './openai-language-model.js';
19
19
 
20
20
  /**
21
21
  * Family-level defaults inferred from the OpenAI model id. Sourced from
@@ -14,9 +14,9 @@
14
14
  // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
15
15
  // *****************************************************************************
16
16
  import { expect } from 'chai';
17
- import { OpenAiModelUtils } from './openai-model-utils';
17
+ import { OpenAiModelUtils } from './openai-model-utils.js';
18
18
  import { LanguageModelMessage } from '@theia/ai-core';
19
- import { OpenAiResponseApiUtils } from './openai-response-api-utils';
19
+ import { OpenAiResponseApiUtils } from './openai-response-api-utils.js';
20
20
 
21
21
  const utils = new OpenAiModelUtils();
22
22
  const responseUtils = new OpenAiResponseApiUtils();
@@ -17,8 +17,8 @@
17
17
  import { formatToolCallContentForModel, ImageContent, LanguageModelMessage } from '@theia/ai-core';
18
18
  import { injectable } from '@theia/core/shared/inversify';
19
19
  import { ChatCompletionAssistantMessageParam, ChatCompletionMessageParam } from 'openai/resources';
20
- import { DeveloperMessageSettings } from './openai-language-model';
21
- import { processSystemMessages } from './openai-response-api-utils';
20
+ import { DeveloperMessageSettings } from './openai-language-model.js';
21
+ import { processSystemMessages } from './openai-response-api-utils.js';
22
22
 
23
23
  /**
24
24
  * Utility class for processing messages for the OpenAI language model.
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { LanguageModelRequest, resolveCompactionTokenThreshold, resolveServerSideCompaction } from '@theia/ai-core';
18
18
  import { isObject } from '@theia/core';
19
- import { openAiReasoningFor } from './openai-reasoning';
19
+ import { openAiReasoningFor } from './openai-reasoning.js';
20
20
 
21
21
  /** Merges request settings with reasoning defaults, preserving user fields while the selected level determines effort. */
22
22
  export function getOpenAiRequestSettings(request: LanguageModelRequest, forResponseApi: boolean, supportsReasoning: boolean): Record<string, unknown> {