Open History to see the last commit
1import { ZAI_THINKING_MODE_URL } from '../provider-replay.ts'
2import { GLM_REPLAY_FIXTURE } from '../fixtures/provider-replay.ts'
3import { afterEach, describe, expect, it } from 'vitest'
4
5import {
6 parseZaiContextWindows,
7 parseZaiOutputCaps,
8 parseZaiReasoning,
9 parseZaiThinkingSwitch,
10 provider,
11 ZAI_OPENAPI_URL,
12 ZAI_OVERVIEW_URL,
13 ZAI_PRICING_URL,
14 ZAI_THINKING_URL,
15 zaiSpecFacts,
16 zaiSupportedBy,
17} from './zai.ts'
18
19/** `max_tokens` descriptions of https://docs.z.ai/openapi.json (2026-10-06). */
20const TEXT_MAX_TOKENS =
21 'The maximum number of tokens for model output, the GLM-5.3, GLM-5.2, GLM-5.1, GLM-5, GLM-4.7, GLM-4.6 series supports 128K maximum output, the GLM-4.5 series supports 96K maximum output, the GLM-4.6v series supports 32K maximum output, the GLM-4.5v series supports 16K maximum output, GLM-4-32B-0414-128K supports 16K maximum output.'
22const VISION_MAX_TOKENS =
23 'The maximum number of tokens for model output. `GLM-5.3-Flash` series supports a maximum output length of 128K, the GLM-4.6V series supports 32K, the GLM-4.5V series supports 16K, and autoglm-phone-multilingual supports 4K. It is recommended to set it to no less than 1024.'
24
25/** `ChatThinking.type` of https://docs.z.ai/openapi.json (2026-10-07). */
26const THINKING_TYPE = {
27 type: 'string',
28 description:
29 'Whether to enable the chain of thought(`GLM-5.3` `GLM-5.3-FLASH` series can only be enabled, and the thinking depth is controlled by `reasoning_effort`; for other models, when enabled, GLM-5.2 GLM-5.1 GLM-5 GLM-4.6 GLM-4.5 and others will automatically determine whether to think, while GLM-4.7 and GLM-4.5V will think compulsorily), default: enabled',
30 default: 'enabled',
31 enum: ['enabled', 'disabled'],
32}
33
34const part = (type: string) => ({
35 type: 'object',
36 properties: { type: { type: 'string', enum: [type] } },
37})
38
39const message = (role: string, content: Array<unknown>) => ({
40 type: 'object',
41 properties: {
42 role: { type: 'string', enum: [role] },
43 content: { oneOf: content },
44 },
45})
46
47/** Excerpt of https://docs.z.ai/openapi.json (2026-10-06), same nesting. */
48function spec(
49 overrides: {
50 textMaxTokens?: string
51 visionMaxTokens?: string
52 parts?: Array<string>
53 thinking?: string
54 thinkingType?: unknown
55 visionTools?: string
56 } = {},
57) {
58 const shared = {
59 temperature: { type: 'number' },
60 thinking: { $ref: '#/components/schemas/ChatThinking' },
61 tool_choice: { oneOf: [{ type: 'string', enum: ['auto'] }] },
62 }
63 return {
64 openapi: '3.0.1',
65 info: { title: 'Z.AI API', version: '1' },
66 paths: {
67 '/paas/v4/chat/completions': {
68 post: {
69 requestBody: {
70 content: {
71 'application/json': {
72 schema: {
73 oneOf: [
74 { $ref: '#/components/schemas/ChatCompletionTextRequest' },
75 {
76 $ref: '#/components/schemas/ChatCompletionVisionRequest',
77 },
78 ],
79 },
80 },
81 },
82 },
83 responses: { '200': {} },
84 },
85 },
86 '/paas/v4/images/generations': {
87 post: {
88 requestBody: {
89 content: {
90 'application/json': {
91 schema: { $ref: '#/components/schemas/CreateImageRequest' },
92 },
93 },
94 },
95 },
96 },
97 '/paas/v4/tokenizer': {
98 post: {
99 requestBody: {
100 content: {
101 'application/json': {
102 schema: { $ref: '#/components/schemas/TokenizerRequest' },
103 },
104 },
105 },
106 },
107 },
108 },
109 components: {
110 schemas: {
111 ChatCompletionTextRequest: {
112 type: 'object',
113 properties: {
114 model: {
115 type: 'string',
116 enum: [
117 'glm-5.3',
118 'glm-5.2',
119 'glm-5',
120 'glm-4.7-flash',
121 'glm-4.5-air',
122 'glm-4-32b-0414-128k',
123 ],
124 },
125 messages: {
126 type: 'array',
127 items: {
128 oneOf: [
129 message('user', [{ type: 'string' }]),
130 message('system', [{ type: 'string' }]),
131 ],
132 },
133 },
134 max_tokens: {
135 type: 'integer',
136 description: overrides.textMaxTokens ?? TEXT_MAX_TOKENS,
137 maximum: 131072,
138 },
139 reasoning_effort: {
140 type: 'string',
141 description:
142 "Controls the model's reasoning effort level, takes effect when `thinking` is enabled. Default is `max`, supported by `GLM-5.2` and above. For the `GLM-5.3` `GLM-5.3-FLASH` model, only the `low` / `high` / `max` levels are supported.",
143 enum: [
144 'max',
145 'xhigh',
146 'high',
147 'medium',
148 'low',
149 'minimal',
150 'none',
151 ],
152 },
153 response_format: {
154 type: 'object',
155 description:
156 'Specifies the response format of the model. Defaults to text. Only text models support this field.',
157 properties: { type: { type: 'string' } },
158 },
159 tool_stream: { type: 'boolean' },
160 tools: {
161 type: 'array',
162 description:
163 'A list of tools the model may call. Currently, only functions are supported as a tool. A max of 128 functions are supported.\n',
164 },
165 ...shared,
166 },
167 },
168 ChatThinking: {
169 type: 'object',
170 description:
171 overrides.thinking ??
172 'Only supported by GLM-4.5 series and higher models. This parameter is used to control whether the model enable the chain of thought.',
173 properties: { type: overrides.thinkingType ?? THINKING_TYPE },
174 },
175 ChatCompletionVisionRequest: {
176 type: 'object',
177 properties: {
178 model: {
179 type: 'string',
180 enum: [
181 'glm-5.3-flashx',
182 'glm-5.3-flash',
183 'glm-4.6v',
184 'glm-4.5v',
185 'autoglm-phone-multilingual',
186 ],
187 },
188 messages: {
189 type: 'array',
190 items: {
191 oneOf: [
192 message('user', [
193 {
194 type: 'array',
195 items: {
196 $ref: '#/components/schemas/VisionMultimodalContentItem',
197 },
198 },
199 { type: 'string' },
200 ]),
201 message('assistant', [{ type: 'string' }]),
202 ],
203 },
204 },
205 max_tokens: {
206 type: 'integer',
207 description: overrides.visionMaxTokens ?? VISION_MAX_TOKENS,
208 maximum: 131072,
209 },
210 reasoning_effort: {
211 type: 'string',
212 description:
213 "Controls the model's reasoning effort level, takes effect when `thinking` is enabled. Default is `max`.",
214 enum: ['max', 'high', 'low'],
215 },
216 tools: {
217 type: 'array',
218 description:
219 overrides.visionTools ??
220 'A list of tools the model may call. Only supported by `GLM-5.3-Flash` series, the GLM-4.6V series, and autoglm-phone-multilingual. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n',
221 },
222 ...shared,
223 },
224 },
225 VisionMultimodalContentItem: {
226 oneOf: (
227 overrides.parts ?? ['text', 'image_url', 'video_url', 'file']
228 ).map(part),
229 },
230 CreateImageRequest: {
231 type: 'object',
232 properties: { model: { type: 'string', enum: ['glm-image'] } },
233 },
234 TokenizerRequest: {
235 type: 'object',
236 properties: {
237 model: { type: 'string', enum: ['glm-5', 'glm-ocr'] },
238 },
239 },
240 },
241 },
242 }
243}
244
245/** Excerpt of https://docs.z.ai/guides/overview/pricing.md (2026-10-06). */
246const PRICING = `
247Prices per 1M tokens.
248
249| Model | Input | Cached Input | Cached Input Storage | Output |
250| :- | :- | :- | :- | :- |
251| GLM-5.3 | \\$1.4 | \\$0.26 | Limited-time Free | \\$4.4 |
252| GLM-5.3-Flash | \\$0.15 | \\$0.03 | Limited-time Free | \\$0.50 |
253| GLM-4-32B-0414-128K | \\$0.1 | - | - | \\$0.1 |
254| GLM-4.7-Flash | Free | Free | Free | Free |
255| Not-A-Model | \\$9 | \\$1 | - | \\$9 |
256
257### Image Generation Models
258
259Prices per image.
260
261| Model | Price |
262| GLM-Image | \\$0.015 |
263`
264
265/** Excerpt of https://docs.z.ai/guides/overview/overview.md (2026-10-06). */
266const OVERVIEW = `
267## Featured Models
268
269| Model | Strength | Language | Context | Resource |
270| :- | :- | :- | :- | :- |
271| GLM-5.3-Flash | Delivering frontier intelligence at radically lower cost | English & Chinese | 1M | [Guide](/guides/vlm/glm-5.3-flash) |
272| GLM-5.3-FlashX | Delivering inference speeds of 200 tokens/s | English & Chinese | 1M | [Guide](/guides/vlm/glm-5.3-flash) |
273| GLM-5.3 | Stronger in long-horizon, complex tasks | English & Chinese | 1M | [Guide](/guides/llm/glm-5.3) |
274| GLM-5.2 | Open-source SOTA coding | English & Chinese | 1M | [Guide](/guides/llm/glm-5.2) |
275| GLM-OCR | Document Parsing<br />Information Extraction | Multiple | / | [Guide](/guides/vlm/glm-ocr) |
276
277<AccordionGroup>
278 <Accordion title="Other Models, Agents and Tools">
279 ### Text Models
280
281 | Model | Strength | Language | Context | Resource |
282 | :- | :- | :- | :- | :- |
283 | GLM-5 | Agentic Long-Term Planning and Execution | English & Chinese | 200K | [Guide](/guides/llm/glm-5) |
284 | GLM-4.5-Air | Cost-Effective<br />High Performance | English & Chinese | 128K | [Guide](/guides/llm/glm-4.5) |
285 | GLM-4-32B-0414-128K | High intelligence | English & Chinese | 128K | [Guide](/guides/llm/glm-4-32b-0414-128k) |
286 | GLM-4.7-Flash | Free, Lightweight | English & Chinese | 200K | [Guide](/guides/llm/glm-4.7) |
287
288 ### Vision Models
289
290 | Model | Strength | Language | Context | Resource |
291 | :- | :- | :- | :- | :- |
292 | GLM-4.6V | Native Function Call Support | English & Chinese | 128K | [Guide](/guides/vlm/glm-4.6v) |
293
294 ### Built-in Tools
295
296 | Tool | Capability |
297 | :- | :- |
298 | Web Search | Provide real-time, concise, direct answers |
299
300 ### Image Generation Models
301
302 | Model | Strength | Language | Resolution | Resource |
303 | :- | :- | :- | :- | :- |
304 | GLM-Image | Open-source SOTA in text rendering | English & Chinese | multiple resolutions | [Guide](/guides/image/glm-image) |
305 </Accordion>
306</AccordionGroup>
307`
308
309/** Excerpt of https://docs.z.ai/guides/capabilities/thinking.md (2026-10-06). */
310const THINKING = `
311### Core Parameters
312
313* **\`reasoning_effort\`**: Controls the degree of reasoning within the thought chain, and is only supported by \`GLM-5.2\` and above.
314 * Available values: \`max\` (default and recommended, deep inference), \`high\` (enhanced inference), \`low\` (mild inference, only supported by GLM-5.3 and GLM-5.3-FLASH)
315 * In the API request:
316 * * For GLM-5.3 and GLM-5.3-FLASH, only \`max\`, \`high\` and \`low\` are supported. Any other input will result in an error.
317 * * For GLM-5.2, the supported options are \`max\` (default and recommended, for deep inference), \`xhigh\`, \`high\` (enhanced inference), \`medium\`, \`low\`, \`minimal\`, and \`none\`. Among them, \`none\` or \`minimal\` indicate that the model stops thinking; \`low\`/\`medium\` are mapped to \`high\`; \`xhigh\` is mapped to \`max\`.
318 * In the Coding Plan request:
319 * * For GLM-5.3 and GLM-5.3-FLASH, \`none\`, \`minimal\`, and \`low\` are mapped to \`low\`; \`medium\`, \`high\` are mapped to \`high\`; \`xhigh\` and \`max\` are mapped to \`max\`.
320* **\`model\`**: A model that enables deep thinking, supported by \`GLM-4.5\` and above versions.
321`
322
323const originalFetch = globalThis.fetch
324
325afterEach(() => {
326 globalThis.fetch = originalFetch
327})
328
329function serve(docs: Record<string, string>): Array<string> {
330 const urls: Array<string> = []
331 globalThis.fetch = ((url: string) => {
332 urls.push(String(url))
333 const body = docs[String(url)]
334 return body === undefined
335 ? Promise.reject(new Error(`unexpected fetch: ${String(url)}`))
336 : Promise.resolve(new Response(body))
337 }) as typeof fetch
338 return urls
339}
340
341const DOCS = {
342 [ZAI_THINKING_MODE_URL]: GLM_REPLAY_FIXTURE,
343 [ZAI_OPENAPI_URL]: JSON.stringify(spec()),
344 [ZAI_PRICING_URL]: PRICING,
345 [ZAI_OVERVIEW_URL]: OVERVIEW,
346 [ZAI_THINKING_URL]: THINKING,
347}
348
349describe('zai', () => {
350 it('lists OpenAPI model ids and per-1M prices that match those ids', async () => {
351 const urls = serve(DOCS)
352
353 const listed = await provider.listModels({})
354 const fetched = await provider.fetchSpec({})
355 const byId = new Map(listed.models.map((model) => [model.rawId, model]))
356
357 expect(listed.models.map((model) => model.rawId)).toEqual([
358 'glm-4-32b-0414-128k',
359 'glm-4.5-air',
360 'glm-4.5v',
361 'glm-4.6v',
362 'glm-4.7-flash',
363 'glm-5',
364 'glm-5.2',
365 'glm-5.3',
366 'glm-5.3-flash',
367 'glm-5.3-flashx',
368 'glm-image',
369 'glm-ocr',
370 ])
371 expect(byId.get('glm-5.3')?.pricing).toMatchObject({
372 tables: {
373 rate: {
374 base: {
375 input_tokens: 1.4 / 1_000_000,
376 output_tokens: 4.4 / 1_000_000,
377 cache_read_tokens: 0.26 / 1_000_000,
378 },
379 },
380 },
381 })
382 expect(byId.get('glm-5.3-flash')?.pricing).toMatchObject({
383 tables: {
384 rate: {
385 base: {
386 input_tokens: 0.15 / 1_000_000,
387 output_tokens: 0.5 / 1_000_000,
388 },
389 },
390 },
391 })
392 // "Free" and "-" are not rates.
393 expect(byId.get('glm-4.7-flash')?.pricing).toBeNull()
394 expect(byId.get('glm-4-32b-0414-128k')?.pricing).not.toHaveProperty(
395 'tables.rate.base.cache_read_tokens',
396 )
397 expect(byId.get('glm-image')?.pricing).toBeNull()
398 expect(listed.models.some((model) => model.rawId === 'not-a-model')).toBe(
399 false,
400 )
401 expect(fetched.specs).toHaveLength(1)
402 expect(fetched.sources[0]?.url).toBe(ZAI_OPENAPI_URL)
403 expect(provider.classify('/paas/v4/chat/completions', {})).toBe('chat')
404 expect(provider.classify('/paas/v4/images/generations', {})).toBe('image')
405 expect(provider.classify('/paas/v4/tokenizer', {})).toBeNull()
406 expect(urls).toEqual([
407 ZAI_OPENAPI_URL,
408 ZAI_PRICING_URL,
409 ZAI_OVERVIEW_URL,
410 ZAI_THINKING_URL,
411 ZAI_THINKING_MODE_URL,
412 ZAI_OPENAPI_URL,
413 ])
414 expect(provider.classify('/paas/v4/videos/generations', {})).toBe('video')
415 expect(provider.classify('/paas/v4/audio/speech', {})).toBe('audio')
416 })
417
418 it('binds each id to the route whose request lists it', async () => {
419 serve(DOCS)
420 const { models } = await provider.listModels({})
421 const byId = new Map(models.map((model) => [model.rawId, model]))
422
423 for (const id of ['glm-5.3', 'glm-4.5-air', 'glm-4.6v', 'glm-5.3-flashx']) {
424 expect(byId.get(id)?.activity).toBe('chat')
425 expect(byId.get(id)?.schemaEndpointId).toBe('paas/v4/chat/completions')
426 }
427 // glm-5 is also a tokenizer model; the chat route binds it.
428 expect(byId.get('glm-5')?.activity).toBe('chat')
429 expect(byId.get('glm-image')?.activity).toBe('image')
430 expect(byId.get('glm-image')?.schemaEndpointId).toBe(
431 'paas/v4/images/generations',
432 )
433 // The tokenizer is not a generation route.
434 expect(byId.get('glm-ocr')?.activity).toBeUndefined()
435 expect(byId.get('glm-ocr')?.schemaEndpointId).toBeUndefined()
436 })
437
438 it('fills chat facts from the spec, the overview, and the thinking page', async () => {
439 serve(DOCS)
440 const { models } = await provider.listModels({})
441 const byId = new Map(models.map((model) => [model.rawId, model]))
442
443 expect(byId.get('glm-5.3')).toMatchObject({
444 contextWindow: 1_000_000,
445 // "128K" is the label of the spec's exact `maximum`.
446 maxOutput: 131_072,
447 modalities: { input: ['text'], output: ['text'] },
448 reasoning: {
449 mode: 'effort',
450 mandatory: true,
451 efforts: ['max', 'high', 'low'],
452 },
453 })
454 expect(byId.get('glm-5.2')?.reasoning).toEqual({
455 mode: 'effort',
456 mandatory: false,
457 efforts: ['max', 'xhigh', 'high', 'medium', 'low', 'minimal', 'none'],
458 })
459 // The vision request has its own cap list and content parts.
460 expect(byId.get('glm-5.3-flashx')).toMatchObject({
461 contextWindow: 1_000_000,
462 maxOutput: 131_072,
463 modalities: { input: ['text', 'image', 'video', 'file'] },
464 reasoning: { mandatory: true, efforts: ['max', 'high', 'low'] },
465 })
466 expect(byId.get('glm-4.6v')).toMatchObject({
467 contextWindow: 128_000,
468 maxOutput: 32_000,
469 modalities: { input: ['text', 'image', 'video', 'file'] },
470 })
471 // A series cap covers its variants; glm-5 is not glm-5.x.
472 expect(byId.get('glm-4.5-air')?.maxOutput).toBe(96_000)
473 expect(byId.get('glm-4.7-flash')?.maxOutput).toBe(131_072)
474 expect(byId.get('glm-4-32b-0414-128k')?.maxOutput).toBe(16_000)
475 expect(byId.get('glm-5')).toMatchObject({
476 contextWindow: 200_000,
477 maxOutput: 131_072,
478 })
479 // No effort list names these: `thinking.type` is their whole control,
480 // and only the GLM-5.3 series "can only be enabled".
481 for (const id of ['glm-5', 'glm-4.5-air', 'glm-4.7-flash', 'glm-4.6v']) {
482 expect(byId.get(id)?.reasoning).toEqual({
483 mode: 'toggle',
484 mandatory: false,
485 })
486 expect(byId.get(id)?.factSources?.reasoning).toMatchObject({
487 derivation: 'upstream-spec',
488 sourceUrl: ZAI_OPENAPI_URL,
489 path: 'thinking.type',
490 })
491 }
492 // `thinking` is "GLM-4.5 series and higher": no switch, no object.
493 expect(byId.get('glm-4-32b-0414-128k')?.reasoning).toBeUndefined()
494 expect(
495 byId.get('glm-4-32b-0414-128k')?.factSources?.reasoning,
496 ).toBeUndefined()
497 expect(byId.get('glm-image')?.reasoning).toBeUndefined()
498 // "/" and a Resolution column are not context windows.
499 expect(byId.get('glm-ocr')?.contextWindow).toBeUndefined()
500 expect(byId.get('glm-image')?.contextWindow).toBeUndefined()
501 })
502
503 it('names the document each fact came from', async () => {
504 serve(DOCS)
505 const { models } = await provider.listModels({})
506 const sources = models.find(
507 (model) => model.rawId === 'glm-5.3',
508 )?.factSources
509
510 expect(sources?.pricing).toMatchObject({
511 derivation: 'docs-derived',
512 sourceUrl: ZAI_PRICING_URL,
513 })
514 expect(sources?.contextWindow).toMatchObject({
515 derivation: 'docs-derived',
516 sourceUrl: ZAI_OVERVIEW_URL,
517 })
518 expect(sources?.reasoning).toMatchObject({
519 derivation: 'docs-derived',
520 sourceUrl: ZAI_THINKING_URL,
521 })
522 expect(sources?.maxOutput).toMatchObject({
523 derivation: 'upstream-spec',
524 sourceUrl: ZAI_OPENAPI_URL,
525 path: 'max_tokens',
526 })
527 expect(sources?.modalities).toMatchObject({
528 derivation: 'upstream-spec',
529 sourceUrl: ZAI_OPENAPI_URL,
530 })
531 expect(sources?.maxOutput?.sourceHash).toMatch(/^[0-9a-f]{64}$/)
532 expect(sources?.capabilities?.tools).toMatchObject({
533 derivation: 'upstream-spec',
534 sourceUrl: ZAI_OPENAPI_URL,
535 endpointId: 'paas/v4/chat/completions',
536 path: '/properties/tools',
537 })
538 // The thinking page does not name FlashX; its request variant's own
539 // `reasoning_effort` enum is the same list.
540 expect(
541 models.find((model) => model.rawId === 'glm-5.3-flashx')?.factSources
542 ?.reasoning,
543 ).toMatchObject({
544 derivation: 'upstream-spec',
545 sourceUrl: ZAI_OPENAPI_URL,
546 path: 'reasoning_effort',
547 })
548 expect(
549 models.find((model) => model.rawId === 'glm-ocr')?.factSources,
550 ).toBeUndefined()
551 })
552
553 it('lists only the flags the spec gives each model', async () => {
554 serve(DOCS)
555 const { models } = await provider.listModels({})
556 const flags = (id: string) => {
557 const model = models.find((row) => row.rawId === id)
558 expect(model?.exactCapabilities).toBe(true)
559 return [...(model?.capabilities as Array<string>)].sort()
560 }
561 const base = ['max_tokens', 'temperature']
562
563 expect(flags('glm-5.3')).toEqual(
564 [
565 ...base,
566 'reasoning',
567 'reasoning_effort',
568 'response_format',
569 'tool_choice',
570 'tools',
571 ].sort(),
572 )
573 // `reasoning_effort` is "supported by GLM-5.2 and above".
574 expect(flags('glm-5')).toEqual(
575 [...base, 'reasoning', 'response_format', 'tool_choice', 'tools'].sort(),
576 )
577 // `thinking` is "GLM-4.5 series and higher".
578 expect(flags('glm-4-32b-0414-128k')).toEqual(
579 [...base, 'response_format', 'tool_choice', 'tools'].sort(),
580 )
581 // The vision request has no `response_format`.
582 expect(flags('glm-5.3-flashx')).toEqual(
583 [...base, 'reasoning', 'reasoning_effort', 'tool_choice', 'tools'].sort(),
584 )
585 // No effort list names glm-4.6v, whatever enum its variant carries.
586 expect(flags('glm-4.6v')).toEqual(
587 [...base, 'reasoning', 'tool_choice', 'tools'].sort(),
588 )
589 // Vision `tools` names the series it is supported by; not glm-4.5v.
590 expect(flags('glm-4.5v')).toEqual([...base, 'reasoning'].sort())
591 expect(
592 models.find((row) => row.rawId === 'glm-image')?.capabilities,
593 ).toBeUndefined()
594 })
595
596 it('throws on a 200 that is a web page', async () => {
597 serve({
598 ...DOCS,
599 [ZAI_OVERVIEW_URL]: '<!DOCTYPE html><html><body>Not found</body></html>',
600 })
601 await expect(provider.listModels({})).rejects.toThrow(/returned HTML/)
602 })
603})
604
605describe('zai parsers fail closed', () => {
606 it('reads each output cap with its own models', () => {
607 expect(parseZaiOutputCaps(VISION_MAX_TOKENS)).toEqual([
608 { names: ['glm-5.3-flash'], series: true, tokens: 128_000 },
609 { names: ['glm-4.6v'], series: true, tokens: 32_000 },
610 { names: ['glm-4.5v'], series: true, tokens: 16_000 },
611 { names: ['autoglm-phone-multilingual'], series: false, tokens: 4_000 },
612 ])
613 })
614
615 it('throws on a reworded output cap', () => {
616 // Without the throw, glm-4.5 would take the next clause's 32K.
617 expect(() =>
618 parseZaiOutputCaps(
619 TEXT_MAX_TOKENS.replace(
620 'supports 96K maximum output',
621 'supports up to 96K of output',
622 ),
623 ),
624 ).toThrow(/unreadable output cap/)
625 // A clause with another verb must not take the next clause's cap:
626 // unguarded, the 128K series would be stored as 96K ...
627 expect(() =>
628 parseZaiOutputCaps(
629 TEXT_MAX_TOKENS.replace(
630 'GLM-4.6 series supports 128K maximum output',
631 'GLM-4.6 series allows up to 128K of output',
632 ),
633 ),
634 ).toThrow(/unreadable output cap/)
635 // ... and glm-4.6v as 16K.
636 expect(() =>
637 zaiSpecFacts(
638 spec({
639 visionMaxTokens: VISION_MAX_TOKENS.replace(
640 'the GLM-4.6V series supports 32K',
641 'the GLM-4.6V series can output 32K',
642 ),
643 }),
644 ),
645 ).toThrow(/unreadable output cap/)
646 // The last clause has no next one to fall into; it is left over.
647 expect(() =>
648 parseZaiOutputCaps(
649 VISION_MAX_TOKENS.replace(
650 'autoglm-phone-multilingual supports 4K',
651 'autoglm-phone-multilingual is capped at 4K',
652 ),
653 ),
654 ).toThrow(/model with no output cap/)
655 expect(() =>
656 parseZaiOutputCaps('The maximum number of tokens for model output.'),
657 ).toThrow(/states no output cap/)
658 expect(() =>
659 zaiSpecFacts(spec({ textMaxTokens: 'Up to 128K for every model.' })),
660 ).toThrow(/states no output cap/)
661 })
662
663 it('drops a flag whose "supported by" clause it cannot read', () => {
664 expect(zaiSupportedBy('A list of tools. A max of 128.', 'glm-5')).toBeNull()
665 expect(
666 zaiSupportedBy('Only supported by GLM-4.5 series and higher.', 'glm-5'),
667 ).toBe(true)
668 expect(
669 zaiSupportedBy('Only supported by GLM-4.5 series and higher.', 'glm-4'),
670 ).toBe(false)
671
672 const reasoning = (thinking: string, id: string) =>
673 Object.keys(
674 zaiSpecFacts(spec({ thinking })).get(id)?.capabilities ?? {},
675 ).includes('reasoning')
676 // Reworded floor: nobody keeps the flag.
677 expect(
678 reasoning('Only supported by models newer than GLM-4.5.', 'glm-5.3'),
679 ).toBe(false)
680 expect(
681 reasoning('Only supported by GLM-4.5 or GLM-5 on request.', 'glm-5'),
682 ).toBe(false)
683
684 const tools = Object.keys(
685 zaiSpecFacts(
686 spec({ visionTools: 'Only supported by most GLM-4.6V models.' }),
687 ).get('glm-4.6v')?.capabilities ?? {},
688 )
689 expect(tools).not.toContain('tools')
690 expect(tools).not.toContain('tool_choice')
691 })
692
693 it('throws on a content part it does not know', () => {
694 expect(() =>
695 zaiSpecFacts(spec({ parts: ['text', 'image_url', 'hologram_url'] })),
696 ).toThrow(/unknown message content part: hologram_url/)
697 })
698
699 it('throws when the chat request lists no model ids', () => {
700 const document = spec()
701 document.components.schemas.ChatCompletionTextRequest.properties.model.enum =
702 []
703 document.components.schemas.ChatCompletionVisionRequest.properties.model.enum =
704 []
705 expect(() => zaiSpecFacts(document)).toThrow(/lists no model ids/)
706 })
707
708 it('throws on a context cell that is not a token count', () => {
709 expect(() =>
710 parseZaiContextWindows(OVERVIEW.replace('| 200K |', '| up to 200K |')),
711 ).toThrow(/unreadable context window for GLM-5/)
712 expect(() =>
713 parseZaiContextWindows(OVERVIEW.replaceAll('Context', 'Window')),
714 ).toThrow(/no context windows/)
715 })
716
717 it('reads who cannot turn thinking off from the switch itself', () => {
718 expect(parseZaiThinkingSwitch(THINKING_TYPE)).toEqual({
719 names: ['glm-5.3', 'glm-5.3-flash'],
720 series: true,
721 })
722 })
723
724 it('stores a toggle that cannot be turned off as mandatory', async () => {
725 // A model the description locks, with no effort list of its own.
726 serve({
727 ...DOCS,
728 [ZAI_OPENAPI_URL]: JSON.stringify(
729 spec({
730 thinkingType: {
731 ...THINKING_TYPE,
732 description: THINKING_TYPE.description.replace(
733 '`GLM-5.3` `GLM-5.3-FLASH` series',
734 '`GLM-5.3` `GLM-5.3-FLASH` `GLM-4.7` series',
735 ),
736 },
737 }),
738 ),
739 })
740 const { models } = await provider.listModels({})
741 const reasoning = (id: string) =>
742 models.find((model) => model.rawId === id)?.reasoning
743 expect(reasoning('glm-4.7-flash')).toEqual({
744 mode: 'toggle',
745 mandatory: true,
746 })
747 expect(reasoning('glm-5')).toEqual({ mode: 'toggle', mandatory: false })
748 // An effort row keeps its own reading.
749 expect(reasoning('glm-5.3')?.mode).toBe('effort')
750 })
751
752 it('throws on a thinking.type switch it cannot read', async () => {
753 const reworded = [
754 // The sentence that says who may send `disabled` is gone.
755 {
756 ...THINKING_TYPE,
757 description: 'Whether to enable the chain of thought',
758 },
759 {
760 ...THINKING_TYPE,
761 description: THINKING_TYPE.description.replace(
762 'series can only be enabled',
763 'series always think',
764 ),
765 },
766 {
767 ...THINKING_TYPE,
768 description: THINKING_TYPE.description.replace(
769 'for other models, when enabled',
770 'other models cannot be disabled either',
771 ),
772 },
773 // The locked list is not a plain list of models.
774 {
775 ...THINKING_TYPE,
776 description: THINKING_TYPE.description.replace(
777 '`GLM-5.3` `GLM-5.3-FLASH` series',
778 'every model except `GLM-4.5` series',
779 ),
780 },
781 // A third position is not an on/off switch.
782 { ...THINKING_TYPE, enum: ['enabled', 'disabled', 'auto'] },
783 { ...THINKING_TYPE, enum: ['enabled'] },
784 { type: 'string' },
785 ]
786 for (const thinkingType of reworded) {
787 expect(() => parseZaiThinkingSwitch(thinkingType)).toThrow(
788 /unreadable thinking.type switch/,
789 )
790 serve({
791 ...DOCS,
792 [ZAI_OPENAPI_URL]: JSON.stringify(spec({ thinkingType })),
793 })
794 await expect(provider.listModels({})).rejects.toThrow(
795 /unreadable thinking.type switch/,
796 )
797 }
798 })
799
800 it('throws on a reworded reasoning_effort list', () => {
801 expect(() =>
802 parseZaiReasoning(
803 THINKING.replace(
804 'For GLM-5.2, the supported options are',
805 'GLM-5.2 takes',
806 ),
807 ),
808 ).toThrow(/unreadable reasoning_effort line/)
809 expect(() =>
810 parseZaiReasoning(THINKING.replace('In the API request:', 'API:')),
811 ).toThrow(/no API reasoning_effort list/)
812 })
813})
814
815it('sources GLM replay from the native thinking-mode guide and rejects malformed guides', async () => {
816 serve(DOCS)
817 const model = (await provider.listModels({})).models.find(
818 (row) => row.rawId === 'glm-5.2',
819 )
820 expect(model?.requestMap?.replayReasoningContent).toBe(true)
821 expect(model?.factSources?.requestMap?.sourceUrl).toBe(ZAI_THINKING_MODE_URL)
822 serve({
823 ...DOCS,
824 [ZAI_THINKING_MODE_URL]:
825 '# Thinking Mode\nThe response contains reasoning_content.',
826 })
827 await expect(provider.listModels({})).rejects.toThrow(/no verified replay/)
828})