Elffuss BraidHub

kikocis/continue public

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