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

text.ts

231 lines7.7 KB

1import OpenAI from 'openai'
2import { fileReferenceFor, isFileSource } from '@tanstack/ai'
3import {
4 OpenAIBaseResponsesTextAdapter,
5 toResponsesToolChoice,
6} from '@tanstack/openai-base'
7import {
8 GROK_MODEL_INPUT_MODALITIES,
9 GROK_MODEL_REASONING,
10} from '../model-meta'
11import { getGrokApiKeyFromEnv, withGrokDefaults } from '../utils/client'
12import { convertToolsToProviderFormat } from '../tools'
13import type {
14 GROK_CHAT_MODELS,
15 GrokChatModelToolCapabilitiesByName,
16 GrokModelReasoningByName,
17 GrokTextAdapterModel,
18 ResolveInputModalities,
19 ResolveProviderOptions,
20} from '../model-meta'
21import type { ContentPart, Modality, TextOptions } from '@tanstack/ai'
22import type { GrokMessageMetadataByModality } from '../message-types'
23import type { GrokClientConfig } from '../utils/client'
24import type {
25 ResponseCreateParams,
26 ResponseInputContent,
27} from 'openai/resources/responses/responses'
28​
29/**
30 * Resolve tool capabilities for a specific Grok model.
31 */
32/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
33type ResolveReasoning<TModel extends string> =
34 TModel extends keyof GrokModelReasoningByName
35 ? GrokModelReasoningByName[TModel]
36 : never
37​
38type ResolveToolCapabilities<TModel extends string> =
39 TModel extends keyof GrokChatModelToolCapabilitiesByName
40 ? NonNullable<GrokChatModelToolCapabilitiesByName[TModel]>
41 : readonly []
42​
43/**
44 * Configuration for Grok text adapter
45 */
46export interface GrokTextConfig extends GrokClientConfig {}
47​
48/**
49 * Alias for TextProviderOptions for external use
50 */
51export type { ExternalTextProviderOptions as GrokTextProviderOptions } from '../text/text-provider-options'
52​
53/**
54 * Grok Text (Chat) Adapter
55 *
56 * Tree-shakeable adapter for Grok chat/text completion functionality.
57 * Uses xAI's OpenAI-compatible Responses API.
58 *
59 * Delegates implementation to {@link OpenAIBaseResponsesTextAdapter}
60 * from `@tanstack/openai-base` and threads Grok-specific tool-capability
61 * typing through the 5th generic of the base class.
62 */
63export class GrokTextAdapter<
64 TModel extends GrokTextAdapterModel,
65 // Use `Record<string, any>` (not `unknown`) to match the OpenAI text
66 // adapter: the resolved Grok provider options are a type-alias intersection
67 // with no explicit index signature, which is assignable to
68 // `Record<string, any>` but not `Record<string, unknown>`. See issue #821.
69 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
70 TInputModalities extends ReadonlyArray<Modality> =
71 ResolveInputModalities<TModel>,
72 TToolCapabilities extends ReadonlyArray<string> =
73 ResolveToolCapabilities<TModel>,
74> extends OpenAIBaseResponsesTextAdapter<
75 TModel,
76 TProviderOptions,
77 TInputModalities,
78 GrokMessageMetadataByModality,
79 TToolCapabilities,
80 ResolveReasoning<TModel>
81> {
82 override readonly kind = 'text' as const
83 override readonly name = 'grok' as const
84 // Consumes handles issued by grokFiles(), whose wire reference is an xAI
85 // public URL. See convertContentPartToInput below for why it is a URL and
86 // not a file_id.
87 override readonly supportsFileSources = true
88 override readonly inputModalities = GROK_MODEL_INPUT_MODALITIES[this.model]
89​
90 constructor(config: GrokTextConfig, model: TModel) {
91 const options = withGrokDefaults(config)
92 super(model, 'grok', new OpenAI(options), { fetch: options.fetch })
93 }
94​
95 /**
96 * xAI has no error code for a context overflow. It answers 400 with the
97 * tag `[input_too_large]` in the error text.
98 */
99 protected override isContextOverflow(error: {
100 message: string
101 code: string | undefined
102 }): boolean {
103 return (
104 super.isContextOverflow(error) ||
105 (error.code === '400' && error.message.includes('[input_too_large]'))
106 )
107 }
108​
109 protected override modelReasoning(model: string) {
110 return GROK_MODEL_REASONING[model]
111 }
112​
113 /**
114 * Route a `{ type: 'file' }` source to xAI's URL-shaped fields rather than
115 * the `file_id` the OpenAI Responses base emits.
116 *
117 * xAI accepts `file_id` only on `input_file`, and only on agentic-capable
118 * models; its image path takes `image_url`. A `grokFiles()` handle carries
119 * an xAI public URL, which both fields accept, so one handle works for
120 * every modality on every chat model.
121 */
122 protected override convertContentPartToInput(
123 part: ContentPart,
124 ): ResponseInputContent {
125 if ('source' in part && isFileSource(part.source)) {
126 const url = fileReferenceFor(part.source, this.name)
127 if (part.type === 'image') {
128 const imageMetadata = part.metadata as
129 | { detail?: 'auto' | 'low' | 'high' }
130 | undefined
131 return {
132 type: 'input_image',
133 image_url: url,
134 detail: imageMetadata?.detail || 'auto',
135 }
136 }
137 return { type: 'input_file', file_url: url }
138 }
139 return super.convertContentPartToInput(part)
140 }
141​
142 protected override mapOptionsToRequest(
143 options: TextOptions<TProviderOptions>,
144 ): Omit<ResponseCreateParams, 'stream'> {
145 const { tools: _baseTools, ...request } = super.mapOptionsToRequest({
146 ...options,
147 tools: undefined,
148 })
149 void _baseTools
150​
151 const tools = options.tools
152 ? convertToolsToProviderFormat(options.tools)
153 : undefined
154​
155 // The base saw no tools, so it sent no `chat({ toolChoice })`. Set it
156 // here when the request has tools. It goes before `request`, so a
157 // `tool_choice` from modelOptions wins.
158 const toolChoiceField =
159 tools?.length && options.toolChoice !== undefined
160 ? { tool_choice: toResponsesToolChoice(options.toolChoice) }
161 : undefined
162​
163 return {
164 ...toolChoiceField,
165 ...request,
166 // xAI recommends encrypted reasoning for reasoning-capable Responses
167 // requests; callers can still override either field in modelOptions.
168 store: request.store ?? false,
169 include: request.include ?? ['reasoning.encrypted_content'],
170 ...(tools &&
171 tools.length > 0 && { tools: tools as ResponseCreateParams['tools'] }),
172 }
173 }
175​
176/**
177 * Creates a Grok text adapter with explicit API key.
178 * Type resolution happens here at the call site.
179 *
180 * @param model - The model name (e.g., 'grok-build-0.1')
181 * @param apiKey - Your xAI API key
182 * @param config - Optional additional configuration
183 * @returns Configured Grok text adapter instance with resolved types
184 *
185 * @example
186 * ```typescript
187 * const adapter = createGrokText('grok-build-0.1', "xai-...");
188 * // adapter has type-safe providerOptions for grok-build-0.1
189 * ```
190 */
191export function createGrokText<
192 TModel extends (typeof GROK_CHAT_MODELS)[number],
193>(
194 model: TModel,
195 apiKey: string,
196 config?: Omit<GrokTextConfig, 'apiKey'>,
197): GrokTextAdapter<TModel> {
198 return new GrokTextAdapter({ apiKey, ...config }, model)
200​
201/**
202 * Creates a Grok text adapter with automatic API key detection from environment variables.
203 * Type resolution happens here at the call site.
204 *
205 * Looks for `XAI_API_KEY` in:
206 * - `process.env` (Node.js)
207 * - `window.env` (Browser with injected env)
208 *
209 * @param model - The model name (e.g., 'grok-build-0.1')
210 * @param config - Optional configuration (excluding apiKey which is auto-detected)
211 * @returns Configured Grok text adapter instance with resolved types
212 * @throws Error if XAI_API_KEY is not found in environment
213 *
214 * @example
215 * ```typescript
216 * // Automatically uses XAI_API_KEY from environment
217 * const adapter = grokText('grok-build-0.1');
218 *
219 * const stream = chat({
220 * adapter,
221 * messages: [{ role: "user", content: "Hello!" }]
222 * });
223 * ```
224 */
225export function grokText<TModel extends (typeof GROK_CHAT_MODELS)[number]>(
226 model: TModel,
227 config?: Omit<GrokTextConfig, 'apiKey'>,
228): GrokTextAdapter<TModel> {
229 const apiKey = getGrokApiKeyFromEnv()
230 return createGrokText(model, apiKey, config)