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

text.ts

251 lines9.0 KB

1import OpenAI from 'openai'
2import {
3 OpenAIBaseResponsesTextAdapter,
4 warnStrictFallback,
5} from '@tanstack/openai-base'
6import { validateTextProviderOptions } from '../text/text-provider-options'
7import { convertToolsToProviderFormat } from '../tools'
8import { getOpenAIApiKeyFromEnv } from '../utils/client'
9import { openAIModelRejectsSamplingParams } from '../model-meta'
10import type {
11 OPENAI_CHAT_MODELS,
12 OpenAIChatModel,
13 OpenAIChatModelProviderOptionsByName,
14 OpenAIChatModelToolCapabilitiesByName,
15 OpenAIModelInputModalitiesByName,
16} from '../model-meta'
17import type { ResponseCreateParams } from 'openai/resources/responses/responses'
18import type { Modality, TextOptions } from '@tanstack/ai'
19import type {
20 ExternalTextProviderOptions,
21 InternalTextProviderOptions,
22} from '../text/text-provider-options'
23import type { OpenAIMessageMetadataByModality } from '../message-types'
24import type { OpenAIClientConfig } from '../utils/client'
25import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
26​
27/**
28 * Configuration for OpenAI text adapter
29 */
30export interface OpenAITextConfig
31 extends OpenAIClientConfig, OpenAIBaseTextAdapterOptions {}
32​
33/**
34 * Alias for TextProviderOptions
35 */
36export type OpenAITextProviderOptions = ExternalTextProviderOptions
37​
38// ===========================
39// Type Resolution Helpers
40// ===========================
41​
42/**
43 * Resolve provider options for a specific model.
44 * If the model has explicit options in the map, use those; otherwise use base options.
45 */
46type ResolveProviderOptions<TModel extends string> =
47 TModel extends keyof OpenAIChatModelProviderOptionsByName
48 ? OpenAIChatModelProviderOptionsByName[TModel]
49 : OpenAITextProviderOptions
50​
51/**
52 * Resolve input modalities for a specific model.
53 * If the model has explicit modalities in the map, use those; otherwise use all modalities.
54 */
55type ResolveInputModalities<TModel extends string> =
56 TModel extends keyof OpenAIModelInputModalitiesByName
57 ? OpenAIModelInputModalitiesByName[TModel]
58 : readonly ['text', 'image', 'audio']
59​
60/**
61 * Resolve tool capabilities for a specific model.
62 * If the model has explicit tools in the map, use those; otherwise use empty tuple.
63 */
64type ResolveToolCapabilities<TModel extends string> =
65 TModel extends keyof OpenAIChatModelToolCapabilitiesByName
66 ? NonNullable<OpenAIChatModelToolCapabilitiesByName[TModel]>
67 : readonly []
68​
69// ===========================
70// Adapter Implementation
71// ===========================
72​
73/**
74 * OpenAI Text (Chat) Adapter
75 *
76 * Tree-shakeable adapter for OpenAI chat/text completion functionality.
77 * Delegates implementation to {@link OpenAIBaseResponsesTextAdapter} from
78 * `@tanstack/openai-base`. The base calls `openai.responses.create`
79 * directly; this subclass just hands it a configured client and overrides
80 * `mapOptionsToRequest` to route through OpenAI's full tool converter
81 * (supporting file_search, web_search, etc.) and to apply provider option
82 * validation.
83 */
84export class OpenAITextAdapter<
85 TModel extends OpenAIChatModel,
86 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
87 TInputModalities extends ReadonlyArray<Modality> =
88 ResolveInputModalities<TModel>,
89 TToolCapabilities extends ReadonlyArray<string> =
90 ResolveToolCapabilities<TModel>,
91> extends OpenAIBaseResponsesTextAdapter<
92 TModel,
93 TProviderOptions,
94 TInputModalities,
95 OpenAIMessageMetadataByModality,
96 TToolCapabilities
97> {
98 override readonly kind = 'text' as const
99 override readonly name = 'openai' as const
100 // OpenAI's Responses endpoint consumes `file_id` references issued by its
101 // Files API (`openaiFiles()`). The default is undefined (unsupported) so
102 // compatible subclasses of the openai-base adapter (Grok, Bedrock, custom)
103 // — which have no such surface — fail closed in preflight.
104 override readonly supportsFileSources = true
105​
106 constructor(config: OpenAITextConfig, model: TModel) {
107 super(model, 'openai', new OpenAI(config), config)
108 }
109​
110 /**
111 * Maps common options to OpenAI-specific format.
112 * Overrides the base class to use OpenAI's full tool converter
113 * (supporting special tool types like file_search, web_search, etc.)
114 * and to apply OpenAI-specific provider option validation.
115 */
116 protected override mapOptionsToRequest(
117 options: TextOptions<TProviderOptions>,
118 ): Omit<ResponseCreateParams, 'stream'> {
119 // The structural type the validator expects is broader than what
120 // `TProviderOptions` is bound to per-model, so narrow via the internal
121 // shape rather than re-exposing it on the public override signature.
122 const modelOptions = options.modelOptions as
123 | InternalTextProviderOptions
124 | undefined
125 if (modelOptions) {
126 validateTextProviderOptions({
127 ...modelOptions,
128 input: this.convertMessagesToInput(options.messages),
129 model: options.model,
130 })
131 }
132​
133 // Delegate to the base for input mapping, system prompts, modelOptions
134 // precedence, and native combined-mode `text.format` wiring (#605). We
135 // hand it a tools-less view of `options` so the base doesn't run its
136 // narrower tool converter — we re-run them through OpenAI's full
137 // converter (file_search, web_search, etc.) and layer the result on top.
138 const { tools: _baseTools, ...baseRequest } = super.mapOptionsToRequest({
139 ...options,
140 tools: undefined,
141 })
142​
143 if (this.strictFallbackWarning) {
144 warnStrictFallback(options.tools, options.logger)
145 }
146 const tools = options.tools
147 ? convertToolsToProviderFormat(options.tools)
148 : undefined
149​
150 const request: Omit<ResponseCreateParams, 'stream'> = {
151 ...baseRequest,
152 ...(tools && tools.length > 0 && { tools }),
153 }
154​
155 // Reasoning models 400 on `temperature`/`top_p`. Callers (and the summarize
156 // adapter's low-temperature default) can't know a given model rejects them,
157 // so drop the pair here — stripping only ever averts a guaranteed 400, never
158 // changes an otherwise-valid request.
159 if (openAIModelRejectsSamplingParams(options.model)) {
160 delete request.temperature
161 delete request.top_p
162 }
163​
164 // Reasoning models pair each function_call with a reasoning item. Request
165 // the encrypted blob so convertMessagesToInput can replay it. Pre-5 chat
166 // models do not emit those items, so leave include unset for them.
167 // Callers can still set include in modelOptions.
168 if (
169 request.include === undefined &&
170 openAIModelRejectsSamplingParams(options.model)
171 ) {
172 request.include = ['reasoning.encrypted_content']
173 }
174​
175 // OpenAI only returns the URLs used by a hosted web search when this
176 // response item is included. Preserve caller entries and add the item for
177 // branded web search tools only. A custom function named `web_search` has
178 // no internal provider-tool discriminator and must not change the request.
179 const hasWebSearchTool = options.tools?.some((tool) => {
180 const kind = tool.metadata?.['__kind']
181 return (
182 kind === 'openai.web_search' || kind === 'openai.web_search_preview'
183 )
184 })
185 if (hasWebSearchTool) {
186 const include = request.include ?? []
187 if (!include.includes('web_search_call.action.sources')) {
188 request.include = [...include, 'web_search_call.action.sources']
189 }
190 }
191​
192 return request
193 }
195​
196/**
197 * Creates an OpenAI chat adapter with explicit API key.
198 * Type resolution happens here at the call site.
199 *
200 * @param model - The model name (e.g., 'gpt-4o', 'gpt-4-turbo')
201 * @param apiKey - Your OpenAI API key
202 * @param config - Optional additional configuration
203 * @returns Configured OpenAI chat adapter instance with resolved types
204 *
205 * @example
206 * ```typescript
207 * const adapter = createOpenaiChat('gpt-4o', "sk-...");
208 * // adapter has type-safe modelOptions for gpt-4o
209 * ```
210 */
211export function createOpenaiChat<
212 TModel extends (typeof OPENAI_CHAT_MODELS)[number],
213>(
214 model: TModel,
215 apiKey: string,
216 config?: Omit<OpenAITextConfig, 'apiKey'>,
217): OpenAITextAdapter<TModel> {
218 return new OpenAITextAdapter({ apiKey, ...config }, model)
220​
221/**
222 * Creates an OpenAI text adapter with automatic API key detection from environment variables.
223 * Type resolution happens here at the call site.
224 *
225 * Looks for `OPENAI_API_KEY` in:
226 * - `process.env` (Node.js)
227 * - `window.env` (Browser with injected env)
228 *
229 * @param model - The model name (e.g., 'gpt-4o', 'gpt-4-turbo')
230 * @param config - Optional configuration (excluding apiKey which is auto-detected)
231 * @returns Configured OpenAI text adapter instance with resolved types
232 * @throws Error if OPENAI_API_KEY is not found in environment
233 *
234 * @example
235 * ```typescript
236 * // Automatically uses OPENAI_API_KEY from environment
237 * const adapter = openaiText('gpt-4o');
238 *
239 * const stream = chat({
240 * adapter,
241 * messages: [{ role: "user", content: "Hello!" }]
242 * });
243 * ```
244 */
245export function openaiText<TModel extends (typeof OPENAI_CHAT_MODELS)[number]>(
246 model: TModel,
247 config?: Omit<OpenAITextConfig, 'apiKey'>,
248): OpenAITextAdapter<TModel> {
249 const apiKey = getOpenAIApiKeyFromEnv()
250 return createOpenaiChat(model, apiKey, config)