Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client.ts

132 lines3.7 KB

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
38​
39/**
40 * Creates a Mistral SDK client instance. A `fetcher` replaces the SDK's fetch.
41 */
42export function createMistralClient(
43 config: MistralClientConfig,
44 fetcher?: typeof fetch,
45): Mistral {
46 const {
47 apiKey,
48 baseURL,
49 timeoutMs,
50 defaultHeaders,
51 getAccessToken,
52 resolveRequestUrl,
53 } = config
54 const serverURL = baseURL ?? config.serverURL
55​
56 const needsHook =
57 (defaultHeaders !== undefined && Object.keys(defaultHeaders).length > 0) ||
58 getAccessToken !== undefined ||
59 resolveRequestUrl !== undefined
60​
61 let httpClient: HTTPClient | undefined
62 if (needsHook || fetcher) {
63 httpClient = new HTTPClient({
64 // The SDK sends a Request. Send a URL and an init, as a plain fetch
65 // call does, so a wrapper that reads `init.headers` keeps them.
66 fetcher:
67 fetcher &&
68 (async (input) => {
69 const request = new Request(input)
70 return fetcher(request.url, {
71 method: request.method,
72 headers: request.headers,
73 body: request.body && (await request.arrayBuffer()),
74 signal: request.signal,
75 })
76 }),
77 })
78 }
79 if (httpClient && needsHook) {
80 httpClient.addHook('beforeRequest', async (req) => {
81 const nextUrl =
82 resolveRequestUrl === undefined ? req.url : resolveRequestUrl(false)
83 const next = new Request(nextUrl, req)
84 if (defaultHeaders) {
85 for (const [key, value] of Object.entries(defaultHeaders)) {
86 next.headers.set(key, value)
87 }
88 }
89 if (getAccessToken !== undefined) {
90 next.headers.set('Authorization', `Bearer ${await getAccessToken()}`)
91 }
92 return next
93 })
94 }
95​
96 return new Mistral({
97 apiKey,
98 ...(serverURL !== undefined ? { serverURL } : {}),
99 ...(timeoutMs !== undefined ? { timeoutMs } : {}),
100 ...(httpClient !== undefined ? { httpClient } : {}),
101 })
103​
104/**
105 * Gets Mistral API key from environment variables.
106 * @throws Error if MISTRAL_API_KEY is not found
107 */
108export function getMistralApiKeyFromEnv(): string {
109 let key: string | undefined
110​
111 if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
112 key = process.env.MISTRAL_API_KEY
113 } else {
114 const g = globalThis as { window?: { env?: Record<string, string> } }
115 key = g.window?.env?.MISTRAL_API_KEY
116 }
117​
118 if (!key) {
119 throw new Error(
120 '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.',
121 )
122 }
123​
124 return key
126​
127/**
128 * Generates a unique ID with a prefix.
129 */
130export function generateId(prefix: string): string {
131 return `${prefix}-${crypto.randomUUID()}`