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