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

mistral-request.ts

173 lines5.4 KB

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 /**
25 * False when the assistant message schema omits `reasoning_content` and
26 * sets `additionalProperties: false`. Null when that schema is absent or
27 * open.
28 */
29 replayReasoningContent: boolean | null
30 hash: string
32​
33function isRecord(value: unknown): value is Record<string, unknown> {
34 return typeof value === 'object' && value !== null && !Array.isArray(value)
36​
37function roleNames(messages: unknown): Array<string> {
38 const names: Array<string> = []
39 const visit = (node: unknown) => {
40 if (Array.isArray(node)) {
41 node.forEach(visit)
42 return
43 }
44 if (!isRecord(node)) return
45 const discriminator = node.discriminator
46 if (isRecord(discriminator) && discriminator.propertyName === 'role') {
47 const mapping = discriminator.mapping
48 if (isRecord(mapping)) names.push(...Object.keys(mapping))
49 }
50 for (const value of Object.values(node)) visit(value)
51 }
52 visit(messages)
53 return names
55​
56/** Fields the shared chat body publishes. Throws when that schema is absent. */
57export function parseMistralChatWire(
58 text: string,
59): Omit<MistralChatWire, 'hash'> {
60 const spec = parse(text) as unknown
61 const schemas =
62 isRecord(spec) && isRecord(spec.components)
63 ? spec.components.schemas
64 : undefined
65 const chat =
66 isRecord(schemas) && isRecord(schemas.ChatCompletionRequest)
67 ? schemas.ChatCompletionRequest
68 : null
69 const properties = chat && isRecord(chat.properties) ? chat.properties : null
70 if (!properties) {
71 throw new Error('mistral openapi: ChatCompletionRequest missing')
72 }
73 const has = (name: string) =>
74 Object.prototype.hasOwnProperty.call(properties, name)
75 let maxTokensField: MistralChatWire['maxTokensField'] = null
76 if (has('max_tokens') && !has('max_completion_tokens')) {
77 maxTokensField = 'max_tokens'
78 } else if (has('max_completion_tokens') && !has('max_tokens')) {
79 maxTokensField = 'max_completion_tokens'
80 }
81 const roles = roleNames(properties.messages)
82 const developerRole = roles.length === 0 ? null : roles.includes('developer')
83 const reasoningEffort = has('reasoning_effort')
84 ? true
85 : chat?.additionalProperties === false
86 ? false
87 : null
88 const assistant = isRecord(schemas) ? schemas.AssistantMessage : undefined
89 const assistantProperties =
90 isRecord(assistant) && isRecord(assistant.properties)
91 ? assistant.properties
92 : null
93 const closedAssistant =
94 isRecord(assistant) && assistant.additionalProperties === false
95 const replayReasoningContent =
96 assistantProperties && closedAssistant
97 ? 'reasoning_content' in assistantProperties
98 ? null
99 : false
100 : null
101 return {
102 maxTokensField,
103 developerRole,
104 reasoningEffort,
105 replayReasoningContent,
106 }
108​
109export async function mistralChatWire(
110 kv?: KVNamespace,
111): Promise<MistralChatWire> {
112 return cachedDocs(kv, MISTRAL_OPENAPI_URL, async () => {
113 const text = await fetchText(MISTRAL_OPENAPI_URL)
114 return { ...parseMistralChatWire(text), hash: await sha256Text(text) }
115 })
117​
118function effortLevels(efforts: Array<string>): EffortLevelMap {
119 const levels = Object.fromEntries(
120 SHARED_EFFORT_LEVELS.map((level) => [level, null]),
121 ) as EffortLevelMap
122 for (const effort of efforts) {
123 if (effort === 'none') levels.off = 'none'
124 else if ((SHARED_EFFORT_LEVELS as ReadonlyArray<string>).includes(effort)) {
125 levels[effort as keyof EffortLevelMap] = effort
126 }
127 }
128 return levels
130​
131/**
132 * `on` uses `high` when this model allows it. `off` is `none` when the
133 * model's own list includes it, or when the guide says `none` omits the
134 * chunk and publishes no list. Levels come only from that list.
135 */
136export function mistralThinking(
137 reasoning: ModelReasoning | null | undefined,
138): ThinkingRequest | null {
139 if (!reasoning || reasoning.mode !== 'effort') return null
140 const efforts = reasoning.efforts
141 const allowsHigh = !efforts || efforts.includes('high')
142 if (!allowsHigh) return null
143 const off = efforts
144 ? efforts.includes('none')
145 ? { reasoning_effort: 'none' }
146 : null
147 : reasoning.mandatory === false
148 ? { reasoning_effort: 'none' }
149 : null
150 return {
151 on: { reasoning_effort: 'high' },
152 off,
153 levels: efforts ? effortLevels(efforts) : null,
154 }
156​
157export function mistralRequestMap(
158 wire: Omit<MistralChatWire, 'hash'>,
159 reasoning: ModelReasoning | null | undefined,
160): ChatRequestMap {
161 return {
162 thinking: mistralThinking(reasoning),
163 maxTokensField: wire.maxTokensField,
164 developerRole: wire.developerRole,
165 replayReasoningContent: wire.replayReasoningContent,
166 store: null,
167 strictTools: null,
168 sessionAffinity: null,
169 cacheControl: null,
170 toolStream: null,
171 reasoningEffort: wire.reasoningEffort,
172 }