Elffuss BraidHub

kikocis/continue public

main · 12.8 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import { BaseLlmApi } from "@continuedev/openai-adapters";
3import type { ChatHistoryItem } from "core/index.js";
4import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js";
5import * as dotenv from "dotenv";
6import type {
7 ChatCompletionMessageParam,
8 ChatCompletionTool,
9} from "openai/resources.mjs";
10
11import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js";
12import { systemMessageService } from "../services/SystemMessageService.js";
13import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
14import { posthogService } from "../telemetry/posthogService.js";
15import { telemetryService } from "../telemetry/telemetryService.js";
16import { ToolCall } from "../tools/index.js";
17import {
18 chatCompletionStreamWithBackoff,
19 isContextLengthError,
20 withExponentialBackoff,
21} from "../util/exponentialBackoff.js";
22import { logger } from "../util/logger.js";
23import { validateContextLength } from "../util/tokenizer.js";
24
25import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
26import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
27import {
28 processChunkContent,
29 processToolCallDelta,
30 recordStreamTelemetry,
31 trackFirstTokenTime,
32} from "./streamChatResponse.helpers.js";
33import {
34 getDefaultCompletionOptions,
35 StreamCallbacks,
36} from "./streamChatResponse.types.js";
37
38dotenv.config();
39
40function updateFinalResponse(
41 content: string,
42 shouldContinue: boolean,
43 isHeadless: boolean,
44 currentFinalResponse: string,
45): string {
46 if (!shouldContinue) {
47 return content;
48 } else if (isHeadless && content) {
49 return content;
50 }
51 return currentFinalResponse;
52}
53
54function handleContentDisplay(
55 content: string,
56 callbacks: StreamCallbacks | undefined,
57 isHeadless: boolean,
58): void {
59 // Add newline after content if needed
60 if (!callbacks?.onContent && !isHeadless && content) {
61 logger.info("");
62 }
63
64 // Notify content complete
65 if (content && callbacks?.onContentComplete) {
66 callbacks.onContentComplete(content);
67 }
68}
69
70// Helper function to process a single chunk
71interface ProcessChunkOptions {
72 chunk: any;
73 aiResponse: string;
74 toolCallsMap: Map<string, ToolCall>;
75 indexToIdMap: Map<number, string>;
76 callbacks?: StreamCallbacks;
77 isHeadless?: boolean;
78}
79
80function processChunk(options: ProcessChunkOptions): {
81 aiResponse: string;
82 shouldContinue: boolean;
83} {
84 const {
85 chunk,
86 aiResponse,
87 toolCallsMap,
88 indexToIdMap,
89 callbacks,
90 isHeadless,
91 } = options;
92 // Safety check: ensure chunk has the expected structure
93 if (!chunk.choices || !chunk.choices[0]) {
94 return { aiResponse, shouldContinue: true };
95 }
96
97 const choice = chunk.choices[0];
98 if (!choice.delta) {
99 return { aiResponse, shouldContinue: true };
100 }
101
102 let updatedResponse = aiResponse;
103
104 // Handle content streaming
105 if (choice.delta.content) {
106 updatedResponse = processChunkContent(
107 choice.delta.content,
108 aiResponse,
109 callbacks,
110 isHeadless,
111 );
112 }
113
114 // Handle tool calls
115 if (choice.delta.tool_calls) {
116 for (const toolCallDelta of choice.delta.tool_calls) {
117 processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap);
118 }
119 }
120
121 return { aiResponse: updatedResponse, shouldContinue: true };
122}
123
124interface ProcessStreamingResponseOptions {
125 chatHistory: ChatHistoryItem[];
126 model: ModelConfig;
127 llmApi: BaseLlmApi;
128 abortController: AbortController;
129 callbacks?: StreamCallbacks;
130 isHeadless?: boolean;
131 tools?: ChatCompletionTool[];
132}
133
134// Process a single streaming response and return whether we need to continue
135export async function processStreamingResponse(
136 options: ProcessStreamingResponseOptions,
137): Promise<{
138 content: string;
139 finalContent: string; // Added field for final content only
140 toolCalls: ToolCall[];
141 shouldContinue: boolean;
142}> {
143 const {
144 chatHistory,
145 model,
146 llmApi,
147 abortController,
148 callbacks,
149 isHeadless,
150 tools,
151 } = options;
152
153 // Validate context length before making the request
154 const validation = validateContextLength(chatHistory, model);
155 if (!validation.isValid) {
156 throw new Error(`Context length validation failed: ${validation.error}`);
157 }
158
159 // Get fresh system message and inject it
160 const systemMessage = await systemMessageService.getSystemMessage();
161 const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
162 chatHistory,
163 systemMessage,
164 ) as ChatCompletionMessageParam[];
165 const requestStartTime = Date.now();
166
167 const streamFactory = async (retryAbortSignal: AbortSignal) => {
168 logger.debug("Creating chat completion stream", {
169 model,
170 messageCount: chatHistory.length,
171 toolCount: tools?.length || 0,
172 });
173 return await chatCompletionStreamWithBackoff(
174 llmApi,
175 {
176 model: model.model,
177 messages: openaiChatHistory,
178 stream: true,
179 tools,
180 ...getDefaultCompletionOptions(model.defaultCompletionOptions),
181 },
182 retryAbortSignal,
183 );
184 };
185
186 let aiResponse = "";
187 let finalContent = "";
188 const toolCallsMap = new Map<string, ToolCall>();
189 const indexToIdMap = new Map<number, string>(); // Track index to ID mapping
190 let firstTokenTime: number | null = null;
191 let inputTokens = 0;
192 let outputTokens = 0;
193
194 try {
195 const streamWithBackoff = withExponentialBackoff(
196 streamFactory,
197 abortController.signal,
198 );
199
200 let chunkCount = 0;
201 for await (const chunk of streamWithBackoff) {
202 chunkCount++;
203
204 logger.debug("Received chunk", { chunkCount, chunk });
205
206 // Track token usage if available
207 if (chunk.usage) {
208 inputTokens = chunk.usage.prompt_tokens || 0;
209 outputTokens = chunk.usage.completion_tokens || 0;
210 }
211
212 // Check if we should abort
213 if (abortController?.signal.aborted) {
214 logger.debug("Stream aborted");
215 break;
216 }
217
218 // Track first token time
219 firstTokenTime = trackFirstTokenTime(
220 firstTokenTime,
221 chunk,
222 requestStartTime,
223 model,
224 tools,
225 );
226
227 const result = processChunk({
228 chunk,
229 aiResponse,
230 toolCallsMap,
231 indexToIdMap,
232 callbacks,
233 isHeadless,
234 });
235 aiResponse = result.aiResponse;
236 if (!result.shouldContinue) break;
237 }
238
239 const responseEndTime = Date.now();
240 const cost = recordStreamTelemetry({
241 requestStartTime,
242 responseEndTime,
243 inputTokens,
244 outputTokens,
245 model,
246 tools,
247 });
248 const totalDuration = responseEndTime - requestStartTime;
249
250 logger.debug("Stream complete", {
251 chunkCount,
252 responseLength: aiResponse.length,
253 toolCallsCount: toolCallsMap.size,
254 inputTokens,
255 outputTokens,
256 cost,
257 duration: totalDuration,
258 });
259 } catch (error: any) {
260 const errorDuration = Date.now() - requestStartTime;
261
262 // Log failed API request
263 telemetryService.logApiRequest({
264 model: model.model,
265 durationMs: errorDuration,
266 success: false,
267 error: error.message || String(error),
268 });
269
270 try {
271 posthogService.capture("apiRequest", {
272 model: model.model,
273 durationMs: errorDuration,
274 success: false,
275 error: error.message || String(error),
276 });
277 } catch {}
278
279 if (error.name === "AbortError" || abortController?.signal.aborted) {
280 logger.debug("Stream aborted by user");
281 return {
282 content: aiResponse,
283 finalContent: aiResponse,
284 toolCalls: [],
285 shouldContinue: false,
286 };
287 }
288
289 // Handle context length errors with helpful message
290 if (isContextLengthError(error)) {
291 logger.debug(`Context length exceeded: ${error}`);
292 throw new Error(`Context length exceeded: ${error}`);
293 }
294
295 throw error;
296 }
297
298 const toolCalls = Array.from(toolCallsMap.values());
299
300 // Validate tool calls have complete arguments
301 const validToolCalls = toolCalls.filter((tc) => {
302 if (!tc.arguments || !tc.name) {
303 logger.error("Incomplete tool call", {
304 id: tc.id,
305 name: tc.name,
306 hasArguments: !!tc.arguments,
307 argumentsStr: tc.argumentsStr,
308 });
309 return false;
310 }
311 return true;
312 });
313
314 // Always preserve the content - it should be displayed regardless of tool calls
315 finalContent = aiResponse;
316
317 return {
318 content: aiResponse,
319 finalContent: finalContent,
320 toolCalls: validToolCalls,
321 shouldContinue: validToolCalls.length > 0,
322 };
323}
324
325// Main function that handles the conversation loop
326// eslint-disable-next-line complexity
327export async function streamChatResponse(
328 chatHistory: ChatHistoryItem[],
329 model: ModelConfig,
330 llmApi: BaseLlmApi,
331 abortController: AbortController,
332 callbacks?: StreamCallbacks,
333) {
334 logger.debug("streamChatResponse called", {
335 model,
336 historyLength: chatHistory.length,
337 hasCallbacks: !!callbacks,
338 });
339
340 const serviceResult = getServiceSync<ToolPermissionServiceState>(
341 SERVICE_NAMES.TOOL_PERMISSIONS,
342 );
343 const isHeadless = serviceResult.value?.isHeadless ?? false;
344
345 let fullResponse = "";
346 let finalResponse = "";
347
348 while (true) {
349 // If ChatHistoryService is available, refresh local chatHistory view
350 const chatHistorySvc = services.chatHistory;
351 if (
352 typeof chatHistorySvc?.isReady === "function" &&
353 chatHistorySvc.isReady()
354 ) {
355 try {
356 chatHistory = chatHistorySvc.getHistory();
357 } catch {}
358 }
359 logger.debug("Starting conversation iteration");
360
361 // Pre-API auto-compaction checkpoint
362 const { wasCompacted: preCompacted, chatHistory: preCompactHistory } =
363 await handleAutoCompaction(chatHistory, model, llmApi, {
364 isHeadless,
365 callbacks: {
366 onSystemMessage: callbacks?.onSystemMessage,
367 onContent: callbacks?.onContent,
368 },
369 });
370
371 if (preCompacted) {
372 logger.debug("Pre-API compaction occurred, updating chat history");
373 // Update chat history after pre-compaction
374 const chatHistorySvc2 = services.chatHistory;
375 if (
376 typeof chatHistorySvc2?.isReady === "function" &&
377 chatHistorySvc2.isReady()
378 ) {
379 chatHistorySvc2.setHistory(preCompactHistory);
380 chatHistory = chatHistorySvc2.getHistory();
381 } else {
382 chatHistory = [...preCompactHistory];
383 }
384 }
385
386 // Recompute tools on each iteration to handle mode changes during streaming
387 const tools = await getAllTools();
388
389 logger.debug("Tools prepared", {
390 toolCount: tools.length,
391 toolNames: tools.map((t) => t.function.name),
392 });
393
394 // Get response from LLM
395 const { content, toolCalls, shouldContinue } =
396 await processStreamingResponse({
397 chatHistory,
398 model,
399 llmApi,
400 abortController,
401 callbacks,
402 isHeadless,
403 tools,
404 });
405
406 if (abortController?.signal.aborted) {
407 return finalResponse || content || fullResponse;
408 }
409
410 fullResponse += content;
411
412 // Update final response based on mode
413 finalResponse = updateFinalResponse(
414 content,
415 shouldContinue,
416 isHeadless,
417 finalResponse,
418 );
419
420 // Handle content display
421 handleContentDisplay(content, callbacks, isHeadless);
422
423 // Handle tool calls and check for early return. This updates history via ChatHistoryService.
424 const shouldReturn = await handleToolCalls(
425 toolCalls,
426 chatHistory,
427 content,
428 callbacks,
429 isHeadless,
430 );
431
432 if (shouldReturn) {
433 return finalResponse || content || fullResponse;
434 }
435
436 // Check for auto-compaction after tool execution
437 if (shouldContinue) {
438 const { wasCompacted, chatHistory: updatedChatHistory } =
439 await handleAutoCompaction(chatHistory, model, llmApi, {
440 isHeadless,
441 callbacks: {
442 onSystemMessage: callbacks?.onSystemMessage,
443 onContent: callbacks?.onContent,
444 },
445 });
446
447 // Only update chat history if compaction actually occurred
448 if (wasCompacted) {
449 // Always prefer service; local copy is for temporary reads only
450 const chatHistorySvc2 = services.chatHistory;
451 if (
452 typeof chatHistorySvc2?.isReady === "function" &&
453 chatHistorySvc2.isReady()
454 ) {
455 chatHistorySvc2.setHistory(updatedChatHistory);
456 chatHistory = chatHistorySvc2.getHistory();
457 } else {
458 // Fallback only when service is unavailable
459 chatHistory = [...updatedChatHistory];
460 }
461 }
462 }
463
464 // Check if we should continue
465 if (!shouldContinue) {
466 break;
467 }
468 }
469
470 logger.debug("streamChatResponse complete", {
471 totalResponseLength: fullResponse.length,
472 totalMessages: chatHistory.length,
473 });
474
475 // For headless mode, we return only the final response
476 // Otherwise, return the full response
477 return isHeadless ? finalResponse : fullResponse;
478}
479export { getAllTools };