-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathchatMLFetcher.ts
More file actions
2198 lines (2014 loc) · 88.7 KB
/
chatMLFetcher.ts
File metadata and controls
2198 lines (2014 loc) · 88.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 { Raw } from '@vscode/prompt-tsx';
import type { OpenAI } from 'openai';
import type { CancellationToken } from 'vscode';
import { IAuthenticationService } from '../../../platform/authentication/common/authentication';
import { CopilotToken } from '../../../platform/authentication/common/copilotToken';
import { FetchStreamRecorder, IChatMLFetcher, IFetchMLOptions, Source } from '../../../platform/chat/common/chatMLFetcher';
import { IChatQuotaService } from '../../../platform/chat/common/chatQuotaService';
import { ChatFetchError, ChatFetchResponseType, ChatFetchRetriableError, ChatLocation, ChatResponse, ChatResponses, RESPONSE_CONTAINED_NO_CHOICES } from '../../../platform/chat/common/commonTypes';
import { IConversationOptions } from '../../../platform/chat/common/conversationOptions';
import { getTextPart, toTextParts } from '../../../platform/chat/common/globalStringUtils';
import { IInteractionService } from '../../../platform/chat/common/interactionService';
import { ConfigKey, HARD_TOOL_LIMIT, IConfigurationService } from '../../../platform/configuration/common/configurationService';
import { ICAPIClientService } from '../../../platform/endpoint/common/capiClient';
import { isAutoModel } from '../../../platform/endpoint/node/autoChatEndpoint';
import { OpenAIResponsesProcessor, responseApiInputToRawMessagesForLogging, sendCompletionOutputTelemetry } from '../../../platform/endpoint/node/responsesApi';
import { collectSingleLineErrorMessage, ILogService } from '../../../platform/log/common/logService';
import { isAnthropicToolSearchEnabled } from '../../../platform/networking/common/anthropic';
import { FinishedCallback, getRequestId, IResponseDelta, OptionalChatRequestParams, RequestId } from '../../../platform/networking/common/fetch';
import { FetcherId, IFetcherService, Response } from '../../../platform/networking/common/fetcherService';
import { IBackgroundRequestOptions, IChatEndpoint, IEndpointBody, ISubagentRequestOptions, postRequest, stringifyUrlOrRequestMetadata } from '../../../platform/networking/common/networking';
import { CAPIChatMessage, ChatCompletion, FilterReason, FinishedCompletionReason, rawMessageToCAPI } from '../../../platform/networking/common/openai';
import { sendEngineMessagesTelemetry } from '../../../platform/networking/node/chatStream';
import { CAPIWebSocketErrorEvent, IChatWebSocketManager, isCAPIWebSocketError } from '../../../platform/networking/node/chatWebSocketManager';
import { sendCommunicationErrorTelemetry } from '../../../platform/networking/node/stream';
import { ChatFailKind, ChatRequestCanceled, ChatRequestFailed, ChatResults, FetchResponseKind } from '../../../platform/openai/node/fetch';
import { CopilotChatAttr, emitInferenceDetailsEvent, GenAiAttr, GenAiMetrics, GenAiOperationName, GenAiProviderName, StdAttr, toInputMessages, truncateForOTel } from '../../../platform/otel/common/index';
import { IOTelService, ISpanHandle, SpanKind, SpanStatusCode } from '../../../platform/otel/common/otelService';
import { getCurrentCapturingToken, IRequestLogger } from '../../../platform/requestLogger/node/requestLogger';
import { IExperimentationService } from '../../../platform/telemetry/common/nullExperimentationService';
import { ITelemetryService, TelemetryProperties } from '../../../platform/telemetry/common/telemetry';
import { TelemetryData } from '../../../platform/telemetry/common/telemetryData';
import { isEncryptedThinkingDelta } from '../../../platform/thinking/common/thinking';
import { calculateLineRepetitionStats, isRepetitive } from '../../../util/common/anomalyDetection';
import { ErrorUtils } from '../../../util/common/errors';
import { AsyncIterableObject } from '../../../util/vs/base/common/async';
import { isCancellationError } from '../../../util/vs/base/common/errors';
import { Emitter } from '../../../util/vs/base/common/event';
import { Disposable } from '../../../util/vs/base/common/lifecycle';
import { escapeRegExpCharacters } from '../../../util/vs/base/common/strings';
import { generateUuid } from '../../../util/vs/base/common/uuid';
import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation';
import { isBYOKModel } from '../../byok/node/openAIEndpoint';
import { EXTENSION_ID } from '../../common/constants';
import { IPowerService } from '../../power/common/powerService';
import { ChatMLFetcherTelemetrySender as Telemetry } from './chatMLFetcherTelemetry';
export interface IMadeChatRequestEvent {
readonly messages: Raw.ChatMessage[];
readonly model: string;
readonly source?: Source;
readonly tokenCount?: number;
}
export abstract class AbstractChatMLFetcher extends Disposable implements IChatMLFetcher {
declare _serviceBrand: undefined;
constructor(
protected readonly options: IConversationOptions,
) {
super();
}
protected preparePostOptions(requestOptions: OptionalChatRequestParams): OptionalChatRequestParams {
return {
temperature: this.options.temperature,
top_p: this.options.topP,
// we disallow `stream=false` because we don't support non-streamed response
...requestOptions,
stream: true
};
}
protected readonly _onDidMakeChatMLRequest = this._register(new Emitter<IMadeChatRequestEvent>());
readonly onDidMakeChatMLRequest = this._onDidMakeChatMLRequest.event;
public async fetchOne(opts: IFetchMLOptions, token: CancellationToken): Promise<ChatResponse> {
const resp = await this.fetchMany({
...opts,
requestOptions: { ...opts.requestOptions, n: 1 }
}, token);
if (resp.type === ChatFetchResponseType.Success) {
return { ...resp, value: resp.value[0] };
}
return resp;
}
/**
* Note: the returned array of strings may be less than `n` (e.g., in case there were errors during streaming)
*/
public abstract fetchMany(opts: IFetchMLOptions, token: CancellationToken): Promise<ChatResponses>;
}
export class ChatMLFetcherImpl extends AbstractChatMLFetcher {
private static readonly _maxConsecutiveWebSocketFallbacks = 3;
/**
* Delays (in ms) between connectivity check attempts before retrying a failed request.
* Configurable for testing purposes.
*/
public connectivityCheckDelays = [1000, 10000, 10000];
/**
* Tracks consecutive WebSocket request failures where the HTTP retry succeeded.
* After {@link _maxConsecutiveWebSocketFallbacks} such failures, WebSocket requests are disabled entirely.
*/
private _consecutiveWebSocketRetryFallbacks = 0;
constructor(
@IFetcherService private readonly _fetcherService: IFetcherService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IRequestLogger private readonly _requestLogger: IRequestLogger,
@ILogService private readonly _logService: ILogService,
@IAuthenticationService private readonly _authenticationService: IAuthenticationService,
@IInteractionService private readonly _interactionService: IInteractionService,
@IChatQuotaService private readonly _chatQuotaService: IChatQuotaService,
@ICAPIClientService private readonly _capiClientService: ICAPIClientService,
@IConversationOptions options: IConversationOptions,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IExperimentationService private readonly _experimentationService: IExperimentationService,
@IPowerService private readonly _powerService: IPowerService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IChatWebSocketManager private readonly _webSocketManager: IChatWebSocketManager,
@IOTelService private readonly _otelService: IOTelService,
) {
super(options);
}
/**
* Note: the returned array of strings may be less than `n` (e.g., in case there were errors during streaming)
*/
public async fetchMany(opts: IFetchMLOptions, token: CancellationToken): Promise<ChatResponses> {
let { debugName, endpoint: chatEndpoint, finishedCb, location, messages, requestOptions, source, telemetryProperties, userInitiatedRequest, requestKindOptions, conversationId, turnId, useWebSocket, ignoreStatefulMarker } = opts;
if (useWebSocket && this._consecutiveWebSocketRetryFallbacks >= ChatMLFetcherImpl._maxConsecutiveWebSocketFallbacks) {
this._logService.debug(`[ChatWebSocketManager] Disabling WebSocket for request due to ${this._consecutiveWebSocketRetryFallbacks} consecutive WebSocket failures with successful HTTP fallback.`);
useWebSocket = false;
ignoreStatefulMarker = true;
}
if (!telemetryProperties) {
telemetryProperties = {};
}
if (!telemetryProperties.messageSource) {
telemetryProperties.messageSource = debugName;
}
const transport = useWebSocket ? 'websocket' : 'http';
// TODO @lramos15 telemetry should not drive request ids
const ourRequestId = telemetryProperties.requestId ?? telemetryProperties.messageId ?? generateUuid();
const maxResponseTokens = chatEndpoint.maxOutputTokens;
if (!requestOptions?.prediction) {
requestOptions = { max_tokens: maxResponseTokens, ...requestOptions };
}
// Avoid sending a prediction with no content as this will yield a 400 Bad Request
if (!requestOptions.prediction?.content) {
delete requestOptions['prediction'];
}
const postOptions = this.preparePostOptions(requestOptions);
const requestBody = chatEndpoint.createRequestBody({
...opts,
ignoreStatefulMarker,
requestId: ourRequestId,
postOptions
});
const baseTelemetry = TelemetryData.createAndMarkAsIssued({
...telemetryProperties,
baseModel: chatEndpoint.model,
uiKind: ChatLocation.toString(location)
});
const pendingLoggedChatRequest = this._requestLogger.logChatRequest(debugName, chatEndpoint, {
messages: opts.messages,
model: chatEndpoint.model,
ourRequestId,
location: opts.location,
body: requestBody,
ignoreStatefulMarker,
isConversationRequest: opts.isConversationRequest,
customMetadata: opts.customMetadata
});
let tokenCount = -1;
const streamRecorder = new FetchStreamRecorder(finishedCb);
const enableRetryOnError = opts.enableRetryOnError ?? opts.enableRetryOnFilter;
const canRetryOnce = opts.canRetryOnceWithoutRollback ?? !(opts.enableRetryOnFilter || opts.enableRetryOnError);
let usernameToScrub: string | undefined;
let actualFetcher: FetcherId | undefined;
let actualBytesReceived: number | undefined;
let actualStatusCode: number | undefined;
let suspendEventSeen: boolean | undefined;
let resumeEventSeen: boolean | undefined;
let otelInferenceSpan: ISpanHandle | undefined;
try {
let response: ChatResults | ChatRequestFailed | ChatRequestCanceled;
const payloadValidationResult = isValidChatPayload(opts.messages, postOptions, chatEndpoint, this._configurationService, this._experimentationService);
if (!payloadValidationResult.isValid) {
response = {
type: FetchResponseKind.Failed,
modelRequestId: undefined,
failKind: ChatFailKind.ValidationFailed,
reason: payloadValidationResult.reason,
};
} else {
const copilotToken = await this._authenticationService.getCopilotToken();
usernameToScrub = copilotToken.username;
const fetchResult = await this._fetchAndStreamChat(
chatEndpoint,
requestBody,
baseTelemetry,
streamRecorder.callback,
requestOptions.secretKey,
copilotToken,
opts.location,
ourRequestId,
postOptions.n,
token,
userInitiatedRequest,
useWebSocket,
turnId,
conversationId,
telemetryProperties,
opts.useFetcher,
canRetryOnce,
requestKindOptions,
);
response = fetchResult.result;
actualFetcher = fetchResult.fetcher;
actualBytesReceived = fetchResult.bytesReceived;
actualStatusCode = fetchResult.statusCode;
suspendEventSeen = fetchResult.suspendEventSeen;
resumeEventSeen = fetchResult.resumeEventSeen;
otelInferenceSpan = fetchResult.otelSpan;
// Tag span with debug name so orphaned spans (title, progressMessages, etc.) are identifiable
otelInferenceSpan?.setAttribute(GenAiAttr.AGENT_NAME, debugName);
// Extract and set structured prompt sections — gated by captureContent to prevent OTLP leakage
if (otelInferenceSpan && this._otelService.config.captureContent) {
// Support both Chat Completions API (messages) and Responses API (input) formats
const capiMessages = (requestBody.messages ?? requestBody.input) as ReadonlyArray<{ role?: string; content?: string | unknown[] }> | undefined;
// User request: last user-role message
const userMessages = capiMessages?.filter(m => m.role === 'user');
const lastUserMsg = userMessages?.[userMessages.length - 1];
if (lastUserMsg?.content) {
const userContent = typeof lastUserMsg.content === 'string'
? lastUserMsg.content
: JSON.stringify(lastUserMsg.content);
otelInferenceSpan.setAttribute(CopilotChatAttr.USER_REQUEST, truncateForOTel(userContent));
}
// System instructions — check messages array, top-level system (Anthropic), or instructions (Responses API)
const systemMsg = capiMessages?.find(m => m.role === 'system');
const systemContent = systemMsg?.content
?? (requestBody as Record<string, unknown>).system
?? (requestBody as Record<string, unknown>).instructions;
if (systemContent) {
let systemText: string;
if (typeof systemContent === 'string') {
systemText = systemContent;
} else if (Array.isArray(systemContent)) {
// Anthropic format: array of content blocks — extract text only,
// dropping metadata like cache_control so the value is stable across turns.
systemText = (systemContent as Array<{ text?: string }>)
.map(b => b.text ?? '')
.join('\n');
} else {
systemText = JSON.stringify(systemContent);
}
otelInferenceSpan.setAttribute(GenAiAttr.SYSTEM_INSTRUCTIONS, systemText);
}
}
// Capture full request content — gated by captureContent to prevent OTLP leakage
if (otelInferenceSpan && this._otelService.config.captureContent) {
const capiMessages = (requestBody.messages ?? requestBody.input) as ReadonlyArray<{ role?: string; content?: string | unknown[] }> | undefined;
if (capiMessages) {
// Normalize non-string content (Anthropic arrays, Responses API parts) to strings for OTel schema
const normalized = capiMessages.map(m => ({
...m,
content: typeof m.content === 'string' ? m.content : m.content ? JSON.stringify(m.content) : undefined,
}));
otelInferenceSpan.setAttribute(GenAiAttr.INPUT_MESSAGES, truncateForOTel(JSON.stringify(toInputMessages(normalized))));
}
}
tokenCount = await chatEndpoint.acquireTokenizer().countMessagesTokens(messages);
const extensionId = source?.extensionId ?? EXTENSION_ID;
this._onDidMakeChatMLRequest.fire({
messages,
model: chatEndpoint.model,
source: { extensionId },
tokenCount
});
}
const timeToFirstToken = Date.now() - baseTelemetry.issuedTime;
pendingLoggedChatRequest?.markTimeToFirstToken(timeToFirstToken);
switch (response.type) {
case FetchResponseKind.Success: {
const result = await this.processSuccessfulResponse(response, messages, requestBody, ourRequestId, maxResponseTokens, tokenCount, timeToFirstToken, streamRecorder, baseTelemetry, chatEndpoint, userInitiatedRequest, transport, actualFetcher, actualBytesReceived, suspendEventSeen, resumeEventSeen);
// Handle FilteredRetry case with augmented messages
if (result.type === ChatFetchResponseType.FilteredRetry) {
if (opts.enableRetryOnFilter) {
streamRecorder.callback('', 0, { text: '', retryReason: result.category });
const filteredContent = result.value[0];
if (filteredContent) {
const retryMessage = (result.category === FilterReason.Copyright) ?
`The previous response (copied below) was filtered due to being too similar to existing public code. Please suggest something similar in function that does not match public code. Here's the previous response: ${filteredContent}\n\n` :
`The previous response (copied below) was filtered due to triggering our content safety filters, which looks for hateful, self-harm, sexual, or violent content. Please suggest something similar in content that does not trigger these filters. Here's the previous response: ${filteredContent}\n\n`;
const augmentedMessages: Raw.ChatMessage[] = [
...messages,
{
role: Raw.ChatRole.User,
content: toTextParts(retryMessage)
}
];
// Retry with augmented messages
const retryResult = await this.fetchMany({
...opts,
debugName: 'retry-' + debugName,
messages: augmentedMessages,
finishedCb,
location,
endpoint: chatEndpoint,
source,
requestOptions,
userInitiatedRequest: false, // do not mark the retry as user initiated
telemetryProperties: { ...telemetryProperties, retryAfterFilterCategory: result.category ?? 'uncategorized' },
enableRetryOnFilter: false,
canRetryOnceWithoutRollback: false,
enableRetryOnError,
}, token);
pendingLoggedChatRequest?.resolve(retryResult, streamRecorder.deltas);
if (retryResult.type === ChatFetchResponseType.Success) {
return retryResult;
}
}
}
return {
type: ChatFetchResponseType.Filtered,
category: result.category,
reason: 'Response got filtered.',
requestId: result.requestId,
serverRequestId: result.serverRequestId
};
}
pendingLoggedChatRequest?.resolve(result, streamRecorder.deltas);
// Record OTel token usage metrics if available
if (result.type === ChatFetchResponseType.Success && result.usage) {
const metricAttrs = {
operationName: GenAiOperationName.CHAT,
providerName: GenAiProviderName.GITHUB,
requestModel: chatEndpoint.model,
responseModel: result.resolvedModel,
};
if (result.usage.prompt_tokens) {
GenAiMetrics.recordTokenUsage(this._otelService, result.usage.prompt_tokens, 'input', metricAttrs);
}
if (result.usage.completion_tokens) {
GenAiMetrics.recordTokenUsage(this._otelService, result.usage.completion_tokens, 'output', metricAttrs);
}
// Set token usage and response details on the chat span before ending it
otelInferenceSpan?.setAttributes({
[GenAiAttr.USAGE_INPUT_TOKENS]: result.usage.prompt_tokens ?? 0,
[GenAiAttr.USAGE_OUTPUT_TOKENS]: result.usage.completion_tokens ?? 0,
[GenAiAttr.RESPONSE_MODEL]: result.resolvedModel ?? chatEndpoint.model,
[GenAiAttr.RESPONSE_ID]: result.requestId,
[GenAiAttr.RESPONSE_FINISH_REASONS]: ['stop'],
...(result.usage.prompt_tokens_details?.cached_tokens
? { [GenAiAttr.USAGE_CACHE_READ_INPUT_TOKENS]: result.usage.prompt_tokens_details.cached_tokens }
: {}),
[CopilotChatAttr.TIME_TO_FIRST_TOKEN]: timeToFirstToken,
...(result.serverRequestId ? { [CopilotChatAttr.SERVER_REQUEST_ID]: result.serverRequestId } : {}),
...(result.usage.completion_tokens_details?.reasoning_tokens
? { [GenAiAttr.USAGE_REASONING_TOKENS]: result.usage.completion_tokens_details.reasoning_tokens }
: {}),
});
}
// Capture response content — gated by captureContent to prevent OTLP leakage
if (otelInferenceSpan && this._otelService.config.captureContent && result.type === ChatFetchResponseType.Success) {
const responseText = streamRecorder.deltas.map(d => d.text).join('');
const toolCalls = streamRecorder.deltas
.filter(d => d.copilotToolCalls?.length)
.flatMap(d => d.copilotToolCalls!.map(tc => ({
type: 'tool_call' as const, id: tc.id, name: tc.name, arguments: tc.arguments
})));
const parts: Array<{ type: string; content?: string; id?: string; name?: string; arguments?: unknown }> = [];
if (responseText) {
parts.push({ type: 'text', content: responseText });
}
parts.push(...toolCalls);
if (parts.length > 0) {
otelInferenceSpan.setAttribute(GenAiAttr.OUTPUT_MESSAGES, truncateForOTel(JSON.stringify([{ role: 'assistant', parts }])));
}
// Capture reasoning/thinking text if present
const hasThinking = streamRecorder.deltas.some(d => d.thinking);
if (hasThinking) {
const thinkingTexts = streamRecorder.deltas
.filter(d => d.thinking && !isEncryptedThinkingDelta(d.thinking) && d.thinking.text)
.map(d => {
const t = d.thinking!;
if ('encrypted' in t) { return ''; }
return Array.isArray(t.text) ? t.text.join('') : (t.text ?? '');
});
const reasoningText = thinkingTexts.join('');
otelInferenceSpan.setAttribute(CopilotChatAttr.REASONING_CONTENT, truncateForOTel(reasoningText || '[encrypted]'));
}
}
// Emit OTel inference details event BEFORE ending the span
// so the log record inherits the active trace context
emitInferenceDetailsEvent(
this._otelService,
{
model: chatEndpoint.model,
temperature: requestOptions?.temperature,
maxTokens: requestOptions?.max_tokens,
},
result.type === ChatFetchResponseType.Success ? {
id: result.requestId,
model: result.resolvedModel,
finishReasons: ['stop'],
inputTokens: result.usage?.prompt_tokens,
outputTokens: result.usage?.completion_tokens,
} : undefined,
);
otelInferenceSpan?.end();
otelInferenceSpan = undefined;
// Record OTel time-to-first-token metric
if (timeToFirstToken > 0) {
GenAiMetrics.recordTimeToFirstToken(this._otelService, chatEndpoint.model, timeToFirstToken / 1000);
}
if (useWebSocket && result.type === ChatFetchResponseType.Success) {
this._consecutiveWebSocketRetryFallbacks = 0;
}
return result;
}
case FetchResponseKind.Canceled:
Telemetry.sendCancellationTelemetry(
this._telemetryService,
{
source: telemetryProperties.messageSource ?? 'unknown',
requestId: ourRequestId,
model: chatEndpoint.model,
apiType: chatEndpoint.apiType,
transport,
associatedRequestId: telemetryProperties.associatedRequestId,
retryAfterError: telemetryProperties.retryAfterError,
retryAfterErrorGitHubRequestId: telemetryProperties.retryAfterErrorGitHubRequestId,
connectivityTestError: telemetryProperties.connectivityTestError,
connectivityTestErrorGitHubRequestId: telemetryProperties.connectivityTestErrorGitHubRequestId,
retryAfterFilterCategory: telemetryProperties.retryAfterFilterCategory,
fetcher: actualFetcher,
suspendEventSeen,
resumeEventSeen,
},
{
totalTokenMax: chatEndpoint.modelMaxPromptTokens ?? -1,
promptTokenCount: tokenCount,
tokenCountMax: maxResponseTokens,
timeToFirstToken,
timeToFirstTokenEmitted: (baseTelemetry && streamRecorder.firstTokenEmittedTime) ? streamRecorder.firstTokenEmittedTime - baseTelemetry.issuedTime : -1,
timeToCancelled: Date.now() - baseTelemetry.issuedTime,
isVisionRequest: this.filterImageMessages(messages) ? 1 : -1,
isBYOK: isBYOKModel(chatEndpoint),
isAuto: isAutoModel(chatEndpoint),
bytesReceived: actualBytesReceived,
issuedTime: baseTelemetry.issuedTime,
});
pendingLoggedChatRequest?.resolveWithCancelation();
// Set canceled status on OTel span
otelInferenceSpan?.setAttributes({
[GenAiAttr.RESPONSE_FINISH_REASONS]: ['cancelled'],
[CopilotChatAttr.CANCELED]: true,
});
otelInferenceSpan?.end();
otelInferenceSpan = undefined;
return this.processCanceledResponse(response, ourRequestId, streamRecorder, telemetryProperties);
case FetchResponseKind.Failed: {
const processed = this.processFailedResponse(response, ourRequestId, isAutoModel(chatEndpoint) === 1);
// Retry on server errors based on configured status codes
const retryServerErrorStatusCodes = this._configurationService.getExperimentBasedConfig(ConfigKey.TeamInternal.RetryServerErrorStatusCodes, this._experimentationService);
const statusCodesToRetry = retryServerErrorStatusCodes
.split(',')
.map(s => parseInt(s.trim(), 10));
const retryAfterServerError = enableRetryOnError && actualStatusCode !== undefined && statusCodesToRetry.includes(actualStatusCode);
const retryWithoutWebSocket = enableRetryOnError && useWebSocket && (response.failKind === ChatFailKind.ServerError || response.failKind === ChatFailKind.Unknown);
if (retryAfterServerError || retryWithoutWebSocket) {
const { retryResult } = await this._retryAfterError({
opts,
processed,
telemetryProperties,
requestBody,
tokenCount,
maxResponseTokens,
timeToError: timeToFirstToken,
transport,
actualFetcher,
bytesReceived: actualBytesReceived,
baseTelemetry,
streamRecorder,
retryReason: 'server_error',
debugNamePrefix: 'retry-server-error-',
pendingLoggedChatRequest,
token,
usernameToScrub,
suspendEventSeen,
resumeEventSeen,
});
if (retryResult) {
return retryResult;
}
}
Telemetry.sendResponseErrorTelemetry(this._telemetryService, {
processed,
telemetryProperties,
chatEndpointInfo: chatEndpoint,
requestBody,
tokenCount,
maxResponseTokens,
timeToFirstToken,
isVisionRequest: this.filterImageMessages(messages),
transport,
fetcher: actualFetcher,
bytesReceived: actualBytesReceived,
issuedTime: baseTelemetry.issuedTime,
wasRetried: false,
suspendEventSeen,
resumeEventSeen,
});
pendingLoggedChatRequest?.resolve(processed);
return processed;
}
}
} catch (err) {
// End OTel inference span on error if not already ended
if (otelInferenceSpan) {
otelInferenceSpan.setStatus(SpanStatusCode.ERROR, err instanceof Error ? err.message : String(err));
otelInferenceSpan.setAttribute(StdAttr.ERROR_TYPE, err instanceof Error ? err.constructor.name : 'Error');
otelInferenceSpan.setAttribute(GenAiAttr.RESPONSE_FINISH_REASONS, ['error']);
otelInferenceSpan.recordException(err);
otelInferenceSpan.end();
}
const timeToError = Date.now() - baseTelemetry.issuedTime;
if (err.fetcherId) {
actualFetcher = err.fetcherId;
}
if (err.suspendEventSeen) {
suspendEventSeen = true;
}
if (err.resumeEventSeen) {
resumeEventSeen = true;
}
const processed = this.processError(err, ourRequestId, err.gitHubRequestId, usernameToScrub, isAutoModel(chatEndpoint) === 1);
const retryNetworkError = enableRetryOnError && processed.type === ChatFetchResponseType.NetworkError && this._configurationService.getExperimentBasedConfig(ConfigKey.TeamInternal.RetryNetworkErrors, this._experimentationService);
const retryWithoutWebSocket = enableRetryOnError && useWebSocket && (processed.type === ChatFetchResponseType.NetworkError || processed.type === ChatFetchResponseType.Failed);
if (retryNetworkError || retryWithoutWebSocket) {
const { retryResult, connectivityTestError, connectivityTestErrorGitHubRequestId } = await this._retryAfterError({
opts,
processed,
telemetryProperties,
requestBody,
tokenCount,
maxResponseTokens,
timeToError,
transport,
actualFetcher,
bytesReceived: err.bytesReceived,
baseTelemetry,
streamRecorder,
retryReason: 'network_error',
debugNamePrefix: 'retry-error-',
pendingLoggedChatRequest,
token,
usernameToScrub,
suspendEventSeen,
resumeEventSeen,
});
if (retryResult) {
return retryResult;
}
telemetryProperties = { ...telemetryProperties, connectivityTestError, connectivityTestErrorGitHubRequestId };
}
if (processed.type === ChatFetchResponseType.Canceled) {
Telemetry.sendCancellationTelemetry(
this._telemetryService,
{
source: telemetryProperties.messageSource ?? 'unknown',
requestId: ourRequestId,
model: chatEndpoint.model,
apiType: chatEndpoint.apiType,
transport,
associatedRequestId: telemetryProperties.associatedRequestId,
retryAfterError: telemetryProperties.retryAfterError,
retryAfterErrorGitHubRequestId: telemetryProperties.retryAfterErrorGitHubRequestId,
connectivityTestError: telemetryProperties.connectivityTestError,
connectivityTestErrorGitHubRequestId: telemetryProperties.connectivityTestErrorGitHubRequestId,
retryAfterFilterCategory: telemetryProperties.retryAfterFilterCategory,
fetcher: actualFetcher,
suspendEventSeen,
resumeEventSeen,
},
{
totalTokenMax: chatEndpoint.modelMaxPromptTokens ?? -1,
promptTokenCount: tokenCount,
tokenCountMax: maxResponseTokens,
timeToFirstToken: undefined,
timeToCancelled: timeToError,
isVisionRequest: this.filterImageMessages(messages) ? 1 : -1,
isBYOK: isBYOKModel(chatEndpoint),
isAuto: isAutoModel(chatEndpoint),
bytesReceived: err.bytesReceived,
issuedTime: baseTelemetry.issuedTime,
}
);
} else {
Telemetry.sendResponseErrorTelemetry(this._telemetryService, {
processed,
telemetryProperties,
chatEndpointInfo: chatEndpoint,
requestBody,
tokenCount,
maxResponseTokens,
timeToFirstToken: timeToError,
isVisionRequest: this.filterImageMessages(messages),
transport,
fetcher: actualFetcher,
bytesReceived: err.bytesReceived,
issuedTime: baseTelemetry.issuedTime,
wasRetried: false,
suspendEventSeen,
resumeEventSeen,
});
}
pendingLoggedChatRequest?.resolve(processed);
return processed;
}
}
private async _checkNetworkConnectivity(useFetcher?: FetcherId): Promise<{ retryRequest: boolean; connectivityTestError?: string; connectivityTestErrorGitHubRequestId?: string }> {
// Ping CAPI to check network connectivity before retrying
const delays = this.connectivityCheckDelays;
let connectivityTestError: string | undefined = undefined;
let connectivityTestErrorGitHubRequestId: string | undefined = undefined;
for (const delay of delays) {
this._logService.info(`Waiting ${delay}ms before pinging CAPI to check network connectivity...`);
await new Promise(resolve => setTimeout(resolve, delay));
try {
const isGHEnterprise = this._capiClientService.dotcomAPIURL !== 'https://api.github.com';
const url = this._capiClientService.capiPingURL;
const headers = await this._getAuthHeaders(isGHEnterprise, url);
const res = await this._fetcherService.fetch(url, {
headers,
useFetcher,
callSite: 'capi-ping',
});
if (res.status >= 200 && res.status < 300) {
this._logService.info(`CAPI ping successful, proceeding with chat request retry...`);
return { retryRequest: true, connectivityTestError, connectivityTestErrorGitHubRequestId };
} else {
connectivityTestError = `Status ${res.status}: ${res.statusText}`;
connectivityTestErrorGitHubRequestId = res.headers.get('x-github-request-id') ?? '';
this._logService.info(`CAPI ping returned status ${res.status}, retrying ping...`);
}
} catch (err) {
connectivityTestError = collectSingleLineErrorMessage(err, true);
connectivityTestErrorGitHubRequestId = undefined; // no response headers yet
this._logService.info(`CAPI ping failed with error, retrying ping: ${connectivityTestError}`);
}
}
return { retryRequest: false, connectivityTestError, connectivityTestErrorGitHubRequestId };
}
private async _getAuthHeaders(isGHEnterprise: boolean, url: string) {
const authHeaders: Record<string, string> = {};
if (isGHEnterprise) {
let token = '';
if (url === this._capiClientService.dotcomAPIURL) {
token = this._authenticationService.anyGitHubSession?.accessToken || '';
} else {
try {
token = (await this._authenticationService.getCopilotToken()).token;
} catch (_err) {
// Ignore error
token = '';
}
}
authHeaders['Authorization'] = `Bearer ${token}`;
}
return authHeaders;
}
private async _retryAfterError(params: {
opts: IFetchMLOptions;
processed: ChatFetchError;
telemetryProperties: TelemetryProperties;
requestBody: IEndpointBody;
tokenCount: number;
maxResponseTokens: number;
timeToError: number;
transport: string;
actualFetcher: FetcherId | undefined;
bytesReceived: number | undefined;
baseTelemetry: TelemetryData;
streamRecorder: FetchStreamRecorder;
retryReason: 'network_error' | 'server_error';
debugNamePrefix: string;
pendingLoggedChatRequest: ReturnType<IRequestLogger['logChatRequest']>;
token: CancellationToken;
usernameToScrub: string | undefined;
suspendEventSeen: boolean | undefined;
resumeEventSeen: boolean | undefined;
}): Promise<{ retryResult?: ChatResponses; connectivityTestError?: string; connectivityTestErrorGitHubRequestId?: string }> {
const {
opts,
processed,
telemetryProperties,
requestBody,
tokenCount,
maxResponseTokens,
timeToError,
transport,
actualFetcher,
bytesReceived,
baseTelemetry,
streamRecorder,
retryReason,
debugNamePrefix,
pendingLoggedChatRequest,
token,
usernameToScrub,
suspendEventSeen,
resumeEventSeen,
} = params;
// net::ERR_NETWORK_CHANGED: https://github.com/microsoft/vscode/issues/260297
const isNetworkChangedError = ['darwin', 'linux'].includes(process.platform) && processed.reason.indexOf('net::ERR_NETWORK_CHANGED') !== -1;
// When Electron's network process crashes, all requests through it fail permanently.
// Fall back to node-fetch which bypasses Electron's network stack entirely.
const fallbackEnabled = this._configurationService.getExperimentBasedConfig(
ConfigKey.TeamInternal.FallbackNodeFetchOnNetworkProcessCrash, this._experimentationService);
const isNetworkProcessCrash = processed.type === ChatFetchResponseType.NetworkError
&& processed.isNetworkProcessCrash === true
&& fallbackEnabled;
const useFetcher = (isNetworkChangedError || isNetworkProcessCrash) ? 'node-fetch' : opts.useFetcher;
this._logService.info(`Retrying chat request with ${useFetcher || 'default'} fetcher after: ${processed.reasonDetail || processed.reason}`);
const connectivity = await this._checkNetworkConnectivity(useFetcher);
const connectivityTestError = connectivity.connectivityTestError ? this.scrubErrorDetail(connectivity.connectivityTestError, usernameToScrub) : undefined;
const connectivityTestErrorGitHubRequestId = connectivity.connectivityTestErrorGitHubRequestId;
if (!connectivity.retryRequest) {
this._logService.info(`Not retrying chat request as network connectivity could not be re-established.`);
return { connectivityTestError, connectivityTestErrorGitHubRequestId };
}
Telemetry.sendResponseErrorTelemetry(
this._telemetryService,
{
processed,
telemetryProperties,
chatEndpointInfo: opts.endpoint,
requestBody,
tokenCount,
maxResponseTokens,
timeToFirstToken: timeToError,
isVisionRequest: this.filterImageMessages(opts.messages),
transport,
fetcher: actualFetcher,
bytesReceived,
issuedTime: baseTelemetry.issuedTime,
wasRetried: true,
suspendEventSeen,
resumeEventSeen,
},
);
streamRecorder.callback('', 0, { text: '', retryReason });
const retryResult = await this.fetchMany({
...opts,
useWebSocket: false,
ignoreStatefulMarker: opts.useWebSocket || opts.ignoreStatefulMarker,
debugName: debugNamePrefix + opts.debugName,
userInitiatedRequest: false, // do not mark the retry as user initiated
telemetryProperties: {
...telemetryProperties,
retryAfterError: processed.reasonDetail || processed.reason,
retryAfterErrorGitHubRequestId: processed.serverRequestId,
connectivityTestError,
connectivityTestErrorGitHubRequestId,
},
enableRetryOnError: false,
useFetcher,
}, token);
pendingLoggedChatRequest?.resolve(retryResult, streamRecorder.deltas);
if (opts.useWebSocket && retryResult.type === ChatFetchResponseType.Success) {
this._consecutiveWebSocketRetryFallbacks++;
this._logService.info(`[ChatWebSocketManager] WebSocket request failed with successful HTTP fallback (${this._consecutiveWebSocketRetryFallbacks} consecutive).`);
if (opts.conversationId) {
// Closing here because the retry is transparent.
this._webSocketManager.closeConnection(opts.conversationId);
}
}
return { retryResult, connectivityTestError, connectivityTestErrorGitHubRequestId };
}
private async _fetchAndStreamChat(
chatEndpointInfo: IChatEndpoint,
request: IEndpointBody,
baseTelemetryData: TelemetryData,
finishedCb: FinishedCallback,
secretKey: string | undefined,
copilotToken: CopilotToken,
location: ChatLocation,
ourRequestId: string,
nChoices: number | undefined,
cancellationToken: CancellationToken,
userInitiatedRequest?: boolean,
useWebSocket?: boolean,
turnId?: string,
conversationId?: string,
telemetryProperties?: TelemetryProperties | undefined,
useFetcher?: FetcherId,
canRetryOnce?: boolean,
requestKindOptions?: IBackgroundRequestOptions | ISubagentRequestOptions,
): Promise<{ result: ChatResults | ChatRequestFailed | ChatRequestCanceled; fetcher?: FetcherId; bytesReceived?: number; statusCode?: number; suspendEventSeen?: boolean; resumeEventSeen?: boolean; otelSpan?: ISpanHandle }> {
const isPowerSaveBlockerEnabled = this._configurationService.getExperimentBasedConfig(ConfigKey.TeamInternal.ChatRequestPowerSaveBlocker, this._experimentationService);
const blockerHandle = isPowerSaveBlockerEnabled && location !== ChatLocation.Other ? this._powerService.acquirePowerSaveBlocker() : undefined;
let suspendEventSeen = false;
let resumeEventSeen = false;
const suspendListener = this._powerService.onDidSuspend(() => {
suspendEventSeen = true;
this._logService.info(`System suspended during streaming request ${ourRequestId} (${ChatLocation.toString(location)})`);
});
const resumeListener = this._powerService.onDidResume(() => {
resumeEventSeen = true;
this._logService.info(`System resumed during streaming request ${ourRequestId} (${ChatLocation.toString(location)})`);
});
try {
const fetchResult = await this._doFetchAndStreamChat(
chatEndpointInfo,
request,
baseTelemetryData,
finishedCb,
secretKey,
copilotToken,
location,
ourRequestId,
nChoices,
cancellationToken,
userInitiatedRequest,
useWebSocket,
turnId,
conversationId,
telemetryProperties,
useFetcher,
canRetryOnce,
requestKindOptions,
);
return { ...fetchResult, suspendEventSeen: suspendEventSeen || undefined, resumeEventSeen: resumeEventSeen || undefined };
} catch (err) {
if (suspendEventSeen) {
err.suspendEventSeen = true;
}
if (resumeEventSeen) {
err.resumeEventSeen = true;
}
throw err;
} finally {
suspendListener.dispose();
resumeListener.dispose();
blockerHandle?.dispose();
}
}
private async _doFetchAndStreamChat(
chatEndpointInfo: IChatEndpoint,
request: IEndpointBody,
baseTelemetryData: TelemetryData,
finishedCb: FinishedCallback,
secretKey: string | undefined,
copilotToken: CopilotToken,
location: ChatLocation,
ourRequestId: string,
nChoices: number | undefined,
cancellationToken: CancellationToken,
userInitiatedRequest?: boolean,
useWebSocket?: boolean,
turnId?: string,
conversationId?: string,
telemetryProperties?: TelemetryProperties | undefined,
useFetcher?: FetcherId,
canRetryOnce?: boolean,
requestKindOptions?: IBackgroundRequestOptions | ISubagentRequestOptions,
): Promise<{ result: ChatResults | ChatRequestFailed | ChatRequestCanceled; fetcher?: FetcherId; bytesReceived?: number; statusCode?: number; otelSpan?: ISpanHandle }> {
if (cancellationToken.isCancellationRequested) {
return { result: { type: FetchResponseKind.Canceled, reason: 'before fetch request' } };
}
// OTel inference span for this LLM call
const serverAddress = typeof chatEndpointInfo.urlOrRequestMetadata === 'string'
? (() => { try { return new URL(chatEndpointInfo.urlOrRequestMetadata).hostname; } catch { return undefined; } })()
: undefined;
const chatSessionId = getCurrentCapturingToken()?.chatSessionId;
const parentChatSessionId = getCurrentCapturingToken()?.parentChatSessionId;
const debugLogLabel = getCurrentCapturingToken()?.debugLogLabel;
const otelSpan = this._otelService.startSpan(`chat ${chatEndpointInfo.model}`, {
kind: SpanKind.CLIENT,
attributes: {
[GenAiAttr.OPERATION_NAME]: GenAiOperationName.CHAT,
[GenAiAttr.PROVIDER_NAME]: GenAiProviderName.GITHUB,
[GenAiAttr.REQUEST_MODEL]: chatEndpointInfo.model,
[GenAiAttr.CONVERSATION_ID]: telemetryProperties?.requestId ?? ourRequestId,
[GenAiAttr.REQUEST_MAX_TOKENS]: request.max_tokens ?? request.max_output_tokens ?? request.max_completion_tokens ?? 2048,
...(request.temperature !== undefined ? { [GenAiAttr.REQUEST_TEMPERATURE]: request.temperature } : {}),
...(request.top_p !== undefined ? { [GenAiAttr.REQUEST_TOP_P]: request.top_p } : {}),
[CopilotChatAttr.MAX_PROMPT_TOKENS]: chatEndpointInfo.modelMaxPromptTokens,
...(serverAddress ? { [StdAttr.SERVER_ADDRESS]: serverAddress } : {}),
...(conversationId ? { [CopilotChatAttr.SESSION_ID]: conversationId } : {}),
...(chatSessionId ? { [CopilotChatAttr.CHAT_SESSION_ID]: chatSessionId } : {}),
...(parentChatSessionId ? { [CopilotChatAttr.PARENT_CHAT_SESSION_ID]: parentChatSessionId } : {}),
...(debugLogLabel ? { [CopilotChatAttr.DEBUG_LOG_LABEL]: debugLogLabel } : {}),
},
});
const otelStartTime = Date.now();
try {
this._logService.debug(`modelMaxPromptTokens ${chatEndpointInfo.modelMaxPromptTokens}`);
this._logService.debug(`modelMaxResponseTokens ${request.max_tokens ?? 2048}`);
this._logService.debug(`chat model ${chatEndpointInfo.model}`);
secretKey ??= copilotToken.token;
if (!secretKey) {
// If no key is set we error
const urlOrRequestMetadata = stringifyUrlOrRequestMetadata(chatEndpointInfo.urlOrRequestMetadata);
this._logService.error(`Failed to send request to ${urlOrRequestMetadata} due to missing key`);
sendCommunicationErrorTelemetry(this._telemetryService, `Failed to send request to ${urlOrRequestMetadata} due to missing key`);
return {
result: {
type: FetchResponseKind.Failed,
modelRequestId: undefined,
failKind: ChatFailKind.TokenExpiredOrInvalid,
reason: 'key is missing'
}
};
}
// WebSocket path: use persistent WebSocket connection for Responses API endpoints
if (useWebSocket && turnId && conversationId) {
const wsResult = await this._doFetchViaWebSocket(
chatEndpointInfo,
request,
baseTelemetryData,
finishedCb,
secretKey,
location,
ourRequestId,
turnId,
conversationId,
cancellationToken,
userInitiatedRequest,
telemetryProperties,
requestKindOptions,
);
return { ...wsResult, otelSpan };
}
const httpResult = await this._doFetchViaHttp(
chatEndpointInfo,
request,
baseTelemetryData,
finishedCb,
secretKey,
location,
ourRequestId,