Open History to see the last commit
1import { HTTPClient, Mistral } from '@mistralai/mistralai'
2
3export interface MistralClientConfig {
4 /** Mistral API key. */
5 apiKey: string
6
7 /**
8 * Base URL for every request. Same option name as the other adapters, so a
9 * gateway config can be spread into any of them. Wins over `serverURL` when
10 * both are set.
11 */
12 baseURL?: string
13
14 /** Alias of `baseURL`. */
15 serverURL?: string
16
17 /** Optional request timeout (ms). */
18 timeoutMs?: number
19
20 /** Optional default headers to include with every request. */
21 defaultHeaders?: Record<string, string>
22
23 /**
24 * Optional Google / Vertex access token. When set, it replaces
25 * `apiKey` on the Authorization header.
26 */
27 getAccessToken?: () => Promise<string>
28
29 /**
30 * Optional chat completions URL. Vertex uses this for
31 * `:rawPredict` and `:streamRawPredict`.
32 */
33 resolveRequestUrl?: (stream: boolean) => string
34
35 /** Optional model id sent on the wire. Vertex uses publisher model ids. */
36 requestModel?: string
37}
38
39/**
40 * Creates a Mistral SDK client instance.
41 */
42export function createMistralClient(config: MistralClientConfig): Mistral {
43 const {
44 apiKey,
45 baseURL,
46 timeoutMs,
47 defaultHeaders,
48 getAccessToken,
49 resolveRequestUrl,
50 } = config
51 const serverURL = baseURL ?? config.serverURL
52
53 const needsHook =
54 (defaultHeaders !== undefined && Object.keys(defaultHeaders).length > 0) ||
55 getAccessToken !== undefined ||
56 resolveRequestUrl !== undefined
57
58 let httpClient: HTTPClient | undefined
59 if (needsHook) {
60 httpClient = new HTTPClient()
61 httpClient.addHook('beforeRequest', async (req) => {
62 const nextUrl =
63 resolveRequestUrl === undefined ? req.url : resolveRequestUrl(false)
64 const next = new Request(nextUrl, req)
65 if (defaultHeaders) {
66 for (const [key, value] of Object.entries(defaultHeaders)) {
67 next.headers.set(key, value)
68 }
69 }
70 if (getAccessToken !== undefined) {
71 next.headers.set('Authorization', `Bearer ${await getAccessToken()}`)
72 }
73 return next
74 })
75 }
76
77 return new Mistral({
78 apiKey,
79 ...(serverURL !== undefined ? { serverURL } : {}),
80 ...(timeoutMs !== undefined ? { timeoutMs } : {}),
81 ...(httpClient !== undefined ? { httpClient } : {}),
82 })
83}
84
85/**
86 * Gets Mistral API key from environment variables.
87 * @throws Error if MISTRAL_API_KEY is not found
88 */
89export function getMistralApiKeyFromEnv(): string {
90 let key: string | undefined
91
92 if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
93 key = process.env.MISTRAL_API_KEY
94 } else {
95 const g = globalThis as { window?: { env?: Record<string, string> } }
96 key = g.window?.env?.MISTRAL_API_KEY
97 }
98
99 if (!key) {
100 throw new Error(
101 'MISTRAL_API_KEY is required. In Node.js set it as an environment variable; in browser environments inject it via window.env.MISTRAL_API_KEY or use the factory function with an explicit API key.',
102 )
103 }
104
105 return key
106}
107
108/**
109 * Generates a unique ID with a prefix.
110 */
111export function generateId(prefix: string): string {
112 return `${prefix}-${crypto.randomUUID()}`
113}