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

text.ts

193 lines6.5 KB

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