diff --git a/core/llm/index.ts b/core/llm/index.ts index 041693363..c5a0d5c79 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -138,7 +138,7 @@ export abstract class BaseLLM implements ILLM { private _llmOptions: LLMOptions; - private openaiAdapter?: BaseLlmApi; + protected openaiAdapter?: BaseLlmApi; constructor(_options: LLMOptions) { this._llmOptions = _options; @@ -212,12 +212,7 @@ export abstract class BaseLLM implements ILLM { this.projectId = options.projectId; this.profile = options.profile; - this.openaiAdapter = constructLlmApi({ - provider: this.providerName as any, - apiKey: this.apiKey ?? "", - apiBase: this.apiBase, - requestOptions: this.requestOptions, - }); + this.openaiAdapter = this.createOpenAiAdapter(); this.maxEmbeddingBatchSize = options.maxEmbeddingBatchSize ?? DEFAULT_MAX_BATCH_SIZE; @@ -226,6 +221,15 @@ export abstract class BaseLLM implements ILLM { this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; } + protected createOpenAiAdapter() { + return constructLlmApi({ + provider: this.providerName as any, + apiKey: this.apiKey ?? "", + apiBase: this.apiBase, + requestOptions: this.requestOptions, + }); + } + listModels(): Promise { return Promise.resolve([]); } diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index 124957a41..26f135c7f 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -3,6 +3,8 @@ import { codestralEditPrompt } from "../templates/edit/codestral.js"; import OpenAI from "./OpenAI.js"; +type MistralApiKeyType = "mistral" | "codestral"; + class Mistral extends OpenAI { static providerName = "mistral"; static defaultOptions: Partial = { @@ -14,6 +16,17 @@ class Mistral extends OpenAI { maxEmbeddingBatchSize: 128, }; + private async autodetectApiKeyType(): Promise { + const mistralResp = await fetch("https://api.mistral.ai/v1/models", { + method: "GET", + headers: this._getHeaders(), + }); + if (mistralResp.status === 401) { + return "codestral"; + } + return "mistral"; + } + constructor(options: LLMOptions) { super(options); if ( @@ -26,6 +39,28 @@ class Mistral extends OpenAI { if (!this.apiBase?.endsWith("/")) { this.apiBase += "/"; } + + // Unless the user explicitly specifies, we will autodetect the API key type and adjust the API base accordingly + if (!options.apiBase) { + this.autodetectApiKeyType() + .then((keyType) => { + switch (keyType) { + case "codestral": + this.apiBase = "https://codestral.mistral.ai/v1/"; + break; + case "mistral": + this.apiBase = "https://api.mistral.ai/v1/"; + break; + } + + this.openaiAdapter = this.createOpenAiAdapter(); + }) + .catch((err: any) => { + console.log( + `Error autodetecting API key type for Mistral: ${err.message}`, + ); + }); + } } private static modelConversion: { [key: string]: string } = {