Merge pull request #5211 from fbricon/download-embedder-ollama

Show embedding model errors and prompt for download missing local embedding models
This commit is contained in:
Patrick Erichsen 2025-04-28 16:30:18 -07:00 • committed by GitHub
commit 228335f3d5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 194 additions and 68 deletions

View file

@ -57,6 +57,7 @@ import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMError } from "./llm";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -1032,25 +1033,23 @@ export class Core {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
// TODO reconsider this status overwrite?
// original goal was to not concern users with edge noncritical errors
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try {
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1068,22 +1067,22 @@ export class Core {
return;
}
this.indexingCancellationController = new AbortController();
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
if (update.status === "failed") {
updateToSend.status = "done";
updateToSend.desc = "Indexing complete";
updateToSend.progress = 1.0;
}
try{
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
files,
)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
@ -1093,4 +1092,19 @@ export class Core {
}
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

4
core/index.d.ts vendored
View file

@ -157,6 +157,10 @@ export interface ModelInstaller {
signal: AbortSignal,
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any>;
isInstallingModel(
modelName: string
): Promise<boolean>;
}
export type ContextProviderType = "normal" | "query" | "submenu";

View file

@ -7,6 +7,8 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -350,6 +352,10 @@ export class CodebaseIndexer {
): IndexingProgressUpdate {
console.log("error when indexing: ", err);
if (err instanceof Error) {
const cause = getRootCause(err);
if (cause instanceof LLMError) {
throw cause;
}
return this.errorToProgressUpdate(err);
}
return {
@ -361,7 +367,8 @@ export class CodebaseIndexer {
}
private errorToProgressUpdate(err: Error): IndexingProgressUpdate {
let errMsg: string = `${err}`;
const cause = getRootCause(err);
let errMsg: string = `${cause}`;
let shouldClearIndexes = false;
// Check if any of the error regexes match

View file

@ -36,6 +36,7 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import type * as LanceType from "vectordb";
import { LLMError } from "../../llm";
import { DocsCache, SiteIndexingResults } from "./DocsCache";
// Purposefully lowercase because lancedb converts
@ -421,6 +422,7 @@ export default class DocsService {
return false;
}
// eslint-disable-next-line max-statements
async indexAndAdd(
siteIndexingConfig: SiteIndexingConfig,
forceReindex: boolean = false,
@ -506,6 +508,16 @@ export default class DocsService {
try {
await provider.embed(["continue-test-run"]);
} catch (e) {
if (e instanceof LLMError) {
// Report the error to the IDE
this.messenger?.request("reportError", e);
}
this.handleStatusUpdate({
...fixedStatus,
description: `Failed to test embeddings connection. ${e}`,
status: "failed",
progress: 1,
});
console.error("Failed to test embeddings connection", e);
return;
}

View file

@ -71,7 +71,7 @@ export class LLMError extends Error {
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";;
}
type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";

View file

@ -1,3 +1,4 @@
import { Mutex } from "async-mutex";
import { spawn } from "child_process";
import { LLMOptions, ModelInstaller } from "../../index.js";
import OpenAI from "./OpenAI.js";
@ -47,6 +48,9 @@ class Docker extends OpenAI implements ModelInstaller {
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M",
};
private static modelsBeingInstalled: Set<string> = new Set();
private static modelsBeingInstalledMutex = new Mutex();
constructor(options: LLMOptions) {
super(options);
@ -164,6 +168,16 @@ class Docker extends OpenAI implements ModelInstaller {
): Promise<any> {
const targetModel = this.modelMap[modelName] || modelName;
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
if (Docker.modelsBeingInstalled.has(modelName)) {
throw new Error(`Model '${modelName}' is already being installed.`);
}
Docker.modelsBeingInstalled.add(modelName);
} finally {
release();
}
try {
// Report starting the installation
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
@ -184,12 +198,28 @@ class Docker extends OpenAI implements ModelInstaller {
return { success: true, stdout, stderr };
} catch (error) {
console.error(`Failed to install Docker model ${targetModel}:`, error);
// Fix: Type check the error before accessing message property
// Fix: Type check the error before accessing message property
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to install Docker model ${targetModel}: ${errorMessage}`,
);
} finally {
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
Docker.modelsBeingInstalled.delete(modelName);
} finally {
release();
}
}
}
public async isInstallingModel(modelName: string): Promise<boolean> {
const release = await Docker.modelsBeingInstalledMutex.acquire();
try {
return Docker.modelsBeingInstalled.has(modelName);
} finally {
release();
}
}
}

View file

@ -1,3 +1,4 @@
import { Mutex } from "async-mutex";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import {
@ -138,6 +139,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
maxEmbeddingBatchSize: 64,
};
private static modelsBeingInstalled: Set<string> = new Set();
private static modelsBeingInstalledMutex = new Mutex();
private fimSupported: boolean = false;
constructor(options: LLMOptions) {
@ -592,33 +596,62 @@ class Ollama extends BaseLLM implements ModelInstaller {
if (!modelInfo) {
throw new Error(`'${modelName}' not found in the Ollama registry!`);
}
const response = await fetch(this.getEndpoint("api/pull"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal,
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = (await reader?.read()) || {
done: true,
value: undefined,
};
if (done) {
break;
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
if (Ollama.modelsBeingInstalled.has(modelName)) {
throw new Error(`Model '${modelName}' is already being installed.`);
}
Ollama.modelsBeingInstalled.add(modelName);
} finally {
release();
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split("\n").filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
try {
const response = await fetch(this.getEndpoint("api/pull"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ name: modelName }),
signal,
});
const reader = response.body?.getReader();
//TODO: generate proper progress based on modelInfo size
while (true) {
const { done, value } = (await reader?.read()) || {
done: true,
value: undefined,
};
if (done) {
break;
}
const chunk = new TextDecoder().decode(value);
const lines = chunk.split("\n").filter(Boolean);
for (const line of lines) {
const data = JSON.parse(line);
progressReporter?.(data.status, data.completed, data.total);
}
}
} finally {
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
Ollama.modelsBeingInstalled.delete(modelName);
} finally {
release();
}
}
}
public async isInstallingModel(modelName: string): Promise<boolean> {
const release = await Ollama.modelsBeingInstalledMutex.acquire();
try {
return Ollama.modelsBeingInstalled.has(modelName);
} finally {
release();
}
}
}

View file

@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
ControlPlaneSessionInfo | undefined,
];
logoutOfControlPlane: [undefined, void];
reportError:[any, void];
closeSidebar: [undefined, void];
};

13
core/util/errors.ts Normal file
View file

@ -0,0 +1,13 @@
/**
* Recursively retrieves the root cause of an error by traversing through its `cause` property.
*
* @param err - The error object to analyze. It can be of any type.
* @returns The root cause of the error, or the original error if no further cause is found.
*/
export function getRootCause(err: any): any {
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}

View file

@ -5,11 +5,11 @@ import {
type AutocompleteOutcome,
} from "core/autocomplete/util/types";
import { ConfigHandler } from "core/config/ConfigHandler";
import { startLocalOllama } from "core/util/ollamaHelper";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { handleLLMError } from "../util/errorHandling";
import { showFreeTrialLoginMessage } from "../util/messages";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
@ -24,7 +24,6 @@ import {
} from "./statusBar";
import type { IDE } from "core";
import { handleLLMError } from "../util/errorHandling";
interface VsCodeCompletionInput {
document: vscode.TextDocument;
@ -34,8 +33,8 @@ interface VsCodeCompletionInput {
export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider {
private onError(e: any) {
if (handleLLMError(e)) {
private async onError(e: any) {
if (await handleLLMError(e)) {
return;
}
let message = e.message;

View file

@ -22,6 +22,7 @@ import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
} from "../stubs/WorkOsAuthProvider";
import { handleLLMError } from "../util/errorHandling";
import { showTutorial } from "../util/tutorial";
import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
@ -237,11 +238,11 @@ export class VsCodeMessenger {
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
this.onWebview(messageType, async (msg) => {
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
});
});
@ -410,5 +411,9 @@ export class VsCodeMessenger {
this.onWebviewOrCore("getUniqueId", async (msg) => {
return await ide.getUniqueId();
});
this.onWebviewOrCore("reportError", async (msg) => {
handleLLMError(msg.data);
});
}
}

View file

@ -1,3 +1,5 @@
import { ILLM } from "core";
import { isModelInstaller } from "core/llm";
import * as vscode from "vscode";
function supportSpecialHandling(error: any): boolean {
@ -9,7 +11,7 @@ function supportSpecialHandling(error: any): boolean {
* @param error Handles common LLM errors. Currently only handles Ollama-related errors.
* @returns true if error is handled, false otherwise
*/
export function handleLLMError(error: any): boolean {
export async function handleLLMError(error: any): Promise<boolean> {
if (!supportSpecialHandling(error)) {
return false;
}
@ -23,6 +25,11 @@ export function handleLLMError(error: any): boolean {
} else if (message.includes("ollama run") && error.llm) {
//extract model name from error message matching the pattern "ollama run <model-name>"
modelName = message.match(/`ollama run (.*)`/)?.[1];
const llm = error.llm as ILLM;
if (isModelInstaller(llm) && await llm.isInstallingModel(modelName!)){
console.log(`${llm.providerName} already installing ${modelName}`);
return false;
}
message = `Model "${modelName}" is not found in Ollama. You need to install it.`;
options = [`Install Model`];
}

View file

@ -87,7 +87,7 @@ export class VsCodeWebviewProtocol
respond({ done: true, content: response, status: "success" });
}
} catch (e: any) {
if (handleLLMError(e)) {
if (await handleLLMError(e)) {
// Respond without an error, so the UI doesn't show the error component
respond({ done: true, status: "error" });
}

View file

@ -6,7 +6,8 @@ export interface IndexingProgressBarProps {
}
function IndexingProgressBar({ update }: IndexingProgressBarProps) {
const progressPercentage = getProgressPercentage(update.progress);
// Show 100% red progress bar if indexing failed
const progressPercentage = update.status === "failed" ? 100 : getProgressPercentage(update.progress);
return (
<div className="my-2 h-1.5 w-full rounded-md border border-solid border-gray-400">

View file

@ -31,7 +31,7 @@ function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) {
}
return (
<div className="flex items-center gap-2 italic">
<div className="flex items-center gap-2 italic text-red-600">
<XCircleIcon className="h-4 w-4" />
<span className="leading-relaxed">{update.desc}</span>
</div>