Open History to see the last commit
1import OpenAI from 'openai'
2import { OpenAIBaseResponsesTextAdapter } from '@tanstack/openai-base'
3import { validateTextProviderOptions } from '../text/text-provider-options'
4import { convertToolsToProviderFormat } from '../tools'
5import { getOpenAIApiKeyFromEnv } from '../utils/client'
6import {
7 OPENAI_MODEL_INPUT_MODALITIES,
8 OPENAI_MODEL_MID_CONVERSATION_CHANNELS,
9 OPENAI_MODEL_REASONING,
10 openAIModelRejectsSamplingParams,
11 openAIModelUsesExplicitPromptCache,
12} from '../model-meta'
13import { responsesPromptCacheFields } from '../prompt-cache'
14import type {
15 OPENAI_CHAT_MODELS,
16 OpenAIChatModel,
17 OpenAIChatModelProviderOptionsByName,
18 OpenAIChatModelToolCapabilitiesByName,
19 OpenAIModelInputModalitiesByName,
20 OpenAIModelReasoningByName,
21} from '../model-meta'
22import type {
23 ResponseCreateParams,
24 Tool as ResponsesTool,
25} from 'openai/resources/responses/responses'
26import type {
27 AnyTool,
28 MidConversationChannels,
29 Modality,
30 ReasoningCapability,
31 TextOptions,
32} from '@tanstack/ai'
33import type {
34 ExternalTextProviderOptions,
35 InternalTextProviderOptions,
36} from '../text/text-provider-options'
37import type { OpenAIMessageMetadataByModality } from '../message-types'
38import type { OpenAIClientConfig } from '../utils/client'
39import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
40
41/**
42 * Configuration for OpenAI text adapter
43 */
44export interface OpenAITextConfig
45 extends OpenAIClientConfig, OpenAIBaseTextAdapterOptions {
46 /**
47 * The mid-conversation channels (`additional_tools` and a mid-conversation
48 * `developer` message) of the models that have them. When absent, they are
49 * on only for OpenAI's own API: a `baseURL`, a `fetch`, or the SDK's
50 * `OPENAI_BASE_URL` env var turns the default off.
51 * `true` turns them on anyway, for a gateway that passes the changes.
52 * `false` turns them off, so every request is built as before.
53 */
54 midConversationChannels?: boolean
55}
56
57/**
58 * Alias for TextProviderOptions
59 */
60export type OpenAITextProviderOptions = ExternalTextProviderOptions
61
62// ===========================
63// Type Resolution Helpers
64// ===========================
65
66/**
67 * Resolve provider options for a specific model.
68 * If the model has explicit options in the map, use those; otherwise use base options.
69 */
70type ResolveProviderOptions<TModel extends string> =
71 TModel extends keyof OpenAIChatModelProviderOptionsByName
72 ? OpenAIChatModelProviderOptionsByName[TModel]
73 : OpenAITextProviderOptions
74
75/**
76 * Resolve input modalities for a specific model.
77 * If the model has explicit modalities in the map, use those; otherwise use all modalities.
78 */
79type ResolveInputModalities<TModel extends string> =
80 TModel extends keyof OpenAIModelInputModalitiesByName
81 ? OpenAIModelInputModalitiesByName[TModel]
82 : readonly ['text', 'image', 'audio']
83
84/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
85type ResolveReasoning<TModel extends string> =
86 TModel extends keyof OpenAIModelReasoningByName
87 ? OpenAIModelReasoningByName[TModel]
88 : never
89
90/**
91 * Resolve tool capabilities for a specific model.
92 * If the model has explicit tools in the map, use those; otherwise use empty tuple.
93 */
94type ResolveToolCapabilities<TModel extends string> =
95 TModel extends keyof OpenAIChatModelToolCapabilitiesByName
96 ? NonNullable<OpenAIChatModelToolCapabilitiesByName[TModel]>
97 : readonly []
98
99// ===========================
100// Adapter Implementation
101// ===========================
102
103/**
104 * OpenAI Text (Chat) Adapter
105 *
106 * Tree-shakeable adapter for OpenAI chat/text completion functionality.
107 * Delegates implementation to {@link OpenAIBaseResponsesTextAdapter} from
108 * `@tanstack/openai-base`. The base calls `openai.responses.create`
109 * directly; this subclass just hands it a configured client and overrides
110 * `mapOptionsToRequest` to route through OpenAI's full tool converter
111 * (supporting file_search, web_search, etc.) and to apply provider option
112 * validation.
113 */
114export class OpenAITextAdapter<
115 TModel extends OpenAIChatModel,
116 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
117 TInputModalities extends ReadonlyArray<Modality> =
118 ResolveInputModalities<TModel>,
119 TToolCapabilities extends ReadonlyArray<string> =
120 ResolveToolCapabilities<TModel>,
121 TReasoning extends ReasoningCapability = ResolveReasoning<TModel>,
122> extends OpenAIBaseResponsesTextAdapter<
123 TModel,
124 TProviderOptions,
125 TInputModalities,
126 OpenAIMessageMetadataByModality,
127 TToolCapabilities,
128 TReasoning
129> {
130 override readonly kind = 'text' as const
131 override readonly name = 'openai' as const
132 // OpenAI's Responses endpoint consumes `file_id` references issued by its
133 // Files API (`openaiFiles()`). The default is undefined (unsupported) so
134 // compatible subclasses of the openai-base adapter (Grok, Bedrock, custom)
135 // — which have no such surface — fail closed in preflight.
136 override readonly supportsFileSources = true
137 override readonly inputModalities = OPENAI_MODEL_INPUT_MODALITIES[this.model]
138 /** Set from `OPENAI_MODEL_MID_CONVERSATION_CHANNELS` in the constructor. */
139 override readonly midConversationChannels:
140 | MidConversationChannels
141 | undefined = undefined
142
143 constructor(config: OpenAITextConfig, model: TModel) {
144 super(model, 'openai', new OpenAI(config), config)
145 // On by default only on OpenAI's own API: a proxy or a gateway (a
146 // `baseURL`, a `fetch`, or the SDK's OPENAI_BASE_URL env var) may not
147 // pass the changes. The option wins.
148 const envBaseURL =
149 typeof process !== 'undefined' && Boolean(process.env.OPENAI_BASE_URL)
150 if (
151 config.midConversationChannels ??
152 !(config.baseURL || config.fetch || envBaseURL)
153 ) {
154 this.midConversationChannels =
155 OPENAI_MODEL_MID_CONVERSATION_CHANNELS[model]
156 }
157 }
158
159 /** OpenAI's full tool converter (file_search, web_search, etc.). */
160 protected override convertTools(tools: Array<AnyTool>): Array<ResponsesTool> {
161 return convertToolsToProviderFormat(tools)
162 }
163
164 /** `chat({ reasoning })` goes out as `reasoning: { effort, summary }`. */
165 protected override modelReasoning(model: string) {
166 return OPENAI_MODEL_REASONING[model]
167 }
168
169 /**
170 * Maps common options to OpenAI-specific format.
171 * Overrides the base class to apply OpenAI-specific provider option
172 * validation and request fields. The tools go through `convertTools`.
173 */
174 protected override mapOptionsToRequest(
175 options: TextOptions<TProviderOptions>,
176 ): Omit<ResponseCreateParams, 'stream'> {
177 // The structural type the validator expects is broader than what
178 // `TProviderOptions` is bound to per-model, so narrow via the internal
179 // shape rather than re-exposing it on the public override signature.
180 const modelOptions = options.modelOptions as
181 | InternalTextProviderOptions
182 | undefined
183 if (modelOptions) {
184 validateTextProviderOptions({
185 ...modelOptions,
186 input: this.convertMessagesToInput(options.messages),
187 model: options.model,
188 })
189 }
190
191 // Delegate to the base for input mapping, system prompts, tools,
192 // modelOptions precedence, and native combined-mode `text.format` wiring
193 // (#605). The base converts the tools with `convertTools` (OpenAI's full
194 // converter), so a mid-conversation change sends the start set and its
195 // `additional_tools` items in this format too. The base also gives the
196 // strict-fallback warning.
197 const { tools: baseTools, ...baseRequest } = super.mapOptionsToRequest(
198 options,
199 )
200 // Only tools from `options.tools`, as before: the base also keeps a
201 // `modelOptions.tools`, which this adapter has never sent.
202 const tools = options.tools?.length ? baseTools : undefined
203
204 // `chat({ promptCache })` fields go first, so a value the caller set in
205 // `modelOptions` (already on `baseRequest`) wins.
206 const promptCacheFields = responsesPromptCacheFields(options.promptCache, {
207 explicitMode: openAIModelUsesExplicitPromptCache(options.model),
208 longRetention: true,
209 baseURL: this.client.baseURL ?? '',
210 })
211 const request: Omit<ResponseCreateParams, 'stream'> = {
212 ...promptCacheFields,
213 ...baseRequest,
214 ...(tools && tools.length > 0 && { tools }),
215 }
216
217 // Reasoning models 400 on `temperature`/`top_p`. Callers (and the summarize
218 // adapter's low-temperature default) can't know a given model rejects them,
219 // so drop the pair here — stripping only ever averts a guaranteed 400, never
220 // changes an otherwise-valid request.
221 if (openAIModelRejectsSamplingParams(options.model)) {
222 delete request.temperature
223 delete request.top_p
224 }
225
226 // Reasoning models pair each function_call with a reasoning item. Request
227 // the encrypted blob so convertMessagesToInput can replay it. Pre-5 chat
228 // models do not emit those items, so leave include unset for them.
229 // Callers can still set include in modelOptions.
230 if (
231 request.include === undefined &&
232 openAIModelRejectsSamplingParams(options.model)
233 ) {
234 request.include = ['reasoning.encrypted_content']
235 }
236
237 // OpenAI only returns the URLs used by a hosted web search when this
238 // response item is included. Preserve caller entries and add the item for
239 // branded web search tools only. A custom function named `web_search` has
240 // no internal provider-tool discriminator and must not change the request.
241 const hasWebSearchTool = options.tools?.some((tool) => {
242 const kind = tool.metadata?.['__kind']
243 return (
244 kind === 'openai.web_search' || kind === 'openai.web_search_preview'
245 )
246 })
247 if (hasWebSearchTool) {
248 const include = request.include ?? []
249 if (!include.includes('web_search_call.action.sources')) {
250 request.include = [...include, 'web_search_call.action.sources']
251 }
252 }
253
254 return request
255 }
256}
257
258/**
259 * Creates an OpenAI chat adapter with explicit API key.
260 * Type resolution happens here at the call site.
261 *
262 * @param model - The model name (e.g., 'gpt-4o', 'gpt-4-turbo')
263 * @param apiKey - Your OpenAI API key
264 * @param config - Optional additional configuration
265 * @returns Configured OpenAI chat adapter instance with resolved types
266 *
267 * @example
268 * ```typescript
269 * const adapter = createOpenaiChat('gpt-4o', "sk-...");
270 * // adapter has type-safe modelOptions for gpt-4o
271 * ```
272 */
273export function createOpenaiChat<
274 TModel extends (typeof OPENAI_CHAT_MODELS)[number],
275>(
276 model: TModel,
277 apiKey: string,
278 config?: Omit<OpenAITextConfig, 'apiKey'>,
279): OpenAITextAdapter<TModel> {
280 return new OpenAITextAdapter({ apiKey, ...config }, model)
281}
282
283/**
284 * Creates an OpenAI text adapter with automatic API key detection from environment variables.
285 * Type resolution happens here at the call site.
286 *
287 * Looks for `OPENAI_API_KEY` in:
288 * - `process.env` (Node.js)
289 * - `window.env` (Browser with injected env)
290 *
291 * @param model - The model name (e.g., 'gpt-4o', 'gpt-4-turbo')
292 * @param config - Optional configuration (excluding apiKey which is auto-detected)
293 * @returns Configured OpenAI text adapter instance with resolved types
294 * @throws Error if OPENAI_API_KEY is not found in environment
295 *
296 * @example
297 * ```typescript
298 * // Automatically uses OPENAI_API_KEY from environment
299 * const adapter = openaiText('gpt-4o');
300 *
301 * const stream = chat({
302 * adapter,
303 * messages: [{ role: "user", content: "Hello!" }]
304 * });
305 * ```
306 */
307export function openaiText<TModel extends (typeof OPENAI_CHAT_MODELS)[number]>(
308 model: TModel,
309 config?: Omit<OpenAITextConfig, 'apiKey'>,
310): OpenAITextAdapter<TModel> {
311 const apiKey = getOpenAIApiKeyFromEnv()
312 return createOpenaiChat(model, apiKey, config)
313}