| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | import type { ChatHistoryItem } from "core/index.js"; |
| 4 | import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js"; |
| 5 | import * as dotenv from "dotenv"; |
| 6 | import type { |
| 7 | ChatCompletionMessageParam, |
| 8 | ChatCompletionTool, |
| 9 | } from "openai/resources.mjs"; |
| 10 | |
| 11 | import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; |
| 12 | import { systemMessageService } from "../services/SystemMessageService.js"; |
| 13 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 14 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 15 | import { ToolCall } from "../tools/index.js"; |
| 16 | import { |
| 17 | chatCompletionStreamWithBackoff, |
| 18 | withExponentialBackoff, |
| 19 | } from "../util/exponentialBackoff.js"; |
| 20 | import { logger } from "../util/logger.js"; |
| 21 | |
| 22 | import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; |
| 23 | import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; |
| 24 | import { |
| 25 | processChunkContent, |
| 26 | processToolCallDelta, |
| 27 | recordStreamTelemetry, |
| 28 | trackFirstTokenTime, |
| 29 | } from "./streamChatResponse.helpers.js"; |
| 30 | import { |
| 31 | getDefaultCompletionOptions, |
| 32 | StreamCallbacks, |
| 33 | } from "./streamChatResponse.types.js"; |
| 34 | |
| 35 | dotenv.config(); |
| 36 | |
| 37 | function 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 | |
| 51 | function 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 |
| 68 | interface 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 | |
| 77 | function 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 | |
| 121 | interface 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 |
| 132 | export 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 | export async function streamChatResponse( |
| 302 | chatHistory: ChatHistoryItem[], |
| 303 | model: ModelConfig, |
| 304 | llmApi: BaseLlmApi, |
| 305 | abortController: AbortController, |
| 306 | callbacks?: StreamCallbacks, |
| 307 | ) { |
| 308 | logger.debug("streamChatResponse called", { |
| 309 | model, |
| 310 | historyLength: chatHistory.length, |
| 311 | hasCallbacks: !!callbacks, |
| 312 | }); |
| 313 | |
| 314 | const serviceResult = getServiceSync<ToolPermissionServiceState>( |
| 315 | SERVICE_NAMES.TOOL_PERMISSIONS, |
| 316 | ); |
| 317 | const isHeadless = serviceResult.value?.isHeadless ?? false; |
| 318 | |
| 319 | let fullResponse = ""; |
| 320 | let finalResponse = ""; |
| 321 | |
| 322 | while (true) { |
| 323 | logger.debug("Starting conversation iteration"); |
| 324 | |
| 325 | // Recompute tools on each iteration to handle mode changes during streaming |
| 326 | const tools = await getAllTools(); |
| 327 | |
| 328 | logger.debug("Tools prepared", { |
| 329 | toolCount: tools.length, |
| 330 | toolNames: tools.map((t) => t.function.name), |
| 331 | }); |
| 332 | |
| 333 | // Get response from LLM |
| 334 | const { content, toolCalls, shouldContinue } = |
| 335 | await processStreamingResponse({ |
| 336 | chatHistory, |
| 337 | model, |
| 338 | llmApi, |
| 339 | abortController, |
| 340 | callbacks, |
| 341 | isHeadless, |
| 342 | tools, |
| 343 | }); |
| 344 | |
| 345 | fullResponse += content; |
| 346 | |
| 347 | // Update final response based on mode |
| 348 | finalResponse = updateFinalResponse( |
| 349 | content, |
| 350 | shouldContinue, |
| 351 | isHeadless, |
| 352 | finalResponse, |
| 353 | ); |
| 354 | |
| 355 | // Handle content display |
| 356 | handleContentDisplay(content, callbacks, isHeadless); |
| 357 | |
| 358 | // Handle tool calls and check for early return |
| 359 | const shouldReturn = await handleToolCalls( |
| 360 | toolCalls, |
| 361 | chatHistory, |
| 362 | content, |
| 363 | callbacks, |
| 364 | isHeadless, |
| 365 | ); |
| 366 | |
| 367 | if (shouldReturn) { |
| 368 | return finalResponse || content || fullResponse; |
| 369 | } |
| 370 | |
| 371 | // Check for auto-compaction after tool execution |
| 372 | if (shouldContinue) { |
| 373 | const { wasCompacted, chatHistory: updatedChatHistory } = |
| 374 | await handleAutoCompaction(chatHistory, model, llmApi, { |
| 375 | isHeadless, |
| 376 | callbacks: { |
| 377 | onSystemMessage: callbacks?.onSystemMessage, |
| 378 | onContent: callbacks?.onContent, |
| 379 | }, |
| 380 | }); |
| 381 | |
| 382 | // Only update chat history if compaction actually occurred |
| 383 | if (wasCompacted) { |
| 384 | chatHistory = [...updatedChatHistory]; |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // Check if we should continue |
| 389 | if (!shouldContinue) { |
| 390 | break; |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | logger.debug("streamChatResponse complete", { |
| 395 | totalResponseLength: fullResponse.length, |
| 396 | totalMessages: chatHistory.length, |
| 397 | }); |
| 398 | |
| 399 | // For headless mode, we return only the final response |
| 400 | // Otherwise, return the full response |
| 401 | return isHeadless ? finalResponse : fullResponse; |
| 402 | } |
| 403 | export { getAllTools }; |