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

mistral.test.ts

334 lines11.8 KB

1import { readFileSync } from 'node:fs'
2​
3import { describe, expect, it } from 'vitest'
4​
5import {
6 MISTRAL_WEBSEARCH_GUIDE,
7 mistralModelPage,
8 tip,
9} from '../fixtures/mistral-model-page.ts'
10import { provider } from './mistral.ts'
11import { MISTRAL_DEPRECATIONS_URL } from '../deprecations.ts'
12import { MISTRAL_WEBSEARCH_URL } from '../mistral-pricing.ts'
13import { MISTRAL_REASONING_URL } from '../reasoning-config.ts'
14​
15const MODELS_PAGE = readFileSync(
16 new URL('../fixtures/mistral-models.md.txt', import.meta.url),
17 'utf8',
19​
20describe('mistral classify', () => {
21 it('maps generation paths to the claimed activities', () => {
22 expect(provider.classify('/v1/chat/completions', {})).toBe('chat')
23 expect(provider.classify('/v1/fim/completions', {})).toBe('chat')
24 expect(provider.classify('/v1/agents/completions', {})).toBe('chat')
25 expect(provider.classify('/v1/embeddings', {})).toBe('embeddings')
26 expect(provider.classify('/v1/moderations', {})).toBe('moderation')
27 expect(provider.classify('/v1/chat/moderations', {})).toBe('moderation')
28 expect(provider.classify('/v1/audio/transcriptions', {})).toBe('audio')
29 expect(provider.classify('/v1/audio/transcriptions#stream', {})).toBe(
30 'audio',
31 )
32 expect(provider.classify('/v1/audio/speech', {})).toBe('audio')
33 })
34​
35 it('drops platform, admin, files, fine-tune, batch, and classifiers that are not moderation', () => {
36 expect(provider.classify('/v1/files', {})).toBeNull()
37 expect(
38 provider.classify('/v1/fine_tuning/models/{model_id}', {}),
39 ).toBeNull()
40 expect(provider.classify('/v1/batch/jobs', {})).toBeNull()
41 expect(provider.classify('/v1/admin/users', {})).toBeNull()
42 expect(provider.classify('/v1/agents', {})).toBeNull()
43 expect(provider.classify('/v1/conversations', {})).toBeNull()
44 expect(provider.classify('/v1/ocr', {})).toBeNull()
45 expect(provider.classify('/v1/classifications', {})).toBeNull()
46 expect(provider.classify('/v1/chat/classifications', {})).toBeNull()
47 expect(provider.classify('/v1/models', {})).toBeNull()
48 })
49})
50​
51describe('mistral listModels', () => {
52 it('skips with an empty catalog when MISTRAL_API_KEY is absent', async () => {
53 const { models, skipped } = await provider.listModels({})
54 expect(models).toEqual([])
55 expect(skipped).toBe('mistral: MISTRAL_API_KEY not set — skipped')
56 })
57​
58 it('maps live rows and sends the bearer key', async () => {
59 const original = globalThis.fetch
60 const calls: Array<{ url: string; auth: string | null }> = []
61 globalThis.fetch = ((url: string, init?: RequestInit) => {
62 const href = String(url)
63 calls.push({
64 url: href,
65 auth: new Headers(init?.headers).get('authorization'),
66 })
67 if (href === MISTRAL_DEPRECATIONS_URL) {
68 return Promise.resolve(new Response(MODELS_PAGE))
69 }
70 // Docs stay off the network. A live pricing table plus one page
71 // per slug blows the 5s test limit once missing ids pull markdown.
72 if (!href.startsWith('https://api.mistral.ai/')) {
73 return Promise.resolve(new Response('not found', { status: 404 }))
74 }
75 return Promise.resolve(
76 new Response(
77 JSON.stringify({
78 object: 'list',
79 data: [
80 { id: 'mistral-small-latest', created: 1_700_000_000 },
81 { id: 'mistral-embed' },
82 ],
83 }),
84 ),
85 )
86 }) as typeof fetch
87 try {
88 const { models, skipped, deprecations } = await provider.listModels({
89 MISTRAL_API_KEY: 'mistral-test',
90 })
91 expect(skipped).toBeUndefined()
92 expect(
93 deprecations?.find((entry) => entry.rawId === 'pixtral-12b-2409')
94 ?.replacedBy,
95 ).toEqual(['ministral-14b-2512'])
96 expect(calls[0]?.url).toBe('https://api.mistral.ai/v1/models')
97 expect(calls[0]?.auth).toBe('Bearer mistral-test')
98 expect(
99 models.map(
100 ({
101 pricing: _pricing,
102 factSources: _sources,
103 reasoning: _reasoning,
104 modalities: _modalities,
105 serverTools: _tools,
106 maxOutput: _maxOutput,
107 requestMap: _requestMap,
108 absent: _absent,
109 ...rest
110 }) => rest,
111 ),
112 ).toEqual([
113 {
114 rawId: 'mistral-small-latest',
115 releasedAt: 1_700_000_000,
116 activity: null,
117 },
118 { rawId: 'mistral-embed', releasedAt: null, activity: 'embeddings' },
119 ])
120 } finally {
121 globalThis.fetch = original
122 }
123 })
124})
125​
126describe('mistral listModels modalities', () => {
127 it('puts the modalities a model page states on the rows it names', async () => {
128 const pages: Record<string, string> = {
129 'https://api.mistral.ai/v1/models': JSON.stringify({
130 data: [
131 {
132 id: 'mistral-small-latest',
133 capabilities: { completion_chat: true },
134 aliases: ['mistral-vibe-cli-fast'],
135 },
136 {
137 id: 'mistral-vibe-cli-fast',
138 capabilities: { completion_chat: true },
139 aliases: ['mistral-small-latest'],
140 },
141 { id: 'mistral-unpriced', capabilities: { completion_chat: true } },
142 ],
143 }),
144 'https://docs.mistral.ai/inference/pricing': `<h2>Flagship models</h2>
145<p>Prices /M Tokens</p>
146<table>
147<tr><td><a href="/models/mistral-small-4-0-26-03">Small</a></td><td>$0.1</td><td>—</td><td>$0.3</td></tr>
148</table>`,
149 'https://docs.mistral.ai/resources/changelogs': '',
150 [MISTRAL_WEBSEARCH_URL]: MISTRAL_WEBSEARCH_GUIDE,
151 'https://docs.mistral.ai/models/mistral-small-4-0-26-03':
152 mistralModelPage(
153 ['mistral-small-2603', 'mistral-small-latest'],
154 [
155 [
156 tip('Text input'),
157 tip('Image input'),
158 tip('Reasoning output'),
159 tip('Text output'),
160 ],
161 ],
162 ),
163 [MISTRAL_REASONING_URL]:
164 '- `mistral-small-latest`: Supports adjustable reasoning via the `reasoning_effort` parameter.',
165 'https://docs.mistral.ai/models':
166 '<a href="/models/not-a-listed-id">x</a>',
167 'https://docs.mistral.ai/models.md':
168 '| [Nope](/models/not-a-listed-id) | `not-a-listed-id` | GA |',
169 'https://docs.mistral.ai/openapi.yaml': `components:
170 schemas:
171 ChatCompletionRequest:
172 additionalProperties: false
173 properties:
174 max_tokens: { type: integer }
175 reasoning_effort: { type: string }
176 messages:
177 items:
178 discriminator:
179 propertyName: role
180 mapping:
181 system: '#/components/schemas/SystemMessage'
182 user: '#/components/schemas/UserMessage'
183 assistant: '#/components/schemas/AssistantMessage'
184 tool: '#/components/schemas/ToolMessage'
185`,
186 }
187 const original = globalThis.fetch
188 globalThis.fetch = ((url: string) => {
189 const body = pages[String(url)]
190 return Promise.resolve(
191 body === undefined
192 ? new Response('not found', { status: 404 })
193 : new Response(body),
194 )
195 }) as typeof fetch
196 try {
197 const { models } = await provider.listModels({ MISTRAL_API_KEY: 'k' })
198 const [small, vibe, unpriced] = models
199 expect(small?.modalities).toEqual({
200 input: ['text', 'image'],
201 output: ['text'],
202 })
203 expect(small?.factSources?.modalities).toMatchObject({
204 derivation: 'docs-derived',
205 sourceUrl: 'https://docs.mistral.ai/models/mistral-small-4-0-26-03',
206 path: 'modalities',
207 })
208 expect(small?.pricing).toBeTruthy()
209 expect(small?.requestMap).toMatchObject({
210 maxTokensField: 'max_tokens',
211 developerRole: false,
212 reasoningEffort: true,
213 thinking: { on: { reasoning_effort: 'high' }, off: null, levels: null },
214 })
215 expect(small?.factSources?.requestMap).toMatchObject({
216 derivation: 'docs-derived',
217 sourceUrl: 'https://docs.mistral.ai/openapi.yaml',
218 })
219 // The page names only small-latest. The listing says vibe is that model.
220 expect(vibe?.modalities).toEqual(small?.modalities)
221 expect(vibe?.pricing).toEqual(small?.pricing)
222 expect(vibe?.factSources?.modalities?.sourceUrl).toBe(
223 'https://docs.mistral.ai/models/mistral-small-4-0-26-03',
224 )
225 // No page names this id: unknown, not a guess, and not a cleared price.
226 expect(unpriced?.modalities).toBeUndefined()
227 expect(unpriced?.factSources?.modalities).toBeUndefined()
228 expect(unpriced?.absent).toBeUndefined()
229 } finally {
230 globalThis.fetch = original
231 }
232 })
233})
234​
235describe('mistral listModels docs failures', () => {
236 it('keeps stored facts and reports the pages when the docs 404', async () => {
237 const original = globalThis.fetch
238 globalThis.fetch = ((url: string) => {
239 const href = String(url)
240 if (href === 'https://api.mistral.ai/v1/models') {
241 return Promise.resolve(
242 new Response(
243 JSON.stringify({
244 data: [
245 {
246 id: 'mistral-small-latest',
247 capabilities: { completion_chat: true },
248 },
249 ],
250 }),
251 ),
252 )
253 }
254 if (href === 'https://docs.mistral.ai/openapi.yaml') {
255 return Promise.resolve(
256 new Response(`components:
257 schemas:
258 ChatCompletionRequest:
259 properties:
260 max_tokens: { type: integer }
261`),
262 )
263 }
264 return Promise.resolve(new Response('not found', { status: 404 }))
265 }) as typeof fetch
266 try {
267 const { models, docsFailures } = await provider.listModels({
268 MISTRAL_API_KEY: 'k',
269 })
270 expect(models.map((model) => model.rawId)).toEqual([
271 'mistral-small-latest',
272 ])
273 expect(models[0]?.absent).toMatchObject({
274 pricing: 'unavailable',
275 serverTools: 'unavailable',
276 modalities: 'unavailable',
277 maxOutput: 'unavailable',
278 reasoning: 'unavailable',
279 requestMap: 'unavailable',
280 })
281 expect(models[0]?.requestMap).toBeUndefined()
282 expect(docsFailures?.first.map((failure) => failure.source)).toEqual(
283 expect.arrayContaining([
284 'https://docs.mistral.ai/inference/pricing',
285 MISTRAL_REASONING_URL,
286 ]),
287 )
288 } finally {
289 globalThis.fetch = original
290 }
291 })
292})
293​
294describe('mistral fetchSpec', () => {
295 it('loads the public OpenAPI document without a key', async () => {
296 const fixture = JSON.stringify({
297 openapi: '3.1.0',
298 info: { title: 'Mistral AI API', version: '1.0.0' },
299 paths: {
300 '/v1/chat/completions': { post: { summary: 'Chat Completion' } },
301 },
302 })
303 const original = globalThis.fetch
304 const urls: Array<string> = []
305 globalThis.fetch = ((url: string) => {
306 urls.push(String(url))
307 return Promise.resolve(new Response(fixture))
308 }) as typeof fetch
309 try {
310 const fetched = await provider.fetchSpec({})
311 expect(urls).toEqual(['https://docs.mistral.ai/openapi.yaml'])
312 expect(fetched.outputStrategy).toBe('post-200')
313 expect(fetched.specs).toHaveLength(1)
314 expect(fetched.specs[0]?.info?.title).toBe('Mistral AI API')
315 expect(fetched.sources[0]?.url).toBe(
316 'https://docs.mistral.ai/openapi.yaml',
317 )
318 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
319 } finally {
320 globalThis.fetch = original
321 }
322 })
323})
324​
325describe('mistral provider metadata', () => {
326 it('exports the seed fields required for auto-registration', () => {
327 expect(provider.id).toBe('mistral')
328 expect(provider.displayName).toBe('Mistral')
329 expect(provider.authEnvVar).toBe('MISTRAL_API_KEY')
330 expect(provider.defaultDerivation).toBe('upstream-spec')
331 expect(provider.specSourceUrl).toBe('https://docs.mistral.ai/openapi.yaml')
332 expect(provider.modelsEndpoint).toBe('https://api.mistral.ai/v1/models')
333 })
334})