@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.
- package/lib/browser/openai-frontend-application-contribution.d.ts +1 -1
- package/lib/browser/openai-frontend-application-contribution.d.ts.map +1 -1
- package/lib/browser/openai-frontend-application-contribution.js +55 -60
- package/lib/browser/openai-frontend-application-contribution.js.map +1 -1
- package/lib/browser/openai-frontend-application-contribution.spec.js +13 -15
- package/lib/browser/openai-frontend-application-contribution.spec.js.map +1 -1
- package/lib/browser/openai-frontend-module.js +13 -15
- package/lib/browser/openai-frontend-module.js.map +1 -1
- package/lib/common/index.d.ts +1 -1
- package/lib/common/index.d.ts.map +1 -1
- package/lib/common/index.js +1 -4
- package/lib/common/index.js.map +1 -1
- package/lib/common/openai-language-models-manager.js +3 -6
- package/lib/common/openai-language-models-manager.js.map +1 -1
- package/lib/common/openai-preferences.js +52 -55
- package/lib/common/openai-preferences.js.map +1 -1
- package/lib/node/openai-backend-module.d.ts.map +1 -1
- package/lib/node/openai-backend-module.js +31 -31
- package/lib/node/openai-backend-module.js.map +1 -1
- package/lib/node/openai-chat-completion-stream.d.ts +6 -9
- package/lib/node/openai-chat-completion-stream.d.ts.map +1 -1
- package/lib/node/openai-chat-completion-stream.js +34 -43
- package/lib/node/openai-chat-completion-stream.js.map +1 -1
- package/lib/node/openai-chat-completion-stream.spec.js +159 -76
- package/lib/node/openai-chat-completion-stream.spec.js.map +1 -1
- package/lib/node/openai-language-model.d.ts +4 -3
- package/lib/node/openai-language-model.d.ts.map +1 -1
- package/lib/node/openai-language-model.js +68 -76
- package/lib/node/openai-language-model.js.map +1 -1
- package/lib/node/openai-language-model.spec.js +137 -75
- package/lib/node/openai-language-model.spec.js.map +1 -1
- package/lib/node/openai-language-models-manager-impl.d.ts +3 -3
- package/lib/node/openai-language-models-manager-impl.d.ts.map +1 -1
- package/lib/node/openai-language-models-manager-impl.js +29 -36
- package/lib/node/openai-language-models-manager-impl.js.map +1 -1
- package/lib/node/openai-language-models-manager-impl.spec.js +34 -36
- package/lib/node/openai-language-models-manager-impl.spec.js.map +1 -1
- package/lib/node/openai-model-defaults.d.ts +1 -1
- package/lib/node/openai-model-defaults.d.ts.map +1 -1
- package/lib/node/openai-model-defaults.js +1 -4
- package/lib/node/openai-model-defaults.js.map +1 -1
- package/lib/node/openai-model-defaults.spec.js +52 -54
- package/lib/node/openai-model-defaults.spec.js.map +1 -1
- package/lib/node/openai-model-utils.d.ts +1 -1
- package/lib/node/openai-model-utils.d.ts.map +1 -1
- package/lib/node/openai-model-utils.js +14 -17
- package/lib/node/openai-model-utils.js.map +1 -1
- package/lib/node/openai-model-utils.spec.js +45 -47
- package/lib/node/openai-model-utils.spec.js.map +1 -1
- package/lib/node/openai-reasoning.js +1 -4
- package/lib/node/openai-reasoning.js.map +1 -1
- package/lib/node/openai-request-settings.js +9 -13
- package/lib/node/openai-request-settings.js.map +1 -1
- package/lib/node/openai-response-api-utils.d.ts +5 -3
- package/lib/node/openai-response-api-utils.d.ts.map +1 -1
- package/lib/node/openai-response-api-utils.js +84 -70
- package/lib/node/openai-response-api-utils.js.map +1 -1
- package/lib/node/openai-response-api-utils.spec.js +320 -166
- package/lib/node/openai-response-api-utils.spec.js.map +1 -1
- package/lib/node/openai-server-tools.js +4 -7
- package/lib/node/openai-server-tools.js.map +1 -1
- package/lib/node/openai-streaming-iterator.d.ts +2 -1
- package/lib/node/openai-streaming-iterator.d.ts.map +1 -1
- package/lib/node/openai-streaming-iterator.js +5 -8
- package/lib/node/openai-streaming-iterator.js.map +1 -1
- package/lib/node/openai-streaming-iterator.spec.js +37 -40
- package/lib/node/openai-streaming-iterator.spec.js.map +1 -1
- package/lib/node/openai-streaming-retry.d.ts +8 -0
- package/lib/node/openai-streaming-retry.d.ts.map +1 -0
- package/lib/node/openai-streaming-retry.js +108 -0
- package/lib/node/openai-streaming-retry.js.map +1 -0
- package/lib/node/openai-streaming-retry.spec.d.ts +2 -0
- package/lib/node/openai-streaming-retry.spec.d.ts.map +1 -0
- package/lib/node/openai-streaming-retry.spec.js +182 -0
- package/lib/node/openai-streaming-retry.spec.js.map +1 -0
- package/lib/node/streaming-response-iterator.js +5 -9
- package/lib/node/streaming-response-iterator.js.map +1 -1
- package/lib/node/streaming-response-iterator.spec.js +6 -8
- package/lib/node/streaming-response-iterator.spec.js.map +1 -1
- package/package.json +16 -7
- package/src/browser/openai-frontend-application-contribution.spec.ts +3 -3
- package/src/browser/openai-frontend-application-contribution.ts +2 -2
- package/src/browser/openai-frontend-module.ts +3 -3
- package/src/common/index.ts +1 -1
- package/src/node/openai-backend-module.ts +9 -7
- package/src/node/openai-chat-completion-stream.spec.ts +88 -3
- package/src/node/openai-chat-completion-stream.ts +20 -15
- package/src/node/openai-language-model.spec.ts +84 -7
- package/src/node/openai-language-model.ts +37 -32
- package/src/node/openai-language-models-manager-impl.spec.ts +3 -3
- package/src/node/openai-language-models-manager-impl.ts +4 -4
- package/src/node/openai-model-defaults.spec.ts +1 -1
- package/src/node/openai-model-defaults.ts +1 -1
- package/src/node/openai-model-utils.spec.ts +2 -2
- package/src/node/openai-model-utils.ts +2 -2
- package/src/node/openai-request-settings.ts +1 -1
- package/src/node/openai-response-api-utils.spec.ts +180 -27
- package/src/node/openai-response-api-utils.ts +45 -21
- package/src/node/openai-streaming-iterator.spec.ts +1 -1
- package/src/node/openai-streaming-iterator.ts +2 -1
- package/src/node/openai-streaming-retry.spec.ts +195 -0
- package/src/node/openai-streaming-retry.ts +110 -0
- package/src/node/streaming-response-iterator.spec.ts +1 -1
- package/lib/node/openai-request-api-context.d.ts +0 -4
- package/lib/node/openai-request-api-context.d.ts.map +0 -1
- package/lib/node/openai-request-api-context.js +0 -19
- package/lib/node/openai-request-api-context.js.map +0 -1
- package/src/node/openai-request-api-context.ts +0 -23
|
@@ -20,15 +20,16 @@ import {
|
|
|
20
20
|
CompactionMessage, isCompactionResponsePart, isServerToolCallResponsePart, isTextResponsePart, isThinkingResponsePart, isToolCallResponsePart,
|
|
21
21
|
isUsageResponsePart, LanguageModelMessage, LanguageModelResponse, LanguageModelStreamResponsePart, ToolCallExecutor, ToolCallExecutorImpl, UserRequest
|
|
22
22
|
} from '@theia/ai-core';
|
|
23
|
-
import { ILogger } from '@theia/core';
|
|
23
|
+
import { CancellationError, CancellationTokenSource, ILogger } from '@theia/core';
|
|
24
24
|
import { Container } from '@theia/core/shared/inversify';
|
|
25
25
|
import { MockLogger } from '@theia/core/lib/common/test/mock-logger';
|
|
26
26
|
import { Deferred } from '@theia/core/lib/common/promise-util';
|
|
27
|
-
import { OpenAiModelUtils } from './openai-model-utils';
|
|
27
|
+
import { OpenAiModelUtils } from './openai-model-utils.js';
|
|
28
28
|
import { OpenAI } from 'openai';
|
|
29
29
|
import type { ResponseStreamEvent } from 'openai/resources/responses/responses';
|
|
30
|
-
import { OPENAI_FUNCTION_CALL_REASONING_DATA_KEY, OpenAiResponseApiUtils } from './openai-response-api-utils';
|
|
31
|
-
import { OPENAI_WEB_SEARCH, OPENAI_WEB_SEARCH_REPLAY_DATA_KEY } from './openai-server-tools';
|
|
30
|
+
import { OPENAI_FUNCTION_CALL_REASONING_DATA_KEY, OpenAiResponseApiUtils } from './openai-response-api-utils.js';
|
|
31
|
+
import { OPENAI_WEB_SEARCH, OPENAI_WEB_SEARCH_REPLAY_DATA_KEY } from './openai-server-tools.js';
|
|
32
|
+
import { OpenAiStreamingRetry } from './openai-streaming-retry.js';
|
|
32
33
|
|
|
33
34
|
async function* toStream(events: unknown[]): AsyncIterable<unknown> {
|
|
34
35
|
for (const event of events) {
|
|
@@ -46,9 +47,10 @@ function outputItemEvents(item: Record<string, unknown>, outputIndex: number): u
|
|
|
46
47
|
];
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
function createTestUtils(): OpenAiResponseApiUtils {
|
|
50
|
+
function createTestUtils(logger: ILogger = new MockLogger()): OpenAiResponseApiUtils {
|
|
50
51
|
const container = new Container();
|
|
51
|
-
container.bind(ILogger).
|
|
52
|
+
container.bind(ILogger).toConstantValue(logger);
|
|
53
|
+
container.bind(OpenAiStreamingRetry).toSelf();
|
|
52
54
|
container.bind(ToolCallExecutor).to(ToolCallExecutorImpl).inSingletonScope();
|
|
53
55
|
container.bind(OpenAiResponseApiUtils).toSelf();
|
|
54
56
|
return container.get(OpenAiResponseApiUtils);
|
|
@@ -148,15 +150,12 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
148
150
|
};
|
|
149
151
|
const openai = {
|
|
150
152
|
responses: {
|
|
151
|
-
stream: (payload: Record<string, unknown>) => {
|
|
152
|
-
recordRequest(payload);
|
|
153
|
-
return toStream(payloads.length === 1
|
|
154
|
-
? functionCalls.flatMap((item, index) => outputItemEvents(item, index))
|
|
155
|
-
: [{ type: 'response.output_text.delta', delta: 'done' }]);
|
|
156
|
-
},
|
|
157
153
|
create: async (payload: Record<string, unknown>) => {
|
|
158
154
|
recordRequest(payload);
|
|
159
|
-
return
|
|
155
|
+
return payload.stream ? toStream(payloads.length === 1
|
|
156
|
+
? functionCalls.flatMap((item, index) => outputItemEvents(item, index))
|
|
157
|
+
: [{ type: 'response.output_text.delta', delta: 'done' }])
|
|
158
|
+
: { output: payloads.length === 1 ? functionCalls : [], output_text: payloads.length === 1 ? '' : 'done' };
|
|
160
159
|
}
|
|
161
160
|
}
|
|
162
161
|
};
|
|
@@ -233,7 +232,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
233
232
|
const streamRequests: Record<string, unknown>[] = [];
|
|
234
233
|
const openai = {
|
|
235
234
|
responses: {
|
|
236
|
-
|
|
235
|
+
create: async (responseRequest: Record<string, unknown>) => {
|
|
237
236
|
streamRequests.push(responseRequest);
|
|
238
237
|
return toStream(streams.shift() ?? []);
|
|
239
238
|
}
|
|
@@ -298,7 +297,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
298
297
|
const streamRequests: Record<string, unknown>[] = [];
|
|
299
298
|
const openai = {
|
|
300
299
|
responses: {
|
|
301
|
-
|
|
300
|
+
create: async (responseRequest: Record<string, unknown>) => {
|
|
302
301
|
streamRequests.push(responseRequest);
|
|
303
302
|
return toStream(streams.shift() ?? []);
|
|
304
303
|
}
|
|
@@ -341,7 +340,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
341
340
|
const payloads: Record<string, unknown>[] = [];
|
|
342
341
|
const openai = {
|
|
343
342
|
responses: {
|
|
344
|
-
|
|
343
|
+
create: async (payload: Record<string, unknown>) => {
|
|
345
344
|
payloads.push(payload);
|
|
346
345
|
return toStream(payloads.length === 1 ? [
|
|
347
346
|
{ type: 'response.output_item.done', output_index: 0, item: { type: 'compaction', id: 'c1', encrypted_content: 'enc1' } },
|
|
@@ -418,7 +417,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
418
417
|
const payloads: Record<string, unknown>[] = [];
|
|
419
418
|
const openai = {
|
|
420
419
|
responses: {
|
|
421
|
-
|
|
420
|
+
create: async (payload: Record<string, unknown>) => {
|
|
422
421
|
payloads.push(payload);
|
|
423
422
|
return toStream(streams.shift() ?? []);
|
|
424
423
|
}
|
|
@@ -486,7 +485,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
486
485
|
};
|
|
487
486
|
const openai = {
|
|
488
487
|
responses: {
|
|
489
|
-
|
|
488
|
+
create: async () => toStream([
|
|
490
489
|
{ type: 'response.output_item.done', output_index: 0, item: reasoningItem },
|
|
491
490
|
{ type: 'response.output_item.added', output_index: 1, item: { ...searchCall, status: 'in_progress' } },
|
|
492
491
|
{ type: 'response.output_item.done', output_index: 1, item: searchCall },
|
|
@@ -609,7 +608,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
609
608
|
];
|
|
610
609
|
const openai = {
|
|
611
610
|
responses: {
|
|
612
|
-
|
|
611
|
+
create: async (responseRequest: Record<string, unknown>) => {
|
|
613
612
|
requests.push(responseRequest);
|
|
614
613
|
return toStream(streams.shift() ?? []);
|
|
615
614
|
}
|
|
@@ -664,6 +663,158 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
664
663
|
}]);
|
|
665
664
|
});
|
|
666
665
|
|
|
666
|
+
describe('transient stream failures', () => {
|
|
667
|
+
let clock: sinon.SinonFakeTimers;
|
|
668
|
+
let logError: sinon.SinonSpy;
|
|
669
|
+
const busy = { type: 'response.failed', response: { error: { code: 'server_error', message: 'The server is too busy.' } } };
|
|
670
|
+
const request: UserRequest = { sessionId: 's', requestId: 'r', messages: [{ actor: 'user', type: 'text', text: 'hello' }] };
|
|
671
|
+
|
|
672
|
+
beforeEach(() => {
|
|
673
|
+
clock = sinon.useFakeTimers();
|
|
674
|
+
const logger = new MockLogger();
|
|
675
|
+
logError = sinon.spy(logger, 'error');
|
|
676
|
+
utils = createTestUtils(logger);
|
|
677
|
+
});
|
|
678
|
+
afterEach(() => sinon.restore());
|
|
679
|
+
|
|
680
|
+
for (const withTools of [false, true]) {
|
|
681
|
+
it(`retries quietly after lifecycle events ${withTools ? 'with tools' : 'without tools'}`, async () => {
|
|
682
|
+
const payloads: unknown[] = [];
|
|
683
|
+
const openai = {
|
|
684
|
+
maxRetries: 1,
|
|
685
|
+
responses: {
|
|
686
|
+
create: async (payload: unknown) => {
|
|
687
|
+
payloads.push(payload);
|
|
688
|
+
return toStream(payloads.length === 1
|
|
689
|
+
? [{ type: 'response.created' }, { type: 'response.in_progress' }, busy]
|
|
690
|
+
: [{ type: 'response.output_text.delta', delta: 'done' }]);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
const response = await utils.handleRequest(openai as never, {
|
|
695
|
+
...request,
|
|
696
|
+
tools: withTools ? [{ id: 'lookup', name: 'lookup', parameters: { type: 'object', properties: {} }, handler: async () => 'result' }] : undefined
|
|
697
|
+
}, {}, 'gpt-5', new OpenAiModelUtils(), 'developer', 'openai/gpt-5', true);
|
|
698
|
+
const parts: LanguageModelStreamResponsePart[] = [];
|
|
699
|
+
const consume = (async () => {
|
|
700
|
+
if ('stream' in response) {
|
|
701
|
+
for await (const part of response.stream) { parts.push(part); }
|
|
702
|
+
}
|
|
703
|
+
})();
|
|
704
|
+
await clock.runAllAsync();
|
|
705
|
+
await consume;
|
|
706
|
+
expect(parts).to.deep.equal([{ content: 'done' }]);
|
|
707
|
+
expect(payloads).to.have.length(2);
|
|
708
|
+
expect(payloads[1]).to.deep.equal(payloads[0]);
|
|
709
|
+
expect(logError.called).to.equal(false);
|
|
710
|
+
});
|
|
711
|
+
|
|
712
|
+
for (const event of [busy, { type: 'error', code: 'server_error', message: 'Stream failed' }]) {
|
|
713
|
+
it(`logs the terminal ${event.type} once after exhausting retries ${withTools ? 'with tools' : 'without tools'}`, async () => {
|
|
714
|
+
const create = sinon.stub().callsFake(async () => toStream([event]));
|
|
715
|
+
const response = await utils.handleRequest({ maxRetries: 1, responses: { create } } as never, {
|
|
716
|
+
...request,
|
|
717
|
+
tools: withTools ? [{ id: 'lookup', name: 'lookup', parameters: { type: 'object', properties: {} }, handler: async () => 'result' }] : undefined
|
|
718
|
+
}, {}, 'gpt-5', new OpenAiModelUtils(), 'developer', 'openai/gpt-5', true);
|
|
719
|
+
const consume = (async () => {
|
|
720
|
+
if ('stream' in response) {
|
|
721
|
+
for await (const part of response.stream) { expect.fail(`Unexpected output ${JSON.stringify(part)}`); }
|
|
722
|
+
}
|
|
723
|
+
})().then(() => undefined, caught => caught);
|
|
724
|
+
await clock.runAllAsync();
|
|
725
|
+
const error = await consume;
|
|
726
|
+
expect(error).to.be.instanceOf(Error).with.property('code', 'server_error');
|
|
727
|
+
expect(create.callCount).to.equal(2);
|
|
728
|
+
expect(logError.calledOnceWithExactly('Response API error:', error)).to.equal(true);
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
it(`cancels during backoff ${withTools ? 'with tools' : 'without tools'}`, async () => {
|
|
733
|
+
const source = new CancellationTokenSource();
|
|
734
|
+
const create = sinon.stub().callsFake(async () => toStream([busy]));
|
|
735
|
+
const response = await utils.handleRequest({ maxRetries: 3, responses: { create } } as never, {
|
|
736
|
+
...request,
|
|
737
|
+
tools: withTools ? [{ id: 'lookup', name: 'lookup', parameters: { type: 'object', properties: {} }, handler: async () => 'result' }] : undefined
|
|
738
|
+
}, {}, 'gpt-5', new OpenAiModelUtils(), 'developer', 'openai/gpt-5', true, source.token);
|
|
739
|
+
const consume = (async () => {
|
|
740
|
+
try {
|
|
741
|
+
if ('stream' in response) {
|
|
742
|
+
for await (const part of response.stream) { expect.fail(`Unexpected output ${JSON.stringify(part)}`); }
|
|
743
|
+
}
|
|
744
|
+
} catch (error) {
|
|
745
|
+
return error;
|
|
746
|
+
}
|
|
747
|
+
return undefined;
|
|
748
|
+
})();
|
|
749
|
+
await clock.tickAsync(0);
|
|
750
|
+
source.cancel();
|
|
751
|
+
expect(await consume).to.be.instanceOf(CancellationError);
|
|
752
|
+
await clock.runAllAsync();
|
|
753
|
+
expect(create.callCount).to.equal(1);
|
|
754
|
+
expect(create.firstCall.args[1].signal.aborted).to.equal(true);
|
|
755
|
+
expect(logError.called).to.equal(false);
|
|
756
|
+
source.dispose();
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
it('reports cancellation when a simple upstream stream ends normally on abort', async () => {
|
|
761
|
+
const source = new CancellationTokenSource();
|
|
762
|
+
const create = sinon.stub().callsFake(async (_payload: unknown, options: { signal: AbortSignal }) => (async function* (): AsyncIterable<unknown> {
|
|
763
|
+
yield { type: 'response.created' };
|
|
764
|
+
await new Promise<void>(resolve => options.signal.addEventListener('abort', () => resolve(), { once: true }));
|
|
765
|
+
})());
|
|
766
|
+
const response = await utils.handleRequest({ maxRetries: 3, responses: { create } } as never, request,
|
|
767
|
+
{}, 'gpt-5', new OpenAiModelUtils(), 'developer', 'openai/gpt-5', true, source.token);
|
|
768
|
+
const consume = (async () => {
|
|
769
|
+
try {
|
|
770
|
+
if ('stream' in response) {
|
|
771
|
+
for await (const part of response.stream) { expect.fail(`Unexpected output ${JSON.stringify(part)}`); }
|
|
772
|
+
}
|
|
773
|
+
} catch (error) {
|
|
774
|
+
return error;
|
|
775
|
+
}
|
|
776
|
+
return undefined;
|
|
777
|
+
})();
|
|
778
|
+
await clock.tickAsync(0);
|
|
779
|
+
source.cancel();
|
|
780
|
+
expect(await consume).to.be.instanceOf(CancellationError);
|
|
781
|
+
expect(create.callCount).to.equal(1);
|
|
782
|
+
source.dispose();
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
it('retries the next model turn without repeating completed tools', async () => {
|
|
786
|
+
const handler = sinon.stub().resolves('result');
|
|
787
|
+
const payloads: { input: unknown[] }[] = [];
|
|
788
|
+
const openai = {
|
|
789
|
+
maxRetries: 1,
|
|
790
|
+
responses: {
|
|
791
|
+
create: async (payload: { input: unknown[] }) => {
|
|
792
|
+
payloads.push(payload);
|
|
793
|
+
return toStream(payloads.length === 1
|
|
794
|
+
? outputItemEvents({ id: 'call-1', call_id: 'call-1', type: 'function_call', name: 'lookup', arguments: '{}' }, 0)
|
|
795
|
+
: payloads.length === 2 ? [busy] : [{ type: 'response.output_text.delta', delta: 'done' }]);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
const response = await utils.handleRequest(openai as never, {
|
|
800
|
+
...request, tools: [{ id: 'lookup', name: 'lookup', parameters: { type: 'object', properties: {} }, handler }]
|
|
801
|
+
}, {}, 'gpt-5', new OpenAiModelUtils(), 'developer', 'openai/gpt-5', true);
|
|
802
|
+
const parts: LanguageModelStreamResponsePart[] = [];
|
|
803
|
+
const consume = (async () => {
|
|
804
|
+
if ('stream' in response) {
|
|
805
|
+
for await (const part of response.stream) { parts.push(part); }
|
|
806
|
+
}
|
|
807
|
+
})();
|
|
808
|
+
await clock.runAllAsync();
|
|
809
|
+
await consume;
|
|
810
|
+
expect(handler.callCount).to.equal(1);
|
|
811
|
+
expect(parts.filter(isTextResponsePart)).to.deep.equal([{ content: 'done' }]);
|
|
812
|
+
expect(payloads).to.have.length(3);
|
|
813
|
+
expect(payloads[2]).to.deep.equal(payloads[1]);
|
|
814
|
+
expect(payloads[2].input).to.deep.include({ type: 'function_call_output', call_id: 'call-1', output: 'result' });
|
|
815
|
+
});
|
|
816
|
+
});
|
|
817
|
+
|
|
667
818
|
describe('reasoning summaries', () => {
|
|
668
819
|
// Two summary parts of one reasoning item, as the Responses API streams them with `reasoning.summary` set.
|
|
669
820
|
const summaryEvents = [
|
|
@@ -691,7 +842,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
691
842
|
it('streams reasoning summaries as thoughts, separating summary parts', async () => {
|
|
692
843
|
const openai = {
|
|
693
844
|
responses: {
|
|
694
|
-
|
|
845
|
+
create: async () => toStream([...summaryEvents, { type: 'response.output_text.delta', delta: 'Answer' }])
|
|
695
846
|
}
|
|
696
847
|
};
|
|
697
848
|
const request: UserRequest = {
|
|
@@ -727,7 +878,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
727
878
|
];
|
|
728
879
|
const openai = {
|
|
729
880
|
responses: {
|
|
730
|
-
|
|
881
|
+
create: async () => toStream(streams.shift() ?? [])
|
|
731
882
|
}
|
|
732
883
|
};
|
|
733
884
|
const request: UserRequest = {
|
|
@@ -775,7 +926,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
775
926
|
const sent: { reasoning?: { effort?: string; summary?: string } }[] = [];
|
|
776
927
|
const openai = {
|
|
777
928
|
responses: {
|
|
778
|
-
|
|
929
|
+
create: async (params: { reasoning?: { summary?: string } }) => {
|
|
779
930
|
sent.push(params);
|
|
780
931
|
return summaryOf(params)
|
|
781
932
|
? rejectingStream(badRequest('reasoning.summary'))
|
|
@@ -892,8 +1043,11 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
892
1043
|
};
|
|
893
1044
|
const openai = {
|
|
894
1045
|
responses: {
|
|
895
|
-
|
|
1046
|
+
create: async (payload: Record<string, unknown>) => {
|
|
896
1047
|
const items = nextOutput(payload);
|
|
1048
|
+
if (!payload.stream) {
|
|
1049
|
+
return { output: items, output_text: '' };
|
|
1050
|
+
}
|
|
897
1051
|
return toStream([
|
|
898
1052
|
...items.flatMap((item, output_index) => [
|
|
899
1053
|
{ type: 'response.output_item.added', output_index, item },
|
|
@@ -905,8 +1059,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
905
1059
|
...items.map((item, output_index) => ({ type: 'response.output_item.done', output_index, item })).reverse(),
|
|
906
1060
|
{ type: 'response.completed', response: { usage: { input_tokens: 10, output_tokens: 5 } } }
|
|
907
1061
|
]);
|
|
908
|
-
}
|
|
909
|
-
create: async (payload: Record<string, unknown>) => ({ output: nextOutput(payload), output_text: '' })
|
|
1062
|
+
}
|
|
910
1063
|
}
|
|
911
1064
|
};
|
|
912
1065
|
const request: UserRequest = {
|
|
@@ -1070,7 +1223,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
1070
1223
|
];
|
|
1071
1224
|
const openai = {
|
|
1072
1225
|
responses: {
|
|
1073
|
-
|
|
1226
|
+
create: async (payload: Record<string, unknown>) => {
|
|
1074
1227
|
payloads.push(payload);
|
|
1075
1228
|
return toStream(streams.shift() ?? []);
|
|
1076
1229
|
}
|
|
@@ -1114,7 +1267,7 @@ describe('OpenAiResponseApiUtils', () => {
|
|
|
1114
1267
|
];
|
|
1115
1268
|
const openai = {
|
|
1116
1269
|
responses: {
|
|
1117
|
-
|
|
1270
|
+
create: async () => toStream(streams.shift() ?? [])
|
|
1118
1271
|
}
|
|
1119
1272
|
};
|
|
1120
1273
|
// `a` only resolves once `b` has started: a sequential implementation would deadlock here.
|
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
ToolRequest,
|
|
27
27
|
UserRequest
|
|
28
28
|
} from '@theia/ai-core';
|
|
29
|
-
import { CancellationToken, isObject, nls, unreachable, ILogger } from '@theia/core';
|
|
29
|
+
import { CancellationError, CancellationToken, CancellationTokenSource, isObject, nls, unreachable, ILogger } from '@theia/core';
|
|
30
30
|
import { injectable, inject, named } from '@theia/core/shared/inversify';
|
|
31
31
|
import { OpenAI } from 'openai';
|
|
32
32
|
import { toResponseInputItems } from 'openai/lib/responses/ResponseInputItems';
|
|
@@ -45,10 +45,11 @@ import type {
|
|
|
45
45
|
ResponseToolSearchOutputItem
|
|
46
46
|
} from 'openai/resources/responses/responses';
|
|
47
47
|
import type { ResponsesModel } from 'openai/resources/shared';
|
|
48
|
-
import { DeveloperMessageSettings } from './openai-language-model';
|
|
49
|
-
import type { OpenAiModelUtils } from './openai-model-utils';
|
|
50
|
-
import { OPENAI_WEB_SEARCH, OPENAI_WEB_SEARCH_REPLAY_DATA_KEY } from './openai-server-tools';
|
|
51
|
-
import { AbstractStreamingResponseIterator } from './streaming-response-iterator';
|
|
48
|
+
import { DeveloperMessageSettings } from './openai-language-model.js';
|
|
49
|
+
import type { OpenAiModelUtils } from './openai-model-utils.js';
|
|
50
|
+
import { OPENAI_WEB_SEARCH, OPENAI_WEB_SEARCH_REPLAY_DATA_KEY } from './openai-server-tools.js';
|
|
51
|
+
import { AbstractStreamingResponseIterator } from './streaming-response-iterator.js';
|
|
52
|
+
import { OpenAiStreamingRetry } from './openai-streaming-retry.js';
|
|
52
53
|
|
|
53
54
|
export const OPENAI_FUNCTION_CALL_REASONING_DATA_KEY = 'openAiFunctionCallReasoning';
|
|
54
55
|
|
|
@@ -90,6 +91,9 @@ export class OpenAiResponseApiUtils {
|
|
|
90
91
|
@inject(ToolCallExecutor)
|
|
91
92
|
protected readonly toolCallExecutor: ToolCallExecutor;
|
|
92
93
|
|
|
94
|
+
@inject(OpenAiStreamingRetry)
|
|
95
|
+
protected readonly streamingRetry: OpenAiStreamingRetry;
|
|
96
|
+
|
|
93
97
|
@inject(ILogger) @named('ai-openai:OpenAiResponseApiUtils')
|
|
94
98
|
protected readonly logger: ILogger;
|
|
95
99
|
|
|
@@ -130,7 +134,7 @@ export class OpenAiResponseApiUtils {
|
|
|
130
134
|
input,
|
|
131
135
|
...sentSettings,
|
|
132
136
|
stream: true
|
|
133
|
-
}));
|
|
137
|
+
}, cancellationToken));
|
|
134
138
|
return { stream: this.createSimpleResponseApiStreamIterator(stream, cancellationToken) };
|
|
135
139
|
} else {
|
|
136
140
|
const response = await this.sendWithReasoningSummaryFallback(effectiveSettings, modelId, sentSettings => openai.responses.create({
|
|
@@ -169,10 +173,6 @@ export class OpenAiResponseApiUtils {
|
|
|
169
173
|
return { stream: iterator };
|
|
170
174
|
}
|
|
171
175
|
|
|
172
|
-
streamResponse(openai: OpenAI, parameters: ResponseCreateParamsStreaming): AsyncIterable<ResponseStreamEvent> {
|
|
173
|
-
return openai.responses.stream(parameters);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
176
|
/**
|
|
177
177
|
* Converts ToolRequest objects to the format expected by the Response API.
|
|
178
178
|
*/
|
|
@@ -288,6 +288,15 @@ export class OpenAiResponseApiUtils {
|
|
|
288
288
|
}
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
+
streamResponse(openai: OpenAI, parameters: ResponseCreateParamsStreaming, cancellationToken?: CancellationToken): AsyncIterable<ResponseStreamEvent> {
|
|
292
|
+
return this.streamingRetry.retry(
|
|
293
|
+
async signal => openai.responses.create(parameters, { signal }),
|
|
294
|
+
openai.maxRetries ?? 3,
|
|
295
|
+
event => ['response.created', 'response.queued', 'response.in_progress', 'response.metadata'].includes(event.type),
|
|
296
|
+
cancellationToken
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
291
300
|
protected createSimpleResponseApiStreamIterator(
|
|
292
301
|
stream: AsyncIterable<ResponseStreamEvent>,
|
|
293
302
|
cancellationToken?: CancellationToken
|
|
@@ -304,7 +313,7 @@ export class OpenAiResponseApiUtils {
|
|
|
304
313
|
try {
|
|
305
314
|
for await (const event of stream) {
|
|
306
315
|
if (cancellationToken?.isCancellationRequested) {
|
|
307
|
-
|
|
316
|
+
throw new CancellationError();
|
|
308
317
|
}
|
|
309
318
|
|
|
310
319
|
if (event.type === 'response.output_text.delta') {
|
|
@@ -340,11 +349,13 @@ export class OpenAiResponseApiUtils {
|
|
|
340
349
|
output_tokens: responseEvent.response.usage.output_tokens,
|
|
341
350
|
};
|
|
342
351
|
}
|
|
343
|
-
} else if (event.type === 'error') {
|
|
344
|
-
logger.error('Response API error:', event.message);
|
|
345
|
-
throw new Error(`Response API error: ${event.message}`);
|
|
346
352
|
}
|
|
347
353
|
}
|
|
354
|
+
} catch (error) {
|
|
355
|
+
if (!cancellationToken?.isCancellationRequested && !(error instanceof CancellationError)) {
|
|
356
|
+
logger.error('Response API error:', error);
|
|
357
|
+
}
|
|
358
|
+
throw error;
|
|
348
359
|
} finally {
|
|
349
360
|
// Yield partial usage data when stream is aborted before response.completed
|
|
350
361
|
if (!usageYielded && lastUsage && (lastUsage.input_tokens > 0 || lastUsage.output_tokens > 0)) {
|
|
@@ -509,6 +520,7 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
509
520
|
protected readonly instructions?: string;
|
|
510
521
|
protected pendingReasoningItems: ResponseInputItem[] = [];
|
|
511
522
|
protected currentOutput: ResponseOutputItem[] = [];
|
|
523
|
+
protected readonly streamCancellation = new CancellationTokenSource();
|
|
512
524
|
|
|
513
525
|
constructor(
|
|
514
526
|
protected readonly openai: OpenAI,
|
|
@@ -530,6 +542,13 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
530
542
|
this.currentInput = input;
|
|
531
543
|
this.tools = utils.convertToolsForResponseApi(request.tools, request.deferredToolIds, request.serverTools);
|
|
532
544
|
|
|
545
|
+
this.toDispose.push(this.streamCancellation);
|
|
546
|
+
if (cancellationToken) {
|
|
547
|
+
this.toDispose.push(cancellationToken.onCancellationRequested(() => {
|
|
548
|
+
this.terminalError = new CancellationError();
|
|
549
|
+
this.dispose();
|
|
550
|
+
}));
|
|
551
|
+
}
|
|
533
552
|
// Start the first iteration
|
|
534
553
|
this.startIteration();
|
|
535
554
|
}
|
|
@@ -540,6 +559,10 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
540
559
|
this.logger.debug(`Starting Response API iteration ${this.iteration} with ${this.currentInput.length} input messages`);
|
|
541
560
|
|
|
542
561
|
await this.processStream();
|
|
562
|
+
if (this.done || this.cancellationToken?.isCancellationRequested) {
|
|
563
|
+
this.dispose();
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
543
566
|
|
|
544
567
|
// Check if we have tool calls that need execution
|
|
545
568
|
if (this.currentToolCalls.size === 0) {
|
|
@@ -559,8 +582,13 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
559
582
|
// Cancelled, or abandoned by the consumer.
|
|
560
583
|
this.dispose();
|
|
561
584
|
} catch (error) {
|
|
562
|
-
this.
|
|
563
|
-
|
|
585
|
+
if (!this.done) {
|
|
586
|
+
if (!this.cancellationToken?.isCancellationRequested && !(error instanceof CancellationError)) {
|
|
587
|
+
this.logger.error('Response API error:', error);
|
|
588
|
+
}
|
|
589
|
+
this.terminalError = error instanceof Error ? error : new Error(String(error));
|
|
590
|
+
this.dispose();
|
|
591
|
+
}
|
|
564
592
|
}
|
|
565
593
|
}
|
|
566
594
|
|
|
@@ -578,7 +606,7 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
578
606
|
tools: this.tools,
|
|
579
607
|
...settings,
|
|
580
608
|
stream: true
|
|
581
|
-
}));
|
|
609
|
+
}, this.streamCancellation.token));
|
|
582
610
|
|
|
583
611
|
for await (const event of stream) {
|
|
584
612
|
if (this.done || this.cancellationToken?.isCancellationRequested) {
|
|
@@ -715,10 +743,6 @@ class ResponseApiToolCallIterator extends AbstractStreamingResponseIterator {
|
|
|
715
743
|
});
|
|
716
744
|
}
|
|
717
745
|
break;
|
|
718
|
-
|
|
719
|
-
case 'error':
|
|
720
|
-
this.logger.error('Response API error:', event.message);
|
|
721
|
-
throw new Error(`Response API error: ${event.message}`);
|
|
722
746
|
}
|
|
723
747
|
}
|
|
724
748
|
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { expect } from 'chai';
|
|
18
18
|
import * as sinon from 'sinon';
|
|
19
|
-
import { StreamingAsyncIterator } from './openai-streaming-iterator';
|
|
19
|
+
import { StreamingAsyncIterator } from './openai-streaming-iterator.js';
|
|
20
20
|
import { ChatCompletionStream } from 'openai/lib/ChatCompletionStream';
|
|
21
21
|
import { CancellationTokenSource, CancellationError } from '@theia/core';
|
|
22
22
|
import { LanguageModelStreamResponsePart, isTextResponsePart, isToolCallResponsePart } from '@theia/ai-core';
|
|
@@ -18,8 +18,9 @@ import { LanguageModelStreamResponsePart, ToolCallResult, ToolCallTextResult } f
|
|
|
18
18
|
import { CancellationError, CancellationToken } from '@theia/core';
|
|
19
19
|
import { ChatCompletionStream, ChatCompletionStreamEvents } from 'openai/lib/ChatCompletionStream';
|
|
20
20
|
import { ChatCompletionContentPartText } from 'openai/resources';
|
|
21
|
-
import { AbstractStreamingResponseIterator } from './streaming-response-iterator';
|
|
21
|
+
import { AbstractStreamingResponseIterator } from './streaming-response-iterator.js';
|
|
22
22
|
|
|
23
|
+
/** @deprecated Use `ChatCompletionStreamingAsyncIterator` from './openai-chat-completion-stream' instead. */
|
|
23
24
|
export class StreamingAsyncIterator extends AbstractStreamingResponseIterator {
|
|
24
25
|
|
|
25
26
|
constructor(
|