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