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

openai.ts

125 lines3.9 KB

1/**
2 * OpenAI — spec from openai-node's `api_reference/openapi.transformed.yml`
3 * (Castiron generation input). This leads the public openai-openapi export,
4 * which lags API releases (gpt-image-2 is enum-typed here; the public repo
5 * still caps at gpt-image-1.5). Models endpoint requires OPENAI_API_KEY.
6 */
7import type { Activity } from '#/db/schema.ts'
8import { bearerConnect } from './connect.ts'
9import {
10 displayNameFromRawId,
11 openaiGenerationEndpointId,
12 openaiModelActivity,
13} from './model-meta.ts'
14import { docsReport, docsRun } from './model-facts.ts'
15import { openaiModelFacts } from './openai-model-docs.ts'
16import { fetchOpenApi, fetchWithRetry, skippedResult } from './types.ts'
17import type {
18 ListModelsResult,
19 OpenApiOperation,
20 ProviderConfig,
21 ProviderEnvironment,
22 ProviderSecrets,
23 SpecFetchResult,
24} from './types.ts'
25import { usEgressFetch } from './us-egress.ts'
26​
27export const OPENAI_SPEC_URL =
28 'https://raw.githubusercontent.com/openai/openai-node/main/api_reference/openapi.transformed.yml'
29const OPENAI_MODELS_URL = 'https://api.openai.com/v1/models'
30​
31/**
32 * Tag → activity mapping. Tags absent from this map (Assistants, Batch,
33 * Files, Fine-tuning, Vector stores, and the organization/admin surface)
34 * are platform endpoints and classify to null.
35 */
36const OPENAI_TAG_ACTIVITIES: Record<string, Activity> = {
37 Chat: 'chat',
38 Completions: 'chat',
39 Responses: 'chat',
40 Conversations: 'chat',
41 Realtime: 'chat',
42 Audio: 'audio',
43 Images: 'image',
44 Videos: 'video',
45 Embeddings: 'embeddings',
46 Moderations: 'moderation',
48​
49function classify(path: string, op: OpenApiOperation): Activity | null {
50 const tags = Array.isArray(op.tags) ? (op.tags as Array<string>) : []
51 for (const tag of tags) {
52 const activity = OPENAI_TAG_ACTIVITIES[tag]
53 if (activity) return activity
54 }
55 // A handful of Responses-API operations ship untagged
56 // (/responses/input_tokens, /responses/compact).
57 if (path.startsWith('/responses')) return 'chat'
58 return null
60​
61async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
62 const { spec, hash } = await fetchOpenApi(OPENAI_SPEC_URL)
63 return {
64 specs: [spec],
65 sources: [{ url: OPENAI_SPEC_URL, hash }],
66 outputStrategy: 'post-200',
67 // Floating `main` URL — the document hash is the revision id.
68 specRevision: hash,
69 }
71​
72interface OpenAiModelList {
73 data?: Array<{ id: string; created?: number }>
75​
76async function listModels(
77 env: ProviderEnvironment,
78 kv?: KVNamespace,
79): Promise<ListModelsResult> {
80 const key = env.OPENAI_API_KEY
81 if (!key) {
82 return { models: [], ...skippedResult('openai', 'OPENAI_API_KEY') }
83 }
84 // One transient 504 on the listing used to sink the whole poll (#100004).
85 const body = await fetchWithRetry(
86 OPENAI_MODELS_URL,
87 () => ({ headers: { Authorization: `Bearer ${key}` } }),
88 async (response) => (await response.json()) as OpenAiModelList,
89 )
90 const listed = body.data ?? []
91 const docs = docsRun()
92 // developers.openai.com answered 403 to docs loads from Cloudflare's hkg1
93 // colo, where the cron can land, so docs loads leave from the US egress
94 // (#505). The listing call worked from there and stays on the global fetch.
95 const facts = await openaiModelFacts(
96 listed.map((m) => m.id),
97 kv,
98 docs,
99 usEgressFetch(env),
100 )
101 return {
102 docsFailures: docsReport(docs),
103 models: listed.map((m) => ({
104 rawId: m.id,
105 displayName: displayNameFromRawId(m.id),
106 activity: openaiModelActivity(m.id),
107 releasedAt: m.created ?? null,
108 ...facts(m.id),
109 })),
110 }
112​
113export const openaiProvider: ProviderConfig = {
114 id: 'openai',
115 displayName: 'OpenAI',
116 authEnvVar: 'OPENAI_API_KEY',
117 defaultDerivation: 'upstream-spec',
118 specGrain: 'provider',
119 connect: bearerConnect('https://api.openai.com/v1'),
120 fetchSpec,
121 listModels,
122 classify,
123 generationEndpointId: ({ rawId, activity }) =>
124 openaiGenerationEndpointId(rawId, activity),