autodetect mistral API key type

This commit is contained in:
Nate 2024-12-16 12:31:37 -08:00
parent 3a3bf73cb7
commit 6169618807
2 changed files with 46 additions and 7 deletions

View file

@ -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<string[]> {
return Promise.resolve([]);
}

View file

@ -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<LLMOptions> = {
@ -14,6 +16,17 @@ class Mistral extends OpenAI {
maxEmbeddingBatchSize: 128,
};
private async autodetectApiKeyType(): Promise<MistralApiKeyType> {
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 } = {