neon-ai-gateway
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFIRST: Use the parent skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
neonIf the skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
neonbash
npx skills add neondatabase/agent-skills --skill neon重要提示:如需了解Neon概览、快速入门、开发最佳实践等内容,请使用父级技能。
neonbash
npx skills add neondatabase/agent-skills --skill neonNeon AI Gateway
Neon AI网关
This is a public beta feature and only available in .
us-east-2The Neon AI Gateway is the LLM inference layer built into your Neon branch: one API and one Neon credential give you access to frontier and open-source models from Anthropic, OpenAI, Google, Meta, Alibaba, DeepSeek, and Databricks — powered by Databricks. Your existing OpenAI/Anthropic/Gemini SDK works by changing only the base URL.
Use this skill to help the user send model calls through the gateway, wire it into the AI SDK or Mastra, and switch providers without rewiring code. Deliver a working inference request, a configured agent, or a precise answer from the official Neon docs.
这是一项公开测试功能,仅在区域可用。
us-east-2Neon AI网关是内置于Neon分支的LLM推理层:通过单一API和Neon凭证,即可访问来自Anthropic、OpenAI、Google、Meta、阿里巴巴、DeepSeek及Databricks的前沿与开源模型——由Databricks提供算力支持。只需修改基础URL,你现有的OpenAI/Anthropic/Gemini SDK即可直接使用。
使用本技能可帮助用户通过网关发送模型调用请求、将其接入AI SDK或Mastra,无需重写代码即可切换模型提供商。本技能可提供可运行的推理请求示例、配置完成的Agent,或来自Neon官方文档的精准答案。
When to Use
使用场景
Reach for the AI Gateway whenever an app or agent needs to call an LLM and the user would rather not manage model providers themselves:
- One credential instead of many provider accounts. A single Neon credential reaches the entire model catalog across seven providers. No separate OpenAI / Anthropic / Google billing, keys, or signups to provision and rotate.
- Switch models without rewiring. The unified endpoint is OpenAI-compatible and works with every model in the catalog — change one field to move between Claude, GPT, and Gemini. Standard SDKs (OpenAI, Anthropic, google-genai) work with just a base-URL change.
model - AI follows your branches. Each branch has its own gateway endpoint, scoped with the same lineage as your database. AI requests from a preview/feature branch are isolated to that branch — the same isolation your data already gets — which makes preview, CI, and agent environments self-contained.
- No extra infrastructure, and it's already next to your data. The gateway lives inside your Neon project (and is injected into Neon Functions automatically), runs on the same Databricks infrastructure that serves trillions of tokens a month, and supports streaming (SSE) out of the box.
If the user already has a deep, single-provider integration and no interest in Neon branching or multi-model routing, a direct provider SDK is fine — but the moment they want one credential, model portability, or branch-scoped AI, this is the reason to use it.
当应用或Agent需要调用LLM,且用户不想自行管理模型提供商时,即可使用AI网关:
- 单一凭证替代多账户:仅需一个Neon凭证即可访问7家提供商的全量模型目录。无需单独管理OpenAI/Anthropic/Google的账单、密钥或注册账户,也无需处理密钥轮换。
- 无需重写代码即可切换模型:统一端点兼容OpenAI协议,支持目录内所有模型——只需修改字段即可在Claude、GPT和Gemini之间切换。标准SDK(OpenAI、Anthropic、google-genai)仅需修改基础URL即可使用。
model - AI随分支同步:每个分支都有独立的网关端点,与数据库拥有相同的谱系范围。预览/功能分支的AI请求将被隔离在该分支内——与你的数据隔离机制一致,让预览、CI和Agent环境实现独立自治。
- 无需额外基础设施,紧邻你的数据:网关部署在你的Neon项目内部(并自动注入Neon Functions),运行在Databricks的基础设施上(该基础设施每月处理数万亿token),且原生支持流式传输(SSE)。
若用户已深度集成单一提供商,且对Neon分支或多模型路由无需求,直接使用提供商SDK即可——但当用户需要单一凭证、模型可移植性或分支级AI隔离时,Neon AI网关将是最佳选择。
What It Does
核心功能
- One API for all models — Frontier and open-source models behind a single endpoint, addressed by their catalog ID (e.g. ,
claude-sonnet-4-6,gpt-5-mini).gemini-2-5-flash - Standard SDKs, one URL change — OpenAI SDK and AI SDK (OpenAI-compatible MLflow/Responses routes), Anthropic SDK (native Messages), google-genai (native Gemini).
- Branch-scoped — Each branch gets its own gateway host; the Neon credential authorizes requests for that branch and its descendants.
- Streaming — Server-sent events work on all endpoints with no extra configuration.
- 统一API适配所有模型:前沿及开源模型均通过单一端点提供服务,使用模型目录ID即可访问(例如、
claude-sonnet-4-6、gpt-5-mini)。gemini-2-5-flash - 标准SDK兼容,仅需修改URL:支持OpenAI SDK和AI SDK(兼容OpenAI的MLflow/Responses路由)、Anthropic SDK(原生Messages接口)、google-genai(原生Gemini接口)。
- 分支级隔离:每个分支拥有独立的网关主机;Neon凭证仅授权该分支及其子分支的请求。
- 流式传输支持:所有端点原生支持Server-Sent Events,无需额外配置。
Availability
可用性
Check these preconditions before setting anything up:
The AI Gateway is a public beta feature available only on new projects in the region; it can't be enabled on existing projects. Foundation model access requires a paid Neon plan. Confirm the user's project is a new project in .
us-east-2us-east-2在进行任何设置前,请确认以下前提条件:
AI网关是公开测试功能,仅在区域的新项目中可用;无法在现有项目中启用。访问基础模型需要付费Neon套餐。请确认用户的项目是区域的新项目。
us-east-2us-east-2Enabling the gateway: plan and model-catalog gating
网关启用限制:套餐与模型目录管控
The AI Gateway is credential-gated rather than a provisioning step, but two plan/beta limits gate it — one blocks provisioning, the other only trims the catalog — and the CLI surfaces each:
- Free plan → provisioning is blocked. /
neon config applyanddeployrefuse to enable the gateway on a Free plan (the gateway can't serve requests there), with a friendly "upgrade to a paid plan, or removeneon checkout" error. A dry-runpreview.aiGatewayandneon config plandon't provision, so they only warn. So: to use the gateway the project's account must be on a paid Neon plan.neon env pull - Paid plan with a reduced model catalog. On a paid plan the gateway provisions and serves, but during the beta an account can start with a trimmed catalog — some flagship models (e.g. Anthropic Opus, OpenAI Codex / ) are missing from
*-pro. This is expected;GET /v1/models(and the env pull bundled intoneon env pull/apply/deploy) warns and links the user to their branch's AI Gateway page in the Neon Console (checkout) to request access to more models. Verify what's actually available for the branch by readinghttps://console.neon.tech/app/projects/<project-id>/branches/<branch-id>/ai-gateway(see the models section below) rather than assuming the full catalog./v1/models
When helping a user debug "the gateway isn't working" or "a model is missing", use plus the account's plan to distinguish these two cases — a Free plan blocks provisioning entirely, while a reduced catalog on a paid plan just needs a model-access request.
/v1/modelsAI网关采用凭证管控而非预配置步骤,但存在两项套餐/测试阶段限制——一项会阻止预配置,另一项仅会缩减模型目录——CLI会明确提示这两种情况:
- 免费套餐 → 无法预配置:/
neon config apply和deploy会拒绝在免费套餐上启用网关(网关无法在此环境下提供服务),并显示友好提示:“升级至付费套餐,或移除neon checkout配置”。预演命令preview.aiGateway和neon config plan不会执行预配置,仅会发出警告。因此:要使用网关,项目账户必须处于付费Neon套餐。neon env pull - 付费套餐模型目录缩减:付费套餐下网关可正常预配置并提供服务,但在测试阶段,部分账户的模型目录会被缩减——部分旗舰模型(例如Anthropic Opus、OpenAI Codex/)不会出现在
*-pro的返回结果中。这是预期情况;GET /v1/models(以及neon env pull/apply/deploy中附带的env拉取操作)会发出警告,并引导用户前往Neon控制台的分支AI网关页面(checkout)申请访问更多模型。请通过https://console.neon.tech/app/projects/<project-id>/branches/<branch-id>/ai-gateway接口(见下方模型章节)验证分支实际可用的模型,而非假设全量目录可用。/v1/models
当帮助用户排查“网关无法工作”或“模型缺失”问题时,请结合返回结果和账户套餐区分两种情况——免费套餐会完全阻止预配置,而付费套餐的缩减目录仅需提交模型访问申请即可解决。
/v1/modelsSetup
配置步骤
The gateway is part of (see the skill for the branch-first workflow and basics). Enable it under :
neon.tsneonneon.tspreview.aiGatewaytypescript
// neon.ts
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
preview: {
aiGateway: true,
},
});bash
neon deploy # provisions the gateway on the linked branch网关是的一部分(如需了解分支优先工作流和基础,请参考技能)。在下启用:
neon.tsneon.tsneonpreview.aiGatewaytypescript
// neon.ts
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
preview: {
aiGateway: true,
},
});bash
neon deploy # 在关联分支上预配置网关Neon Infrastructure as Code (neon.ts
)
neon.tsNeon基础设施即代码(neon.ts
)
neon.tsThe toggle above is part of , Neon's infrastructure-as-code file — one TypeScript file declares the gateway alongside every other branch service, in version control (see the skill for the full reference). Reconcile it against a branch the Terraform way:
preview.aiGatewayneon.tsneonbash
neon config status # print the branch's live config (is the gateway on?)
neon config plan # dry-run diff of what apply would change
neon config apply # enable the gateway on the branch (neon deploy is an alias)The gateway is branch-scoped: each branch gets its own gateway host. When a is present, applies the policy as it creates a branch, so a fresh preview/CI branch comes up with the gateway already enabled. Checking out an existing branch doesn't reconcile it — run to apply changes. Provisioning ( / ), , and also pull the branch's gateway credentials into your local , so local runs hit the same branch gateway as the deployed function (no manual needed).
neon.tsneon checkoutneon deployconfig applydeploylinkcheckout.env.localenv pull上述开关是Neon基础设施即代码文件的一部分——一个TypeScript文件即可声明网关及所有其他分支服务,并纳入版本控制(完整参考请见技能)。采用类似Terraform的方式与分支配置同步:
preview.aiGatewayneon.tsneonbash
neon config status # 打印分支的实时配置(网关是否已启用?)
neon config plan # 预演`apply`操作会产生的变更
neon config apply # 在分支上启用网关 (`neon deploy`是该命令的别名)网关是分支级隔离的:每个分支拥有独立的网关主机。当存在时,会在创建分支时应用配置,因此新的预览/CI分支会自动启用网关。切换至现有分支时不会同步配置——需运行来应用变更。预配置(/)、和操作还会将分支的网关凭证拉取到本地文件中,因此本地运行的请求会命中与部署函数相同的分支网关(无需手动执行)。
neon.tsneon checkoutneon deployconfig applydeploylinkcheckout.env.localenv pullEnvironment Variables
环境变量
When is enabled, Neon injects the gateway credentials as Neon-branded env vars. Inside a deployed Neon Function these are injected automatically; locally, writes them to / (or use to inject at runtime without a file):
preview.aiGatewayneon env pull.env.env.localneon-env run -- <cmd>| Variable | Meaning |
|---|---|
| Gateway bearer token (a Neon credential, |
| Bare branch gateway host ( |
Neon injects only these two vars — it does not set/OPENAI_API_KEY. TheOPENAI_BASE_URLand Mastra's@neon/ai-sdk-providerreadneon/<model>directly (zero config); for the plain OpenAI SDK /NEON_AI_GATEWAY_*, build the client's@ai-sdk/openai+apiKeyfrom them (shown below), or set your ownbaseURLby hand (OPENAI_*leaves user-set vars untouched).env pull
NEON_AI_GATEWAY_BASE_URL@neon/ai-sdk-provider- — unified, OpenAI Chat Completions-compatible; recommended default, works with every provider (
/v1)./v1/chat/completions - — OpenAI Responses API (required for
/openai/v1variants andgpt-5-…-codex); thegpt-5-5-proprovider uses the Responses API by default (@ai-sdk/openai)./openai/v1/responses - — native Anthropic Messages (extended thinking, prompt caching); mirrors the real Anthropic API path (
/anthropic/v1)./anthropic/v1/messages - — native Gemini
/gemini/v1beta/...(generateContent)./gemini/v1beta/models/<model>:generateContent
So is the chat-completions endpoint, the OpenAI Responses endpoint, and so on.
${NEON_AI_GATEWAY_BASE_URL}/v1${NEON_AI_GATEWAY_BASE_URL}/openai/v1For typed, validated access to the injected credentials, pass the same config object to from — it returns an namespace (, ) derived from your config.
neon.tsparseEnv@neon/envenv.aiGatewayapiKeybaseUrl当启用后,Neon会将网关凭证注入为Neon专属环境变量。在已部署的Neon Function中,这些变量会自动注入;在本地环境中,会将其写入/文件(或使用在运行时注入,无需写入文件):
preview.aiGatewayneon env pull.env.env.localneon-env run -- <cmd>| 变量名 | 含义 |
|---|---|
| 网关Bearer令牌(Neon凭证,格式为 |
| 分支网关裸主机地址( |
Neon仅会注入上述两个变量——不会设置/OPENAI_API_KEY。OPENAI_BASE_URL和Mastra的@neon/ai-sdk-provider会直接读取neon/<model>变量(零配置);对于原生OpenAI SDK/NEON_AI_GATEWAY_*,需手动从上述变量构建客户端的@ai-sdk/openai+apiKey(示例见下文),或自行设置baseURL变量(OPENAI_*操作不会覆盖用户自行设置的变量)。env pull
NEON_AI_GATEWAY_BASE_URL@neon/ai-sdk-provider- ——统一的、兼容OpenAI Chat Completions的路由;推荐作为默认路由,支持所有提供商(
/v1)。/v1/chat/completions - ——OpenAI Responses API(适用于
/openai/v1变体和gpt-5-…-codex);gpt-5-5-pro提供商默认使用Responses API(@ai-sdk/openai)。/openai/v1/responses - ——原生Anthropic Messages接口(支持扩展思考、提示缓存);与真实Anthropic API路径一致(
/anthropic/v1)。/anthropic/v1/messages - ——原生Gemini
/gemini/v1beta/...接口(generateContent)。/gemini/v1beta/models/<model>:generateContent
因此,是聊天补全端点,是OpenAI Responses端点,以此类推。
${NEON_AI_GATEWAY_BASE_URL}/v1${NEON_AI_GATEWAY_BASE_URL}/openai/v1如需类型化、验证后的凭证访问,可将配置对象传入的函数——它会返回命名空间(包含、),该命名空间由你的配置衍生而来。
neon.ts@neon/envparseEnvenv.aiGatewayapiKeybaseUrlBuild Agents with the Vercel AI SDK (Recommended)
使用Vercel AI SDK构建Agent(推荐)
The Vercel AI SDK is the recommended way to call the gateway and build agents from TypeScript: one set of primitives (, , tool calling, structured output) over every catalog model, with first-class streaming for the long agent responses Neon Functions are built to host.
generateTextstreamTextThe dedicated reads + from the injected env with zero config and routes each model to the best endpoint (Anthropic → Messages, OpenAI/Codex → Responses, everything else → MLflow). On a Neon Function that streams text and generates images, just pick a catalog model:
@neon/ai-sdk-providerNEON_AI_GATEWAY_BASE_URLNEON_AI_GATEWAY_TOKENtypescript
import { neon } from "@neon/ai-sdk-provider";
import { streamText } from "ai";
const result = streamText({
model: neon("gpt-5-mini"), // or claude-sonnet-4-6, gemini-2-5-flash, ...
messages,
tools: {
image_generation: neon.tools.imageGeneration({
outputFormat: "jpeg",
size: "1024x1024",
}),
},
});
return result.toUIMessageStreamResponse();A single completion is the same provider with :
generateTexttypescript
import { neon } from "@neon/ai-sdk-provider";
import { generateText } from "ai";
const { text } = await generateText({
model: neon("claude-haiku-4-5"), // or gpt-5-3-codex, gemini-2-5-flash, ...
prompt: "Summarize Postgres for me.",
});Preferover the bare@neon/ai-sdk-provider@ai-sdk/openai: Neon injects onlyopenai(), notNEON_AI_GATEWAY_*, soOPENAI_*won't pick up the gateway from the env on its own. If you do useopenai(), configure it explicitly with@ai-sdk/openai${process.env.NEON_AI_GATEWAY_BASE_URL}/openai/v1createOpenAI({ apiKey: process.env.NEON_AI_GATEWAY_TOKEN, baseURL:.})
To build an agent — a model that calls tools in a loop and then answers — add and a budget. The loop runs in-process, so on a Neon Function it isn't cut off by lambda-style timeouts:
toolsstopWhentypescript
import { neon } from "@neon/ai-sdk-provider";
import { generateText, tool, stepCountIs } from "ai";
import { z } from "zod";
const { text } = await generateText({
model: neon("claude-sonnet-4-6"),
prompt: "How many open todos do I have, and what's the oldest one?",
tools: {
listTodos: tool({
description: "List the user's open todos.",
inputSchema: z.object({}), // AI SDK v5+: `inputSchema`, not `parameters`
execute: async () => db.select().from(todos),
}),
},
stopWhen: stepCountIs(5), // let the model call tools, then summarize
});For a full AI SDK agent deployed as a Neon Function (streaming, tool calling, image generation, persistence), see the skill's .
neon-functionsreferences/ai-sdk.mdVercel AI SDK是从TypeScript调用网关并构建Agent的推荐方式:通过一套原语(、、工具调用、结构化输出)即可访问目录内所有模型,且原生支持流式传输,非常适合Neon Functions托管的长Agent响应。
generateTextstreamText专用的会从注入的环境变量中自动读取+,零配置即可将每个模型路由至最佳端点(Anthropic→Messages、OpenAI/Codex→Responses、其他模型→MLflow)。在支持流式文本和图片生成的Neon Function中,只需选择一个目录模型即可:
@neon/ai-sdk-providerNEON_AI_GATEWAY_BASE_URLNEON_AI_GATEWAY_TOKENtypescript
import { neon } from "@neon/ai-sdk-provider";
import { streamText } from "ai";
const result = streamText({
model: neon("gpt-5-mini"), // 也可使用claude-sonnet-4-6、gemini-2-5-flash等
messages,
tools: {
image_generation: neon.tools.imageGeneration({
outputFormat: "jpeg",
size: "1024x1024",
}),
},
});
return result.toUIMessageStreamResponse();单次补全操作只需将上述代码中的替换为即可:
streamTextgenerateTexttypescript
import { neon } from "@neon/ai-sdk-provider";
import { generateText } from "ai";
const { text } = await generateText({
model: neon("claude-haiku-4-5"), // 也可使用gpt-5-3-codex、gemini-2-5-flash等
prompt: "为我总结PostgreSQL。",
});优先使用而非原生@neon/ai-sdk-provider的@ai-sdk/openai:Neon仅注入openai()变量,而非NEON_AI_GATEWAY_*,因此OPENAI_*无法自动从环境变量中读取网关配置。若确实需要使用openai(),请显式配置:@ai-sdk/openai${process.env.NEON_AI_GATEWAY_BASE_URL}/openai/v1createOpenAI({ apiKey: process.env.NEON_AI_GATEWAY_TOKEN, baseURL:。})
如需构建Agent——即循环调用工具后给出答案的模型——只需添加和预算。循环在进程内运行,因此在Neon Function中不会被Lambda式超时中断:
toolsstopWhentypescript
import { neon } from "@neon/ai-sdk-provider";
import { generateText, tool, stepCountIs } from "ai";
import { z } from "zod";
const { text } = await generateText({
model: neon("claude-sonnet-4-6"),
prompt: "我有多少个未完成的待办事项?最久的那个是什么?",
tools: {
listTodos: tool({
description: "列出用户的未完成待办事项。",
inputSchema: z.object({}), // AI SDK v5+:使用`inputSchema`,而非`parameters`
execute: async () => db.select().from(todos),
}),
},
stopWhen: stepCountIs(5), // 允许模型调用工具,然后总结结果
});如需查看部署为Neon Function的完整AI SDK Agent示例(包含流式传输、工具调用、图片生成、持久化),请参考技能的文档。
neon-functionsreferences/ai-sdk.mdBuild Agents with Mastra (Recommended)
使用Mastra构建Agent(推荐)
Mastra is the recommended framework when you want batteries-included agents — built-in memory, tools, workflows, and tracing — with the model still pointed at the gateway. With 1.47+, use a magic string; Mastra reads and from the environment (injected by when is enabled). Use only for other declared services (e.g. for memory):
@mastra/coreneon/<model>NEON_AI_GATEWAY_BASE_URLNEON_AI_GATEWAY_TOKENneon deploypreview.aiGatewayparseEnvenv.postgres.databaseUrl@mastra/pgtypescript
import { Agent } from "@mastra/core/agent";
import { parseEnv } from "@neon/env";
import config from "../neon";
const env = parseEnv(config);
export const personalAssistant = new Agent({
id: "personal-assistant",
name: "personal-assistant",
instructions:
"You are a warm, concise personal assistant with long-term memory.",
model: "neon/claude-haiku-4-5",
memory, // your Mastra memory store, e.g. @mastra/pg on env.postgres.databaseUrl
});Mastra是构建功能完备Agent的推荐框架——内置内存、工具、工作流和追踪功能,同时模型仍指向网关。使用 1.47+版本时,只需使用魔法字符串;Mastra会从环境中读取和(当启用时,会自动注入这些变量)。仅需对其他声明的服务使用(例如用于内存存储):
@mastra/coreneon/<model>NEON_AI_GATEWAY_BASE_URLNEON_AI_GATEWAY_TOKENpreview.aiGatewayneon deployparseEnvenv.postgres.databaseUrl@mastra/pgtypescript
import { Agent } from "@mastra/core/agent";
import { parseEnv } from "@neon/env";
import config from "../neon";
const env = parseEnv(config);
export const personalAssistant = new Agent({
id: "personal-assistant",
name: "personal-assistant",
instructions:
"你是一位热情、简洁的个人助理,具备长期记忆能力。",
model: "neon/claude-haiku-4-5",
memory, // 你的Mastra内存存储,例如基于env.postgres.databaseUrl的@mastra/pg
});Use with Plain SDKs (Lower-Level)
使用原生SDK(底层调用)
When you don't need an agent framework — a single completion, an existing provider-SDK integration, or native provider features — call the gateway with the plain SDKs. Neon injects the vars (not ), so set the client's + from them. For the OpenAI Responses dialect ():
NEON_AI_GATEWAY_*OPENAI_*apiKeybaseURL/openai/v1typescript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.NEON_AI_GATEWAY_TOKEN,
baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/openai/v1`,
});
const res = await client.responses.create({
model: "gpt-5-mini", // swap to claude-sonnet-4-6, gemini-2-5-flash, ...
input: "What is Neon?",
});For the unified chat-completions dialect, point at instead:
baseURL/v1typescript
const client = new OpenAI({
apiKey: process.env.NEON_AI_GATEWAY_TOKEN,
baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/v1`,
});
const res = await client.chat.completions.create({
model: "claude-sonnet-4-6",
messages: [{ role: "user", content: "What is Neon?" }],
});The Anthropic SDK and google-genai work the same way for native provider features — point the Anthropic SDK at (it appends itself) and google-genai at (it appends ).
${NEON_AI_GATEWAY_BASE_URL}/anthropic/v1/messages${NEON_AI_GATEWAY_BASE_URL}/gemini/v1beta/models/...当不需要Agent框架时——例如单次补全、现有提供商SDK集成或原生提供商功能——可直接使用原生SDK调用网关。Neon注入的是变量(而非),因此需从这些变量设置客户端的+。对于OpenAI Responses协议():
NEON_AI_GATEWAY_*OPENAI_*apiKeybaseURL/openai/v1typescript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.NEON_AI_GATEWAY_TOKEN,
baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/openai/v1`,
});
const res = await client.responses.create({
model: "gpt-5-mini", // 可替换为claude-sonnet-4-6、gemini-2-5-flash等
input: "Neon是什么?",
});对于统一的聊天补全协议,只需将指向:
baseURL/v1typescript
const client = new OpenAI({
apiKey: process.env.NEON_AI_GATEWAY_TOKEN,
baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/v1`,
});
const res = await client.chat.completions.create({
model: "claude-sonnet-4-6",
messages: [{ role: "user", content: "Neon是什么?" }],
});Anthropic SDK和google-genai的使用方式类似,以支持原生提供商功能——将Anthropic SDK指向(它会自动添加路径),将google-genai指向(它会自动添加路径)。
${NEON_AI_GATEWAY_BASE_URL}/anthropic/v1/messages${NEON_AI_GATEWAY_BASE_URL}/gemini/v1beta/models/...Model Identifiers
模型标识符
Use a model's catalog ID directly in the field — e.g. , , . No provider prefix is needed. To look up the exact identifiers the gateway serves, which underlying model each maps to, and their context windows, pricing, and capabilities, use any of:
modelclaude-sonnet-4-6gpt-5-minigemini-2-5-flash- models.dev Neon provider page: https://models.dev/providers/neon — the canonical, always-current list of the Neon provider's model IDs and their underlying models. The machine-readable catalog is at https://models.dev/api.json (the key).
neon - Models doc: see Further Reading.
直接在字段中使用模型的目录ID即可——例如、、。无需添加提供商前缀。如需查看网关支持的精确标识符、每个标识符对应的底层模型及其上下文窗口、定价和功能,可通过以下方式获取:
modelclaude-sonnet-4-6gpt-5-minigemini-2-5-flash- **models.dev Neon提供商页面:https://models.dev/providers/neon**——这是Neon提供商模型ID及其对应底层模型的权威、实时更新列表。机器可读的目录位于https://models.dev/api.json(`neon`字段下)。
- 模型文档:请参考下文「延伸阅读」部分。
List Available Models at Runtime (/v1/models
)
/v1/models在运行时列出可用模型(/v1/models
)
/v1/modelsThe gateway also exposes the model catalog live from your own branch endpoint, so an app or agent can discover exactly which models this branch serves without hard-coding the list. It is an OpenAI-compatible list endpoint, served only on the unified dialect ():
/v1bash
curl "$NEON_AI_GATEWAY_BASE_URL/v1/models" \
-H "Authorization: Bearer $NEON_AI_GATEWAY_TOKEN"- → 200
GET ${NEON_AI_GATEWAY_BASE_URL}/v1/models - → 404 (not served on the Responses dialect — use
GET ${NEON_AI_GATEWAY_BASE_URL}/openai/v1/models)/v1
Getting the credentials for the request. Both values come from the same branch-scoped Neon credential the gateway uses everywhere else — you never manage a provider key:
- Provision via (recommended). Enable
neon.tsinpreview.aiGatewayand runneon.ts(orneon deploy). Provisioning,neon config apply, andneon linkpullneon checkout+NEON_AI_GATEWAY_TOKENinto your localNEON_AI_GATEWAY_BASE_URL; inside a deployed Neon Function they're injected automatically. See Setup and Environment Variables above..env.local - Pull into the environment via CLI. writes the two vars to
neon env pull/.env, or.env.localinjects them at runtime without a file — but only whenneon-env run -- <cmd>declaresneon.ts; the vars are never pulled off branch state alone.preview.aiGateway - Provision via the Console UI. Enable the AI Gateway on the branch in the Neon Console and copy the branch's gateway base URL and a Neon credential (token) from the project's connection/credentials view.
Any Neon credential () valid for the branch works as the bearer token; is the bare branch host (no path).
nt_live_...NEON_AI_GATEWAY_BASE_URLResponse shape — OpenAI/OpenRouter-compatible list:
jsonc
{
"object": "list",
"data": [
{
"id": "claude-sonnet-4-6", // catalog model ID — use directly in the `model` field
"canonical_slug": "claude-sonnet-4-6",
"name": "Claude Sonnet 4.6", // human-readable display name
"object": "model",
"owned_by": "anthropic", // anthropic | openai | google | meta | alibaba | databricks
"created": 0,
"enabled": true,
"context_length": null,
"architecture": {
"modality": "text->text",
"input_modalities": ["text"],
"output_modalities": ["text"],
"tokenizer": "Claude", // Claude | Gemini | GPT | "" (empty for open-source)
"instruct_type": null
},
"top_provider": {
"is_moderated": false,
"context_length": null,
"max_completion_tokens": null
},
"pricing": null,
"per_request_limits": null
}
// ... one entry per model in the branch's catalog
]
}Note:,context_length, andpricingare currentlyper_request_limitsandnulliscreatedfor every entry — for context windows, pricing, and capabilities use the models.dev catalog above. Use0when you need the live, branch-scoped list of servable model IDs (e.g. to populate a model picker or validate a/v1/modelsbefore a request).model
网关还会从你的分支端点实时暴露模型目录,因此应用或Agent可发现该分支实际支持的模型,无需硬编码列表。这是一个兼容OpenAI的列表端点,仅在统一协议()下提供:
/v1bash
curl "$NEON_AI_GATEWAY_BASE_URL/v1/models" \
-H "Authorization: Bearer $NEON_AI_GATEWAY_TOKEN"- → 200(成功)
GET ${NEON_AI_GATEWAY_BASE_URL}/v1/models - → 404(Responses协议下不提供该接口——请使用
GET ${NEON_AI_GATEWAY_BASE_URL}/openai/v1/models)/v1
获取请求所需的凭证:两个值均来自网关使用的分支级Neon凭证——你无需管理任何提供商密钥:
- 通过预配置(推荐):在
neon.ts中启用neon.ts并运行preview.aiGateway(或neon deploy)。预配置、neon config apply和neon link操作会将neon checkout+NEON_AI_GATEWAY_TOKEN拉取到本地NEON_AI_GATEWAY_BASE_URL文件中;在已部署的Neon Function中,这些变量会自动注入。请参考上文「配置步骤」和「环境变量」部分。.env.local - 通过CLI拉取到环境中:会将两个变量写入
neon env pull/.env文件,或使用.env.local在运行时注入,无需写入文件——但仅当neon-env run -- <cmd>中声明了neon.ts时才会生效;不会仅从分支状态拉取这些变量。preview.aiGateway - 通过控制台UI预配置:在Neon控制台中为分支启用AI网关,并从项目的连接/凭证视图中复制分支的网关基础URL和Neon凭证(令牌)。
任何对该分支有效的Neon凭证()均可作为Bearer令牌使用;是分支的裸主机地址(无路径)。
nt_live_...NEON_AI_GATEWAY_BASE_URL响应格式——兼容OpenAI/OpenRouter的列表:
jsonc
{
"object": "list",
"data": [
{
"id": "claude-sonnet-4-6", // 目录模型ID——直接在`model`字段中使用
"canonical_slug": "claude-sonnet-4-6",
"name": "Claude Sonnet 4.6", // 人类可读的显示名称
"object": "model",
"owned_by": "anthropic", // anthropic | openai | google | meta | alibaba | databricks
"created": 0,
"enabled": true,
"context_length": null,
"architecture": {
"modality": "text->text",
"input_modalities": ["text"],
"output_modalities": ["text"],
"tokenizer": "Claude", // Claude | Gemini | GPT | ""(开源模型为空)
"instruct_type": null
},
"top_provider": {
"is_moderated": false,
"context_length": null,
"max_completion_tokens": null
},
"pricing": null,
"per_request_limits": null
}
// ... 分支目录中每个模型对应一个条目
]
}注意:目前所有条目的、context_length和pricing均为per_request_limits,null均为created——如需获取上下文窗口、定价和功能信息,请参考上述models.dev目录。当你需要实时的、分支级的可服务模型ID列表时(例如填充模型选择器或在请求前验证0字段),请使用model接口。/v1/models
Neon Documentation
Neon官方文档
The Neon documentation is the source of truth and the AI Gateway is evolving rapidly, so always verify against the official docs. Any doc page can be fetched as markdown by appending to the URL or by requesting . Find the right page from the docs index (https://neon.com/docs/llms.txt) and the changelog announcements.
.mdAccept: text/markdownNeon官方文档是权威来源,且AI网关正在快速演进,因此请始终以官方文档为准。任何文档页面均可通过在URL后添加或请求获取Markdown格式内容。可从文档索引(https://neon.com/docs/llms.txt)和更新日志中找到对应页面。
.mdAccept: text/markdownFurther Reading
延伸阅读
- https://neon.com/docs/ai-gateway/overview.md
- https://neon.com/docs/ai-gateway/get-started.md
- https://neon.com/docs/ai-gateway/models.md
- https://neon.com/docs/ai-gateway/chat-completions.md
- https://neon.com/docs/ai-gateway/anthropic-messages.md
- https://neon.com/docs/ai-gateway/openai-responses.md
- https://neon.com/docs/ai-gateway/gemini.md
- https://neon.com/docs/ai-gateway/authentication.md
- https://neon.com/docs/ai-gateway/troubleshooting.md
- https://neon.com/docs/ai-gateway/overview.md
- https://neon.com/docs/ai-gateway/get-started.md
- https://neon.com/docs/ai-gateway/models.md
- https://neon.com/docs/ai-gateway/chat-completions.md
- https://neon.com/docs/ai-gateway/anthropic-messages.md
- https://neon.com/docs/ai-gateway/openai-responses.md
- https://neon.com/docs/ai-gateway/gemini.md
- https://neon.com/docs/ai-gateway/authentication.md
- https://neon.com/docs/ai-gateway/troubleshooting.md