import type { IOpenAiModelConnection } from './index.js'; import { registerOpenAiCacheTransparentTransport } from './smartai.cache.openai.js'; import { readOpenAiBoundedJson, type TOpenAiChatGptModelListErrorCode, } from './smartai.chatgpt.catalog.js'; import type { TOpenAiChatGptRequestOutcome } from './smartai.chatgpt.openai.js'; /** The OpenAI API every API-key request goes to; the AI SDK's versioned base URL. */ export const OPENAI_API_BASE_URL = 'https://api.openai.com/v1'; export class OpenAiApiKeyAuthError extends Error { public status?: number; public requestOutcome?: TOpenAiChatGptRequestOutcome; constructor(message: string, options: { status?: number; requestOutcome?: TOpenAiChatGptRequestOutcome } = {}) { super(message); this.name = 'OpenAiApiKeyAuthError'; this.status = options.status; this.requestOutcome = options.requestOutcome; } } /** An OpenAI API key, as the OpenAI platform issues it. */ export interface IOpenAiApiKeyAccess { readonly apiKey: string; } export interface IOpenAiApiKeyConnectionOptions extends IOpenAiApiKeyAccess { /** Optional underlying transport. Defaults to the current global fetch. */ readonly fetch?: typeof fetch; } const apiBaseUrl = new URL(OPENAI_API_BASE_URL); /** Whether a request URL is under `OPENAI_API_BASE_URL` and carries no credentials. */ export function isOpenAiApiRequestUrl(urlArg: string): boolean { const url = new URL(urlArg); return url.origin === apiBaseUrl.origin && url.username === '' && url.password === '' && (url.pathname === apiBaseUrl.pathname || url.pathname.startsWith(`${apiBaseUrl.pathname}/`)); } /** * The statuses that refuse the key itself: 401, a key OpenAI does not accept, and 403, a key without the permission * the request needs (a restricted key without model read, for example). Neither changes by sending again. */ const isKeyRefusal = (statusArg: number): boolean => statusArg === 401 || statusArg === 403; const keyRefused = (statusArg: number, requestOutcomeArg?: TOpenAiChatGptRequestOutcome): OpenAiApiKeyAuthError => new OpenAiApiKeyAuthError(statusArg === 401 ? 'OpenAI rejected the API key.' : 'The API key lacks the permission this request needs.', { status: statusArg, ...(requestOutcomeArg === undefined ? {} : { requestOutcome: requestOutcomeArg }) }); const requireAccess = (accessArg: IOpenAiApiKeyAccess | undefined): IOpenAiApiKeyAccess => { if (!accessArg || typeof accessArg.apiKey !== 'string' || accessArg.apiKey.length === 0) { throw new OpenAiApiKeyAuthError('OpenAI API key is invalid.', { requestOutcome: 'notSent' }); } return Object.freeze({ apiKey: accessArg.apiKey }); }; /** * Headers an API-key request never carries from the request it authenticates: * - the ChatGPT backend's identity headers (`originator`, `ChatGPT-Account-ID`, `X-OpenAI-Fedramp`), which a * client of a ChatGPT login sends and which mean nothing to the API; * - `OpenAI-Organization` and `OpenAI-Project`: a key bills to the organization and project it was issued for, * and a client must not move the request, and its spend, to another one the key can reach. */ const strippedRequestHeaders: readonly string[] = [ 'originator', 'chatgpt-account-id', 'x-openai-fedramp', 'openai-organization', 'openai-project', ]; /** * The headers an API-key request authenticates with, over the request's own: the key replaces any credential the * request carried, and the headers of `strippedRequestHeaders` are removed. Shared by inference and the model list. */ export function createOpenAiApiKeyHeaders(accessArg: IOpenAiApiKeyAccess, headersArg?: HeadersInit): Headers { const headers = new Headers(headersArg); for (const name of strippedRequestHeaders) headers.delete(name); headers.set('authorization', `Bearer ${accessArg.apiKey}`); return headers; } /** * An OpenAI API connection on an API key, for inference billed to the key's organization and project. * * Requests go only to `https://api.openai.com/v1`, without following redirects, with the key as the bearer and * without ChatGPT, organization or project headers. A provider 401 (key rejected) or 403 (key lacks the permission) * fails with an `OpenAiApiKeyAuthError` whose `status` names it, since a key does not renew; every other status is * the caller's. Without a custom * `fetch` the connection keeps the provider's prompt-cache timing confirmation. */ export const createOpenAiApiKeyConnection = (optionsArg: IOpenAiApiKeyConnectionOptions): IOpenAiModelConnection => { const access = requireAccess(optionsArg); const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new OpenAiApiKeyAuthError('fetch is not available for OpenAI inference.'); const fetchWithApiKey: typeof fetch = async (inputArg, initArg) => { const request = new Request(inputArg, { ...initArg, redirect: 'error' }); if (!isOpenAiApiRequestUrl(request.url)) { throw new OpenAiApiKeyAuthError('OpenAI API key request URL is outside the OpenAI API.', { requestOutcome: 'notSent' }); } const authenticated = new Request(request, { headers: createOpenAiApiKeyHeaders(access, request.headers) }); authenticated.signal.throwIfAborted(); const response = await transport(authenticated); if (!isKeyRefusal(response.status)) return response; await response.body?.cancel().catch(() => undefined); throw keyRefused(response.status, 'outcomeUnknown'); }; if (optionsArg.fetch === undefined) registerOpenAiCacheTransparentTransport(fetchWithApiKey); return { // The transport authenticates every request; the empty key keeps the AI SDK from reading its own. settings: { apiKey: '', baseURL: OPENAI_API_BASE_URL, fetch: fetchWithApiKey }, }; }; /** A model an API key may use, as `GET /v1/models` lists it. */ export interface IOpenAiApiKeyModel { providerId: 'openai'; modelId: string; /** When the model was created, in Unix seconds. */ created: number; /** The organization that owns the model, such as `openai` or `system`. */ ownedBy: string; /** The date the model shuts down, as the API states it, when it states one. */ shutdownDate?: string; } export class OpenAiApiModelListError extends Error { public readonly code: TOpenAiChatGptModelListErrorCode; public readonly status?: number; constructor(codeArg: TOpenAiChatGptModelListErrorCode, statusArg?: number) { super(`OpenAI model list request failed (${codeArg}${statusArg === undefined ? '' : ` ${statusArg}`}).`); this.name = 'OpenAiApiModelListError'; this.code = codeArg; if (statusArg !== undefined) this.status = statusArg; } } export interface IOpenAiApiKeyModelListOptions { signal?: AbortSignal; /** Optional underlying transport. Defaults to the current global fetch. */ fetch?: typeof fetch; } const maximumListBytes = 1024 * 1024; const maximumModels = 1000; const textEncoder = new TextEncoder(); const protocolError = (): OpenAiApiModelListError => new OpenAiApiModelListError('PROTOCOL_ERROR'); const isRecord = (valueArg: unknown): valueArg is Record => typeof valueArg === 'object' && valueArg !== null && !Array.isArray(valueArg); const boundedString = (valueArg: unknown, maximumBytesArg: number): string => { if (typeof valueArg !== 'string' || valueArg.length === 0 || textEncoder.encode(valueArg).byteLength > maximumBytesArg) { throw protocolError(); } return valueArg; }; /** * Reads the models an API key may use from `GET /v1/models`, one unpaged list, at most 1 MiB and 1000 models. A * refused key fails with an `OpenAiApiKeyAuthError` whose `status` is 401 (rejected) or 403 (no permission to read * models); an abort rejects with the signal's * reason; every other failure is an `OpenAiApiModelListError` whose `code` is `NETWORK_FAILED`, `HTTP_ERROR` (with * `status`) or `PROTOCOL_ERROR`. */ export async function listOpenAiApiKeyModels( accessArg: IOpenAiApiKeyAccess, optionsArg: IOpenAiApiKeyModelListOptions = {}, ): Promise { const access = requireAccess(accessArg); const transport = optionsArg.fetch ?? globalThis.fetch; if (typeof transport !== 'function') throw new OpenAiApiKeyAuthError('fetch is not available for the OpenAI model list.'); const signal = optionsArg.signal; signal?.throwIfAborted(); let response: Response; try { response = await transport(`${OPENAI_API_BASE_URL}/models`, { method: 'GET', redirect: 'error', signal, headers: createOpenAiApiKeyHeaders(access, { accept: 'application/json' }), }); } catch { if (signal?.aborted) throw signal.reason; throw new OpenAiApiModelListError('NETWORK_FAILED'); } if (!response.ok) { await response.body?.cancel().catch(() => undefined); if (isKeyRefusal(response.status)) throw keyRefused(response.status); throw new OpenAiApiModelListError('HTTP_ERROR', response.status); } const body = await readOpenAiBoundedJson(response, signal, maximumListBytes, protocolError); if (!isRecord(body) || (body.object !== undefined && body.object !== 'list') || !Array.isArray(body.data) || body.data.length > maximumModels) { throw protocolError(); } const modelIds = new Set(); return body.data.map((raw): IOpenAiApiKeyModel => { if (!isRecord(raw) || (raw.object !== undefined && raw.object !== 'model')) throw protocolError(); const modelId = boundedString(raw.id, 256); if (modelIds.has(modelId)) throw protocolError(); modelIds.add(modelId); if (!Number.isSafeInteger(raw.created) || (raw.created as number) < 0) throw protocolError(); const shutdownDate = raw.shutdown_date === undefined || raw.shutdown_date === null ? undefined : boundedString(raw.shutdown_date, 64); return { providerId: 'openai', modelId, created: raw.created as number, ownedBy: boundedString(raw.owned_by, 256), ...(shutdownDate === undefined ? {} : { shutdownDate }), }; }); }