Open History to see the last commit
1/**
2 * Neon AI Gateway — `neon.com/models.json` is the catalog Neon calls its
3 * machine-readable source of truth (docs/ai-gateway/models). Prices there
4 * are USD per million tokens, passed through at the provider's rate with
5 * no markup. Decision models (`/typesafe/v1/systemone`) are not a
6 * generation activity here and are left out, as are rows the catalog
7 * marks unreleased. The data plane is a per-branch host
8 * (`NEON_AI_GATEWAY_BASE_URL`); the documented chat-completions and
9 * embeddings routes are generated from OpenAI's document.
10 */
11import { compileTokenCard } from '@modelschemas/rate-card'
12import type { RateCard } from '@modelschemas/rate-card'
13
14import { compatGenerationEndpointId } from '../model-meta.ts'
15import {
16 classifyOpenAiCompat,
17 fetchOpenAiCompatibleSpec,
18} from '../openai-compat.ts'
19import { fetchJson, sha256Text } from '../types.ts'
20import type {
21 ListModelsResult,
22 ModelInfo,
23 ModelReasoning,
24 ProviderConfig,
25 ProviderConnect,
26 ProviderSecrets,
27 SpecFetchResult,
28} from '../types.ts'
29
30export const NEON_CATALOG_URL = 'https://neon.com/models.json'
31const NEON_DOCS_URL = 'https://neon.com/docs/ai-gateway/models'
32/** A placeholder in the shape of a branch host; every branch has its own. */
33const NEON_HOST_PLACEHOLDER = 'br-example-api.ai.c-2.us-east-2.aws.neon.tech'
34
35export const NEON_CONNECT: ProviderConnect = {
36 servers: [
37 {
38 url: 'https://{host}',
39 description: 'Your branch gateway host (NEON_AI_GATEWAY_BASE_URL).',
40 variables: {
41 host: {
42 default: NEON_HOST_PLACEHOLDER,
43 description:
44 'The bare AI Gateway host of your Neon branch, from `neon env pull`.',
45 },
46 },
47 },
48 ],
49 securitySchemes: {
50 bearerAuth: {
51 type: 'http',
52 scheme: 'bearer',
53 description:
54 'The branch gateway token (NEON_AI_GATEWAY_TOKEN) as `Authorization: Bearer <token>`.',
55 },
56 },
57 security: [{ bearerAuth: [] }],
58}
59
60/** `cost` keys (USD per million tokens) → token-card levers. */
61const COST_LEVERS: Record<string, string> = {
62 input: 'input_tokens',
63 output: 'output_tokens',
64 cache_read: 'cache_read_tokens',
65 cache_write: 'cache_write_tokens',
66}
67
68function isRecord(value: unknown): value is Record<string, unknown> {
69 return typeof value === 'object' && value !== null && !Array.isArray(value)
70}
71
72function positive(value: unknown): number | null {
73 return typeof value === 'number' && Number.isFinite(value) && value > 0
74 ? value
75 : null
76}
77
78function stringList(value: unknown): Array<string> | null {
79 if (!Array.isArray(value)) return null
80 return value.every((item): item is string => typeof item === 'string')
81 ? value
82 : null
83}
84
85function neonCard(
86 rawId: string,
87 cost: unknown,
88 source: RateCard['source'],
89): RateCard | null {
90 if (cost === undefined) return null
91 if (!isRecord(cost)) throw new Error(`neon: ${rawId} cost is not an object`)
92 const base: Record<string, number> = {}
93 for (const [key, lever] of Object.entries(COST_LEVERS)) {
94 const value = cost[key]
95 if (value === undefined) continue
96 if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
97 throw new Error(`neon: ${rawId} cost.${key} is not a price`)
98 }
99 base[lever] = value / 1_000_000
100 }
101 return compileTokenCard(base, [], source)
102}
103
104/**
105 * `reasoning_options` states the control: an effort list, a token budget,
106 * or a switch. `mandatory` is unstated everywhere but a list with `none`,
107 * which states thinking can be turned off. A toggle is stored only when
108 * the list says that.
109 */
110function neonReasoning(options: unknown): ModelReasoning | null {
111 if (!Array.isArray(options)) return null
112 for (const option of options) {
113 if (!isRecord(option)) continue
114 const values = stringList(option.values) ?? []
115 if (option.type === 'effort' && values.length > 0) {
116 return {
117 mode: 'effort',
118 mandatory: values.includes('none') ? false : null,
119 efforts: values,
120 }
121 }
122 if (option.type === 'budget_tokens') {
123 return { mode: 'budget', mandatory: null }
124 }
125 }
126 return null
127}
128
129export function parseNeonModels(
130 payload: unknown,
131 source: RateCard['source'],
132): Array<ModelInfo> {
133 const neon = isRecord(payload) ? payload.neon : undefined
134 const rows = isRecord(neon) ? neon.models : undefined
135 if (!isRecord(rows)) throw new Error('neon: catalog has no neon.models')
136 const models: Array<ModelInfo> = []
137 for (const row of Object.values(rows)) {
138 if (!isRecord(row) || typeof row.id !== 'string' || row.id === '') {
139 throw new Error('neon: catalog row has no id')
140 }
141 if (row.released !== true || row.type === 'decision') continue
142 const activity = row.type === 'embedding' ? 'embeddings' : 'chat'
143 const limit = isRecord(row.limit) ? row.limit : {}
144 const input = isRecord(row.modalities)
145 ? stringList(row.modalities.input)
146 : null
147 const output = isRecord(row.modalities)
148 ? stringList(row.modalities.output)
149 : null
150 const modalities = input && output ? { input, output } : null
151 const capabilities: Array<string> = []
152 const unsupported: Array<string> = []
153 const flags: Array<[string, string]> = [
154 ['tool_call', 'tools'],
155 ['structured_output', 'structured_outputs'],
156 ['temperature', 'temperature'],
157 ]
158 for (const [key, flag] of flags) {
159 if (row[key] === true) capabilities.push(flag)
160 else if (row[key] === false) unsupported.push(flag)
161 }
162 const knowledge =
163 typeof row.knowledge === 'string' &&
164 /^\d{4}-\d{2}(?:-\d{2})?$/.test(row.knowledge)
165 ? row.knowledge
166 : null
167 const released =
168 typeof row.release_date === 'string'
169 ? Date.parse(row.release_date)
170 : Number.NaN
171 models.push({
172 rawId: row.id,
173 displayName: typeof row.name === 'string' ? row.name : null,
174 activity,
175 contextWindow: positive(limit.context),
176 maxOutput: positive(limit.output),
177 modalities,
178 pricing: neonCard(row.id, row.cost, source),
179 ...(capabilities.length > 0 ? { capabilities } : {}),
180 ...(unsupported.length > 0
181 ? { unsupportedCapabilities: unsupported }
182 : {}),
183 reasoning: neonReasoning(row.reasoning_options),
184 knowledgeCutoff: knowledge,
185 openWeights:
186 typeof row.open_weights === 'boolean' ? row.open_weights : null,
187 releasedAt: Number.isFinite(released)
188 ? Math.floor(released / 1000)
189 : null,
190 })
191 }
192 if (models.length === 0) throw new Error('neon: catalog listed no models')
193 return models
194}
195
196async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
197 const payload = await fetchJson(NEON_CATALOG_URL)
198 return {
199 models: parseNeonModels(payload, {
200 url: NEON_CATALOG_URL,
201 hash: await sha256Text(JSON.stringify(payload)),
202 extractedAt: new Date().toISOString(),
203 }),
204 }
205}
206
207async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
208 const { spec, url, hash } = await fetchOpenAiCompatibleSpec({
209 title: 'Neon AI Gateway',
210 serverUrl: 'https://{host}/v1',
211 include: ['/chat/completions', '/embeddings'],
212 })
213 // Neon serves these at /v1/... on the bare branch host.
214 const paths = Object.fromEntries(
215 Object.entries(spec.paths ?? {}).map(([path, ops]) => [`/v1${path}`, ops]),
216 )
217 return {
218 specs: [{ ...spec, paths }],
219 sources: [{ url, hash }],
220 outputStrategy: 'post-200',
221 }
222}
223
224export const provider: ProviderConfig = {
225 id: 'neon',
226 displayName: 'Neon AI Gateway',
227 specSourceUrl: NEON_DOCS_URL,
228 modelsEndpoint: NEON_CATALOG_URL,
229 defaultDerivation: 'generated',
230 connect: NEON_CONNECT,
231 fetchSpec,
232 listModels,
233 classify: classifyOpenAiCompat,
234 generationEndpointId: ({ activity }) =>
235 compatGenerationEndpointId(activity, 'v1/'),
236}