import axios, { AxiosRequestConfig } from "axios"; import {Application} from "./application"; import vscode, { Terminal } from "vscode"; import { LlmModel, LlamaChatResponse, LlamaResponse, ChatMessage } from "./types"; import { Utils } from "./utils"; import * as cp from 'child_process'; import * as fs from 'fs'; import { ModelType, PERSISTENCE_KEYS, SUPPORTED_IMG_FILE_EXTS } from "./constants"; import { addToStreamCapture, buildShellInvocation, capturedText, CommandExecutionResult, createStreamCapture, DEFAULT_TIMEOUT_MS } from "./services/terminal-command"; import { buildRuntimePropsUrl, estimateTokenCount, extractRuntimeContextSize, isLikelyLlamaCppProvider, OpenAICompatibleModel, resolveModelTokenLimits, ResolvedModelTokenLimits, } from './language-model-token-limits'; const STATUS_OK = 200; // A login shell started without a real TTY always prints these two warnings; // they are noise for the model and for the user. const HARMLESS_TTY_WARNINGS = [ 'cannot set terminal process group', 'no job control in this shell', ]; const cleanTtyNoise = (text: string): string => text .split('\n') .filter((line: string) => !HARMLESS_TTY_WARNINGS.some(warning => line.includes(warning))) .join('\n'); interface CommandOutcome { stdout: string; stderr: string; exitCode: number; timedOut: boolean; cancelled: boolean; } // Both streams are capped together, so a chatty command cannot exhaust memory. // The cap has to be far above what the model receives: the head AND the tail of // the output are formatted later, so the middle is all that may be dropped. const KILL_GRACE_MS = 3_000; /** * A running shell command. Keeping a handle instead of a promise is what allows * the extension to kill the process group on deactivate: `detached: true` puts * the child in its own group, so the OS would keep it alive otherwise. */ export interface RunningCommand { result: Promise; kill: () => void; } /** * Runs the shell with the given invocation and collects stdout/stderr without * ever throwing. * * Why not execFile with a `timeout`: it kills only the direct child, which is * `bash -ilc ''`, and bash does not forward SIGTERM to the command it * is waiting for. Measured: `sleep 600` survived the kill, the callback never * fired and the tool call never returned - the exact hang the timeout was added * for. So the shell becomes the leader of its own process group and the whole * group is killed on timeout, on abort (Stop button) and on deactivate. */ const startCommand = ( invocation: { file: string; args: string[] }, options: { cwd?: string; timeoutMs: number; signal?: AbortSignal } ): RunningCommand => { const stdout = createStreamCapture(); const stderr = createStreamCapture(); let timedOut = false; let cancelled = false; let settled = false; let escalation: NodeJS.Timeout | undefined; let timer: NodeJS.Timeout | undefined; let child: cp.ChildProcess | undefined; const killTree = (signal: NodeJS.Signals) => { if (!child?.pid) return; if (process.platform === 'win32') { try { cp.execFile('taskkill', ['/pid', String(child.pid), '/T', '/F']); } catch { /* best effort */ } return; } try { process.kill(-child.pid, signal); } catch { /* the group is already gone */ } }; const result = new Promise(resolve => { const finish = (exitCode: number) => { if (settled) return; settled = true; if (timer) clearTimeout(timer); if (escalation) clearTimeout(escalation); options.signal?.removeEventListener('abort', onAbort); resolve({ stdout: capturedText(stdout), stderr: capturedText(stderr), exitCode, timedOut, cancelled }); }; const stop = (reason: 'timeout' | 'cancel') => { if (settled) return; if (reason === 'timeout') timedOut = true; else cancelled = true; killTree('SIGTERM'); // A shell can ignore SIGTERM (an interactive rc may install a trap), // so the group is not allowed to outlive the tool call. escalation = setTimeout(() => killTree('SIGKILL'), KILL_GRACE_MS); escalation.unref(); }; const onAbort = () => stop('cancel'); child = cp.spawn(invocation.file, invocation.args, { cwd: options.cwd, // stdin is closed: a command that waits for input fails instead of // hanging. This is what makes `git commit` without -m return instead // of waiting forever, and how the old `exec` behaved silently. stdio: ['ignore', 'pipe', 'pipe'], // POSIX: a separate process group is what makes killing the whole // command tree possible. Windows uses taskkill /T instead. detached: process.platform !== 'win32', windowsHide: true }); child.stdout?.on('data', (chunk: Buffer) => addToStreamCapture(stdout, chunk.toString())); child.stderr?.on('data', (chunk: Buffer) => addToStreamCapture(stderr, chunk.toString())); child.on('error', (error: Error) => { addToStreamCapture(stderr, error.message); finish(-1); }); child.on('close', (code: number | null, signal: NodeJS.Signals | null) => { // A killed process has no exit code; report 128 the way a shell // would, and -1 when nothing is known. finish(typeof code === 'number' ? code : (signal ? 128 : -1)); }); if (options.signal?.aborted) { stop('cancel'); } else { options.signal?.addEventListener('abort', onAbort); } timer = setTimeout(() => stop('timeout'), options.timeoutMs); timer.unref(); }); // Deactivate and the Stop button share one way of ending the command. return { result, kill: () => killTree('SIGKILL') }; }; export interface LlamaToolsResponse { choices: [{ message:{role?: string, content?: string | null, tool_calls?:[{id:string, function: {name:string, arguments: string}}]}, finish_reason?: string, error?: LlamaApiError, }]; error?: LlamaApiError; truncated?: boolean; tokens_cached?: number; timings?: LlamaResponse['timings']; generation_settings?: LlamaResponse['generation_settings']; usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number; prompt_tokens_details?:any cost?:number cost_usd?:number }; } interface LlamaApiError { message: string; type?: string; n_prompt_tokens?: number; n_ctx?: number; [key: string]: unknown; } export interface LlamaEmbeddingsResponse { "model": string, "object": string, "usage": { "prompt_tokens": number, "total_tokens": number }, "data": [ { "embedding": number[], "index": number, "object": string } ] } interface ApplyTemplateResponse { prompt: string; } interface CounTokensResponse { input_tokens: number; } interface TokenizeResponse { tokens: unknown[]; } interface OpenAIModelsResponse { data: OpenAICompatibleModel[]; } interface RequestDetailsOverride { endpoint: string; model?: string; requestConfig?: AxiosRequestConfig; trace?: RequestTraceContext; tools?: unknown[]; toolChoice?: unknown; } interface ResolvedRequestDetails { endpoint: string; model: string; requestConfig: AxiosRequestConfig; selectedModel: LlmModel; trace?: RequestTraceContext; tools?: unknown[]; toolChoice?: unknown; } export interface RequestTraceContext { requestId: string; caller: string; conversationId?: string; conversationTurn?: number; } export class LlamaServer { private app: Application private vsCodeFimTerminal: Terminal | undefined; private vsCodeChatTerminal: Terminal | undefined; private vsCodeEmbeddingsTerminal: Terminal | undefined; private vsCodeTrainTerminal: Terminal | undefined; private vsCodeCommandTerminal: Terminal | undefined; private vsCodeToolsTerminal: Terminal | undefined; // Every live terminal command, so deactivate/killCommandCmd can end the // process groups. A command removes itself from the set when it finishes. private runningCommands: Set = new Set(); private aiModel = ""; private requestTraceCounter = 0; private toolsTokenLimitsCache: | { key: string; expiresAt: number; limits: ResolvedModelTokenLimits } | undefined; private readonly defaultRequestParams = { top_k: 40, top_p: 0.99, stream: false, samplers: ["top_k", "top_p", "infill"], cache_prompt: true, } as const; constructor(application: Application) { this.app = application; this.vsCodeFimTerminal = undefined; this.vsCodeChatTerminal = undefined; this.vsCodeEmbeddingsTerminal = undefined; this.vsCodeTrainTerminal = undefined; this.vsCodeCommandTerminal = undefined; this.vsCodeToolsTerminal = undefined; } private async handleOpenAICompletion( chunks: any[], inputPrefix: string, inputSuffix: string, prompt: string, isPreparation = false ): Promise { const client = this.app.configuration.openai_client; if (!client) return; const additional_context = chunks.length > 0 ? "Context:\n\n" + chunks.join("\n") : ""; const replacements = { inputPrefix: inputPrefix.slice(-this.app.configuration.n_prefix), prompt: prompt, inputSuffix: inputSuffix.slice(0, this.app.configuration.n_suffix), }; const rsp = await client.completions.create({ model: this.app.configuration.openai_client_model || "", prompt: additional_context + this. app.prompts.replacePlaceholders(this.app.configuration.openai_prompt_template, replacements), max_tokens: this.app.configuration.n_predict, temperature: 0.1, top_p: this.defaultRequestParams.top_p, stream: this.defaultRequestParams.stream, }); if (isPreparation) return; return { content: rsp.choices[0].text, generation_settings: { finish_reason: rsp.choices[0].finish_reason, model: rsp.model, created: rsp.created, }, timings: { prompt_ms: rsp.usage?.prompt_tokens, predicted_ms: rsp.usage?.completion_tokens, predicted_n: rsp.usage?.total_tokens, }, }; } private createRequestPayload(noPredict: boolean, inputPrefix: string, inputSuffix: string, chunks: any[], prompt: string, model: string, nindent?: number) { if (noPredict) { return { id_slot: 0, input_prefix: inputPrefix, input_suffix: inputSuffix, input_extra: chunks, prompt, n_predict: 0, samplers: [], cache_prompt: true, t_max_prompt_ms: this.app.configuration.t_max_prompt_ms, t_max_predict_ms: 1, ...(this.app.configuration.lora_completion.trim() != "" && { lora: [{ id: 0, scale: 0.5 }] }) }; } return { id_slot: 0, input_prefix: inputPrefix, input_suffix: inputSuffix, input_extra: chunks, prompt, n_predict: this.app.configuration.n_predict, n_cmpl: this.app.configuration.max_parallel_completions, ...this.defaultRequestParams, ...(nindent && { n_indent: nindent }), t_max_prompt_ms: this.app.configuration.t_max_prompt_ms, t_max_predict_ms: this.app.configuration.t_max_predict_ms, ...(this.app.configuration.lora_completion.trim() != "" && { lora: [{ id: 0, scale: 0.5 }] }), ...(model.trim() != "" && { model: model}) }; } private createChatEditRequestPayload(instructions: string, originalText: string, context: string, model: string) { const replacements = { instructions: instructions, originalText: originalText, } return { "messages": [ { "role": "system", "content": "You are an expert coder.\n" + context }, { "role": "user", "content": this.app.prompts.replacePlaceholders(this.app.prompts.CHAT_EDIT_TEXT, replacements) } ], "stream": false, "cache_prompt": true, "temperature": 0.8, "top_p": 0.95, ...(this.app.configuration.lora_chat.trim() != "" && { lora: [{ id: 0, scale: 0.5 }] }), ...(model.trim() != "" && { model: model}), }; } // Helper – removes every thought block, regardless of format // ------------------------------------------------------------- /** * Strip all “thought” sections from a message string. * * Supported formats: * … * <|channel|>analysis<|message|> … <|end|> * * If the input is `null` the function returns `null` unchanged. */ private stripThoughts(content: string | null): string | null { if (content === null) return null; // Opening tags: OR <|channel|>analysis<|message|> const OPEN = /|<\|channel\|>analysis<\|message\|>/g; // Closing tags: OR <|end|> const CLOSE = /<\/think>|<\|end\|>/g; // Build a single regex that matches an opening tag, anything (lazy), // then a closing tag. const THOUGHT_BLOCK = new RegExp( `(?:${OPEN.source})[\\s\\S]*?(?:${CLOSE.source})`, 'g' ); // Remove every thought block and trim the result. return content.replace(THOUGHT_BLOCK, '').trim(); } // ------------------------------------------------------------- // Public utility – filter thought from an array of messages // ------------------------------------------------------------- private filterThoughtFromMsgs(messages:any) { return messages.map((msg:any) => { // Non‑assistant messages never contain thoughts, return them untouched. if (msg.role !== 'assistant') { return msg; } // `msg.content` is guaranteed to be a string for assistants, // but we stay defensive and accept `null` as well. const originalContent = msg.content as string | null; const cleanedContent = this.stripThoughts(originalContent); // Preserve every other field (name, function_call, …) unchanged. return { ...msg, content: cleanedContent, }; }); } private createChatRequestPayload(content: string, model: string) { return { "messages": [ { "role": "system", "content": "You are an expert coder." }, { "role": "user", "content": content } ], "stream": false, "temperature": 0.8, ...(this.app.configuration.lora_chat.trim() != "" && { lora: [{ id: 0, scale: 0.5 }] }), ...(model.trim() != "" && { model: model}), }; } private getToolsRequestDetails(): ResolvedRequestDetails { const selectedModel: LlmModel = this.app.getToolsModel(); let model = this.app.configuration.ai_model; if (selectedModel?.aiModel) { model = selectedModel.aiModel; } let endpoint = this.app.configuration.endpoint_tools; if (selectedModel?.endpoint) { endpoint = selectedModel.endpoint; } let requestConfig = this.app.configuration.axiosRequestConfigTools; if (selectedModel?.isKeyRequired) { const apiKey = this.app.persistence.getApiKey(selectedModel.endpoint ?? ""); if (apiKey) { requestConfig = { headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", ...(selectedModel.endpoint?.includes("orcarouter.ai") ? { "X-OrcaRouter-Include-Cost": true } : {}), }, }; } } return { endpoint, model, requestConfig, selectedModel, }; } createRequestTrace(caller: string): RequestTraceContext { this.requestTraceCounter += 1; return { requestId: `${caller}-${Date.now().toString(36)}-${this.requestTraceCounter.toString(36)}`, caller, }; } private resolveRequestDetails(override?: RequestDetailsOverride): ResolvedRequestDetails { const details = this.getToolsRequestDetails(); if (!override) { return { ...details, trace: undefined, }; } return { ...details, endpoint: override.endpoint, model: override.model ?? details.model, requestConfig: override.requestConfig ?? details.requestConfig, trace: override.trace, tools: override.tools, toolChoice: override.toolChoice, }; } private buildToolsMessages(messages: ChatMessage[], imagePath = "") { let filteredMsgs = this.filterThoughtFromMsgs(messages); if (imagePath && fs.existsSync(imagePath)) { let imgType = ""; for (const suffix in SUPPORTED_IMG_FILE_EXTS){ if (imagePath.endsWith(suffix)) { imgType = SUPPORTED_IMG_FILE_EXTS[suffix]; break; } } if (imgType) { const imageBuffer = fs.readFileSync(imagePath); const base64Image = imageBuffer.toString('base64'); const imageMessage = { role: 'user', content: [ { type: 'text', text: 'Here is an image for context:' }, { type: 'image_url', image_url: { url: `data:${imgType};base64,${base64Image}` } } ] }; filteredMsgs = filteredMsgs as any[]; filteredMsgs.push(imageMessage); } } return filteredMsgs; } private getOnlyNewTools(newTools: any, messages: ChatMessage[]): any { let sentToolsNames = new Set() for (const msg of messages){ if (msg.role == "system" && msg.tools) { for (const tool of msg.tools) { sentToolsNames.add(tool.function.name); } } } let uniqueTools = [] for (const tool of newTools){ if (!sentToolsNames.has(tool.function.name)){ uniqueTools.push(tool) sentToolsNames.add(tool.function.name) } } return uniqueTools; } private createToolsRequestPayload(messages: ChatMessage[], model: string, stream = false, imagePath: string = "", iterationsCount = 0, endpoint = "") { this.app.tools.addSelectedTools(); let toolChoice = "auto"; let allTools = [...this.app.tools.getTools(), ...this.app.tools.vscodeTools] if (model.trim().startsWith("kimi-k3") && endpoint.toLowerCase().includes("api.moonshot.ai")) { allTools = [this.app.tools.getSearchToolsTool()]; if (iterationsCount == 1) toolChoice = "required" else if (this.app.tools.getLastSearchToolsResult().length > 0) { const newTools = this.getOnlyNewTools(this.app.tools.getLastSearchToolsResult(), messages) if (newTools) { const systemToolsMsg = { "role": "system", "tools": newTools } messages.push(systemToolsMsg); } } } let filteredMsgs = this.buildToolsMessages(messages, imagePath); return { "messages": filteredMsgs, "stream": stream, ...(stream && { stream_options: { include_usage: true } }), ...(model.trim() != "" && { model: model }), "tools": allTools, "tool_choice": toolChoice }; } private summarizeTemplateMessages(messages: unknown[]): string { const roles = messages.map((message, index) => { if (!message || typeof message !== 'object') { return `${index}:invalid`; } const role = (message as { role?: unknown }).role; return `${index}:${typeof role === 'string' ? role : 'missing-role'}`; }); const result = `count=${messages.length}; roles=[${roles.join(', ')}]`; return result; } private formatTraceDetails(trace?: RequestTraceContext): string { if (!trace) { return ''; } return [ `request_id=${trace.requestId}`, `caller=${trace.caller}`, trace.conversationId ? `conversation_id=${trace.conversationId}` : '', typeof trace.conversationTurn === 'number' ? `conversation_turn=${trace.conversationTurn}` : '', ].filter(Boolean).join(' | '); } private logApiRequest(label: string, method: string, url: string, details = "", trace?: RequestTraceContext) { this.app.logger.addEventLog('API', `${label}_${method}_REQUEST`, [url, this.formatTraceDetails(trace), details].filter(Boolean).join(' | ')); } private logApiResponse(label: string, method: string, url: string, details = "", trace?: RequestTraceContext) { this.app.logger.addEventLog('API', `${label}_${method}_RESPONSE`, [url, this.formatTraceDetails(trace), details].filter(Boolean).join(' | ')); } private formatUsageLogDetails(usage: Record | undefined, tokensCached?: number): string[] { const completionTokenDetails = this.getUsageRecordField(usage, 'completion_tokens_details'); const promptTokenDetails = this.getUsageRecordField(usage, 'prompt_tokens_details'); const cachedPromptTokens = this.getUsageNumberField(promptTokenDetails, 'cached_tokens'); return [ `prompt_tokens=${this.getUsageNumberField(usage, 'prompt_tokens') ?? 'unknown'}`, `completion_tokens=${this.getUsageNumberField(usage, 'completion_tokens') ?? 'unknown'}`, `total_tokens=${this.getUsageNumberField(usage, 'total_tokens') ?? 'unknown'}`, `reasoning_tokens=${this.getUsageNumberField(completionTokenDetails, 'reasoning_tokens') ?? 'unknown'}`, `cached_prompt_tokens=${cachedPromptTokens ?? tokensCached ?? 'unknown'}`, ]; } private getUsageRecordField(record: Record | undefined, field: string): Record | undefined { const value = record?.[field]; return value && typeof value === 'object' ? value as Record : undefined; } private getUsageNumberField(record: Record | undefined, field: string): number | undefined { const value = record?.[field]; return typeof value === 'number' ? value : undefined; } private logApiError(label: string, method: string, url: string, error: unknown, details = "", trace?: RequestTraceContext) { const apiError = this.extractApiError(error); this.app.logger.addEventLog( 'API', `${label}_${method}_ERROR`, [url, this.formatTraceDetails(trace), details, `error=${apiError.message}`].filter(Boolean).join(' | ') ); } logBudgetDecision( trace: RequestTraceContext, details: { endpoint: string; model: string; promptTokens?: number; promptCountSource: 'exact' | 'fallback'; maxInputTokens: number; maxOutputTokens: number; chosenMaxTokens: number; safetyMarginTokens: number; } ) { this.app.logger.addEventLog( 'BUDGET', 'REQUEST_DECISION', [ this.formatTraceDetails(trace), `endpoint=${details.endpoint}`, `model=${details.model || 'none'}`, `prompt_tokens=${details.promptTokens ?? 'unknown'}`, `prompt_count_source=${details.promptCountSource}`, `max_input_tokens=${details.maxInputTokens}`, `max_output_tokens=${details.maxOutputTokens}`, `chosen_max_tokens=${details.chosenMaxTokens}`, `safety_margin_tokens=${details.safetyMarginTokens}`, ].join(' | ') ); } logBudgetFallback( trace: RequestTraceContext, details: { endpoint: string; model: string; fallbackPromptTokens: number; fallbackReason: string; } ) { this.app.logger.addEventLog( 'BUDGET', 'EXACT_COUNT_FALLBACK', [ this.formatTraceDetails(trace), `endpoint=${details.endpoint}`, `model=${details.model || 'none'}`, `fallback_prompt_tokens=${details.fallbackPromptTokens}`, `reason=${details.fallbackReason}`, ].join(' | ') ); } async getToolsModelTokenLimits(): Promise { const { endpoint, model, requestConfig } = this.getToolsRequestDetails(); const cacheKey = [ endpoint, model, this.app.configuration.ai_api_version, this.app.configuration.lm_max_input_tokens, this.app.configuration.lm_max_output_tokens, ].join('|'); if (this.toolsTokenLimitsCache && this.toolsTokenLimitsCache.key === cacheKey && this.toolsTokenLimitsCache.expiresAt > Date.now()) { return this.toolsTokenLimitsCache.limits; } const configuredMaxInputTokens = this.app.configuration.lm_max_input_tokens; const configuredMaxOutputTokens = this.app.configuration.lm_max_output_tokens; const fallbackLimits = resolveModelTokenLimits( { id: model || 'tools-model' }, { configuredMaxInputTokens, configuredMaxOutputTokens, } ); if (!endpoint) { return fallbackLimits; } const modelsUrl = `${Utils.trimTrailingSlash(endpoint)}/${this.app.configuration.ai_api_version}/models`; try { this.logApiRequest('TOOLS_MODELS', 'GET', modelsUrl, `model=${model || 'none'}`); const response = await axios.get( modelsUrl, requestConfig ); this.logApiResponse('TOOLS_MODELS', 'GET', modelsUrl, `count=${response.data?.data?.length ?? 0}`); const models = response.data?.data ?? []; const matchedModel = models.find((candidate) => candidate.id === model) ?? (models.length === 1 ? models[0] : undefined); if (!matchedModel) { return fallbackLimits; } let runtimeContextSize: number | undefined; if (configuredMaxInputTokens <= 0 && isLikelyLlamaCppProvider([matchedModel])) { try { const propsUrl = models.length === 1 ? buildRuntimePropsUrl(endpoint) : buildRuntimePropsUrl(endpoint, matchedModel.id); this.logApiRequest('TOOLS_PROPS', 'GET', propsUrl, `model=${matchedModel.id}`); const propsResponse = await axios.get(propsUrl, requestConfig); runtimeContextSize = extractRuntimeContextSize(propsResponse.data); this.logApiResponse('TOOLS_PROPS', 'GET', propsUrl, `n_ctx=${runtimeContextSize ?? 'unknown'}`); } catch (error) { this.logApiError('TOOLS_PROPS', 'GET', models.length === 1 ? buildRuntimePropsUrl(endpoint) : buildRuntimePropsUrl(endpoint, matchedModel.id), error, `model=${matchedModel.id}`); runtimeContextSize = undefined; } } const limits = resolveModelTokenLimits(matchedModel, { configuredMaxInputTokens, configuredMaxOutputTokens, runtimeContextSize, }); this.toolsTokenLimitsCache = { key: cacheKey, expiresAt: Date.now() + 30000, limits, }; return limits; } catch (error) { this.logApiError('TOOLS_MODELS', 'GET', modelsUrl, error, `model=${model || 'none'}`); return fallbackLimits; } } async applyToolsTemplate( messages: ChatMessage[], imagePath = "", requestDetails?: RequestDetailsOverride ): Promise { const { endpoint, model, requestConfig, trace, tools, toolChoice } = this.resolveRequestDetails(requestDetails); if (!endpoint) { return undefined; } const templateMessages = this.buildToolsMessages(messages, imagePath); const templateUrl = `${Utils.trimTrailingSlash(endpoint)}/apply-template`; try { this.logApiRequest('APPLY_TEMPLATE', 'POST', templateUrl, `model=${model || 'none'} | ${this.summarizeTemplateMessages(templateMessages as unknown[])}`, trace); const response = await axios.post( templateUrl, { messages: templateMessages, ...(model.trim() !== '' && { model }), ...(tools?.length && { tools }), ...(toolChoice !== undefined && { tool_choice: toolChoice }), }, requestConfig ); this.logApiResponse('APPLY_TEMPLATE', 'POST', templateUrl, `prompt_length=${response.data.prompt?.length ?? 0}`, trace); return response.status === STATUS_OK ? response.data.prompt : undefined; } catch (error) { const apiError = this.extractApiError(error); const details = [ `endpoint=${endpoint}`, `model=${model || 'none'}`, this.summarizeTemplateMessages(templateMessages as unknown[]), `error=${apiError}`, ].join(' | '); this.logApiError('APPLY_TEMPLATE', 'POST', templateUrl, error, `model=${model || 'none'} | ${this.summarizeTemplateMessages(templateMessages as unknown[])}`, trace); this.app.logger.addEventLog('TOOLS', 'APPLY_TEMPLATE_ERROR', details); console.error('[llama-vscode] apply-template failed:', details); return undefined; } } async countToolsPromptTokens( messages: ChatMessage[], imagePath = "", requestDetails?: RequestDetailsOverride ): Promise { return this.countTextTokens(messages, requestDetails); } async countTextTokens(messages: ChatMessage[], requestDetails?: RequestDetailsOverride): Promise { const { endpoint, requestConfig, trace } = this.resolveRequestDetails(requestDetails); if (!endpoint) { return undefined; } const countTokensUrl = `${Utils.trimTrailingSlash(endpoint)}/${this.app.configuration.ai_api_version}/messages/count_tokens`; try { this.logApiRequest('TOKENIZE', 'POST', countTokensUrl, `messages_length=${messages.length}`, trace); const response = await axios.post( countTokensUrl, { model: requestDetails?.model ?? this.app.configuration.ai_model, system: "", messages: messages, }, requestConfig ); this.logApiResponse('TOKENIZE', 'POST', countTokensUrl, `tokens=${response.data.input_tokens}`, trace); return response.status === STATUS_OK ? response.data.input_tokens : undefined; } catch (error) { this.logApiError('TOKENIZE', 'POST', countTokensUrl, error, `messages_length=${messages.length}`, trace); return undefined; } } estimateToolsRequestTokens(requestPayload: unknown): number { // Fallback only: exact prompt counting should go through apply-template + tokenize. return estimateTokenCount(requestPayload); } private createErrorResponse(error: LlamaApiError): LlamaToolsResponse { return { choices: [{ message: { role: 'assistant', content: error.message }, finish_reason: 'error', error, }], error, }; } private extractApiError(error: unknown): LlamaApiError { if (axios.isAxiosError(error)) { const responseData = error.response?.data as { error?: LlamaApiError } | undefined; if (responseData?.error) { return responseData.error; } return { message: error.message, ...(typeof error.response?.status === 'number' && { status: error.response.status }), }; } if (error instanceof Error) { return { message: error.message }; } return { message: String(error) }; } private createGetSummaryRequestPayload(messages: ChatMessage[], model: string) { let filteredMsgs = this.filterThoughtFromMsgs(messages) const summaryPromptMsgs: ChatMessage[] = [ { role: 'system', content: this.app.prompts.SUMMARIZE_PROMPT, }, ...filteredMsgs ]; return { "messages": summaryPromptMsgs, "stream": false, "temperature": 0.8, "top_p": 0.95, ...(model.trim() != "" && { model: model}) }; } getFIMCompletion = async ( inputPrefix: string, inputSuffix: string, prompt: string, chunks: any, nindent: number ): Promise => { // If the server is OpenAI compatible, use the OpenAI API to get the completion if (this.app.configuration.use_openai_endpoint) { const response = await this.handleOpenAICompletion(chunks, inputPrefix, inputSuffix, prompt); return response || undefined; } // else, default to llama.cpp let { endpoint, model, requestConfig } = this.getComplModelProperties(); if (!endpoint){ await this.app.modelService.selectDefaultModel(ModelType.Completion, PERSISTENCE_KEYS.DEFAULT_COMPL_MODEL); ({ endpoint, model, requestConfig } = this.getComplModelProperties()); } if (!endpoint) { const selectionMessate = "Select a completion model or an env with completion model to use code completion (code suggestions by AI)." const shouldSelectModel = await this.app.dialogs.showUserChoiceDialog(selectionMessate, "Select") if (shouldSelectModel){ this.app.llamaWebviewProvider.showEnvViewInUi(); vscode.window.showInformationMessage("After the completion model is loaded, try again using code completion.") return; } else { const shouldDisable = await this.app.dialogs.showYesNoDialog("Do you want to disable completions? (You could enable them from llama-vscode menu.)") if (shouldDisable) { await this.app.menu.setCompletion(false); vscode.window.showInformationMessage("The completions are disabled. You could enable them from llama-vscode menu.") } else vscode.window.showErrorMessage("No endpoint for the completion (fim) model. Select an env with completion model or enter the endpoint of a running llama.cpp server with completion (fim) model in setting endpoint. ") return; } } const infillUrl = `${Utils.trimTrailingSlash(endpoint)}/infill`; this.logApiRequest('FIM', 'POST', infillUrl, `model=${model || 'none'} | prompt_length=${prompt.length}`); const response = await axios.post( infillUrl, this.createRequestPayload(false, inputPrefix, inputSuffix, chunks, prompt, model, nindent), requestConfig ); this.logApiResponse('FIM', 'POST', infillUrl, `has_content=${response.data?.content !== undefined}`); return response.status === STATUS_OK ? response.data : undefined; }; getChatEditCompletion = async ( instructions: string, originalText: string, context: string, chunks: any, nindent: number ): Promise => { let { endpoint, model, requestConfig } = this.getChatModelProperties(); const chatUrl = `${Utils.trimTrailingSlash(endpoint)}/${this.app.configuration.ai_api_version}/chat/completions`; this.logApiRequest('CHAT_EDIT', 'POST', chatUrl, `model=${model || 'none'}`); const response = await axios.post( chatUrl, this.createChatEditRequestPayload(instructions, originalText, context, model), requestConfig ); this.logApiResponse('CHAT_EDIT', 'POST', chatUrl, `has_choices=${response.data?.choices?.length ?? 0}`); return response.status === STATUS_OK ? response.data : undefined; }; getChatCompletion = async ( prompt: string, ): Promise => { let { endpoint, model, requestConfig } = this.getChatModelProperties(); const chatUrl = `${Utils.trimTrailingSlash(endpoint)}/${this.app.configuration.ai_api_version}/chat/completions`; this.logApiRequest('CHAT', 'POST', chatUrl, `model=${model || 'none'} | prompt_length=${prompt.length}`); const response = await axios.post( chatUrl, this.createChatRequestPayload(prompt, model), requestConfig ); this.logApiResponse('CHAT', 'POST', chatUrl, `has_choices=${response.data?.choices?.length ?? 0}`); return response.status === STATUS_OK ? response.data : undefined; }; getAgentCompletion = async ( messages: ChatMessage[], isSummarization = false, onDelta?: (delta: string) => void, abortSignal?: AbortSignal, imagePath = "", iterationsCount = 0 ): Promise => { const { endpoint, model, requestConfig } = this.getToolsRequestDetails(); const trace: RequestTraceContext = this.createRequestTrace(isSummarization ? 'agent-summary' : 'agent') let uri = `${Utils.trimTrailingSlash(endpoint)}/${this.app.configuration.ai_api_version}/chat/completions`; let request: any; if (isSummarization) { request = this.createGetSummaryRequestPayload(messages, model); try { this.logApiRequest('TOOLS_SUMMARY', 'POST', uri, `model=${model || 'none'} | ${this.summarizeTemplateMessages(request.messages as unknown[])}`, trace); const response = await axios.post( uri, request, { ...requestConfig, signal: abortSignal } ); this.logApiResponse('TOOLS_SUMMARY', 'POST', uri, `finish_reason=${response.data?.choices?.[0]?.finish_reason ?? 'unknown'}`, trace); return response.status === STATUS_OK ? response.data : undefined; } catch (error) { this.logApiError('TOOLS_SUMMARY', 'POST', uri, error, `model=${model || 'none'}`, trace); return this.createErrorResponse(this.extractApiError(error)); } } // Streaming branch for tools/agent calls request = this.createToolsRequestPayload(messages, model, true, imagePath, iterationsCount, endpoint); try { const streamResponse = await axios.post( uri, request, { ...requestConfig, responseType: 'stream' as const, signal: abortSignal } ); // The search_tools result (if any) is already used in the request and is not needed anymore this.app.tools.clearToolSearch(); return await new Promise((resolve) => { const readable = streamResponse.data as NodeJS.ReadableStream; let buffer = ""; let fullContent = ""; let finishReason: string | undefined = undefined; const toolCalls: any[] = []; const message: any = { role: 'assistant', content: null as string | null }; let responseData: Partial = {}; const finalize = () => { message.content = fullContent || null; if (toolCalls.length > 0) message.tool_calls = toolCalls; // Extract total_tokens from usage and set in llamaAgent let requestTokens = responseData.usage?.total_tokens; if (typeof requestTokens === 'number') { this.app.llamaAgent.setLastReqTokens(requestTokens); this.app.chatService.updateChatTokens( this.app.getChat(), requestTokens, responseData.usage?.prompt_tokens, responseData.usage?.completion_tokens, responseData.usage?.prompt_tokens_details?.cached_tokens, responseData.usage?.cost??responseData.usage?.cost_usd ); this.app.llamaWebviewProvider.updateRequestsInfoInView() } else if (responseData.timings && typeof responseData.timings.predicted_n === 'number' && typeof responseData.timings.prompt_n === 'number' && typeof responseData.timings.cache_n === 'number' ) { requestTokens = responseData.timings.predicted_n + responseData.timings.prompt_n + responseData.timings.cache_n; this.app.llamaAgent.setLastReqTokens(requestTokens); this.app.chatService.updateChatTokens( this.app.getChat(), requestTokens, responseData.timings.prompt_n + responseData.timings.cache_n, responseData.timings.predicted_n, responseData.timings.cache_n, 0 ); this.app.llamaWebviewProvider.updateRequestsInfoInView() } resolve({ choices: [{ message, finish_reason: finishReason, }], ...responseData, }); }; // Handle abort signal if (abortSignal) { abortSignal.addEventListener('abort', () => { (readable as any).destroy?.(); resolve(undefined); }); } readable.on('data', (chunk: Buffer) => { buffer += chunk.toString('utf8'); const lines = buffer.split(/\r?\n/); buffer = lines.pop() || ""; for (const line of lines) { const trimmed = line.trim(); if (!trimmed) continue; if (!trimmed.startsWith('data:')) continue; const payload = trimmed.slice(5).trim(); if (payload === '[DONE]') { finalize(); readable.removeAllListeners(); return; } try { const json = JSON.parse(payload); if (json.usage) responseData.usage = json.usage; if (json.timings) responseData.timings = json.timings; const choice = json.choices && json.choices[0] ? json.choices[0] : undefined; if (!choice) continue; if (typeof json.truncated === 'boolean') responseData.truncated = json.truncated; if (typeof json.tokens_cached === 'number') responseData.tokens_cached = json.tokens_cached; if (json.timings) responseData.timings = json.timings; if (json.generation_settings) responseData.generation_settings = json.generation_settings; if (json.usage) { responseData.usage = json.usage; } // Finish reason may appear on a later chunk if (choice.finish_reason) finishReason = choice.finish_reason; const delta = choice.delta || choice.message || {}; if (delta.role && !message.role) message.role = delta.role; if (typeof delta.content === 'string') { fullContent += delta.content; if (onDelta) onDelta(delta.content); } if (Array.isArray(delta.tool_calls)) { for (const tc of delta.tool_calls) { const idx = typeof tc.index === 'number' ? tc.index : 0; if (!toolCalls[idx]) { toolCalls[idx] = { id: tc.id, type: 'function', function: { name: '', arguments: '' } }; } const tgt = toolCalls[idx]; if (tc.id) tgt.id = tc.id; if (tc.function) { if (tc.function.name) tgt.function.name = tc.function.name; if (tc.function.arguments) tgt.function.arguments = (tgt.function.arguments || '') + tc.function.arguments; } } } } catch (e) { // Ignore malformed chunks } } }); readable.on('end', () => { if (!finishReason) finishReason = 'stop'; finalize(); }); readable.on('error', () => { this.logApiError('TOOLS_STREAM', 'POST', uri, { message: 'Stream error during generation' }, `model=${model || 'none'}`, trace); resolve(this.createErrorResponse({ message: 'Stream error during generation' })); }); }); } catch (err) { this.logApiError('TOOLS_STREAM', 'POST', uri, err, `model=${model || 'none'}`, trace); return this.createErrorResponse(this.extractApiError(err)); } }; updateExtraContext = (chunks: any[]): void => { // If the server is OpenAI compatible, use the OpenAI API to prepare for the next FIM if (this.app.configuration.use_openai_endpoint) { return; } // else, make a request to the API to prepare for the next FIM let { endpoint, model, requestConfig } = this.getComplModelProperties(); const infillUrl = `${Utils.trimTrailingSlash(endpoint)}/infill`; this.logApiRequest('FIM_PREP', 'POST', infillUrl, `model=${model || 'none'} | chunks=${chunks.length ?? 0}`); axios.post( infillUrl, this.createRequestPayload(true, "", "", chunks, "", model, undefined), requestConfig ).then(() => { this.logApiResponse('FIM_PREP', 'POST', infillUrl, 'ok'); }).catch((error) => { this.logApiError('FIM_PREP', 'POST', infillUrl, error, `model=${model || 'none'}`); }); }; getEmbeddings = async (text: string): Promise => { let endpoint = this.app.configuration.endpoint_embeddings; let model = this.app.configuration.ai_model; try { let selectedModel: LlmModel = this.app.getEmbeddingsModel(); if (selectedModel.aiModel) model = selectedModel.aiModel; if (selectedModel.endpoint) endpoint = selectedModel.endpoint; let requestConfig = this.app.configuration.axiosRequestConfigEmbeddings; if (selectedModel.isKeyRequired){ const apiKey = this.app.persistence.getApiKey(selectedModel.endpoint??""); if (apiKey){ requestConfig = { headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, } } } const embeddingsUrl = `${Utils.trimTrailingSlash(endpoint)}/v1/embeddings`; this.logApiRequest('EMBEDDINGS', 'POST', embeddingsUrl, `model=${model || 'none'} | input_length=${text.length}`); const response = await axios.post( embeddingsUrl, { "input": text, // "model": "GPT-4", ...(model.trim() != "" && { model: model}), "encoding_format": "float" }, requestConfig ); this.logApiResponse('EMBEDDINGS', 'POST', embeddingsUrl, `tokens=${response.data.usage?.total_tokens ?? 'unknown'}`); return response.data; } catch (error: any) { this.logApiError('EMBEDDINGS', 'POST', `${Utils.trimTrailingSlash(endpoint)}/v1/embeddings`, error, `model=${model || 'none'}`); console.error('Failed to get embeddings:', error); vscode.window.showInformationMessage(this.app.configuration.getUiText("Error getting embeddings") + " " + error.message); return undefined; } }; shellFimCmd = (launchCmd: string): void => { if (!launchCmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { launchCmd = this.useNewLaunchCommand(launchCmd); this.vsCodeFimTerminal = vscode.window.createTerminal({ name: 'llama.cpp Completion Terminal' }); this.vsCodeFimTerminal.show(true); this.vsCodeFimTerminal.sendText(launchCmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + launchCmd +" : " + err.message); } } } shellChatCmd = (launchCmd: string): void => { if (!launchCmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { launchCmd = this.useNewLaunchCommand(launchCmd); this.vsCodeChatTerminal = vscode.window.createTerminal({ name: 'llama.cpp Chat Terminal' }); this.vsCodeChatTerminal.show(true); this.vsCodeChatTerminal.sendText(launchCmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + launchCmd +" : " + err.message); } } } shellEmbeddingsCmd = (launchCmd: string): void => { if (!launchCmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { launchCmd = this.useNewLaunchCommand(launchCmd); this.vsCodeEmbeddingsTerminal = vscode.window.createTerminal({ name: 'llama.cpp Embeddings Terminal' }); this.vsCodeEmbeddingsTerminal.show(true); this.vsCodeEmbeddingsTerminal.sendText(launchCmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + launchCmd +" : " + err.message); } } } shellToolsCmd = (launchCmd: string): void => { if (!launchCmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { launchCmd = this.useNewLaunchCommand(launchCmd); this.vsCodeToolsTerminal = vscode.window.createTerminal({ name: 'llama.cpp Tools Terminal' }); this.vsCodeToolsTerminal.show(true); this.vsCodeToolsTerminal.sendText(launchCmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + launchCmd +" : " + err.message); } } } shellTrainCmd = (trainCmd: string): void => { if (!trainCmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { this.vsCodeTrainTerminal = vscode.window.createTerminal({ name: 'llama.cpp Train Terminal' }); this.vsCodeTrainTerminal.show(true); this.vsCodeTrainTerminal.sendText(trainCmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + trainCmd +" : " + err.message); } } } shellCommandCmd = (cmd: string): void => { if (!cmd) { vscode.window.showInformationMessage(this.app.configuration.getUiText("There is no command to execute.")??""); return; } try { this.vsCodeCommandTerminal = vscode.window.createTerminal({ name: 'Command Terminal' }); this.vsCodeCommandTerminal.show(true); this.vsCodeCommandTerminal.sendText(cmd); } catch(err){ if (err instanceof Error) { vscode.window.showInformationMessage(this.app.configuration.getUiText("Error executing command") + " " + cmd +" : " + err.message); } } } /** * Runs a command in a non-interactive shell and returns its output. * * Options are additive so the six call sites (architect, menu x2, agent * prompt preprocessing, dsl commands, the tool) keep working unchanged. * Never throws: architect.ts relies on the returned strings only. * * The visible terminal is decorative - the real work happens in the child * process. Nothing is echoed into it, because a double-quoted echo would * still expand $(...) and backticks of model-provided text and could run it. */ executeCommandWithTerminalFeedback = async ( command: string, options?: { cwd?: string; timeoutMs?: number; signal?: AbortSignal } ): Promise => { this.showCommandTerminal(); const invocation = buildShellInvocation(command, process.platform); const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS; this.app.logger.addEventLog("terminal", "exec", command); // The child runs in its own process group, so it must be reachable from // killCommandCmd() as well: otherwise closing VS Code leaves it running. const running = startCommand(invocation, { cwd: options?.cwd, timeoutMs, signal: options?.signal }); this.runningCommands.add(running); try { const outcome = await running.result; const stdout = outcome.stdout; const stderr = cleanTtyNoise(outcome.stderr); this.app.logger.addEventLog("terminal", outcome.timedOut ? "timeout" : outcome.cancelled ? "cancelled" : "exit", String(outcome.exitCode)); this.logCommandOutput(stdout || stderr); return { stdout, stderr, exitCode: outcome.exitCode, timedOut: outcome.timedOut, cancelled: outcome.cancelled }; } catch (error: any) { // Spawning itself failed (a missing shell, EACCES, ...). The contract // is "never throw", so the failure becomes the output. const message = String(error?.message ?? error ?? "unknown error"); this.app.logger.addEventLog("terminal", "error", message); return { stdout: "", stderr: cleanTtyNoise(message), exitCode: -1, timedOut: false, cancelled: false }; } finally { this.runningCommands.delete(running); } } /** * The visible terminal used to receive an `echo` of the output, which meant * interpolating model-provided text into a shell. The output channel shows * the same information without any shell involved, and only the tail: a * build log has thousands of lines and the last ones are the interesting. */ private logCommandOutput = (output: string): void => { const tail = output.trim().split(/\r?\n/).slice(-20).join("\n"); if (tail !== "") this.app.logger.addEventLog("terminal", "output", tail); } /** * Reuses one terminal for command feedback: recreating it on every call (the * old behaviour also called killCommandCmd() first) destroyed the previous * output and made two parallel agent sessions fight over the same handle. */ private showCommandTerminal = (): void => { try { if (!this.vsCodeCommandTerminal) { this.vsCodeCommandTerminal = vscode.window.createTerminal({ name: "llama-vscode Command Terminal" }); } this.vsCodeCommandTerminal.show(true); } catch { // The terminal is only cosmetic; a failure must not fail the command. } } killFimCmd = (): void => { if (this.vsCodeFimTerminal) { this.vsCodeFimTerminal.dispose(); this.vsCodeFimTerminal = undefined; } } isFimRunning = (): boolean => { if (this.vsCodeFimTerminal) return true; else return false; } killChatCmd = (): void => { if (this.vsCodeChatTerminal) { this.vsCodeChatTerminal.dispose(); this.vsCodeChatTerminal = undefined; } } isChatRunning = (): boolean => { if (this.vsCodeChatTerminal) return true; else return false; } killEmbeddingsCmd = (): void => { if (this.vsCodeEmbeddingsTerminal) { this.vsCodeEmbeddingsTerminal.dispose(); this.vsCodeEmbeddingsTerminal = undefined; } } isEmbeddingsRunning = (): boolean => { if (this.vsCodeEmbeddingsTerminal) return true; else return false; } isToolsRunning = (): boolean => { if (this.vsCodeToolsTerminal) return true; else return false; } killTrainCmd = (): void => { if (this.vsCodeTrainTerminal) { this.vsCodeTrainTerminal.dispose(); this.vsCodeChatTerminal = undefined; } } killCommandCmd = (): void => { // The child runs in its own process group (detached), so disposing the // terminal is not enough: the OS would keep the command alive. for (const running of this.runningCommands) running.kill(); this.runningCommands.clear(); if (this.vsCodeCommandTerminal) { this.vsCodeCommandTerminal.dispose(); this.vsCodeCommandTerminal = undefined; } } killToolsCmd = (): void => { if (this.vsCodeToolsTerminal) { this.vsCodeToolsTerminal.dispose(); this.vsCodeToolsTerminal = undefined; } } private useNewLaunchCommand(launchCmd: string) { const oldCommand = "llama-server "; const newCommand = "llama serve "; if (launchCmd.startsWith("llama-server ")) { launchCmd = launchCmd; launchCmd = newCommand + launchCmd.substring(newCommand.length); } return launchCmd; } private getChatModelProperties() { let selectedModel: LlmModel = this.app.getChatModel(); if (!this.app.isChatModelSelected() && !this.app.configuration.endpoint_chat) selectedModel = this.app.getToolsModel(); let endpoint = this.app.configuration.endpoint_chat; let model = this.app.configuration.ai_model; let requestConfig = this.app.configuration.axiosRequestConfigChat; if (!endpoint) { endpoint = this.app.configuration.endpoint_tools; requestConfig = this.app.configuration.axiosRequestConfigTools; } if (selectedModel?.endpoint !== undefined && selectedModel.endpoint) { endpoint = selectedModel.endpoint; if (selectedModel?.aiModel !== undefined && selectedModel.aiModel) model = selectedModel.aiModel; if (selectedModel?.isKeyRequired !== undefined && selectedModel.isKeyRequired) { const apiKey = this.app.persistence.getApiKey(selectedModel.endpoint??""); if (apiKey) { requestConfig = { headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, }; } } } return { endpoint, model, requestConfig }; } private getComplModelProperties() { const selectedComplModel: LlmModel = this.app.getComplModel(); let model = this.app.configuration.ai_model; if (selectedComplModel?.aiModel !== undefined && selectedComplModel.aiModel) model = selectedComplModel.aiModel; let endpoint = this.app.configuration.endpoint; if (selectedComplModel?.endpoint !== undefined && selectedComplModel.endpoint) endpoint = selectedComplModel.endpoint; let requestConfig = this.app.configuration.axiosRequestConfigCompl; if (selectedComplModel?.isKeyRequired !== undefined && selectedComplModel.isKeyRequired) { const apiKey = this.app.persistence.getApiKey(selectedComplModel.endpoint??""); if (apiKey) { requestConfig = { headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, }; } } return { endpoint, model, requestConfig }; } checkHealth = async (modelType: ModelType, model: LlmModel) => { let requestConfig: AxiosRequestConfig = this.app.configuration.axiosRequestConfigCompl; switch (modelType) { case ModelType.Chat: requestConfig = this.app.configuration.axiosRequestConfigChat; break; case ModelType.Completion: requestConfig = this.app.configuration.axiosRequestConfigCompl; break; case ModelType.Tools: requestConfig = this.app.configuration.axiosRequestConfigTools; break; case ModelType.Embeddings: requestConfig = this.app.configuration.axiosRequestConfigEmbeddings; break; } try { // TODO:Make sure to work with OpenRouter too const healthUrl = model.endpoint + "/health"; this.logApiRequest('HEALTH', 'GET', healthUrl, `modelType=${modelType}`); let response = await axios.get(healthUrl, requestConfig); this.logApiResponse('HEALTH', 'GET', healthUrl, `status=${response.data?.status ?? 'missing'}`); if (!response.data.hasOwnProperty("status")) return "Error: No health status field found"; return response.data.status } catch (error) { this.logApiError('HEALTH', 'GET', model.endpoint + "/health", error, `modelType=${modelType}`); if (error instanceof TypeError) { return "TypeError occurred: " + error.message; } else if (error instanceof ReferenceError) { return "ReferenceError occurred:" + error.message; } else { return "An unexpected Error occurred:" + (error as Error).message; } } } }