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

grok.ts

570 lines19.0 KB

1/**
2 * xAI Grok — first-party OpenAPI 3.1 spec at docs.x.ai/openapi.json
3 * (public). Provider id `grok` matches the @tanstack/ai-grok adapter even
4 * though xAI titles the spec "xAI's REST API".
5 */
6import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
7import type { RateCard, UnitCardSpec } from '@modelschemas/rate-card'
8​
9import type { Activity } from '#/db/schema.ts'
10import { bearerConnect } from './connect.ts'
11import {
12 displayNameFromRawId,
13 grokGenerationEndpointId,
14 grokModelActivity,
15} from './model-meta.ts'
16import {
17 NO_FACTS,
18 assertParsed,
19 cachedDocs,
20 mapConcurrent,
21 markdownSection,
22 markdownTableRows,
23 tokenCount,
24} from './model-facts.ts'
25import type { ModelFacts } from './model-facts.ts'
26import { fetchJson, fetchText, sha256Text, skippedResult } from './types.ts'
27import type {
28 ListModelsResult,
29 ModelReasoning,
30 OpenApiDocument,
31 ProviderConfig,
32 ProviderSecrets,
33 SpecFetchResult,
34} from './types.ts'
35​
36const GROK_OPENAPI_URL = 'https://docs.x.ai/openapi.json'
37const GROK_MODELS_URL = 'https://api.x.ai/v1/models'
38/**
39 * First-party extras: per-family model endpoints carry modalities (and
40 * prices — a separate PR). Context windows are only in the docs, served
41 * as markdown with a `| Model | Context | … |` table.
42 */
43const GROK_LANGUAGE_MODELS_URL = 'https://api.x.ai/v1/language-models'
44const GROK_IMAGE_MODELS_URL = 'https://api.x.ai/v1/image-generation-models'
45const GROK_VIDEO_MODELS_URL = 'https://api.x.ai/v1/video-generation-models'
46export const GROK_DOCS_MODELS_URL = 'https://docs.x.ai/docs/models.md'
47const GROK_MODEL_PAGE = (id: string) =>
48 `https://docs.x.ai/developers/models/${id}.md`
49​
50/**
51 * A model page's Capabilities bullets: `**Reasoning:** Yes` and
52 * `**Reasoning efforts (supported):** `low`, …`. Reasoning is optional only
53 * when `none` is listed; a reasoning model whose page names no efforts has
54 * no documented knob and stays null. xAI documents no per-model tool list.
55 */
56export function parseGrokReasoning(markdown: string): ModelReasoning | null {
57 const caps = markdownSection(markdown, 'Capabilities')
58 if (!/\*\*Reasoning:\*\*\s*Yes/.test(caps)) return null
59 const line = caps.match(/\*\*Reasoning efforts \(supported\):\*\*(.+)/)?.[1]
60 const efforts = [...(line ?? '').matchAll(/`([a-z]+)`/g)].flatMap((m) =>
61 m[1] ? [m[1]] : [],
62 )
63 if (efforts.length === 0) return null
64 return { mode: 'effort', mandatory: !efforts.includes('none'), efforts }
66​
67/**
68 * Reasoning is on, but the page names no effort list. The object stays
69 * null; callers record `path: 'silent'` instead of guessing a mode.
70 */
71export function grokReasoningGap(markdown: string): 'silent' | null {
72 if (parseGrokReasoning(markdown)) return null
73 return grokReasons(markdown) ? 'silent' : null
75​
76/** `**Reasoning:** Yes` in the Capabilities bullets, efforts or not. */
77export function grokReasons(markdown: string): boolean {
78 return /\*\*Reasoning:\*\*\s*Yes/.test(
79 markdownSection(markdown, 'Capabilities'),
80 )
82​
83/**
84 * A numeric generation cap from the model page. "No text output limit"
85 * and price rows ("Output | $6.00") are not caps.
86 */
87export function parseGrokMaxOutput(markdown: string): number | null {
88 const labeled = markdown.match(
89 /\*\*(?:Max(?:imum)? output(?: tokens)?|Output limit):\*\*\s*([^\n]+)/i,
90 )?.[1]
91 if (labeled) return grokOutputLimit(labeled)
92 for (const row of markdownTableRows(markdown)) {
93 const label = row[0]?.trim() ?? ''
94 const value = row[1]?.trim() ?? ''
95 if (/^(?:max(?:imum)? output(?: tokens)?|output limit)$/i.test(label)) {
96 return grokOutputLimit(value)
97 }
98 }
99 return null
101​
102function grokOutputLimit(text: string): number | null {
103 if (!/\d/.test(text) || /\bno\b/i.test(text) || text.includes('$')) {
104 return null
105 }
106 return tokenCount(text)
108​
109/** Listing fields that state an output cap. Absent on the live table. */
110function listingMaxOutput(m: GrokExtrasModel): number | null {
111 for (const key of [
112 'max_output_tokens',
113 'max_completion_tokens',
114 'max_output',
115 ]) {
116 const value = m[key]
117 if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
118 return value
119 }
120 }
121 return null
123​
124/**
125 * xAI publishes no per-model tool type list (issue #123). A capabilities
126 * page that mentions search still does not name `tools[].type` ids.
127 */
128export function grokServerTools(_markdown: string): null {
129 return null
131​
132/**
133 * xAI tags every operation `v1`, so classify by path. The text-generation
134 * surface spans the OpenAI-compatible endpoints (chat/completions,
135 * completions, responses) and the Anthropic-compatible ones (messages,
136 * complete). Files and document search are platform endpoints.
137 */
138function classify(path: string): Activity | null {
139 if (
140 path === '/v1/chat/completions' ||
141 path === '/v1/completions' ||
142 path === '/v1/complete' ||
143 path === '/v1/messages' ||
144 path === '/v1/responses' ||
145 path === '/v1/tokenize-text'
146 ) {
147 return 'chat'
148 }
149 if (path.startsWith('/v1/images/')) return 'image'
150 if (path.startsWith('/v1/videos/')) return 'video'
151 if (path === '/v1/embeddings') return 'embeddings'
152 return null
154​
155async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
156 const text = await fetchText(GROK_OPENAPI_URL)
157 const spec = JSON.parse(text) as OpenApiDocument
158 return {
159 specs: [withGrokImageQuality(spec)],
160 sources: [{ url: GROK_OPENAPI_URL, hash: await sha256Text(text) }],
161 outputStrategy: 'post-200',
162 }
164​
165interface GrokModelList {
166 data?: Array<{ id: string; created?: number }>
168​
169interface GrokExtrasModel {
170 id: string
171 aliases?: Array<string>
172 input_modalities?: Array<string>
173 output_modalities?: Array<string>
174 long_context_threshold?: number
175 [price: string]: unknown
177​
178/**
179 * xAI quotes every price as an integer in units of 1e-10 USD per token
180 * (`prompt_text_token_price: 12500` is $1.25 / 1M tokens, the rate its
181 * docs table publishes). `*_long_context` fields re-quote the whole
182 * request once the prompt reaches `long_context_threshold`.
183 */
184const XAI_PRICE_UNIT = 1e-10
185​
186const GROK_PRICE_LEVERS: Record<string, string> = {
187 prompt_text_token_price: 'input_tokens',
188 cached_prompt_text_token_price: 'cache_read_tokens',
189 prompt_image_token_price: 'image_tokens',
190 completion_text_token_price: 'output_tokens',
191 search_price: 'web_searches',
193​
194function grokRates(m: GrokExtrasModel, suffix = ''): Record<string, number> {
195 const rates: Record<string, number> = {}
196 for (const [field, lever] of Object.entries(GROK_PRICE_LEVERS)) {
197 const value = m[`${field}${suffix}`]
198 if (typeof value === 'number') rates[lever] = value * XAI_PRICE_UNIT
199 }
200 return rates
202​
203/**
204 * `quality` is a documented `/v1/images/generations` field that
205 * docs.x.ai/openapi.json omits: the image generation guide names `low`,
206 * `medium`, and `auto`, and xai-sdk-ts adds it to `ImageGenerateParams`
207 * by hand (src/types.ts `ImageRequestFields`). Add it so the bound schema
208 * admits what the API accepts and the image card's lever is a request
209 * field.
210 */
211const GROK_IMAGE_QUALITY = {
212 type: ['string', 'null'],
213 enum: ['low', 'medium', 'auto'],
214 description:
215 'Generation quality. Defaults to `auto`, which serves `low` for generation and `medium` for editing; images are billed at the quality served. Only supported by grok-imagine-image-2.0. Documented in the image generation guide and the official TypeScript SDK, absent from docs.x.ai/openapi.json.',
217​
218export function withGrokImageQuality(spec: OpenApiDocument): OpenApiDocument {
219 for (const name of ['GenerateImageRequest', 'EditImageRequest']) {
220 const schema = spec.components?.schemas?.[name] as
221 | { properties?: Record<string, unknown> }
222 | undefined
223 const properties = schema?.properties
224 if (properties && !('quality' in properties)) {
225 properties.quality = GROK_IMAGE_QUALITY
226 }
227 }
228 return spec
230​
231/**
232 * Image-card levers, outermost first, with the request default. `auto` is
233 * the `quality` default; the guide says it serves `low` for generation,
234 * and the pricing page's $0.04 for grok-imagine-image-2.0 is the low/1k
235 * cell. Images are billed at the quality served.
236 */
237const GROK_IMAGE_KEYS = [
238 { param: 'quality', default: 'auto' },
239 { param: 'resolution', default: '1k' },
241​
242type GrokImageTier = { price_per_image: number } & Record<string, unknown>
243​
244/**
245 * The listing's (quality, resolution) matrix. `undefined` when there is
246 * none; `null` when a tier names a dimension the request cannot state, in
247 * which case the flat `image_price` is one cell, not a rate.
248 */
249function grokImageTiers(
250 m: GrokExtrasModel,
251): Array<GrokImageTier> | null | undefined {
252 const matrix: unknown = m.pricing
253 if (!Array.isArray(matrix)) return undefined
254 const tiers: Array<GrokImageTier> = []
255 for (const tier of matrix) {
256 if (typeof tier !== 'object' || tier === null || Array.isArray(tier)) {
257 return null
258 }
259 const { price_per_image, ...dims } = tier as Record<string, unknown>
260 if (typeof price_per_image !== 'number') return null
261 for (const dim of Object.keys(dims)) {
262 if (!GROK_IMAGE_KEYS.some((key) => key.param === dim)) return null
263 }
264 tiers.push({ price_per_image, ...dims })
265 }
266 return tiers
268​
269/**
270 * Per-image card from the model metadata: the (quality, resolution) matrix
271 * when the listing publishes one, else the flat `image_price`.
272 */
273export async function grokImageCard(
274 m: GrokExtrasModel,
275): Promise<RateCard | null> {
276 // `n` defaults to 1 on the request, as it does here.
277 const quantity = { param: 'n', bound: 'request' as const, default: 1 }
278 const source = async (payload: unknown) => ({
279 url: GROK_IMAGE_MODELS_URL,
280 hash: await sha256Text(JSON.stringify(payload)),
281 extractedAt: new Date().toISOString(),
282 })
283 const tiers = grokImageTiers(m)
284 if (tiers === null) return null
285 if (tiers === undefined) {
286 const flat = m.image_price
287 if (typeof flat !== 'number') return null
288 return compileUnitCard(
289 { quantity, rates: flat * XAI_PRICE_UNIT },
290 await source({ image_price: flat }),
291 )
292 }
293 const dims = GROK_IMAGE_KEYS.filter((key) =>
294 tiers.some((tier) => key.param in tier),
295 )
296 const rates: Record<string, unknown> = {}
297 for (const tier of tiers) {
298 let node = rates
299 for (const [i, dim] of dims.entries()) {
300 const value = tier[dim.param]
301 if (typeof value !== 'string') return null
302 if (i === dims.length - 1) {
303 node[value] = tier.price_per_image * XAI_PRICE_UNIT
304 } else {
305 node = (node[value] ??= {}) as Record<string, unknown>
306 }
307 }
308 }
309 if (dims[0]?.param === 'quality' && rates.low !== undefined) {
310 rates.auto ??= rates.low
311 }
312 const keys = dims.map((dim) => {
313 const values = [
314 ...new Set(tiers.map((tier) => String(tier[dim.param]))),
315 ...(dim.param === 'quality' && rates.auto !== undefined ? ['auto'] : []),
316 ]
317 return {
318 param: dim.param,
319 bound: 'request' as const,
320 values,
321 ...(values.includes(dim.default) && { default: dim.default }),
322 }
323 })
324 return compileUnitCard(
325 { quantity, keys, rates: rates as UnitCardSpec['rates'] },
326 await source({ pricing: tiers }),
327 )
329​
330/**
331 * Per-second video rates from the docs "Imagine Pricing" table
332 * (`| grok-imagine-video | $0.050 / sec |`). The model metadata carries no
333 * price for video models.
334 */
335export function parseGrokVideoPrices(markdown: string): Map<string, number> {
336 const out = new Map<string, number>()
337 for (const [model = '', cost = ''] of markdownTableRows(markdown)) {
338 const rate = cost.match(/^\$([\d.]+)\s*\/\s*sec(ond)?$/)?.[1]
339 if (!/^grok-/.test(model) || rate === undefined) continue
340 if (!out.has(model)) out.set(model, Number(rate))
341 }
342 return out
344​
345/** Per-second card for a video model the docs table prices. */
346export async function grokVideoCard(
347 perSecond: number | undefined,
348): Promise<RateCard | null> {
349 if (perSecond === undefined) return null
350 return compileUnitCard(
351 { quantity: { param: 'duration', bound: 'request' }, rates: perSecond },
352 {
353 url: GROK_DOCS_MODELS_URL,
354 hash: await sha256Text(JSON.stringify({ perSecond })),
355 extractedAt: new Date().toISOString(),
356 },
357 )
359​
360/** Per-model token card from the first-party model metadata. */
361export async function grokRateCard(
362 m: GrokExtrasModel,
363): Promise<RateCard | null> {
364 const base = grokRates(m)
365 if (Object.keys(base).length === 0) return null
366 const long = grokRates(m, '_long_context')
367 const threshold = m.long_context_threshold
368 const tiers =
369 typeof threshold === 'number' && Object.keys(long).length > 0
370 ? // xAI bills the long-context rate at or above the threshold; the
371 // card's tiers are strictly-greater, and token counts are integers.
372 [{ minPromptTokens: threshold - 1, rates: { ...base, ...long } }]
373 : []
374 return compileTokenCard(base, tiers, {
375 url: GROK_LANGUAGE_MODELS_URL,
376 // Hashing only the priced fields keeps the stored card (and its
377 // `extractedAt`) stable across unrelated metadata edits.
378 hash: await sha256Text(
379 JSON.stringify({ base, long, threshold: threshold ?? null }),
380 ),
381 extractedAt: new Date().toISOString(),
382 })
384​
385/** Context windows keyed by model id from the docs pricing table. */
386export function parseGrokContextWindows(markdown: string): Map<string, number> {
387 const out = new Map<string, number>()
388 for (const [model = '', context = ''] of markdownTableRows(markdown)) {
389 const id = model.replace(/\s*\(.*$/, '').trim()
390 if (!/^grok-/.test(id) || !/^[\d,.]+\s*[kKmM]?$/.test(context)) continue
391 const tokens = tokenCount(context)
392 if (tokens !== null && !out.has(id)) out.set(id, tokens)
393 }
394 return out
396​
397async function grokModelFacts(
398 headers: HeadersInit,
399 kv: KVNamespace | undefined,
400): Promise<(rawId: string) => ModelFacts> {
401 const extras = (url: string) =>
402 fetchJson(url, { headers }) as Promise<{ models?: Array<GrokExtrasModel> }>
403 const [language, image, video, docs] = await Promise.all([
404 extras(GROK_LANGUAGE_MODELS_URL),
405 extras(GROK_IMAGE_MODELS_URL),
406 extras(GROK_VIDEO_MODELS_URL),
407 cachedDocs(kv, GROK_DOCS_MODELS_URL, async () => {
408 const markdown = await fetchText(GROK_DOCS_MODELS_URL)
409 const parsed = parseGrokContextWindows(markdown)
410 assertParsed(parsed, 'xai models docs')
411 return {
412 contexts: Object.fromEntries(parsed),
413 videoPerSecond: Object.fromEntries(parseGrokVideoPrices(markdown)),
414 }
415 }),
416 ])
417 const byId = new Map<string, GrokExtrasModel>()
418 for (const m of [
419 ...(language.models ?? []),
420 ...(image.models ?? []),
421 ...(video.models ?? []),
422 ]) {
423 for (const id of [m.id, ...(m.aliases ?? [])]) byId.set(id, m)
424 }
425 const pages = new Map<
426 string,
427 {
428 value: ModelReasoning | null
429 reasons?: boolean
430 maxOutput: number | null
431 hash: string
432 }
433 >()
434 await mapConcurrent(language.models ?? [], 8, async (m) => {
435 try {
436 const page = await cachedDocs(kv, GROK_MODEL_PAGE(m.id), async () => {
437 const markdown = await fetchText(GROK_MODEL_PAGE(m.id))
438 return {
439 value: parseGrokReasoning(markdown),
440 reasons: grokReasons(markdown),
441 maxOutput: parseGrokMaxOutput(markdown),
442 hash: await sha256Text(markdown),
443 }
444 })
445 if (!page.value && !page.reasons && page.maxOutput == null) return
446 for (const id of [m.id, ...(m.aliases ?? [])]) pages.set(id, page)
447 } catch {
448 // A missing page leaves reasoning and maxOutput unknown, never a guess.
449 }
450 })
451 const cards = new Map<string, RateCard | null>()
452 for (const m of language.models ?? []) {
453 const card = await grokRateCard(m)
454 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
455 }
456 for (const m of image.models ?? []) {
457 const card = await grokImageCard(m)
458 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
459 }
460 for (const m of video.models ?? []) {
461 const card = await grokVideoCard(docs.videoPerSecond[m.id])
462 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
463 }
464 return (rawId) => {
465 const m = byId.get(rawId)
466 if (!m) return NO_FACTS
467 const contextWindow = docs.contexts[rawId] ?? null
468 const modalities = m.input_modalities
469 ? { input: m.input_modalities, output: m.output_modalities ?? [] }
470 : null
471 const page = pages.get(rawId)
472 const reasons = page?.reasons === true
473 const listedMax = listingMaxOutput(m)
474 const facts: ModelFacts = {
475 contextWindow,
476 // The spec's 128k figure is a default, not a cap. Only a number the
477 // listing or the model page states is an output limit.
478 maxOutput: listedMax ?? page?.maxOutput ?? null,
479 modalities,
480 // Request-feature flags come from the bound schema; the per-model
481 // docs page adds `reasoning`, which no request property names.
482 capabilities: reasons ? ['reasoning'] : null,
483 pricing: cards.get(rawId) ?? null,
484 reasoning: page?.value ?? null,
485 }
486 const sources: ModelFacts['factSources'] = {}
487 if (contextWindow != null) {
488 sources.contextWindow = {
489 derivation: 'docs-derived',
490 sourceUrl: GROK_DOCS_MODELS_URL,
491 path: 'contextWindow',
492 }
493 }
494 if (listedMax != null) {
495 sources.maxOutput = { derivation: 'listing', path: 'maxOutput' }
496 } else if (page?.maxOutput != null) {
497 sources.maxOutput = {
498 derivation: 'docs-derived',
499 sourceUrl: GROK_MODEL_PAGE(m.id),
500 sourceHash: page.hash,
501 path: 'maxOutput',
502 }
503 }
504 if (page?.value) {
505 sources.reasoning = {
506 derivation: 'docs-derived',
507 sourceUrl: GROK_MODEL_PAGE(m.id),
508 sourceHash: page.hash,
509 path: 'Capabilities',
510 }
511 } else if (page?.reasons) {
512 sources.reasoning = {
513 derivation: 'docs-derived',
514 sourceUrl: GROK_MODEL_PAGE(m.id),
515 sourceHash: page.hash,
516 path: 'silent',
517 }
518 }
519 if (reasons) {
520 sources.capabilities = {
521 reasoning: {
522 derivation: 'docs-derived',
523 sourceUrl: GROK_MODEL_PAGE(m.id),
524 sourceHash: page.hash,
525 path: 'Capabilities.Reasoning',
526 },
527 }
528 }
529 if (Object.keys(sources).length > 0) facts.factSources = sources
530 return facts
531 }
533​
534async function listModels(
535 env: ProviderSecrets,
536 kv?: KVNamespace,
537): Promise<ListModelsResult> {
538 const key = env.XAI_API_KEY
539 if (!key) {
540 return { models: [], ...skippedResult('grok', 'XAI_API_KEY') }
541 }
542 const headers = { Authorization: `Bearer ${key}` }
543 const [body, facts] = await Promise.all([
544 fetchJson(GROK_MODELS_URL, { headers }) as Promise<GrokModelList>,
545 grokModelFacts(headers, kv),
546 ])
547 return {
548 models: (body.data ?? []).map((m) => ({
549 rawId: m.id,
550 displayName: displayNameFromRawId(m.id),
551 activity: grokModelActivity(m.id),
552 releasedAt: m.created ?? null,
553 ...facts(m.id),
554 })),
555 }
557​
558export const grokProvider: ProviderConfig = {
559 id: 'grok',
560 modelNamespaces: ['xai', 'x-ai'],
561 displayName: 'xAI Grok',
562 authEnvVar: 'XAI_API_KEY',
563 defaultDerivation: 'upstream-spec',
564 specGrain: 'provider',
565 connect: bearerConnect('https://api.x.ai'),
566 fetchSpec,
567 listModels,
568 classify,
569 generationEndpointId: ({ activity }) => grokGenerationEndpointId(activity),