Open History to see the last commit
1/**
2 * Z.AI — model ids are the enums in docs.z.ai/openapi.json.
3 * Token prices come from the pricing page when a row lowercases onto one
4 * of those ids. USD per 1M tokens. A row that does not match an enum is ignored.
5 *
6 * The same OpenAPI document gives each id its route (the path whose request
7 * body lists it) and, for chat ids, the output cap (`max_tokens`
8 * description) and input modalities (user message content parts). Context
9 * windows come from the overview page's model tables, reasoning efforts
10 * from the Deep Thinking page. A model with no effort list is a toggle:
11 * the request's `thinking.type` switch, whose description names the models
12 * that cannot turn it off. Each parser throws on a shape it does not know
13 * rather than guess.
14 *
15 * The chat body is a `oneOf` of a text and a vision request, split by
16 * `model` enum with no discriminator, and several properties say in prose
17 * which models they are "supported by". So capability flags are listed
18 * here per model (`exactCapabilities`), not walked from the merged body.
19 */
20import {
21 applyReplay,
22 loadReplayDoc,
23 parseGlmReplay,
24 ZAI_THINKING_MODE_URL,
25} from '../provider-replay.ts'
26import { compileTokenCard } from '@modelschemas/rate-card'
27
28import type { Activity } from '#/db/schema.ts'
29
30import { walkRequestSchema } from '../fact-sources.ts'
31import { tokenCount } from '../model-facts.ts'
32import { fetchOpenApi, fetchText, sha256Text } from '../types.ts'
33import type {
34 FactSource,
35 ListModelsResult,
36 ModelFactSources,
37 ModelInfo,
38 ModelReasoning,
39 ProviderConfig,
40 ProviderSecrets,
41 SpecFetchResult,
42} from '../types.ts'
43
44export const ZAI_OPENAPI_URL = 'https://docs.z.ai/openapi.json'
45export const ZAI_PRICING_URL = 'https://docs.z.ai/guides/overview/pricing.md'
46export const ZAI_OVERVIEW_URL = 'https://docs.z.ai/guides/overview/overview.md'
47export const ZAI_THINKING_URL =
48 'https://docs.z.ai/guides/capabilities/thinking.md'
49
50const FETCH_TIMEOUT_MS = 30_000
51const MODEL_ID = /^(?:glm|cog)[a-z0-9._-]*$/
52
53/**
54 * How one docs site words the prose these parsers read. Z.AI writes
55 * English. Zhipu's China docs state the same facts in the same shapes in
56 * Chinese (`zhipuai-coding-plan.ts`).
57 */
58export interface GlmWording {
59 /** Provider id that prefixes a parser's error. */
60 label: string
61 /** Header cells of the overview table's model and context columns. */
62 modelColumn: string
63 contextColumn: string
64 /** Sits between a `max_tokens` clause's models and its cap. */
65 supports: RegExp
66 /** The cap, at the start of what follows `supports`. Group 1 is the size. */
67 cap: RegExp
68 /** Ends a list of models that are series, not single ids. */
69 series: RegExp
70 /** List filler between model names, as a pattern source. */
71 filler: string
72 /** A description's "only these models" clause. Group 1 is the model list. */
73 supportedBy: RegExp
74 /** Says the clause names a version floor, not a list. */
75 floor: RegExp
76 /** Filler in a version-floor clause, as a pattern source. */
77 floorFiller: string
78}
79
80export const ZAI_WORDING: GlmWording = {
81 label: 'zai',
82 modelColumn: 'Model',
83 contextColumn: 'Context',
84 supports: /\bsupports\b/,
85 cap: /^\s+(?:a maximum output length of\s+)?(\d+(?:\.\d+)?[KM])\b(?:\s+maximum output\b)?/,
86 series: /\bseries\s*$/,
87 filler: '\\b(?:the|and|series)\\b',
88 supportedBy: /supported by (.+?)(?:\.\s|\.$|$)/is,
89 floor: /\b(?:higher|above)\b/i,
90 floorFiller: '\\b(?:series|and|higher|above|models?|versions?)\\b',
91}
92
93/** One fetched source document. */
94export interface ZaiDoc {
95 url: string
96 text: string
97 hash: string
98}
99
100interface TokenPrice {
101 input: number
102 output: number
103 cache: number | null
104}
105
106/** What the docs say about some models, named one by one or as a series. */
107export interface ModelNames {
108 names: Array<string>
109 /** True when a name also covers its variants (`glm-4.7` → `glm-4.7-flash`). */
110 series: boolean
111}
112
113interface OutputCap extends ModelNames {
114 tokens: number
115}
116
117interface ReasoningRow extends ModelNames {
118 reasoning: ModelReasoning
119}
120
121interface SpecFacts {
122 activity: Activity
123 schemaEndpointId: string
124 maxOutput: number | null
125 modalities: { input: Array<string>; output: Array<string> } | null
126 /** The `reasoning_effort` enum of the request variant that lists the id. */
127 efforts: Array<string>
128 /** The variant's `thinking.type` schema, unread; undefined when it has none. */
129 thinkingType: unknown
130 /** Exact model-bound request variant publishes a normative preserved-history rule. */
131 replayReasoningContent?: FactSource
132 /** Chat only: flag → where the variant's own request states it. */
133 capabilities: Record<string, FactSource> | null
134}
135
136function isRecord(value: unknown): value is Record<string, unknown> {
137 return typeof value === 'object' && value !== null && !Array.isArray(value)
138}
139
140function list(value: unknown): Array<unknown> {
141 return Array.isArray(value) ? value : []
142}
143
144function money(cell: string): number | null {
145 const match = cell.match(/\$([0-9]+(?:\.[0-9]+)?)/)
146 if (!match?.[1]) return null
147 const value = Number(match[1])
148 return Number.isFinite(value) && value > 0 ? value : null
149}
150
151const MODEL_NAME = /(?:auto)?glm-[a-z0-9.-]*[a-z0-9]/gi
152
153export function modelNames(text: string): Array<string> {
154 return (text.match(MODEL_NAME) ?? []).map((name) => name.toLowerCase())
155}
156
157/**
158 * The row that names this id. The longest name wins, and a series name must
159 * end where the version does, so `glm-5.3-flash` is `glm-5.3`, never `glm-5`.
160 */
161export function namedBy<T extends ModelNames>(
162 rawId: string,
163 rows: Array<T>,
164): T | null {
165 let best: T | null = null
166 let bestLength = 0
167 for (const row of rows) {
168 for (const name of row.names) {
169 const hit =
170 rawId === name ||
171 (row.series &&
172 rawId.startsWith(name) &&
173 !/[\d.]/.test(rawId.charAt(name.length)))
174 if (hit && name.length > bestLength) {
175 best = row
176 bestLength = name.length
177 }
178 }
179 }
180 return best
181}
182
183export function zaiModelIds(spec: unknown): Array<string> {
184 const ids = new Set<string>()
185 const walk = (node: unknown) => {
186 if (!isRecord(node)) return
187 if (Array.isArray(node.enum)) {
188 for (const value of node.enum) {
189 if (typeof value === 'string' && MODEL_ID.test(value)) ids.add(value)
190 }
191 }
192 for (const value of Object.values(node)) walk(value)
193 }
194 walk(spec)
195 if (ids.size === 0) throw new Error('zai: OpenAPI has no model enums')
196 return [...ids].sort()
197}
198
199/** Per-1M-token tables. The key is the model cell lowercased. */
200export function parseZaiTokenPrices(markdown: string): Map<string, TokenPrice> {
201 if (!/per 1M tokens/i.test(markdown)) {
202 throw new Error('zai: pricing page has no per-1M-token table')
203 }
204 const prices = new Map<string, TokenPrice>()
205 let inTokenTable = false
206 for (const line of markdown.split('\n')) {
207 if (/per 1M tokens/i.test(line)) {
208 inTokenTable = true
209 continue
210 }
211 if (/^#{1,3} /.test(line)) {
212 inTokenTable = false
213 continue
214 }
215 if (!inTokenTable || !line.startsWith('|')) continue
216 if (/^\|\s*:?-+/.test(line)) continue
217 const cells = line
218 .split('|')
219 .slice(1, -1)
220 .map((cell) => cell.trim())
221 const name = cells[0]
222 if (!name || name === 'Model' || cells.length < 5) continue
223 const input = money(cells[1] ?? '')
224 const output = money(cells[4] ?? '')
225 if (input === null || output === null) continue
226 prices.set(name.toLowerCase(), {
227 input,
228 output,
229 cache: money(cells[2] ?? ''),
230 })
231 }
232 return prices
233}
234
235/**
236 * The `Context` column of the overview page's model tables, keyed by the
237 * model cell lowercased. `/` means the model has no context window. With
238 * `only`, the other rows are not read.
239 */
240export function parseZaiContextWindows(
241 markdown: string,
242 wording: GlmWording = ZAI_WORDING,
243 only?: (name: string) => boolean,
244): Map<string, number> {
245 const windows = new Map<string, number>()
246 let header: Array<string> = []
247 let column = -1
248 for (const raw of markdown.split('\n')) {
249 // The "other models" tables sit indented inside an accordion.
250 const line = raw.trim()
251 if (!line.startsWith('|')) {
252 column = -1
253 continue
254 }
255 const cells = line
256 .split('|')
257 .slice(1, -1)
258 .map((cell) => cell.trim())
259 if (cells.every((cell) => /^:?-+:?$/.test(cell))) {
260 column =
261 header[0] === wording.modelColumn
262 ? header.indexOf(wording.contextColumn)
263 : -1
264 continue
265 }
266 header = cells
267 // The China docs link each model name to its page.
268 const name = cells[0]?.replace(/^\[([^\]]+)\]\(.*\)$/, '$1')
269 const cell = cells[column]
270 if (column < 0 || !name || cell === '/') continue
271 if (only && !only(name.toLowerCase())) continue
272 const tokens = /^\d+(?:\.\d+)?[KM]$/.test(cell ?? '')
273 ? tokenCount(cell)
274 : null
275 if (tokens === null) {
276 throw new Error(
277 `${wording.label}: unreadable context window for ${name}: ${String(cell)}`,
278 )
279 }
280 windows.set(name.toLowerCase(), tokens)
281 }
282 if (windows.size === 0) {
283 throw new Error(`${wording.label}: overview page has no context windows`)
284 }
285 return windows
286}
287
288/** True when `text`, its model names aside, is only list filler. */
289function onlyNames(text: string, filler: string): boolean {
290 const rest = text.replace(MODEL_NAME, ' ')
291 return new RegExp(`^(?:[\\s,.\`]|${filler})*$`, 'i').test(rest)
292}
293
294/**
295 * A `max_tokens` description: "<models> [series] supports <N>K", repeated.
296 * Every model name must sit in a clause of exactly that shape. A clause
297 * with another verb would otherwise be read as part of the next clause's
298 * subject and take its cap, so anything left over throws.
299 */
300export function parseZaiOutputCaps(
301 description: string,
302 wording: GlmWording = ZAI_WORDING,
303): Array<OutputCap> {
304 const [first = '', ...rest] = description.split(wording.supports)
305 if (rest.length === 0) {
306 throw new Error(
307 `${wording.label}: max_tokens description states no output cap`,
308 )
309 }
310 const caps: Array<OutputCap> = []
311 // The opening sentence runs up to the first model name.
312 let subject = first.slice(Math.max(first.search(MODEL_NAME), 0))
313 for (const part of rest) {
314 const cap = part.match(wording.cap)
315 const names = modelNames(subject)
316 const tokens = tokenCount(cap?.[1])
317 if (
318 !cap ||
319 tokens === null ||
320 names.length === 0 ||
321 !onlyNames(subject, wording.filler)
322 ) {
323 throw new Error(
324 `${wording.label}: unreadable output cap: ${subject.trim()} supports${part}`,
325 )
326 }
327 caps.push({ names, series: wording.series.test(subject), tokens })
328 subject = part.slice(cap[0].length)
329 }
330 if (modelNames(subject).length > 0) {
331 throw new Error(
332 `${wording.label}: model with no output cap: ${subject.trim()}`,
333 )
334 }
335 return caps
336}
337
338/**
339 * Does a property description's "supported by <models>" clause cover this
340 * id? Null when the description has no such clause. A clause that is not a
341 * plain model list, or a "<model> and higher" floor, covers nothing.
342 */
343export function zaiSupportedBy(
344 description: string,
345 rawId: string,
346 wording: GlmWording = ZAI_WORDING,
347): boolean | null {
348 const clause = description.match(wording.supportedBy)?.[1]
349 if (clause === undefined) return null
350 const names = modelNames(clause)
351 if (names.length === 0) return false
352 if (wording.floor.test(clause)) {
353 const version = (id: string) => id.match(/^glm-(\d+(?:\.\d+)?)/)?.[1]
354 const floor = version(names[0] ?? '')
355 const own = version(rawId)
356 return (
357 names.length === 1 &&
358 onlyNames(clause, wording.floorFiller) &&
359 floor !== undefined &&
360 own !== undefined &&
361 Number(own) >= Number(floor)
362 )
363 }
364 return (
365 onlyNames(clause, wording.filler) &&
366 namedBy(rawId, [{ names, series: true }]) !== null
367 )
368}
369
370/**
371 * The "In the API request" bullets under `reasoning_effort` on the Deep
372 * Thinking page: "For <models>, only | the supported options are <values>."
373 * The page and the spec both speak of these names as series. `mandatory`
374 * here is inferred from the list (no `none` reads as true), which predates
375 * the stated-only rule on `ModelReasoning`.
376 */
377export function parseZaiReasoning(markdown: string): Array<ReasoningRow> {
378 const block = markdown.match(
379 /In the API request:\n([\s\S]*?)\n[^\n]*In the Coding Plan request:/,
380 )?.[1]
381 if (block === undefined) {
382 throw new Error('zai: Deep Thinking page has no API reasoning_effort list')
383 }
384 const rows: Array<ReasoningRow> = []
385 for (const line of block.split('\n')) {
386 if (line.trim() === '') continue
387 const match = line.match(
388 /^[\s*]*For (.+?), (?:only|the supported options are) ([^.]+)\./,
389 )
390 const names = modelNames(match?.[1] ?? '')
391 const efforts = [...(match?.[2] ?? '').matchAll(/`([a-z]+)`/g)].flatMap(
392 (effort) => (effort[1] ? [effort[1]] : []),
393 )
394 if (names.length === 0 || efforts.length === 0) {
395 throw new Error(`zai: unreadable reasoning_effort line: ${line.trim()}`)
396 }
397 rows.push({
398 names,
399 series: true,
400 reasoning: {
401 mode: 'effort',
402 mandatory: !efforts.includes('none'),
403 efforts,
404 },
405 })
406 }
407 if (rows.length === 0) {
408 throw new Error('zai: Deep Thinking page lists no reasoning_effort values')
409 }
410 return rows
411}
412
413/**
414 * The `thinking.type` description: "Whether to enable the chain of
415 * thought(<models> series can only be enabled, …; for other models, when
416 * enabled, …), default: enabled". Group 1 is the models that reject
417 * `disabled`; every other model the switch covers may send either value.
418 */
419const THINKING_TYPE =
420 /^Whether to enable the chain of thought\((.+?) series can only be enabled\b[^;]*; for other models, when enabled, [^)]*\), default: enabled$/
421
422/**
423 * The models whose `thinking.type` cannot be `disabled`, from the switch's
424 * own schema. Throws unless the enum is exactly `enabled | disabled` and
425 * the description has the shape above: a third value or a reworded
426 * sentence is a switch this cannot read.
427 */
428export function parseZaiThinkingSwitch(type: unknown): ModelNames {
429 const node = isRecord(type) ? type : {}
430 const values = list(node.enum).map(String).sort().join()
431 const locked =
432 typeof node.description === 'string'
433 ? node.description.match(THINKING_TYPE)?.[1]
434 : undefined
435 const names = modelNames(locked ?? '')
436 if (
437 values !== 'disabled,enabled' ||
438 locked === undefined ||
439 names.length === 0 ||
440 !onlyNames(locked, ZAI_WORDING.filler)
441 ) {
442 throw new Error('zai: unreadable thinking.type switch')
443 }
444 return { names, series: true }
445}
446
447/** Follow `$ref`s, then walk `keys`; undefined when the path is not there. */
448function at(spec: unknown, node: unknown, ...keys: Array<string>): unknown {
449 const components = isRecord(spec) ? spec.components : undefined
450 const schemas = isRecord(components) ? components.schemas : undefined
451 const deref = (value: unknown): unknown => {
452 let current = value
453 for (
454 let depth = 0;
455 depth < 8 && isRecord(current) && typeof current.$ref === 'string';
456 depth++
457 ) {
458 const name = current.$ref.replace('#/components/schemas/', '')
459 current = isRecord(schemas) ? schemas[name] : undefined
460 }
461 return current
462 }
463 let current = deref(node)
464 for (const key of keys) {
465 if (!isRecord(current)) return undefined
466 current = deref(current[key])
467 }
468 return current
469}
470
471const CONTENT_PART: Record<string, string> = {
472 text: 'text',
473 image_url: 'image',
474 video_url: 'video',
475 file: 'file',
476}
477
478/** What a user message may carry: a string, or the listed content parts. */
479function userInputs(
480 spec: unknown,
481 messages: unknown,
482 label: string,
483): Array<string> {
484 const user = list(at(spec, messages, 'items', 'oneOf')).find((message) =>
485 list(at(spec, message, 'properties', 'role', 'enum')).includes('user'),
486 )
487 const inputs = new Set<string>()
488 // The China document writes a text-only content as a bare string schema.
489 const content = at(spec, user, 'properties', 'content')
490 const shapes = at(spec, content, 'oneOf')
491 const bare = content === undefined ? [] : [content]
492 for (const shape of Array.isArray(shapes) ? shapes : bare) {
493 if (at(spec, shape, 'type') === 'string') {
494 inputs.add('text')
495 continue
496 }
497 const parts = list(at(spec, shape, 'items', 'oneOf'))
498 if (parts.length === 0) {
499 throw new Error(`${label}: user message content lists no parts`)
500 }
501 for (const part of parts) {
502 const type = list(at(spec, part, 'properties', 'type', 'enum'))[0]
503 const modality = typeof type === 'string' ? CONTENT_PART[type] : undefined
504 if (!modality) {
505 throw new Error(
506 `${label}: unknown message content part: ${String(type)}`,
507 )
508 }
509 inputs.add(modality)
510 }
511 }
512 if (inputs.size === 0) {
513 throw new Error(`${label}: chat request has no user message content`)
514 }
515 return ['text', 'image', 'video', 'file'].filter((kind) => inputs.has(kind))
516}
517
518/**
519 * The flags of one request variant that hold for one of its models: the
520 * shared walk's flags for the variant's own properties, less any whose
521 * description says "supported by" other models. `tool_choice` goes with
522 * `tools`.
523 */
524function variantCapabilities(
525 spec: unknown,
526 props: Record<string, unknown>,
527 rawId: string,
528 meta: Parameters<typeof walkRequestSchema>[1],
529 wording: GlmWording,
530): Record<string, FactSource> {
531 const walked = walkRequestSchema({ properties: props }, meta)
532 const kept = Object.entries(walked?.sources.capabilities ?? {}).filter(
533 ([, source]) => {
534 const property = source.path?.split('/')[2] ?? ''
535 const description = at(spec, props[property], 'description')
536 return (
537 typeof description !== 'string' ||
538 zaiSupportedBy(description, rawId, wording) !== false
539 )
540 },
541 )
542 const flags = Object.fromEntries(kept)
543 if (!('tools' in flags)) delete flags.tool_choice
544 return flags
545}
546
547/**
548 * Route and request-body facts for each id a generation path's request
549 * lists under `model`. The first path that lists an id binds it. With
550 * `only`, a request variant that lists none of those ids is not read.
551 */
552export function zaiSpecFacts(
553 spec: unknown,
554 source: { url: string; hash: string } = { url: ZAI_OPENAPI_URL, hash: '' },
555 {
556 wording = ZAI_WORDING,
557 classify = classifyZaiPath,
558 only,
559 }: {
560 wording?: GlmWording
561 classify?: (path: string) => Activity | null
562 only?: (id: string) => boolean
563 } = {},
564): Map<string, SpecFacts> {
565 const facts = new Map<string, SpecFacts>()
566 const paths = at(spec, spec, 'paths')
567 for (const [path, item] of Object.entries(isRecord(paths) ? paths : {})) {
568 const activity = classify(path)
569 if (activity === null) continue
570 const schemaEndpointId = path.replace(/^\//, '')
571 const content = at(spec, item, 'post', 'requestBody', 'content')
572 for (const media of Object.values(isRecord(content) ? content : {})) {
573 const body = at(spec, media, 'schema')
574 const variants = at(spec, body, 'oneOf')
575 for (const variant of Array.isArray(variants) ? variants : [body]) {
576 const props: Record<string, unknown> = {}
577 for (const part of [variant, ...list(at(spec, variant, 'allOf'))]) {
578 const own = at(spec, part, 'properties')
579 if (isRecord(own)) Object.assign(props, own)
580 }
581 const ids = list(at(spec, props.model, 'enum')).filter(
582 (id): id is string =>
583 typeof id === 'string' && MODEL_ID.test(id) && (only?.(id) ?? true),
584 )
585 if (ids.length === 0) continue
586 const chat =
587 activity === 'chat'
588 ? {
589 caps: parseZaiOutputCaps(
590 String(at(spec, props.max_tokens, 'description') ?? ''),
591 wording,
592 ),
593 input: userInputs(spec, props.messages, wording.label),
594 }
595 : null
596 // "128K" is a label; `maximum` is the bound, when it is that tier's.
597 // A label above the bound contradicts it: neither is stored.
598 const maximum = at(spec, props.max_tokens, 'maximum')
599 const exact = (tokens: number | undefined) => {
600 if (tokens === undefined) return null
601 if (typeof maximum !== 'number') return tokens
602 const binary = (tokens / 1000) * 1024
603 if (binary > maximum) return null
604 return binary === maximum ? maximum : tokens
605 }
606 const efforts = list(at(spec, props.reasoning_effort, 'enum')).filter(
607 (effort): effort is string => typeof effort === 'string',
608 )
609 for (const id of ids) {
610 if (facts.has(id)) continue
611 facts.set(id, {
612 activity,
613 schemaEndpointId,
614 maxOutput: chat ? exact(namedBy(id, chat.caps)?.tokens) : null,
615 modalities: chat ? { input: chat.input, output: ['text'] } : null,
616 efforts,
617 thinkingType: at(spec, props.thinking, 'properties', 'type'),
618 ...(() => {
619 const description = at(
620 spec,
621 props.thinking,
622 'properties',
623 'clear_thinking',
624 'description',
625 )
626 if (activity !== 'chat' || typeof description !== 'string')
627 return {}
628 const supported = zaiSupportedBy(description, id, wording)
629 if (supported === false) return {}
630 if (
631 supported === null &&
632 /only (?:supports?|supported|available|applies)|supported only|GLM-[\d.]+\+/i.test(
633 description,
634 )
635 ) {
636 throw new Error(
637 `${wording.label}: unreadable clear_thinking model restriction`,
638 )
639 }
640 if (
641 !/`false`[^\n]*Retains `reasoning_content`/.test(description) ||
642 !/must forward the full, unmodified, and correctly ordered historical `reasoning_content` in `messages`/.test(
643 description,
644 )
645 )
646 return {}
647 return {
648 replayReasoningContent: {
649 derivation: 'upstream-spec' as const,
650 sourceUrl: source.url,
651 sourceHash: source.hash,
652 path: `${schemaEndpointId}/requestBody/model=${id}/thinking/clear_thinking`,
653 },
654 }
655 })(),
656 capabilities: chat
657 ? variantCapabilities(
658 spec,
659 props,
660 id,
661 {
662 derivation: 'upstream-spec',
663 endpointId: schemaEndpointId,
664 sourceUrl: source.url,
665 sourceHash: source.hash,
666 },
667 wording,
668 )
669 : null,
670 })
671 }
672 }
673 }
674 }
675 if (![...facts.values()].some((fact) => fact.activity === 'chat')) {
676 throw new Error(`${wording.label}: OpenAPI chat request lists no model ids`)
677 }
678 return facts
679}
680
681export function parseZaiModels(
682 spec: ZaiDoc,
683 pricing: ZaiDoc,
684 overview: ZaiDoc,
685 thinking: ZaiDoc,
686 extractedAt: string,
687): Array<ModelInfo> {
688 const document: unknown = JSON.parse(spec.text)
689 const prices = parseZaiTokenPrices(pricing.text)
690 const windows = parseZaiContextWindows(overview.text)
691 const reasonings = parseZaiReasoning(thinking.text)
692 const facts = zaiSpecFacts(document, spec)
693 const from = (
694 doc: ZaiDoc,
695 derivation: FactSource['derivation'],
696 path: string,
697 ): FactSource => ({
698 derivation,
699 sourceUrl: doc.url,
700 sourceHash: doc.hash,
701 path,
702 })
703 return zaiModelIds(document).map((rawId) => {
704 const price = prices.get(rawId)
705 const rates = price
706 ? {
707 input_tokens: price.input / 1_000_000,
708 output_tokens: price.output / 1_000_000,
709 ...(price.cache !== null
710 ? { cache_read_tokens: price.cache / 1_000_000 }
711 : {}),
712 }
713 : null
714 const card = rates
715 ? compileTokenCard(rates, [], {
716 url: pricing.url,
717 hash: pricing.hash,
718 extractedAt,
719 })
720 : null
721 const fact = facts.get(rawId)
722 const contextWindow = windows.get(rawId) ?? null
723 const effort = namedBy(rawId, reasonings)?.reasoning ?? null
724 // The thinking page names series. Cite the request variant instead when
725 // its own enum is the same list, as it is for `glm-5.3-flashx`.
726 const specEfforts =
727 effort?.efforts !== undefined &&
728 [...effort.efforts].sort().join() ===
729 [...(fact?.efforts ?? [])].sort().join()
730 // No effort list for the model means no `reasoning_effort` flag either.
731 const capabilities = fact?.capabilities
732 ? Object.fromEntries(
733 Object.entries(fact.capabilities).filter(
734 ([flag]) => flag !== 'reasoning_effort' || effort !== null,
735 ),
736 )
737 : null
738 // No effort list, and `thinking` covers the model: the switch is all
739 // there is. The request variant is shared, so its `disabled` states
740 // nothing; the description says which models may send it.
741 const toggle: ModelReasoning | null =
742 effort === null && capabilities && 'reasoning' in capabilities
743 ? {
744 mode: 'toggle',
745 mandatory:
746 namedBy(rawId, [parseZaiThinkingSwitch(fact?.thinkingType)]) !==
747 null,
748 }
749 : null
750 const reasoning = effort ?? toggle
751 const factSources: ModelFactSources = {
752 ...(card ? { pricing: from(pricing, 'docs-derived', 'Pricing') } : {}),
753 ...(contextWindow !== null
754 ? { contextWindow: from(overview, 'docs-derived', 'Context') }
755 : {}),
756 ...(effort
757 ? {
758 reasoning: specEfforts
759 ? from(spec, 'upstream-spec', 'reasoning_effort')
760 : from(thinking, 'docs-derived', 'reasoning_effort'),
761 }
762 : toggle
763 ? { reasoning: from(spec, 'upstream-spec', 'thinking.type') }
764 : {}),
765 ...(capabilities && Object.keys(capabilities).length > 0
766 ? { capabilities }
767 : {}),
768 ...(fact?.maxOutput != null
769 ? { maxOutput: from(spec, 'upstream-spec', 'max_tokens') }
770 : {}),
771 ...(fact?.modalities
772 ? { modalities: from(spec, 'upstream-spec', 'messages') }
773 : {}),
774 }
775 const model: ModelInfo = {
776 rawId,
777 pricing: card,
778 ...(fact
779 ? {
780 activity: fact.activity,
781 schemaEndpointId: fact.schemaEndpointId,
782 maxOutput: fact.maxOutput,
783 modalities: fact.modalities,
784 }
785 : {}),
786 ...(capabilities
787 ? { capabilities: Object.keys(capabilities), exactCapabilities: true }
788 : {}),
789 ...(contextWindow !== null ? { contextWindow } : {}),
790 ...(reasoning ? { reasoning } : {}),
791 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
792 }
793 return fact?.replayReasoningContent &&
794 model.activity === 'chat' &&
795 (reasoning !== null || capabilities?.reasoning != null)
796 ? applyReplay(model, fact.replayReasoningContent)
797 : model
798 })
799}
800
801export async function fetchZaiDoc(url: string, label = 'zai'): Promise<ZaiDoc> {
802 const text = await fetchText(url, {
803 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
804 })
805 // A 200 that is a web page is an error page, not the document.
806 if (/^\s*<(?:!doctype|html)/i.test(text)) {
807 throw new Error(`${label}: ${url} returned HTML, not the document`)
808 }
809 return { url, text, hash: await sha256Text(text) }
810}
811
812async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
813 const [spec, pricing, overview, thinking] = await Promise.all([
814 fetchZaiDoc(ZAI_OPENAPI_URL),
815 fetchZaiDoc(ZAI_PRICING_URL),
816 fetchZaiDoc(ZAI_OVERVIEW_URL),
817 fetchZaiDoc(ZAI_THINKING_URL),
818 ])
819 const replay = await loadReplayDoc(ZAI_THINKING_MODE_URL)
820 const replayIds = new Set(parseGlmReplay(replay.text))
821 return {
822 models: parseZaiModels(
823 spec,
824 pricing,
825 overview,
826 thinking,
827 new Date().toISOString(),
828 ).map((model) =>
829 replayIds.has(model.rawId) && model.activity === 'chat'
830 ? applyReplay(model, replay.source)
831 : model,
832 ),
833 }
834}
835
836async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
837 const { spec, hash } = await fetchOpenApi(ZAI_OPENAPI_URL)
838 return {
839 specs: [spec],
840 sources: [{ url: ZAI_OPENAPI_URL, hash }],
841 outputStrategy: 'post-200',
842 specRevision: hash,
843 }
844}
845
846export function classifyZaiPath(path: string): Activity | null {
847 if (path.includes('/chat/completions')) return 'chat'
848 if (path.includes('/images/')) return 'image'
849 if (path.includes('/videos/')) return 'video'
850 if (path.includes('/audio/')) return 'audio'
851 return null
852}
853
854export const provider: ProviderConfig = {
855 id: 'zai',
856 displayName: 'Z.AI',
857 specSourceUrl: ZAI_OPENAPI_URL,
858 modelsEndpoint: ZAI_OPENAPI_URL,
859 defaultDerivation: 'upstream-spec',
860 fetchSpec,
861 listModels,
862 classify: (path) => classifyZaiPath(path),
863}