import * as plugins from './plugins.js'; import { isOpenAiCacheTransparentTransport, readOpenAiEffectiveCachePolicy } from './smartai.cache.openai.js'; import { classifyOpenAiLimit } from './smartai.limits.openai.js'; import { OPENAI_API_BASE_URL } from './smartai.apikey.openai.js'; import { openAiChatTerminal, openAiResponsesTerminal } from './smartai.terminal.openai.js'; export { classifyOpenAiLimit, readOpenAiError, type IOpenAiErrorDetails } from './smartai.limits.openai.js'; export { classifyOpenAiChatGptLimit } from './smartai.chatgpt.limits.js'; export { createOpenAiChatGptInstructionsMiddleware, normalizeOpenAiChatGptResponsesRequest } from './smartai.chatgpt.middleware.js'; export { createOpenAiWebSearchTool, type IOpenAiWebSearchToolOptions } from './smartai.websearch.openai.js'; export { createOpenAiChatGptAccessHeaders, createOpenAiChatGptAccessModelConnection, createOpenAiChatGptResolvingModelConnection, OPENAI_CHATGPT_CODEX_BASE_URL, OPENAI_CHATGPT_DEFAULT_ORIGINATOR, OpenAiChatGptAuthError, type IOpenAiChatGptAccess, type IOpenAiChatGptAccessConnectionOptions, type IOpenAiChatGptAccessGrant, type IOpenAiChatGptAccessResolveRequest, type IOpenAiChatGptReadAccess, type IOpenAiChatGptResolvingConnectionOptions, type IOpenAiChatGptWorkspaceIdentity, type TOpenAiChatGptRequestOutcome, } from './smartai.chatgpt.openai.js'; export { listOpenAiChatGptModels, OPENAI_CHATGPT_CATALOG_CLIENT_VERSION, OpenAiChatGptModelListError, type IOpenAiChatGptModel, type IOpenAiChatGptModelListOptions, type IOpenAiChatGptModelReasoningEffort, type IOpenAiChatGptModelServiceTier, type TOpenAiChatGptInputModality, type TOpenAiChatGptModelListErrorCode, } from './smartai.chatgpt.catalog.js'; export { createOpenAiApiKeyConnection, createOpenAiApiKeyHeaders, isOpenAiApiRequestUrl, listOpenAiApiKeyModels, OPENAI_API_BASE_URL, OpenAiApiKeyAuthError, OpenAiApiModelListError, type IOpenAiApiKeyAccess, type IOpenAiApiKeyConnectionOptions, type IOpenAiApiKeyModel, type IOpenAiApiKeyModelListOptions, } from './smartai.apikey.openai.js'; export { getOpenAiApiModel, getOpenAiModelPrice, OPENAI_API_MODELS, OPENAI_MODEL_PRICES, readOpenAiResponsesUsage, type IOpenAiApiModel, } from './smartai.models.openai.js'; /** A Responses API `reasoning.effort`; which ones a model accepts is the model's (`OPENAI_API_MODELS`). */ export type TOpenAiReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'; export type TOpenAiTextVerbosity = 'low' | 'medium' | 'high'; /** `responses` calls `/responses`; `chat` calls `/chat/completions`, the API most OpenAI-compatible servers implement. */ export type TOpenAiApi = 'responses' | 'chat'; /** Provider options of the Responses API (`api: 'responses'`, the default). */ export interface IOpenAiProviderOptions extends plugins.JSONObject, plugins.OpenAIResponsesProviderOptions {} /** * Provider options of the Chat Completions API (`api: 'chat'`). Responses-only options such as * `reasoningSummary`, `previousResponseId`, `include`, `instructions` or `truncation` do not apply * to it; the chat model ignores them. */ export interface IOpenAiChatProviderOptions extends plugins.JSONObject, plugins.OpenAIChatProviderOptions {} /** The provider owns inference; optional authentication components supply this connection. */ export interface IOpenAiModelConnection { settings: plugins.OpenAIProviderSettings; middleware?: plugins.LanguageModelV4Middleware; /** The OpenAI APIs this connection serves. Unset means every API; a model asking for another one is refused. */ apis?: readonly TOpenAiApi[]; /** Reads this connection's own limit dialect first; the OpenAI API dialect handles the rest. */ classifyLimit?: plugins.TModelLimitClassifier; } export interface IOpenAiModelOptions extends plugins.ISmartAiOptions { provider: 'openai'; connection?: IOpenAiModelConnection; /** The API the model calls. Defaults to `responses`. */ api?: TOpenAiApi; /** * With `api: 'chat'`: whether the server takes OpenAI's fields of response storage and the prompt * cache, `store`, `prompt_cache_key`, `prompt_cache_retention` and `prompt_cache_options`. OpenAI's * own API always gets them; another server gets them only with `true`, since an OpenAI-compatible * server may refuse a field it does not know. */ openAiFields?: boolean; } /** The provider options behind those fields, as the AI SDK's chat model reads them. */ const openAiChatFields = ['store', 'promptCacheKey', 'promptCacheRetention', 'promptCacheOptions']; /** * Whether a base URL is OpenAI's own API: `api.openai.com`, or a data residency host such as * `eu.api.openai.com`. A relative base URL, which a browser resolves against its page, is not. */ const isOpenAiApiBaseUrl = (baseUrl: string): boolean => { const url = URL.canParse(baseUrl) ? new URL(baseUrl) : undefined; return url?.protocol === 'https:' && (url.hostname === 'api.openai.com' || url.hostname.endsWith('.api.openai.com')); }; /** Leaves OpenAI's own fields out of a Chat Completions call to another server, whoever set them. */ const withoutOpenAiChatFields: plugins.LanguageModelV4Middleware = { specificationVersion: 'v4', transformParams: async ({ params }) => { const openAiOptions = params.providerOptions?.openai; if (!openAiOptions || !openAiChatFields.some((field) => field in openAiOptions)) return params; const kept = { ...openAiOptions }; for (const field of openAiChatFields) delete kept[field]; return { ...params, providerOptions: { ...params.providerOptions, openai: kept } }; }, }; export const createOpenAiModelProvider = (): plugins.IModelProvider => ({ id: 'openai', getModel: (options) => { const api = options.api ?? 'responses'; if (api !== 'responses' && api !== 'chat') { throw new Error(`Unknown OpenAI API "${String(api)}"; use "responses" or "chat".`); } const servedApis = options.connection?.apis; if (servedApis && !servedApis.includes(api)) { const served = servedApis.map((entry) => `"${entry}"`).join(', '); throw new Error(`This connection serves only the ${served} API; api "${api}" cannot be used with it.`); } const connection = options.connection; // An explicit address, and for a connection an explicit key: the SDK would otherwise take // OPENAI_BASE_URL and OPENAI_API_KEY from the environment. A connection without a key authenticates its own way. const settings: plugins.OpenAIProviderSettings = connection ? { ...connection.settings, apiKey: connection.settings.apiKey ?? '', baseURL: connection.settings.baseURL || OPENAI_API_BASE_URL } : { apiKey: options.apiKey, baseURL: options.baseUrl || OPENAI_API_BASE_URL }; const createModel = (observer?: plugins.TSmartAiCachePolicyObserver): plugins.LanguageModelV4 => { const fetchWithObservation: NonNullable = async (input, init) => { init?.signal?.throwIfAborted(); observer!({ dispatchedAt: Date.now(), policy: readOpenAiEffectiveCachePolicy( input instanceof Request ? input.url : String(input), init?.body, isOpenAiCacheTransparentTransport(settings.fetch), ), }); return (settings.fetch ?? globalThis.fetch)(input, init); }; // An answer ends at its terminal event, not at the end of the connection (AGL-1130). const answers = plugins.endModelStreamsAtTerminalEvent( api === 'chat' ? openAiChatTerminal : openAiResponsesTerminal, observer ? fetchWithObservation : (input, init) => (settings.fetch ?? globalThis.fetch)(input, init), ); const openai = plugins.createOpenAI({ ...settings, fetch: answers.fetch }); const model = api === 'chat' ? openai.chat(options.model) : openai(options.model); const limits = plugins.createModelLimitMiddleware({ provider: 'openai', classify: (failure) => connection?.classifyLimit?.(failure) ?? classifyOpenAiLimit(failure), }); // OpenAI reads only images and PDFs as files, on either API; a text file goes as text const textFiles = plugins.createTextFilePartMiddleware(); // Before the connection's own middleware: a field the connection adds is the connection's to send const ownFields = api === 'chat' && options.openAiFields !== true && !isOpenAiApiBaseUrl(settings.baseURL!) ? [withoutOpenAiChatFields] : []; // The answers' middleware innermost, next to the model whose fetch it pairs with. return plugins.wrapLanguageModel({ model, middleware: [limits, textFiles, ...ownFields, ...(connection?.middleware ? [connection.middleware] : []), answers.middleware], }); }; // Rebuild the owning pipeline with a request-local observer, as the Anthropic provider does. return plugins.registerSmartAiCachePolicyObserver(createModel(), createModel); }, });