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

zai.ts

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