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} from '../mistral-pricing.ts'
22import {
23 MISTRAL_OPENAPI_URL,
24 mistralChatWire,
25 mistralRequestMap,
26} from '../mistral-request.ts'
27import {
28 MISTRAL_REASONING_URL,
29 listsReasoning,
30 mistralModelReasoning,
31 overlayModelFacts,
32} from '../reasoning-config.ts'
33import { fetchOpenApi } from '../types.ts'
34import { bearerConnect } from '../connect.ts'
35import type {
36 ListModelsResult,
37 ModelInfo,
38 ProviderConfig,
39 ProviderSecrets,
40 SpecFetchResult,
41} from '../types.ts'
42
43const MISTRAL_MODELS_URL = 'https://api.mistral.ai/v1/models'
44
45/**
46 * Generation surface only. Chat/fim/agents-completions are chat;
47 * classifiers that are not moderation, OCR, conversations CRUD, files,
48 * fine-tune, batch, and admin classify to null.
49 */
50function classify(path: string): Activity | null {
51 const bare = path.includes('#') ? path.slice(0, path.indexOf('#')) : path
52 if (
53 bare === '/v1/chat/completions' ||
54 bare === '/v1/fim/completions' ||
55 bare === '/v1/agents/completions'
56 ) {
57 return 'chat'
58 }
59 if (bare === '/v1/embeddings') return 'embeddings'
60 if (bare === '/v1/moderations' || bare === '/v1/chat/moderations') {
61 return 'moderation'
62 }
63 if (bare === '/v1/audio/speech' || bare === '/v1/audio/transcriptions') {
64 return 'audio'
65 }
66 return null
67}
68
69/**
70 * A page we read that names no price clears a stored card. Mutual aliases
71 * of that page clear too, unless one of them has a price.
72 */
73function clearUnpriced(
74 models: Array<ModelInfo>,
75 seen: ReadonlySet<string>,
76 aliases: ReadonlyMap<string, ReadonlyArray<string>>,
77): void {
78 const byId = new Map(models.map((model) => [model.rawId, model]))
79 const clear = (model: ModelInfo | undefined) => {
80 if (!model || model.pricing != null) return
81 model.absent = { ...model.absent, pricing: 'cleared' }
82 }
83 for (const model of models) {
84 if (seen.has(model.rawId)) clear(model)
85 }
86 for (const [id, names] of aliases) {
87 const clique = [id, ...names].filter(
88 (other) =>
89 byId.has(other) && (other === id || aliases.get(other)?.includes(id)),
90 )
91 if (!clique.some((other) => seen.has(other))) continue
92 if (clique.some((other) => byId.get(other)?.pricing != null)) continue
93 for (const other of clique) clear(byId.get(other))
94 }
95}
96
97async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
98 const { spec, hash } = await fetchOpenApi(MISTRAL_OPENAPI_URL)
99 return {
100 specs: [spec],
101 sources: [{ url: MISTRAL_OPENAPI_URL, hash }],
102 outputStrategy: 'post-200',
103 }
104}
105
106export const provider: ProviderConfig = {
107 id: 'mistral',
108 displayName: 'Mistral',
109 authEnvVar: 'MISTRAL_API_KEY',
110 specSourceUrl: MISTRAL_OPENAPI_URL,
111 modelsEndpoint: MISTRAL_MODELS_URL,
112 defaultDerivation: 'upstream-spec',
113 connect: bearerConnect('https://api.mistral.ai'),
114 fetchSpec,
115 listModels: async (env, kv): Promise<ListModelsResult> => {
116 const aliases = new Map<string, Array<string>>()
117 const listed = await listOpenAiCompatibleModels({
118 providerId: 'mistral',
119 url: MISTRAL_MODELS_URL,
120 env,
121 envVar: 'MISTRAL_API_KEY',
122 activity: mistralModelActivity,
123 extend: (row) => {
124 const names = row.aliases?.filter(
125 (id) => typeof id === 'string' && id.length > 0,
126 )
127 if (names && names.length > 0) aliases.set(row.id, names)
128 return Promise.resolve({})
129 },
130 })
131 if (listed.models.length === 0) return listed
132 const chat = listed.models.some((model) => model.activity === 'chat')
133 const docs = docsRun()
134 const deprecations = await loadDeprecations(
135 docs,
136 kv,
137 MISTRAL_DEPRECATIONS_URL,
138 parseMistralDeprecations,
139 )
140 // The pricing load reads the pricing table, changelog, models index,
141 // model pages and web search guide; a failing docs page keeps the
142 // stored facts instead of failing the poll.
143 const [pricing, reasoning, wire] = await Promise.all([
144 tryDocs(docs, MISTRAL_PRICING_URL, (cached) =>
145 mistralModelPricing(
146 kv,
147 listed.models.map((model) => model.rawId),
148 cached,
149 ),
150 ),
151 tryDocs(docs, MISTRAL_REASONING_URL, (cached) =>
152 mistralModelReasoning(kv, cached),
153 ),
154 chat ? mistralChatWire(kv) : Promise.resolve(null),
155 ])
156 const models = listed.models.map((model) =>
157 overlayModelFacts(
158 model,
159 pricing
160 ? pricing(model.rawId)
161 : unavailable('pricing', 'serverTools', 'modalities', 'maxOutput'),
162 reasoning
163 ? reasoning(model.rawId, listsReasoning(model.capabilities))
164 : unavailable('reasoning'),
165 ),
166 )
167 copyMistralAliasFacts(models, aliases)
168 if (wire) {
169 for (const model of models) {
170 if (model.activity !== 'chat') continue
171 // The thinking request comes from the reasoning facts; keep the
172 // stored map whole rather than write one built without them.
173 if (!reasoning) {
174 model.absent = { ...model.absent, requestMap: 'unavailable' }
175 continue
176 }
177 model.requestMap = mistralRequestMap(wire, model.reasoning)
178 model.factSources = {
179 ...model.factSources,
180 requestMap: {
181 derivation: 'docs-derived',
182 sourceUrl: MISTRAL_OPENAPI_URL,
183 sourceHash: wire.hash,
184 path: '/components/schemas/ChatCompletionRequest',
185 },
186 }
187 }
188 }
189 if (pricing) clearUnpriced(models, pricing.seen, aliases)
190 return {
191 ...listed,
192 models,
193 ...(deprecations ? { deprecations } : {}),
194 docsFailures: docsReport(docs),
195 }
196 },
197 classify,
198 generationEndpointId: ({ rawId, activity }) =>
199 mistralGenerationEndpointId(rawId, activity),
200}