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

mistral.test.ts

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