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

zai.ts

888 lines29.8 KB

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