Repository navigation
Expand file tree
/
Copy pathresponsesApi.ts
More file actions
1564 lines (1445 loc) · 63.7 KB
/
Copy pathresponsesApi.ts
File metadata and controls
1564 lines (1445 loc) · 63.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as l10n from '@vscode/l10n';
import { Raw } from '@vscode/prompt-tsx';
import type { OpenAI } from 'openai';
import { Response } from '../../../platform/networking/common/fetcherService';
import { coalesce } from '../../../util/vs/base/common/arrays';
import { AsyncIterableObject } from '../../../util/vs/base/common/async';
import { binaryIndexOf } from '../../../util/vs/base/common/buffer';
import { Lazy } from '../../../util/vs/base/common/lazy';
import { SSEParser } from '../../../util/vs/base/common/sseParser';
import { isDefined } from '../../../util/vs/base/common/types';
import { generateUuid } from '../../../util/vs/base/common/uuid';
import { IInstantiationService, ServicesAccessor } from '../../../util/vs/platform/instantiation/common/instantiation';
import { ChatLocation } from '../../chat/common/commonTypes';
import { ConfigKey, IConfigurationService } from '../../configuration/common/configurationService';
import { ILogService } from '../../log/common/logService';
import { CUSTOM_TOOL_SEARCH_NAME } from '../../networking/common/anthropic';
import { FinishedCallback, getRequestId, IResponseDelta, OpenAiFunctionTool, OpenAiResponsesFunctionTool, OpenAiToolSearchTool } from '../../networking/common/fetch';
import { IChatEndpoint, ICreateEndpointBodyOptions, IEndpointBody } from '../../networking/common/networking';
import { APIErrorResponse, ChatCompletion, FilterReason, FinishedCompletionReason, modelsWithoutResponsesContextManagement, openAIContextManagementCompactionType, OpenAIContextManagementResponse, rawMessageToCAPI, TokenLogProb } from '../../networking/common/openai';
import { IToolDeferralService } from '../../networking/common/toolDeferralService';
import { sendEngineMessagesTelemetry, sendResponsesApiCompactionTelemetry } from '../../networking/node/chatStream';
import { IChatWebSocketManager } from '../../networking/node/chatWebSocketManager';
import { IExperimentationService } from '../../telemetry/common/nullExperimentationService';
import { ITelemetryService } from '../../telemetry/common/telemetry';
import { TelemetryData } from '../../telemetry/common/telemetryData';
import { getVerbosityForModelSync, modelSupportCacheBreakPoints } from '../common/chatModelCapabilities';
import { rawPartAsCompactionData } from '../common/compactionDataContainer';
import { rawPartAsPhaseData } from '../common/phaseDataContainer';
import { getIndexOfStatefulMarker, getStatefulMarkerAndIndex, MISSING_STATEFUL_TOOL_RESULT } from '../common/statefulMarkerContainer';
import { rawPartAsThinkingData } from '../common/thinkingDataContainer';
import { createResponsesStreamDumper } from './responsesApiDebugDump';
export function getResponsesApiCompactionThreshold(configService: IConfigurationService, expService: IExperimentationService, endpoint: IChatEndpoint): number | undefined {
const contextManagementEnabled = configService.getExperimentBasedConfig(ConfigKey.ResponsesApiContextManagementEnabled, expService) && !modelsWithoutResponsesContextManagement.has(endpoint.family);
if (!contextManagementEnabled) {
return undefined;
}
return endpoint.modelMaxPromptTokens > 0
? Math.floor(endpoint.modelMaxPromptTokens * 0.9)
: 50000;
}
export function getVerbosityForModelSyncBasedOnExp(configService: IConfigurationService, expService: IExperimentationService, endpoint: IChatEndpoint): 'low' | 'medium' | 'high' | undefined {
return getVerbosityForModelSync(endpoint, configService.getExperimentBasedConfig(ConfigKey.EnableGpt56Verbosity, expService));
}
export function createResponsesRequestBody(accessor: ServicesAccessor, options: ICreateEndpointBodyOptions, model: string, endpoint: IChatEndpoint): IEndpointBody {
const configService = accessor.get(IConfigurationService);
const expService = accessor.get(IExperimentationService);
const verbosity = getVerbosityForModelSyncBasedOnExp(configService, expService, endpoint);
const compactThreshold = getResponsesApiCompactionThreshold(configService, expService, endpoint);
// compaction supported for all the models but works well for codex models and any future models after 5.3
const webSocketStatefulMarker = resolveWebSocketStatefulMarker(accessor, options, model);
// When WebSocket is in use, always defer to the WebSocket marker (which may be
// undefined if the connection is new or the summary state changed). Never fall
// back to the HTTP marker lookup in that case.
const ignoreStatefulMarker = !!options.ignoreStatefulMarker || !!options.useWebSocket;
const modeChanged = !!options.modeChanged;
// Tool search: when enabled, split tools into non-deferred (included in the request) and deferred
// (excluded from the request entirely). Uses OpenAI's client-executed tool search protocol: we add
// { type: 'tool_search', execution: 'client' }. The model emits tool_search_call, which we handle via
// our ToolSearchTool embeddings search, then round-trip as tool_search_output in the next request.
const toolSearchEnabled = !!endpoint.supportsToolSearch
&& !!options.requestOptions?.tools?.some(t => t.function.name === CUSTOM_TOOL_SEARCH_NAME);
const isAllowedConversationAgent = options.location === ChatLocation.Agent || options.location === ChatLocation.MessagesProxy;
const isSubagent = options.telemetryProperties?.subType?.startsWith('subagent') ?? false;
const shouldDeferTools = toolSearchEnabled && isAllowedConversationAgent && !isSubagent;
const toolDeferralService = shouldDeferTools ? accessor.get(IToolDeferralService) : undefined;
type ResponsesFunctionTool = OpenAI.Responses.FunctionTool & OpenAiResponsesFunctionTool;
const functionTools: ResponsesFunctionTool[] = [];
if (options.requestOptions?.tools) {
for (const tool of options.requestOptions.tools) {
if (!tool.function.name || tool.function.name.length === 0) {
continue;
}
// Always skip the tool_search function tool — 'tool_search' is a reserved namespace in the
// Responses API. Client-executed tool search uses { type: 'tool_search', execution: 'client' } instead.
if (tool.function.name === CUSTOM_TOOL_SEARCH_NAME) {
continue;
}
const isDeferred = shouldDeferTools && !toolDeferralService!.isNonDeferredTool(tool.function.name);
// Client-executed tool search: deferred tools are NOT sent in the request.
// They are returned via tool_search_output when the model searches for them.
if (isDeferred) {
continue;
}
functionTools.push({
...tool.function,
type: 'function',
strict: false,
parameters: (tool.function.parameters || { type: 'object', properties: {} }) as Record<string, unknown>,
});
}
}
// Build final tools array
const finalTools: Array<ResponsesFunctionTool | OpenAiToolSearchTool | ClientToolSearchTool> = [...functionTools];
if (shouldDeferTools) {
// Client-executed tool search: the model emits tool_search_call, our ToolSearchTool
// handles the embeddings search, and we return tool_search_output with full definitions.
finalTools.unshift({
type: 'tool_search',
execution: 'client',
description: 'Search for relevant tools by describing what you need. Returns tool definitions for tools matching your query.',
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'Natural language description of what tool capability you are looking for.',
},
},
required: ['query'],
},
} as ClientToolSearchTool);
}
const toolsMap = options.requestOptions?.tools
? new Map(options.requestOptions.tools.map(t => [t.function.name, t]))
: undefined;
const shouldLoadToolFromToolSearch = shouldDeferTools ? (name: string) => !toolDeferralService!.isNonDeferredTool(name) : undefined;
const promptCacheBreakpointsEnabled = configService.getExperimentBasedConfig(ConfigKey.ResponsesApiPromptCacheBreakpointEnabled, expService);
const modelSupportsCacheBreakpoints = modelSupportCacheBreakPoints(endpoint);
const supportsCacheBreakpoints = promptCacheBreakpointsEnabled && modelSupportsCacheBreakpoints;
const body: IEndpointBody = {
model,
...rawMessagesToResponseAPI(model, options.messages, ignoreStatefulMarker, webSocketStatefulMarker, {
toolsMap,
shouldLoadToolFromToolSearch,
modeChanged,
supportsCacheBreakpoints,
}),
stream: true,
tools: finalTools.length > 0 ? finalTools : undefined,
// Only a subset of completion post options are supported, and some
// are renamed. Handle them manually:
max_output_tokens: options.postOptions.max_tokens,
tool_choice: typeof options.postOptions.tool_choice === 'object'
? { type: 'function', name: options.postOptions.tool_choice.function.name }
: options.postOptions.tool_choice,
top_logprobs: options.postOptions.logprobs ? 3 : undefined,
store: false,
text: verbosity ? { verbosity } : undefined,
prompt_cache_options: modelSupportsCacheBreakpoints ? { mode: supportsCacheBreakpoints ? 'explicit' : 'implicit' } : undefined,
};
if (compactThreshold !== undefined) {
body.context_management = [{
'type': openAIContextManagementCompactionType,
// Trigger compaction at 90% of the model max prompt context to keep headroom for active turns.
'compact_threshold': compactThreshold
}];
}
body.truncation = configService.getConfig(ConfigKey.Advanced.UseResponsesApiTruncation) ?
'auto' :
'disabled';
const effortFromSetting = configService.getConfig(ConfigKey.Advanced.ReasoningEffortOverride);
const effort = endpoint.supportsReasoningEffort?.length
? (effortFromSetting || options.modelCapabilities?.reasoningEffort || 'medium')
: undefined;
const summary: string | undefined = undefined;
if (effort || summary) {
body.reasoning = {
...(effort ? { effort } : {}),
...(summary ? { summary } : {})
};
}
body.include = ['reasoning.encrypted_content'];
const promptCacheKeyEnabled = configService.getExperimentBasedConfig(ConfigKey.ResponsesApiPromptCacheKeyEnabled, expService);
if (promptCacheKeyEnabled && options.conversationId) {
body.prompt_cache_key = `${options.conversationId}:${endpoint.family}`;
}
return body;
}
export function getResponsesApiCompactionThresholdFromBody(body: Pick<IEndpointBody, 'context_management'>): number | undefined {
const contextManagement = body.context_management;
if (!Array.isArray(contextManagement)) {
return undefined;
}
for (const item of contextManagement) {
if (item.type === openAIContextManagementCompactionType && typeof item.compact_threshold === 'number') {
return item.compact_threshold;
}
}
return undefined;
}
interface ResponseInputAssistantTextContentPart {
type: 'output_text';
text: string;
}
interface ResponseInputAssistantMessageWithPhase {
type: 'message';
role: 'assistant';
content: ResponseInputAssistantTextContentPart[];
phase?: string;
}
interface ResponseOutputItemWithPhase {
phase?: string;
}
// ── Responses API tool search types ──────────────────────────────────
// These match the shapes from https://developers.openai.com/api/docs/guides/tools-tool-search
/** Client-executed tool_search tool definition for the Responses API */
interface ClientToolSearchTool {
type: 'tool_search';
execution: 'client';
description: string;
parameters: Record<string, unknown>;
}
interface ResponsesToolSearchCall {
type: 'tool_search_call';
id: string;
execution: 'client';
call_id: string | null;
status: string;
arguments?: Record<string, unknown>;
}
/** Input item shape for a client-executed tool_search_call in conversation history */
interface ResponsesToolSearchCallInput {
type: 'tool_search_call';
execution: 'client';
call_id: string;
status: string;
arguments: Record<string, unknown>;
}
/** Input item shape for a client-executed tool_search_output in conversation history */
interface ResponsesToolSearchOutputInput {
type: 'tool_search_output';
execution: 'client';
call_id: string;
status: string;
tools: ToolSearchLoadedTool[];
}
/** A tool definition returned in tool_search_output */
interface ToolSearchLoadedTool {
type: 'function';
name: string;
description: string;
defer_loading: true;
parameters: object;
strict: false;
}
interface LatestCompactionOutput {
readonly item: OpenAIContextManagementResponse;
readonly outputIndex: number;
}
type CompactionResponseOutputItem = OpenAI.Responses.ResponseOutputItem & OpenAIContextManagementResponse;
interface CompactionItemInChunk {
readonly item: OpenAIContextManagementResponse;
readonly outputIndex: number | undefined;
}
interface ResponseStreamEventWithOutputItem {
readonly item: unknown;
readonly output_index: number;
}
interface ResponseStreamEventWithResponseOutput {
readonly response: {
readonly output: OpenAI.Responses.ResponseOutputItem[];
};
}
function resolveWebSocketStatefulMarker(accessor: ServicesAccessor, options: ICreateEndpointBodyOptions, modelId: string): string | undefined {
if (options.ignoreStatefulMarker || !options.useWebSocket || !options.conversationId) {
return undefined;
}
const wsManager = accessor.get(IChatWebSocketManager);
const connectionKey = { conversationId: options.conversationId, modelId, connectionId: options.webSocketConnectionId };
// If client-side summarization state changed since the stateful marker
// was stored (new summary, or rollback removing a summary), the server's
// state no longer matches. Skip the marker so the full history is sent.
const connSummarizedAt = wsManager.getSummarizedAtRoundId(connectionKey);
if (options.summarizedAtRoundId !== connSummarizedAt) {
return undefined;
}
return wsManager.getStatefulMarker(connectionKey);
}
interface RawMessagesToResponseAPIOptions {
readonly toolsMap?: Map<string, OpenAiFunctionTool>;
readonly shouldLoadToolFromToolSearch?: (name: string) => boolean;
readonly modeChanged?: boolean;
readonly supportsCacheBreakpoints?: boolean;
}
function rawMessagesToResponseAPI(modelId: string, messages: readonly Raw.ChatMessage[], ignoreStatefulMarker: boolean, webSocketStatefulMarker: string | undefined, options: RawMessagesToResponseAPIOptions = {}): { input: OpenAI.Responses.ResponseInputItem[]; previous_response_id?: string } {
const { toolsMap, shouldLoadToolFromToolSearch, modeChanged = false, supportsCacheBreakpoints = false } = options;
const latestCompactionMessageIndex = getLatestCompactionMessageIndex(messages);
const latestCompactionMessage = latestCompactionMessageIndex !== undefined ? createCompactionRoundTripMessage(messages[latestCompactionMessageIndex]) : undefined;
let previousResponseId: string | undefined;
let markerIndex: number | undefined;
if (webSocketStatefulMarker) {
// WebSocket path: use the connection's current stateful marker if present in messages
markerIndex = getIndexOfStatefulMarker(webSocketStatefulMarker, messages);
if (markerIndex !== undefined) {
previousResponseId = webSocketStatefulMarker;
}
} else if (!ignoreStatefulMarker) {
// HTTP path: look up the latest marker for this model from messages
const statefulMarkerAndIndex = getStatefulMarkerAndIndex(modelId, messages);
if (statefulMarkerAndIndex) {
previousResponseId = statefulMarkerAndIndex.statefulMarker;
markerIndex = statefulMarkerAndIndex.index;
}
}
if (modeChanged) {
previousResponseId = undefined;
markerIndex = undefined;
}
let statefulToolCalls: Array<{ id: string; name: string }> = [];
if (markerIndex !== undefined) {
const markerMessage = messages[markerIndex];
if (markerMessage.role === Raw.ChatRole.Assistant && markerMessage.toolCalls?.length) {
statefulToolCalls = markerMessage.toolCalls.map(toolCall => ({ id: toolCall.id, name: toolCall.function.name }));
}
}
const toolSearchCallIds = new Set<string>();
const toolSearchLoadedTools = new Set<string>();
// Only pre-scan when history will be sliced (matches the slicing block below);
// otherwise the serialization loop visits each tool_search_call before its
// result and populates these sets in order on its own.
const willSliceHistory = markerIndex !== undefined || latestCompactionMessageIndex !== undefined;
if (willSliceHistory) {
for (const message of messages) {
if (message.role === Raw.ChatRole.Assistant && message.toolCalls) {
for (const toolCall of message.toolCalls) {
if (toolCall.function.name === CUSTOM_TOOL_SEARCH_NAME) {
toolSearchCallIds.add(toolCall.id);
}
}
} else if (message.role === Raw.ChatRole.Tool && message.toolCallId && toolSearchCallIds.has(message.toolCallId) && toolsMap) {
const resultText = message.content
.filter(c => c.type === Raw.ChatCompletionContentPartKind.Text)
.map(c => c.text)
.join('');
for (const t of buildToolSearchOutputTools(resultText, toolsMap, shouldLoadToolFromToolSearch)) {
toolSearchLoadedTools.add(t.name);
}
}
}
}
if (markerIndex !== undefined) {
// Requests that resume from previous_response_id send only post-marker history,
// but they still need the latest compaction item even when that item predates
// the marker. This keeps both websocket and non-websocket traffic aligned.
messages = messages.slice(markerIndex + 1);
if (latestCompactionMessageIndex !== undefined) {
if (latestCompactionMessageIndex > markerIndex) {
messages = messages.slice(latestCompactionMessageIndex - (markerIndex + 1));
} else if (latestCompactionMessage) {
messages = [latestCompactionMessage, ...messages];
}
}
} else if (latestCompactionMessageIndex !== undefined) {
messages = messages.slice(latestCompactionMessageIndex);
}
// The server retains calls from previous_response_id even when prompt pruning removes
// their local results. Close every call absent from the final post-marker message slice.
const sentToolResultIds = new Set(messages
.filter((message): message is Raw.ToolChatMessage => message.role === Raw.ChatRole.Tool)
.map(message => message.toolCallId));
statefulToolCalls = statefulToolCalls.filter(toolCall => !sentToolResultIds.has(toolCall.id));
const input: OpenAI.Responses.ResponseInputItem[] = [];
for (const toolCall of statefulToolCalls) {
if (toolCall.name === CUSTOM_TOOL_SEARCH_NAME) {
input.push({
type: 'tool_search_output',
execution: 'client',
call_id: toolCall.id,
status: 'completed',
tools: [],
} satisfies ResponsesToolSearchOutputInput as unknown as OpenAI.Responses.ResponseInputItem);
} else {
input.push({
type: 'function_call_output',
call_id: toolCall.id,
output: supportsCacheBreakpoints
? [{ type: 'input_text', text: MISSING_STATEFUL_TOOL_RESULT }]
: MISSING_STATEFUL_TOOL_RESULT,
});
}
}
for (const message of messages) {
switch (message.role) {
case Raw.ChatRole.Assistant:
if (message.content.length) {
input.push(...extractCompactionData(message.content));
input.push(...extractThinkingData(message.content));
const asstContent = message.content.map(rawContentToResponsesAssistantContent).filter(isDefined);
if (asstContent.length) {
const assistantMessage: ResponseInputAssistantMessageWithPhase = {
role: 'assistant',
content: asstContent,
type: 'message',
phase: extractPhaseData(message.content),
};
// The Responses API expects previous assistant message content as output_text/refusal,
// but the SDK's ResponseOutputMessage type requires response-only id/status fields.
input.push(assistantMessage as OpenAI.Responses.ResponseInputItem);
}
}
if (message.toolCalls) {
for (const toolCall of message.toolCalls) {
if (toolCall.function.name === CUSTOM_TOOL_SEARCH_NAME) {
// Client-executed tool search: emit as tool_search_call instead of function_call
toolSearchCallIds.add(toolCall.id);
let parsedArgs: Record<string, unknown> = {};
try { parsedArgs = JSON.parse(toolCall.function.arguments || '{}'); } catch { }
input.push({
type: 'tool_search_call',
execution: 'client',
call_id: toolCall.id,
status: 'completed',
arguments: parsedArgs,
} satisfies ResponsesToolSearchCallInput as unknown as OpenAI.Responses.ResponseInputItem);
} else {
// Tools loaded via tool_search need a namespace field to round-trip correctly
const namespace = toolSearchLoadedTools.has(toolCall.function.name) ? toolCall.function.name : undefined;
input.push({ type: 'function_call', name: toolCall.function.name, arguments: toolCall.function.arguments, call_id: toolCall.id, ...(namespace ? { namespace } : {}) });
}
}
}
break;
case Raw.ChatRole.Tool:
if (message.toolCallId) {
if (toolSearchCallIds.has(message.toolCallId)) {
// Client-executed tool search result: convert tool names to tool_search_output with full definitions
const resultText = message.content
.filter(c => c.type === Raw.ChatCompletionContentPartKind.Text)
.map(c => c.text)
.join('');
const loadedTools = toolsMap ? buildToolSearchOutputTools(resultText, toolsMap, shouldLoadToolFromToolSearch) : [];
for (const t of loadedTools) {
toolSearchLoadedTools.add(t.name);
}
input.push({
type: 'tool_search_output',
execution: 'client',
call_id: message.toolCallId,
status: 'completed',
tools: loadedTools,
} satisfies ResponsesToolSearchOutputInput as unknown as OpenAI.Responses.ResponseInputItem);
} else {
if (supportsCacheBreakpoints) {
input.push({
type: 'function_call_output',
call_id: message.toolCallId,
output: rawContentToResponsesContentList(message.content, true),
});
break;
}
const asText = message.content
.filter(c => c.type === Raw.ChatCompletionContentPartKind.Text)
.map(c => c.text)
.join('');
const asImages = message.content
.filter(c => c.type === Raw.ChatCompletionContentPartKind.Image)
.map((c): OpenAI.Responses.ResponseInputImage => ({
type: 'input_image',
detail: c.imageUrl.detail || 'auto',
image_url: c.imageUrl.url,
}));
const asFiles = message.content
.filter((c): c is RawDocumentContentPart => c.type === Raw.ChatCompletionContentPartKind.Document)
.map(rawDocumentToResponsesInputFile)
.filter(isDefined);
// Preserve the legacy string output and synthetic media messages unless explicit
// prompt cache breakpoints are both enabled and supported by the model.
input.push({ type: 'function_call_output', call_id: message.toolCallId, output: asText });
if (asImages.length) {
input.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Image associated with the above tool call:' }, ...asImages] });
}
if (asFiles.length) {
input.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'PDF associated with the above tool call:' }, ...asFiles] });
}
}
}
break;
case Raw.ChatRole.User:
input.push({ type: 'message', role: 'user', content: rawContentToResponsesContentList(message.content, supportsCacheBreakpoints) });
break;
case Raw.ChatRole.System:
input.push({ type: 'message', role: 'system', content: rawContentToResponsesContentList(message.content, supportsCacheBreakpoints) });
break;
}
}
return { input, previous_response_id: previousResponseId };
}
/**
* Converts a JSON array of tool names (from ToolSearchTool) into full tool definitions
* for the tool_search_output. Falls back to an empty array on parse failure.
*/
function buildToolSearchOutputTools(resultText: string, toolsMap: Map<string, OpenAiFunctionTool>, shouldLoadToolFromToolSearch: ((name: string) => boolean) | undefined): ToolSearchLoadedTool[] {
let toolNames: unknown;
try { toolNames = JSON.parse(resultText); } catch { return []; }
if (!Array.isArray(toolNames)) { return []; }
return toolNames
.filter((name): name is string => typeof name === 'string' && name !== CUSTOM_TOOL_SEARCH_NAME && toolsMap.has(name) && shouldLoadToolFromToolSearch?.(name) === true)
.map(name => {
const tool = toolsMap.get(name)!;
return {
type: 'function' as const,
name: tool.function.name,
description: tool.function.description || '',
defer_loading: true as const,
parameters: tool.function.parameters || { type: 'object', properties: {} },
strict: false as const,
};
});
}
function createCompactionRoundTripMessage(message: Raw.ChatMessage): Raw.ChatMessage | undefined {
if (message.role !== Raw.ChatRole.Assistant) {
return undefined;
}
const content = message.content.filter(part => part.type === Raw.ChatCompletionContentPartKind.Opaque && rawPartAsCompactionData(part));
if (!content.length) {
return undefined;
}
return {
role: Raw.ChatRole.Assistant,
content,
};
}
function getLatestCompactionMessageIndex(messages: readonly Raw.ChatMessage[]): number | undefined {
for (let idx = messages.length - 1; idx >= 0; idx--) {
const message = messages[idx];
for (const part of message.content) {
if (part.type === Raw.ChatCompletionContentPartKind.Opaque && rawPartAsCompactionData(part)) {
return idx;
}
}
}
return undefined;
}
type RawDocumentContentPart = Extract<Raw.ChatCompletionContentPart, { type: Raw.ChatCompletionContentPartKind.Document }>;
function rawDocumentToResponsesInputFile(part: RawDocumentContentPart): OpenAI.Responses.ResponseInputFile | undefined {
if (part.documentData.mediaType !== 'application/pdf') {
return undefined;
}
return {
type: 'input_file',
filename: 'document.pdf',
file_data: `data:${part.documentData.mediaType};base64,${part.documentData.data}`,
};
}
type ResponsesConvertibleContent = OpenAI.Responses.ResponseInputText | OpenAI.Responses.ResponseInputImage | OpenAI.Responses.ResponseInputFile;
function rawContentToResponsesContent(part: Raw.ChatCompletionContentPart): ResponsesConvertibleContent | undefined {
switch (part.type) {
case Raw.ChatCompletionContentPartKind.Text:
return { type: 'input_text', text: part.text };
case Raw.ChatCompletionContentPartKind.Image:
return { type: 'input_image', detail: part.imageUrl.detail || 'auto', image_url: part.imageUrl.url };
case Raw.ChatCompletionContentPartKind.Document:
return rawDocumentToResponsesInputFile(part);
case Raw.ChatCompletionContentPartKind.Opaque: {
const maybeCast = part.value as ResponsesConvertibleContent;
if (maybeCast.type === 'input_text' || maybeCast.type === 'input_image' || maybeCast.type === 'input_file') {
return maybeCast;
}
}
}
}
function rawContentToResponsesAssistantContent(part: Raw.ChatCompletionContentPart): Pick<OpenAI.Responses.ResponseOutputText, 'type' | 'text'> | undefined {
switch (part.type) {
case Raw.ChatCompletionContentPartKind.Text:
if (part.text.trim()) {
return { type: 'output_text', text: part.text };
}
}
}
interface ResponsesPromptCacheBreakpoint {
readonly mode: 'explicit';
}
type ResponsesCacheableContent = ResponsesConvertibleContent & {
prompt_cache_breakpoint?: ResponsesPromptCacheBreakpoint;
};
const promptCacheBreakpoint: ResponsesPromptCacheBreakpoint = { mode: 'explicit' };
function rawContentToResponsesContentList(parts: readonly Raw.ChatCompletionContentPart[], supportsCacheBreakpoints: boolean): ResponsesConvertibleContent[] {
const content: ResponsesCacheableContent[] = [];
let target: ResponsesCacheableContent | undefined;
for (const part of parts) {
if (part.type === Raw.ChatCompletionContentPartKind.CacheBreakpoint) {
if (supportsCacheBreakpoints && target) {
target.prompt_cache_breakpoint = promptCacheBreakpoint;
}
continue;
}
const converted = rawContentToResponsesContent(part);
if (converted) {
target = converted;
content.push(target);
} else {
target = undefined;
}
}
return content;
}
/**
* The Responses API rejects the entire request with
* `400 invalid_request_body: Invalid 'input[N].id': '...'. Expected an ID that begins with 'rs'.`
* when a reasoning item is round-tripped with an id it did not issue. Reasoning items
* produced by the Responses API always carry an id beginning with `rs`. Thinking blocks
* that originated from a different API (e.g. the Anthropic Messages API, whose accumulator
* generates `thinking_<index>` ids) can leak into a Responses request — most notably via the
* `vscode.lm` access path, which has no model gate — and their `encrypted_content` is not a
* valid Responses reasoning blob anyway. Such foreign reasoning items must be dropped, not sent.
*/
function isResponsesReasoningId(id: string | undefined): boolean {
return typeof id === 'string' && id.startsWith('rs');
}
function extractThinkingData(content: Raw.ChatCompletionContentPart[]): OpenAI.Responses.ResponseReasoningItem[] {
return coalesce(content.map(part => {
if (part.type === Raw.ChatCompletionContentPartKind.Opaque) {
const thinkingData = rawPartAsThinkingData(part);
// Only round-trip genuine Responses API reasoning items. A foreign id (or a thinking
// block with no encrypted payload) would otherwise 400 the whole request.
if (thinkingData && thinkingData.encrypted && isResponsesReasoningId(thinkingData.id)) {
return {
type: 'reasoning',
id: thinkingData.id,
summary: [],
encrypted_content: thinkingData.encrypted,
} satisfies OpenAI.Responses.ResponseReasoningItem;
}
}
}));
}
function extractPhaseData(content: Raw.ChatCompletionContentPart[]): string | undefined {
for (const part of content) {
if (part.type === Raw.ChatCompletionContentPartKind.Opaque) {
const phase = rawPartAsPhaseData(part);
if (phase) {
return phase;
}
}
}
return undefined;
}
/**
* Extracts compaction data from opaque content parts and converts them to
* Responses API input items for round-tripping.
*/
function extractCompactionData(content: Raw.ChatCompletionContentPart[]): OpenAI.Responses.ResponseInputItem[] {
return coalesce(content.map(part => {
if (part.type === Raw.ChatCompletionContentPartKind.Opaque) {
const compaction = rawPartAsCompactionData(part);
if (compaction) {
return {
type: openAIContextManagementCompactionType,
id: compaction.id,
encrypted_content: compaction.encrypted_content,
} as unknown as OpenAI.Responses.ResponseInputItem;
}
}
}));
}
/**
* This is an approximate responses input -> raw messages helper, should be used for logging only
*/
export function responseApiInputToRawMessagesForLogging(body: OpenAI.Responses.ResponseCreateParams): Raw.ChatMessage[] {
const messages: Raw.ChatMessage[] = [];
const pendingFunctionCalls: Raw.ChatMessageToolCall[] = [];
const flushPendingFunctionCalls = () => {
if (pendingFunctionCalls.length > 0) {
messages.push({
role: Raw.ChatRole.Assistant,
content: [],
toolCalls: pendingFunctionCalls.splice(0)
});
}
};
// Add system instructions if provided
if (body.instructions) {
messages.push({
role: Raw.ChatRole.System,
content: [{ type: Raw.ChatCompletionContentPartKind.Text, text: body.instructions }]
});
}
// Convert input to array format if it's a string
const inputItems = typeof body.input === 'string' ? [{ role: 'user' as const, content: body.input, type: 'message' as const }] : (body.input ?? []);
for (const item of inputItems) {
// Handle message items with roles
if ('role' in item) {
switch (item.role) {
case 'user':
flushPendingFunctionCalls();
messages.push({
role: Raw.ChatRole.User,
content: ensureContentArray(item.content).map(responseContentToRawContent).filter(isDefined)
});
break;
case 'system':
case 'developer':
flushPendingFunctionCalls();
messages.push({
role: Raw.ChatRole.System,
content: ensureContentArray(item.content).map(responseContentToRawContent).filter(isDefined)
});
break;
case 'assistant':
flushPendingFunctionCalls();
if (isResponseOutputMessage(item)) {
messages.push({
role: Raw.ChatRole.Assistant,
content: item.content.map(responseOutputToRawContent).filter(isDefined)
});
} else if (isResponseInputItemMessage(item)) {
messages.push({
role: Raw.ChatRole.Assistant,
content: ensureContentArray(item.content).map(responseContentToRawContent).filter(isDefined)
});
}
break;
}
} else if ('type' in item) {
// Handle other item types without roles
switch (item.type) {
case 'function_call':
// Collect function calls to be grouped with the next assistant message
pendingFunctionCalls.push({
id: item.call_id,
type: 'function',
function: {
name: item.name,
arguments: item.arguments
}
});
break;
case 'function_call_output': {
flushPendingFunctionCalls();
const content = responseFunctionOutputToRawContents(item.output);
messages.push({
role: Raw.ChatRole.Tool,
content,
toolCallId: item.call_id
});
break;
}
case 'reasoning':
// We can't perfectly reconstruct the original thinking data
// but we can add a placeholder for logging
flushPendingFunctionCalls();
messages.push({
role: Raw.ChatRole.Assistant,
content: [{
type: Raw.ChatCompletionContentPartKind.Text,
text: `Reasoning summary: ${item.summary.map(s => s.text).join('\n\n')}`
}]
});
break;
default: {
// Client-executed tool search items (tool_search_call / tool_search_output)
const tsItem = item as unknown as ResponsesToolSearchCallInput | ResponsesToolSearchOutputInput;
if (tsItem.type === 'tool_search_call') {
pendingFunctionCalls.push({
id: tsItem.call_id,
type: 'function',
function: {
name: CUSTOM_TOOL_SEARCH_NAME,
arguments: JSON.stringify(tsItem.arguments ?? {}),
}
});
} else if (tsItem.type === 'tool_search_output') {
flushPendingFunctionCalls();
const toolNames = tsItem.tools.map(t => t.name);
messages.push({
role: Raw.ChatRole.Tool,
content: [{
type: Raw.ChatCompletionContentPartKind.Text,
text: JSON.stringify(toolNames),
}],
toolCallId: tsItem.call_id,
});
}
break;
}
}
}
}
// Flush any remaining function calls at the end
if (pendingFunctionCalls.length > 0) {
messages.push({
role: Raw.ChatRole.Assistant,
content: [],
toolCalls: pendingFunctionCalls.splice(0)
});
}
return messages;
}
function isResponseOutputMessage(item: OpenAI.Responses.ResponseInputItem): item is OpenAI.Responses.ResponseOutputMessage {
return 'role' in item && item.role === 'assistant' && 'type' in item && item.type === 'message' && 'content' in item && Array.isArray(item.content);
}
function isResponseInputItemMessage(item: OpenAI.Responses.ResponseInputItem): item is OpenAI.Responses.ResponseInputItem.Message {
return 'role' in item && item.role === 'assistant' && (!('type' in item) || item.type !== 'message');
}
function ensureContentArray(content: string | OpenAI.Responses.ResponseInputMessageContentList): OpenAI.Responses.ResponseInputMessageContentList {
if (typeof content === 'string') {
return [{ type: 'input_text', text: content }];
}
return content;
}
function responseContentToRawContent(part: OpenAI.Responses.ResponseInputContent | OpenAI.Responses.ResponseFunctionCallOutputItem): Raw.ChatCompletionContentPart | undefined {
switch (part.type) {
case 'input_text':
return { type: Raw.ChatCompletionContentPartKind.Text, text: part.text };
case 'input_image':
return {
type: Raw.ChatCompletionContentPartKind.Image,
imageUrl: {
url: part.image_url || '',
detail: part.detail === 'auto' ?
undefined :
(part.detail ?? undefined)
}
};
case 'input_file':
// This is a rough approximation for logging
return {
type: Raw.ChatCompletionContentPartKind.Opaque,
value: `[File Input - Filename: ${part.filename || 'unknown'}]`
};
}
}
function responseOutputToRawContent(part: OpenAI.Responses.ResponseOutputText | OpenAI.Responses.ResponseOutputRefusal): Raw.ChatCompletionContentPart | undefined {
switch (part.type) {
case 'output_text':
return { type: Raw.ChatCompletionContentPartKind.Text, text: part.text };
case 'refusal':
return { type: Raw.ChatCompletionContentPartKind.Text, text: `[Refusal: ${part.refusal}]` };
}
}
function responseFunctionOutputToRawContents(output: string | OpenAI.Responses.ResponseFunctionCallOutputItemList): Raw.ChatCompletionContentPart[] {
if (typeof output === 'string') {
return [{ type: Raw.ChatCompletionContentPartKind.Text, text: output }];
}
return coalesce(output.map(responseContentToRawContent));
}
function isCompactionItem(value: unknown): value is OpenAIContextManagementResponse {
return typeof value === 'object' && value !== null && 'type' in value && String(value.type) === openAIContextManagementCompactionType;
}
function hasOutputItem(chunk: OpenAI.Responses.ResponseStreamEvent): chunk is OpenAI.Responses.ResponseStreamEvent & ResponseStreamEventWithOutputItem {
return 'item' in chunk && 'output_index' in chunk && typeof chunk.output_index === 'number';
}
function hasResponseOutput(chunk: OpenAI.Responses.ResponseStreamEvent): chunk is OpenAI.Responses.ResponseStreamEvent & ResponseStreamEventWithResponseOutput {
return 'response' in chunk && Array.isArray(chunk.response.output);
}
function getOutputItemIndex(chunk: ResponseStreamEventWithOutputItem): number {
return chunk.output_index;
}
function isCompactionOutputItem(item: OpenAI.Responses.ResponseOutputItem): item is CompactionResponseOutputItem {
return isCompactionItem(item);
}
function getLatestCompactionOutput(output: OpenAI.Responses.ResponseOutputItem[], preferredOutputIndex: number | undefined): LatestCompactionOutput | undefined {
let latestCompactionOutput: LatestCompactionOutput | undefined;
for (let idx = output.length - 1; idx >= 0; idx--) {
const item = output[idx];
if (isCompactionOutputItem(item)) {
latestCompactionOutput = { item, outputIndex: idx };
break;
}
}
if (preferredOutputIndex !== undefined) {
const preferredItem = output[preferredOutputIndex];
if (preferredItem && isCompactionOutputItem(preferredItem) && (!latestCompactionOutput || preferredOutputIndex >= latestCompactionOutput.outputIndex)) {
return { item: preferredItem, outputIndex: preferredOutputIndex };
}
}
return latestCompactionOutput;
}
function keepLatestCompactionOutput(output: OpenAI.Responses.ResponseOutputItem[], preferredOutputIndex: number | undefined): OpenAI.Responses.ResponseOutputItem[] {
const latestCompactionOutput = getLatestCompactionOutput(output, preferredOutputIndex);
if (!latestCompactionOutput) {
return output;
}
return output.filter((item, idx) => !isCompactionOutputItem(item) || idx === latestCompactionOutput.outputIndex);
}
export async function processResponseFromChatEndpoint(instantiationService: IInstantiationService, telemetryService: ITelemetryService, logService: ILogService, response: Response, expectedNumChoices: number, finishCallback: FinishedCallback, telemetryData: TelemetryData, compactionThreshold?: number, emitStatefulMarker = true): Promise<AsyncIterableObject<ChatCompletion>> {
return new AsyncIterableObject<ChatCompletion>(async feed => {
const requestId = response.headers.get('X-Request-ID') ?? generateUuid();
const ghRequestId = response.headers.get('x-github-request-id') ?? '';
const { serverExperiments } = getRequestId(response.headers);
const processor = instantiationService.createInstance(OpenAIResponsesProcessor, telemetryData, telemetryService, requestId, ghRequestId, serverExperiments, compactionThreshold);
const dumper = createResponsesStreamDumper(requestId, logService);
const parser = new SSEParser((ev) => {
try {
logService.trace(`SSE: ${ev.data}`);
if (ev.data === '[DONE]') {
// Some OpenAI-compatible gateways (e.g. LiteLLM) emit the chat-completions
// `[DONE]` sentinel at the end of a Responses stream. Ignore it.
return;
}
const parsedData = JSON.parse(ev.data);
const responseStreamEvent: OpenAI.Responses.ResponseStreamEvent = { type: ev.type, ...parsedData };
dumper.logEvent(responseStreamEvent);
const completion = processor.push(responseStreamEvent, finishCallback, emitStatefulMarker);
if (completion) {
sendCompletionOutputTelemetry(telemetryService, logService, completion, telemetryData);
feed.emitOne(completion);
}
} catch (e) {
feed.reject(e);
}
});
for await (const chunk of response.body) {
parser.feed(chunk);
}
}, async () => {
await response.body.destroy();
});
}
export function sendCompletionOutputTelemetry(telemetryService: ITelemetryService, logService: ILogService, completion: ChatCompletion, telemetryData: TelemetryData): void {
const telemetryMessage = rawMessageToCAPI(completion.message);
let telemetryDataWithUsage = telemetryData;