Open History to see the last commit
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 { fetchJson, fetchOpenApi, 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',
47}
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
59}
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 }
70}
71
72interface OpenAiModelList {
73 data?: Array<{ id: string; created?: number }>
74}
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 const body = (await fetchJson(OPENAI_MODELS_URL, {
85 headers: { Authorization: `Bearer ${key}` },
86 })) as OpenAiModelList
87 const listed = body.data ?? []
88 const docs = docsRun()
89 // developers.openai.com answered 403 to docs loads from Cloudflare's hkg1
90 // colo, where the cron can land, so docs loads leave from the US egress
91 // (#505). The listing call worked from there and stays on the global fetch.
92 const facts = await openaiModelFacts(
93 listed.map((m) => m.id),
94 kv,
95 docs,
96 usEgressFetch(env),
97 )
98 return {
99 docsFailures: docsReport(docs),
100 models: listed.map((m) => ({
101 rawId: m.id,
102 displayName: displayNameFromRawId(m.id),
103 activity: openaiModelActivity(m.id),
104 releasedAt: m.created ?? null,
105 ...facts(m.id),
106 })),
107 }
108}
109
110export const openaiProvider: ProviderConfig = {
111 id: 'openai',
112 displayName: 'OpenAI',
113 authEnvVar: 'OPENAI_API_KEY',
114 defaultDerivation: 'upstream-spec',
115 specGrain: 'provider',
116 connect: bearerConnect('https://api.openai.com/v1'),
117 fetchSpec,
118 listModels,
119 classify,
120 generationEndpointId: ({ rawId, activity }) =>
121 openaiGenerationEndpointId(rawId, activity),
122}