Open History to see the last commit
1/**
2 * Anthropic — official OpenAPI spec bundled in Anthropic's Stainless-generated
3 * TypeScript SDK (`scripts/mock-spec.json.gz`, refreshed on every SDK
4 * codegen). `.stats.yml` stopped carrying `openapi_spec_url` on 2026-09-03.
5 */
6import type { Activity } from '#/db/schema.ts'
7import {
8 ANTHROPIC_THINKING_URL,
9 anthropicModelFeatures,
10 anthropicServerTools,
11} from './anthropic-features.ts'
12import { docsReport, docsRun, tryDocs, unavailable } from './model-facts.ts'
13import {
14 ANTHROPIC_MODELS_OVERVIEW_URL,
15 anthropicAliasMap,
16 applyDocumentedAliases,
17} from './provider-aliases.ts'
18import type { AnthropicThinkingCaps } from './anthropic-features.ts'
19import {
20 ANTHROPIC_PRICING_URL,
21 anthropicModelPricing,
22} from './anthropic-pricing.ts'
23import { isoToEpochSeconds } from './release-dates.ts'
24import { fetchJson, parseGzippedOpenApi, skippedResult } from './types.ts'
25import { headerApiKeyConnect } from './connect.ts'
26import { usEgressFetch } from './us-egress.ts'
27import type {
28 ListModelsResult,
29 ModelFact,
30 ProviderConfig,
31 ProviderEnvironment,
32 ProviderSecrets,
33 SpecFetchResult,
34} from './types.ts'
35
36export const ANTHROPIC_SPEC_URL =
37 'https://raw.githubusercontent.com/anthropics/anthropic-sdk-typescript/main/scripts/mock-spec.json.gz'
38const ANTHROPIC_MODELS_URL = 'https://api.anthropic.com/v1/models'
39const ANTHROPIC_VERSION = '2023-06-01'
40
41/**
42 * Anthropic's generation surface is messages + the legacy text completion
43 * (plus `?beta=true` variants and token counting). Batches, files, skills,
44 * and the agent-platform surfaces are platform endpoints.
45 */
46function classify(path: string): Activity | null {
47 const bare = path.replace(/\?beta=true$/, '')
48 if (bare.startsWith('/v1/messages/batches')) return null
49 if (bare === '/v1/messages' || bare === '/v1/messages/count_tokens') {
50 return 'chat'
51 }
52 if (bare === '/v1/complete') return 'chat'
53 return null
54}
55
56async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
57 const response = await fetch(ANTHROPIC_SPEC_URL)
58 if (!response.ok) {
59 throw new Error(
60 `fetch failed: ${ANTHROPIC_SPEC_URL} → ${String(response.status)} ${response.statusText}`,
61 )
62 }
63 return parseGzippedOpenApi(
64 new Uint8Array(await response.arrayBuffer()),
65 'anthropic',
66 ANTHROPIC_SPEC_URL,
67 )
68}
69
70interface Supported {
71 supported?: boolean
72}
73
74interface AnthropicModel {
75 id: string
76 display_name?: string
77 created_at?: string
78 max_input_tokens?: number
79 max_tokens?: number
80 capabilities?: {
81 image_input?: Supported
82 pdf_input?: Supported
83 structured_outputs?: Supported
84 } & AnthropicThinkingCaps
85}
86
87interface AnthropicModelList {
88 data?: Array<AnthropicModel>
89 has_more?: boolean
90 last_id?: string
91}
92
93/**
94 * Request features the Models API capability tree states. The tree does
95 * not cover tool use, sampling params, or whether thinking can be turned
96 * off (Fable/Mythos) — those live in prose docs and stay unset here.
97 */
98export function anthropicCapabilities(m: AnthropicModel): Array<string> | null {
99 const caps = m.capabilities
100 const out: Array<string> = []
101 if (caps?.thinking?.supported) out.push('reasoning')
102 if (caps?.effort?.supported) out.push('reasoning_effort')
103 if (caps?.structured_outputs?.supported) {
104 out.push('structured_outputs', 'response_format')
105 }
106 return out.length > 0 ? out : null
107}
108
109async function listModels(
110 env: ProviderEnvironment,
111 kv?: KVNamespace,
112): Promise<ListModelsResult> {
113 const key = env.ANTHROPIC_API_KEY
114 if (!key) {
115 return { models: [], ...skippedResult('anthropic', 'ANTHROPIC_API_KEY') }
116 }
117 const headers = { 'x-api-key': key, 'anthropic-version': ANTHROPIC_VERSION }
118 // A failed docs load leaves the facts it feeds unavailable on every row;
119 // the Models API listing itself is never wrapped.
120 const docs = docsRun()
121 const [pricing, features, aliasMap] = await Promise.all([
122 tryDocs(docs, ANTHROPIC_PRICING_URL, (cached) =>
123 anthropicModelPricing(kv, cached),
124 ),
125 tryDocs(docs, ANTHROPIC_THINKING_URL, (cached) =>
126 anthropicModelFeatures(kv, cached),
127 ),
128 tryDocs(docs, ANTHROPIC_MODELS_OVERVIEW_URL, (cached) =>
129 anthropicAliasMap(kv, cached),
130 ),
131 ])
132 const lost: Array<ModelFact> = [
133 ...(pricing ? [] : ['pricing' as const]),
134 ...(features ? [] : ['reasoning' as const]),
135 ...(aliasMap ? [] : ['aliases' as const]),
136 ]
137 const models: ListModelsResult['models'] = []
138 let afterId: string | undefined
139 do {
140 const url = new URL(ANTHROPIC_MODELS_URL)
141 url.searchParams.set('limit', '100')
142 if (afterId) url.searchParams.set('after_id', afterId)
143 const body = (await fetchJson(
144 url.toString(),
145 { headers },
146 usEgressFetch(env),
147 )) as AnthropicModelList
148 for (const m of body.data ?? []) {
149 const input = ['text']
150 if (m.capabilities?.image_input?.supported) input.push('image')
151 if (m.capabilities?.pdf_input?.supported) input.push('file')
152 const priced = pricing?.(m.display_name) ?? {}
153 // Server tools come from the hand-written table, not the docs load.
154 const feat = features?.(m.id, m.display_name, m.capabilities) ?? {
155 reasoning: null,
156 ...toolsOnly(m.id),
157 }
158 models.push({
159 rawId: m.id,
160 displayName: m.display_name ?? null,
161 activity: 'chat',
162 releasedAt: isoToEpochSeconds(m.created_at),
163 // Models API (since 2026-03) carries limits + a capability tree.
164 contextWindow: m.max_input_tokens ?? null,
165 maxOutput: m.max_tokens ?? null,
166 modalities: m.capabilities ? { input, output: ['text'] } : null,
167 capabilities: m.capabilities ? anthropicCapabilities(m) : null,
168 pricing: priced.pricing,
169 reasoning: feat.reasoning,
170 serverTools: feat.serverTools,
171 factSources: { ...priced.factSources, ...feat.factSources },
172 ...(lost.length > 0 ? unavailable(...lost) : {}),
173 })
174 }
175 afterId = body.has_more ? body.last_id : undefined
176 } while (afterId)
177 return {
178 models: aliasMap ? applyDocumentedAliases(models, aliasMap) : models,
179 docsFailures: docsReport(docs),
180 }
181}
182
183function toolsOnly(rawId: string) {
184 const { serverTools, sources } = anthropicServerTools(rawId)
185 return { serverTools, factSources: { serverTools: sources } }
186}
187
188export const anthropicProvider: ProviderConfig = {
189 id: 'anthropic',
190 displayName: 'Anthropic',
191 authEnvVar: 'ANTHROPIC_API_KEY',
192 defaultDerivation: 'upstream-spec',
193 specGrain: 'provider',
194 connect: headerApiKeyConnect('https://api.anthropic.com', 'x-api-key', {
195 requiredHeaders: { 'anthropic-version': ANTHROPIC_VERSION },
196 }),
197 fetchSpec,
198 listModels,
199 classify,
200 generationEndpointId: () => 'v1/messages',
201}