Open History to see the last commit
1/**
2 * Mistral — public OpenAPI 3.1 at docs.mistral.ai/openapi.yaml.
3 * Models listing requires MISTRAL_API_KEY.
4 */
5import type { Activity } from '#/db/schema.ts'
6import { listOpenAiCompatibleModels } from '../openai-compat.ts'
7import {
8 MISTRAL_DEPRECATIONS_URL,
9 loadDeprecations,
10 parseMistralDeprecations,
11} from '../deprecations.ts'
12import { docsReport, docsRun, tryDocs, unavailable } from '../model-facts.ts'
13import {
14 mistralGenerationEndpointId,
15 mistralModelActivity,
16} from '../model-meta.ts'
17import {
18 MISTRAL_PRICING_URL,
19 copyMistralAliasFacts,
20 mistralModelPricing,
21 parseMistralMakers,
22} from '../mistral-pricing.ts'
23import {
24 MISTRAL_OPENAPI_URL,
25 mistralChatWire,
26 mistralRequestMap,
27} from '../mistral-request.ts'
28import {
29 MISTRAL_REASONING_URL,
30 listsReasoning,
31 mistralModelReasoning,
32 overlayModelFacts,
33} from '../reasoning-config.ts'
34import { fetchOpenApi, fetchText, sha256Text } from '../types.ts'
35import { bearerConnect } from '../connect.ts'
36import type {
37 FactSource,
38 ListModelsResult,
39 ModelInfo,
40 ProviderConfig,
41 ProviderSecrets,
42 SpecFetchResult,
43} from '../types.ts'
44import type { OpenAiCompatModelRow } from '../openai-compat.ts'
45
46const MISTRAL_MODELS_URL = 'https://api.mistral.ai/v1/models'
47
48/**
49 * Generation surface only. Chat/fim/agents-completions are chat;
50 * classifiers that are not moderation, OCR, conversations CRUD, files,
51 * fine-tune, batch, and admin classify to null.
52 */
53function classify(path: string): Activity | null {
54 const bare = path.includes('#') ? path.slice(0, path.indexOf('#')) : path
55 if (
56 bare === '/v1/chat/completions' ||
57 bare === '/v1/fim/completions' ||
58 bare === '/v1/agents/completions'
59 ) {
60 return 'chat'
61 }
62 if (bare === '/v1/embeddings') return 'embeddings'
63 if (bare === '/v1/moderations' || bare === '/v1/chat/moderations') {
64 return 'moderation'
65 }
66 if (bare === '/v1/audio/speech' || bare === '/v1/audio/transcriptions') {
67 return 'audio'
68 }
69 return null
70}
71
72/**
73 * A page we read that names no price clears a stored card. Mutual aliases
74 * of that page clear too, unless one of them has a price.
75 */
76function clearUnpriced(
77 models: Array<ModelInfo>,
78 seen: ReadonlySet<string>,
79 aliases: ReadonlyMap<string, ReadonlyArray<string>>,
80): void {
81 const byId = new Map(models.map((model) => [model.rawId, model]))
82 const clear = (model: ModelInfo | undefined) => {
83 if (!model || model.pricing != null) return
84 model.absent = { ...model.absent, pricing: 'cleared' }
85 }
86 for (const model of models) {
87 if (seen.has(model.rawId)) clear(model)
88 }
89 for (const [id, names] of aliases) {
90 const clique = [id, ...names].filter(
91 (other) =>
92 byId.has(other) && (other === id || aliases.get(other)?.includes(id)),
93 )
94 if (!clique.some((other) => seen.has(other))) continue
95 if (clique.some((other) => byId.get(other)?.pricing != null)) continue
96 for (const other of clique) clear(byId.get(other))
97 }
98}
99
100/**
101 * Alias links a listing row states (issue #709). Every member of an alias
102 * group lists the others in `aliases`: membership is stated. Which id the
103 * others resolve to is not (the listing's `name` is an undescribed display
104 * string), so every grouped row says its target is unstated.
105 */
106export function mistralAliasFacts(
107 row: Pick<OpenAiCompatModelRow, 'id' | 'aliases'>,
108): Partial<ModelInfo> {
109 const aliases = (row.aliases ?? []).filter(
110 (id) => typeof id === 'string' && id.length > 0 && id !== row.id,
111 )
112 if (aliases.length === 0) return {}
113 const source = (path: string): FactSource => ({
114 derivation: 'listing',
115 sourceUrl: MISTRAL_MODELS_URL,
116 path,
117 })
118 return {
119 aliases,
120 aliasOf: null,
121 factSources: { aliases: source('aliases'), aliasOf: source('unstated') },
122 }
123}
124
125/** The models overview, cached apart from its deprecations parse. */
126const MISTRAL_MAKERS_KEY = `${MISTRAL_DEPRECATIONS_URL}#makers`
127
128/**
129 * The maker an overview Summary names for this id. `unstated` only when
130 * the overview's API name column lists the id, or a mutual listing alias
131 * of it, and no Summary in that group names a maker (Mistral's own
132 * models). An alias of a third-party row is left for
133 * `copyMistralAliasFacts`. An id the overview never lists gets nothing:
134 * absence from the table is not a statement.
135 */
136export function mistralMakerFacts(
137 rawId: string,
138 makers: { byId: Record<string, string>; named: Array<string>; hash: string },
139 mutualAliases: ReadonlyArray<string> = [],
140): Partial<ModelInfo> {
141 const maker = makers.byId[rawId] ?? null
142 if (maker === null && !makers.named.includes(rawId)) {
143 const listed = mutualAliases.filter((id) => makers.named.includes(id))
144 if (listed.length === 0 || listed.some((id) => id in makers.byId)) {
145 return {}
146 }
147 }
148 return {
149 maker,
150 factSources: {
151 maker: {
152 derivation: 'docs-derived',
153 sourceUrl: MISTRAL_DEPRECATIONS_URL,
154 sourceHash: makers.hash,
155 path: maker === null ? 'unstated' : 'Summary',
156 },
157 },
158 }
159}
160
161async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
162 const { spec, hash } = await fetchOpenApi(MISTRAL_OPENAPI_URL)
163 return {
164 specs: [spec],
165 sources: [{ url: MISTRAL_OPENAPI_URL, hash }],
166 outputStrategy: 'post-200',
167 }
168}
169
170export const provider: ProviderConfig = {
171 id: 'mistral',
172 displayName: 'Mistral',
173 authEnvVar: 'MISTRAL_API_KEY',
174 specSourceUrl: MISTRAL_OPENAPI_URL,
175 modelsEndpoint: MISTRAL_MODELS_URL,
176 defaultDerivation: 'upstream-spec',
177 connect: bearerConnect('https://api.mistral.ai'),
178 fetchSpec,
179 listModels: async (env, kv): Promise<ListModelsResult> => {
180 const aliases = new Map<string, Array<string>>()
181 const listed = await listOpenAiCompatibleModels({
182 providerId: 'mistral',
183 url: MISTRAL_MODELS_URL,
184 env,
185 envVar: 'MISTRAL_API_KEY',
186 activity: mistralModelActivity,
187 extend: (row) => {
188 const names = row.aliases?.filter(
189 (id) => typeof id === 'string' && id.length > 0,
190 )
191 if (names && names.length > 0) aliases.set(row.id, names)
192 // `created` is the request time on every row, not a release date
193 // (#708). The date comes from the model page's markdown twin.
194 return Promise.resolve({ releasedAt: null, ...mistralAliasFacts(row) })
195 },
196 })
197 if (listed.models.length === 0) return listed
198 const chat = listed.models.some((model) => model.activity === 'chat')
199 const docs = docsRun()
200 const deprecations = await loadDeprecations(
201 docs,
202 kv,
203 MISTRAL_DEPRECATIONS_URL,
204 parseMistralDeprecations,
205 )
206 // The pricing load reads the pricing table, changelog, models index,
207 // model pages and web search guide; a failing docs page keeps the
208 // stored facts instead of failing the poll.
209 const [pricing, reasoning, wire, makers] = await Promise.all([
210 tryDocs(docs, MISTRAL_PRICING_URL, (cached) =>
211 mistralModelPricing(
212 kv,
213 listed.models.map((model) => model.rawId),
214 cached,
215 ),
216 ),
217 tryDocs(docs, MISTRAL_REASONING_URL, (cached) =>
218 mistralModelReasoning(kv, cached),
219 ),
220 chat ? mistralChatWire(kv) : Promise.resolve(null),
221 tryDocs(docs, MISTRAL_MAKERS_KEY, (cached) =>
222 cached(kv, MISTRAL_MAKERS_KEY, async () => {
223 const markdown = await fetchText(MISTRAL_DEPRECATIONS_URL)
224 const { makers: byId, named } = parseMistralMakers(markdown)
225 return {
226 byId: Object.fromEntries(byId),
227 named: [...named],
228 hash: await sha256Text(markdown),
229 }
230 }),
231 ),
232 ])
233 const models = listed.models.map((model) =>
234 overlayModelFacts(
235 model,
236 pricing
237 ? pricing(model.rawId)
238 : unavailable('pricing', 'serverTools', 'modalities', 'maxOutput'),
239 reasoning
240 ? reasoning(model.rawId, listsReasoning(model.capabilities))
241 : unavailable('reasoning'),
242 makers
243 ? mistralMakerFacts(
244 model.rawId,
245 makers,
246 (aliases.get(model.rawId) ?? []).filter((id) =>
247 aliases.get(id)?.includes(model.rawId),
248 ),
249 )
250 : unavailable('maker'),
251 ),
252 )
253 copyMistralAliasFacts(models, aliases)
254 if (wire) {
255 for (const model of models) {
256 if (model.activity !== 'chat') continue
257 // The thinking request comes from the reasoning facts; keep the
258 // stored map whole rather than write one built without them.
259 if (!reasoning) {
260 model.absent = { ...model.absent, requestMap: 'unavailable' }
261 continue
262 }
263 model.requestMap = mistralRequestMap(wire, model.reasoning)
264 model.factSources = {
265 ...model.factSources,
266 requestMap: {
267 derivation: 'docs-derived',
268 sourceUrl: MISTRAL_OPENAPI_URL,
269 sourceHash: wire.hash,
270 path: '/components/schemas/ChatCompletionRequest',
271 },
272 }
273 }
274 }
275 if (pricing) clearUnpriced(models, pricing.seen, aliases)
276 return {
277 ...listed,
278 models,
279 ...(deprecations ? { deprecations } : {}),
280 docsFailures: docsReport(docs),
281 }
282 },
283 classify,
284 generationEndpointId: ({ rawId, activity }) =>
285 mistralGenerationEndpointId(rawId, activity),
286}