Elffuss BraidHub

kikocis/continue public

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