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 { anthropicModelFeatures } from './anthropic-features.ts'
8import {
9 anthropicAliasMap,
10 applyDocumentedAliases,
11} from './provider-aliases.ts'
12import type { AnthropicThinkingCaps } from './anthropic-features.ts'
13import { anthropicModelPricing } from './anthropic-pricing.ts'
14import { isoToEpochSeconds } from './release-dates.ts'
15import { fetchJson, parseGzippedOpenApi, skippedResult } from './types.ts'
16import { headerApiKeyConnect } from './connect.ts'
17import type {
18 ListModelsResult,
19 ProviderConfig,
20 ProviderSecrets,
21 SpecFetchResult,
22} from './types.ts'
23
24export const ANTHROPIC_SPEC_URL =
25 'https://raw.githubusercontent.com/anthropics/anthropic-sdk-typescript/main/scripts/mock-spec.json.gz'
26const ANTHROPIC_MODELS_URL = 'https://api.anthropic.com/v1/models'
27const ANTHROPIC_VERSION = '2023-06-01'
28
29/**
30 * Anthropic's generation surface is messages + the legacy text completion
31 * (plus `?beta=true` variants and token counting). Batches, files, skills,
32 * and the agent-platform surfaces are platform endpoints.
33 */
34function classify(path: string): Activity | null {
35 const bare = path.replace(/\?beta=true$/, '')
36 if (bare.startsWith('/v1/messages/batches')) return null
37 if (bare === '/v1/messages' || bare === '/v1/messages/count_tokens') {
38 return 'chat'
39 }
40 if (bare === '/v1/complete') return 'chat'
41 return null
42}
43
44async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
45 const response = await fetch(ANTHROPIC_SPEC_URL)
46 if (!response.ok) {
47 throw new Error(
48 `fetch failed: ${ANTHROPIC_SPEC_URL} → ${String(response.status)} ${response.statusText}`,
49 )
50 }
51 return parseGzippedOpenApi(
52 new Uint8Array(await response.arrayBuffer()),
53 'anthropic',
54 ANTHROPIC_SPEC_URL,
55 )
56}
57
58interface Supported {
59 supported?: boolean
60}
61
62interface AnthropicModel {
63 id: string
64 display_name?: string
65 created_at?: string
66 max_input_tokens?: number
67 max_tokens?: number
68 capabilities?: {
69 image_input?: Supported
70 pdf_input?: Supported
71 structured_outputs?: Supported
72 } & AnthropicThinkingCaps
73}
74
75interface AnthropicModelList {
76 data?: Array<AnthropicModel>
77 has_more?: boolean
78 last_id?: string
79}
80
81/**
82 * Request features the Models API capability tree states. The tree does
83 * not cover tool use, sampling params, or whether thinking can be turned
84 * off (Fable/Mythos) — those live in prose docs and stay unset here.
85 */
86export function anthropicCapabilities(m: AnthropicModel): Array<string> | null {
87 const caps = m.capabilities
88 const out: Array<string> = []
89 if (caps?.thinking?.supported) out.push('reasoning')
90 if (caps?.effort?.supported) out.push('reasoning_effort')
91 if (caps?.structured_outputs?.supported) {
92 out.push('structured_outputs', 'response_format')
93 }
94 return out.length > 0 ? out : null
95}
96
97async function listModels(
98 env: ProviderSecrets,
99 kv?: KVNamespace,
100): Promise<ListModelsResult> {
101 const key = env.ANTHROPIC_API_KEY
102 if (!key) {
103 return { models: [], ...skippedResult('anthropic', 'ANTHROPIC_API_KEY') }
104 }
105 const headers = { 'x-api-key': key, 'anthropic-version': ANTHROPIC_VERSION }
106 const [pricing, features, aliasMap] = await Promise.all([
107 anthropicModelPricing(kv),
108 anthropicModelFeatures(kv),
109 anthropicAliasMap(kv),
110 ])
111 const models: ListModelsResult['models'] = []
112 let afterId: string | undefined
113 do {
114 const url = new URL(ANTHROPIC_MODELS_URL)
115 url.searchParams.set('limit', '100')
116 if (afterId) url.searchParams.set('after_id', afterId)
117 const body = (await fetchJson(url.toString(), {
118 headers,
119 })) as AnthropicModelList
120 for (const m of body.data ?? []) {
121 const input = ['text']
122 if (m.capabilities?.image_input?.supported) input.push('image')
123 if (m.capabilities?.pdf_input?.supported) input.push('file')
124 const priced = pricing(m.display_name)
125 const feat = features(m.id, m.display_name, m.capabilities)
126 models.push({
127 rawId: m.id,
128 displayName: m.display_name ?? null,
129 activity: 'chat',
130 releasedAt: isoToEpochSeconds(m.created_at),
131 // Models API (since 2026-03) carries limits + a capability tree.
132 contextWindow: m.max_input_tokens ?? null,
133 maxOutput: m.max_tokens ?? null,
134 modalities: m.capabilities ? { input, output: ['text'] } : null,
135 capabilities: m.capabilities ? anthropicCapabilities(m) : null,
136 pricing: priced.pricing,
137 reasoning: feat.reasoning,
138 serverTools: feat.serverTools,
139 factSources: { ...priced.factSources, ...feat.factSources },
140 })
141 }
142 afterId = body.has_more ? body.last_id : undefined
143 } while (afterId)
144 return { models: applyDocumentedAliases(models, aliasMap) }
145}
146
147export const anthropicProvider: ProviderConfig = {
148 id: 'anthropic',
149 displayName: 'Anthropic',
150 authEnvVar: 'ANTHROPIC_API_KEY',
151 defaultDerivation: 'upstream-spec',
152 specGrain: 'provider',
153 connect: headerApiKeyConnect('https://api.anthropic.com', 'x-api-key', {
154 requiredHeaders: { 'anthropic-version': ANTHROPIC_VERSION },
155 }),
156 fetchSpec,
157 listModels,
158 classify,
159 generationEndpointId: () => 'v1/messages',
160}