Open History to see the last commit
1/**
2 * Chat request map from Mistral's OpenAPI `ChatCompletionRequest`.
3 * One body for every chat model. Thinking on/off is filled only for a model
4 * whose own reasoning object names an effort control.
5 */
6import { parse } from 'yaml'
7
8import { cachedDocs } from './model-facts.ts'
9import { SHARED_EFFORT_LEVELS } from './request-map.ts'
10import type {
11 ChatRequestMap,
12 EffortLevelMap,
13 ThinkingRequest,
14} from './request-map.ts'
15import { fetchText, sha256Text } from './types.ts'
16import type { ModelReasoning } from './types.ts'
17
18export const MISTRAL_OPENAPI_URL = 'https://docs.mistral.ai/openapi.yaml'
19
20export interface MistralChatWire {
21 maxTokensField: 'max_completion_tokens' | 'max_tokens' | null
22 developerRole: boolean | null
23 reasoningEffort: boolean | null
24 hash: string
25}
26
27function isRecord(value: unknown): value is Record<string, unknown> {
28 return typeof value === 'object' && value !== null && !Array.isArray(value)
29}
30
31function roleNames(messages: unknown): Array<string> {
32 const names: Array<string> = []
33 const visit = (node: unknown) => {
34 if (Array.isArray(node)) {
35 node.forEach(visit)
36 return
37 }
38 if (!isRecord(node)) return
39 const discriminator = node.discriminator
40 if (isRecord(discriminator) && discriminator.propertyName === 'role') {
41 const mapping = discriminator.mapping
42 if (isRecord(mapping)) names.push(...Object.keys(mapping))
43 }
44 for (const value of Object.values(node)) visit(value)
45 }
46 visit(messages)
47 return names
48}
49
50/** Fields the shared chat body publishes. Throws when that schema is absent. */
51export function parseMistralChatWire(
52 text: string,
53): Omit<MistralChatWire, 'hash'> {
54 const spec = parse(text) as unknown
55 const schemas =
56 isRecord(spec) && isRecord(spec.components)
57 ? spec.components.schemas
58 : undefined
59 const chat =
60 isRecord(schemas) && isRecord(schemas.ChatCompletionRequest)
61 ? schemas.ChatCompletionRequest
62 : null
63 const properties = chat && isRecord(chat.properties) ? chat.properties : null
64 if (!properties) {
65 throw new Error('mistral openapi: ChatCompletionRequest missing')
66 }
67 const has = (name: string) =>
68 Object.prototype.hasOwnProperty.call(properties, name)
69 let maxTokensField: MistralChatWire['maxTokensField'] = null
70 if (has('max_tokens') && !has('max_completion_tokens')) {
71 maxTokensField = 'max_tokens'
72 } else if (has('max_completion_tokens') && !has('max_tokens')) {
73 maxTokensField = 'max_completion_tokens'
74 }
75 const roles = roleNames(properties.messages)
76 const developerRole = roles.length === 0 ? null : roles.includes('developer')
77 const reasoningEffort = has('reasoning_effort')
78 ? true
79 : chat?.additionalProperties === false
80 ? false
81 : null
82 return { maxTokensField, developerRole, reasoningEffort }
83}
84
85export async function mistralChatWire(
86 kv?: KVNamespace,
87): Promise<MistralChatWire> {
88 return cachedDocs(kv, MISTRAL_OPENAPI_URL, async () => {
89 const text = await fetchText(MISTRAL_OPENAPI_URL)
90 return { ...parseMistralChatWire(text), hash: await sha256Text(text) }
91 })
92}
93
94function effortLevels(efforts: Array<string>): EffortLevelMap {
95 const levels = Object.fromEntries(
96 SHARED_EFFORT_LEVELS.map((level) => [level, null]),
97 ) as EffortLevelMap
98 for (const effort of efforts) {
99 if (effort === 'none') levels.off = 'none'
100 else if ((SHARED_EFFORT_LEVELS as ReadonlyArray<string>).includes(effort)) {
101 levels[effort as keyof EffortLevelMap] = effort
102 }
103 }
104 return levels
105}
106
107/**
108 * `on` uses `high` when this model allows it. `off` is `none` when the
109 * model's own list includes it, or when the guide says `none` omits the
110 * chunk and publishes no list. Levels come only from that list.
111 */
112export function mistralThinking(
113 reasoning: ModelReasoning | null | undefined,
114): ThinkingRequest | null {
115 if (!reasoning || reasoning.mode !== 'effort') return null
116 const efforts = reasoning.efforts
117 const allowsHigh = !efforts || efforts.includes('high')
118 if (!allowsHigh) return null
119 const off = efforts
120 ? efforts.includes('none')
121 ? { reasoning_effort: 'none' }
122 : null
123 : reasoning.mandatory === false
124 ? { reasoning_effort: 'none' }
125 : null
126 return {
127 on: { reasoning_effort: 'high' },
128 off,
129 levels: efforts ? effortLevels(efforts) : null,
130 }
131}
132
133export function mistralRequestMap(
134 wire: Omit<MistralChatWire, 'hash'>,
135 reasoning: ModelReasoning | null | undefined,
136): ChatRequestMap {
137 return {
138 thinking: mistralThinking(reasoning),
139 maxTokensField: wire.maxTokensField,
140 developerRole: wire.developerRole,
141 replayReasoningContent: null,
142 store: null,
143 strictTools: null,
144 sessionAffinity: null,
145 cacheControl: null,
146 toolStream: null,
147 reasoningEffort: wire.reasoningEffort,
148 }
149}