| 1 | import { ChatMessage, LLMOptions } from "../../index.js"; |
| 2 | import { codestralEditPrompt } from "../templates/edit/codestral.js"; |
| 3 | |
| 4 | import OpenAI from "./OpenAI.js"; |
| 5 | |
| 6 | type MistralApiKeyType = "mistral" | "codestral"; |
| 7 | |
| 8 | class Mistral extends OpenAI { |
| 9 | static providerName = "mistral"; |
| 10 | static defaultOptions: Partial<LLMOptions> = { |
| 11 | apiBase: "https://api.mistral.ai/v1/", |
| 12 | model: "codestral-latest", |
| 13 | promptTemplates: { |
| 14 | edit: codestralEditPrompt, |
| 15 | }, |
| 16 | maxEmbeddingBatchSize: 128, |
| 17 | }; |
| 18 | |
| 19 | private async autodetectApiKeyType(): Promise<MistralApiKeyType> { |
| 20 | const mistralResp = await fetch("https://api.mistral.ai/v1/models", { |
| 21 | method: "GET", |
| 22 | headers: this._getHeaders(), |
| 23 | }); |
| 24 | if (mistralResp.status === 401) { |
| 25 | return "codestral"; |
| 26 | } |
| 27 | return "mistral"; |
| 28 | } |
| 29 | |
| 30 | constructor(options: LLMOptions) { |
| 31 | super(options); |
| 32 | if ( |
| 33 | options.model.includes("codestral") && |
| 34 | !options.model.includes("mamba") |
| 35 | ) { |
| 36 | this.apiBase = options.apiBase ?? "https://codestral.mistral.ai/v1/"; |
| 37 | } |
| 38 | |
| 39 | if (!this.apiBase?.endsWith("/")) { |
| 40 | this.apiBase += "/"; |
| 41 | } |
| 42 | |
| 43 | // Unless the user explicitly specifies, we will autodetect the API key type and adjust the API base accordingly |
| 44 | if (!options.apiBase) { |
| 45 | this.autodetectApiKeyType() |
| 46 | .then((keyType) => { |
| 47 | switch (keyType) { |
| 48 | case "codestral": |
| 49 | this.apiBase = "https://codestral.mistral.ai/v1/"; |
| 50 | break; |
| 51 | case "mistral": |
| 52 | this.apiBase = "https://api.mistral.ai/v1/"; |
| 53 | break; |
| 54 | } |
| 55 | |
| 56 | this.openaiAdapter = this.createOpenAiAdapter(); |
| 57 | }) |
| 58 | .catch((err: any) => {}); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | private static modelConversion: { [key: string]: string } = { |
| 63 | "mistral-7b": "open-mistral-7b", |
| 64 | "mistral-8x7b": "open-mixtral-8x7b", |
| 65 | }; |
| 66 | protected _convertModelName(model: string): string { |
| 67 | return Mistral.modelConversion[model] ?? model; |
| 68 | } |
| 69 | |
| 70 | _convertArgs(options: any, messages: ChatMessage[]) { |
| 71 | const finalOptions = super._convertArgs(options, messages); |
| 72 | |
| 73 | const lastMessage = finalOptions.messages[finalOptions.messages.length - 1]; |
| 74 | if (lastMessage?.role === "assistant") { |
| 75 | (lastMessage as any).prefix = true; |
| 76 | } |
| 77 | |
| 78 | return finalOptions; |
| 79 | } |
| 80 | |
| 81 | supportsFim(): boolean { |
| 82 | return true; |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | export default Mistral; |