ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Kilo AI Gateway 快速入门:用 Vercel AI SDK、OpenAI SDK、Python 与 cURL 发起你的第一次模型请求

Kilo AI Gateway 快速入门:用 Vercel AI SDK、OpenAI SDK、Python 与 cURL 发起你的第一次模型请求 Kilo AI Gateway 快速入门用 Vercel AI SDK、OpenAI SDK、Python 与 cURL 发起你的第一次模型请求【免费下载链接】kilocodeKilo is the all-in-one agentic engineering platform. Build, ship, and iterate faster with the most popular open source coding agent.项目地址: https://gitcode.com/GitHub_Trending/ki/kilocodeKilo AI GatewayKilo 网关是开源编码代理平台 Kilo 提供的统一 AI 模型接入层通过一个 OpenAI 兼容的 REST 接口聚合数百种模型。本文以 quickstart.md 为骨架带你从零完成环境准备、API Key 配置并分别使用 Vercel AI SDK、OpenAI SDKTypeScript/Python与 cURL 发起第一次流式与非流式模型请求文末结合 kilo-gateway 源码说明网关的认证、路由与请求头机制让你既能照抄运行也能理解其底层原理。前置条件Kilo 账号与 API 额度在使用网关前你需要一个 Kilo 账号并拥有可用的 API 额度credits。注册账号后从账户控制台dashboard添加额度即可开始调用付费模型。如果暂时不想充值也可以直接使用模型 ID 带:free后缀的免费模型如minimax/minimax-m2.1:free、z-ai/glm-5:free进行体验这类请求无需 API Key 也可发起具体限制见下文「认证方式」一节。使用 Vercel AI SDK四步发起第一次请求Vercel AI SDK 提供了面向 TypeScript 的高层流式接口是官方文档推荐的接入方式sdks-and-frameworks.md 中将其标注为 Recommended。1. 创建项目mkdir my-ai-app cd my-ai-app npm init -y2. 安装依赖需要安装 AI SDK 核心包、OpenAI 兼容适配器以及用于加载.env的dotenvnpm install ai ai-sdk/openai dotenv3. 配置 API Key在项目根目录创建.env文件写入你的 Kilo API KeyKILO_API_KEYyour_api_key_here关于如何申请 API Key 的详细步骤可参考仓库内的 setup-authentication 文档其中包含 Kilo Gateway API Key 一节。Kilo 的 API Key 本质上是绑定到账号的 JWT 令牌通过Authorization: Bearer your_api_key头传递。4. 创建并运行脚本创建index.mjsimport { streamText } from ai import { createOpenAI } from ai-sdk/openai import dotenv/config const kilo createOpenAI({ baseURL: https://api.kilo.ai/api/gateway, apiKey: process.env.KILO_API_KEY, }) async function main() { const result streamText({ model: kilo.chat(anthropic/claude-sonnet-4.5), prompt: Invent a new holiday and describe its traditions., }) for await (const textPart of result.textStream) { process.stdout.write(textPart) } console.log() console.log(Token usage:, await result.usage) console.log(Finish reason:, await result.finishReason) } main().catch(console.error)运行脚本node index.mjs脚本将把模型的回复逐 token 流式输出到终端流结束后还会打印本次调用的 token 用量与结束原因finish reason。要点解析baseURL必须指向https://api.kilo.ai/api/gateway这是网关的 OpenAI 兼容端点。在仓库源码中constants.ts 定义了DEFAULT_KILO_API_URL https://api.kilo.ai并支持通过环境变量KILO_API_URL覆盖默认地址KILO_API_BASE process.env[ENV_KILO_API_URL] || DEFAULT_KILO_API_URL网关路径即拼在其后。模型 ID 采用provider/model-name格式例如anthropic/claude-sonnet-4.5。更换模型只需要修改这一字符串无需改动任何业务代码详见 models-and-providers.md。返回对象result.usage与result.finishReason均为 Promise需要在流结束后await。进阶在流式请求中加入工具调用Tool CallingVercel AI SDK 的streamText天然支持工具调用只需传入tools配置。下面的例子在流式生成的同时注册了一个getWeather工具并用 zod 描述参数结构sdks-and-frameworks.md 中的官方示例import { streamText, tool } from ai import { createOpenAI } from ai-sdk/openai import { z } from zod const kilo createOpenAI({ baseURL: https://api.kilo.ai/api/gateway, apiKey: process.env.KILO_API_KEY, }) const result streamText({ model: kilo.chat(anthropic/claude-sonnet-4.5), prompt: What is the weather in San Francisco?, tools: { getWeather: tool({ description: Get the current weather for a location, parameters: z.object({ location: z.string().describe(City name), }), execute: async ({ location }) { return { temperature: 72, condition: sunny } }, }), }, }) for await (const textPart of result.textStream) { process.stdout.write(textPart) }进阶在 Next.js API 路由中流式返回若你的应用基于 Next.js可以直接用result.toDataStreamResponse()把流式结果转成可返回的 Response避免自行处理 SSEimport { streamText } from ai import { createOpenAI } from ai-sdk/openai const kilo createOpenAI({ baseURL: https://api.kilo.ai/api/gateway, apiKey: process.env.KILO_API_KEY, }) export async function POST(request: Request) { const { messages } await request.json() const result streamText({ model: kilo.chat(anthropic/claude-sonnet-4.5), messages, }) return result.toDataStreamResponse() }使用 OpenAI SDKTypeScript 与 Python 双版本Kilo AI Gateway 完全兼容 OpenAI API 协议因此官方 OpenAI SDK 只需把baseURL指向 Kilo 网关即可无需任何适配层。这与仓库中 provider.ts 的实现思路一致——createKilo内部正是基于openrouter/ai-sdk-provider、ai-sdk/anthropic、ai-sdk/openai、ai-sdk/openai-compatible四个 SDK 实例封装而成languageModel、anthropic、openai、openaiCompatible分别暴露对应入口说明网关从设计上就兼容多种 AI SDK 生态。TypeScriptimport OpenAI from openai const client new OpenAI({ apiKey: process.env.KILO_API_KEY, baseURL: https://api.kilo.ai/api/gateway, }) const response await client.chat.completions.create({ model: anthropic/claude-sonnet-4.5, messages: [{ role: user, content: Why is the sky blue? }], }) console.log(response.choices[0].message.content)Pythonpip install openaiimport os from openai import OpenAI client OpenAI( api_keyos.getenv(KILO_API_KEY), base_urlhttps://api.kilo.ai/api/gateway, ) response client.chat.completions.create( modelanthropic/claude-sonnet-4.5, messages[ {role: user, content: Why is the sky blue?} ], ) print(response.choices[0].message.content)OpenAI SDK 同时支持流式调用将请求参数中的stream设为true后TypeScript 侧通过for await (const chunk of stream)逐块读取chunk.choices[0]?.delta?.contentPython 侧同理读取chunk.choices[0].delta.content。完整的流式示例可参考 sdks-and-frameworks.md 与 streaming.md。使用 cURL验证网关的最快方式不引入任何依赖用curl即可完成对网关的冒烟测试curl -X POST https://api.kilo.ai/api/gateway/chat/completions \ -H Authorization: Bearer $KILO_API_KEY \ -H Content-Type: application/json \ -d { model: anthropic/claude-sonnet-4.5, messages: [ { role: user, content: Why is the sky blue? } ], stream: false }响应体结构与 OpenAI Chat Completions 完全一致其中choices[0].message.content即模型回答。流式请求将stream改为true并加上-N参数关闭缓冲让 token 到达即显示curl -N -X POST https://api.kilo.ai/api/gateway/chat/completions \ -H Authorization: Bearer $KILO_API_KEY \ -H Content-Type: application/json \ -d { model: anthropic/claude-sonnet-4.5, messages: [{role: user, content: Write a short story about AI.}], stream: true }网关返回标准的 Server-Sent EventsSSE格式每个事件以data:前缀包裹 JSON 分片末尾以data: [DONE]结束且网关会在所有流式请求中自动注入stream_options.include_usage true因此在[DONE]之前的最后一个 chunkchoices为空数组中会携带完整的usageprompt_tokens / completion_tokens / total_tokens信息方便客户端统计用量详见 streaming.md。认证方式API Key、组织令牌与匿名访问网关的认证体系决定了你“能否调用、按什么价格调用”理解它有助于排查 401/402 错误。相关内容来自 authentication.md此处提炼要点方式凭证说明API KeyAuthorization: Bearer api_key主要方式Key 是绑定 Kilo 账号的 JWT 令牌组织令牌额外携带X-KiloCode-OrganizationId请求头组织级请求令牌约 15 分钟过期强制组织策略模型白名单、提供商限制、按用户消费上限匿名访问无凭证仅限免费模型模型 ID 带:free按 IP 限流每 IP 每小时 200 次请求网关还接受一系列可选请求头用于组织上下文、任务追踪与路由提示Header是否必填说明Authorization是免费模型除外Bearer api_keyContent-Type是application/jsonX-KiloCode-OrganizationId否组织级请求的组织上下文X-KiloCode-TaskId否任务标识用于 prompt 缓存键X-KiloCode-Version否客户端版本号x-kilocode-mode否kilo-auto模型路由的 mode 提示这些头部常量在仓库源码中有完整定义例如 constants.ts 中声明了HEADER_ORGANIZATIONID X-KILOCODE-ORGANIZATIONID、HEADER_TASKID X-KILOCODE-TASKID等headers.ts 则提供buildKiloHeaders/getDefaultHeaders等构造函数负责为 SDK 请求统一附加这些头。Bring Your Own KeyBYOKBYOK 允许你把自己的提供商 API Key 绑定到网关请求会使用你的 Key 直连对应提供商由提供商直接计费Kilo 不附加任何加价网关侧把成本记为 $0。Key 在存储时使用 AES-256 加密可在个人或组织层级配置组织级 Key 需要 owner 或 billing manager 权限管理。已支持的 BYOK 提供商包括 Anthropic、AWS Bedrock、Google AI Studio、OpenAI、MiniMax、Mistral、SpaceXAI、Z.AI 等 20 余家完整清单见 authentication.md。需要注意的是如果 BYOK Key 调用失败网关不会自动回退到 Kilo 的 Key。模型选择与kilo-auto虚拟模型网关通过一个/models端点开放完整模型目录无需认证即可浏览定价、上下文窗口与能力特性GET https://api.kilo.ai/api/gateway/models常用模型 ID 示例详见 models-and-providers.mdanthropic/claude-opus-4.7、anthropic/claude-sonnet-4.6、openai/gpt-5.4、google/gemini-3.1-pro-preview、deepseek/deepseek-v3.2、moonshotai/kimi-k2.5等免费模型则包括stepfun/step-3.7-flash:free、openrouter/free等。除了具体模型网关还提供四个kilo-auto/*虚拟模型由服务端按层级路由到底层模型kilo-auto/frontier最高能力档位按x-kilocode-mode请求头路由——plan/general/architect/orchestrator/ask/debug模式解析到anthropic/claude-opus-4.7build/explore/code模式解析到anthropic/claude-sonnet-4.6默认解析到anthropic/claude-sonnet-4.6。kilo-auto/efficient会话感知路由按任务难度分类并路由到“够用且最便宜”的模型无法置信分类时按客户端所用 API 接口回退基线模型Completions →qwen/qwen3.6-plus、Responses API →openai/gpt-5.5、Messages API →anthropic/claude-sonnet-4.6。kilo-auto/free免费档无需额度从一组免费模型中按会话动态选择。kilo-auto/small面向会话标题、提交信息、摘要等轻量后台任务有余额时路由到google/gemma-4-31b-it无余额时路由到google/gemma-4-26b-a4b-it:free。kilo-auto/*层级 ID 保持稳定但底层映射会随提供商定价与可用性变化而由服务端更新。仓库中 constants.ts 将默认模型与默认免费模型均定义为kilo-auto/free即网关 SDK 的默认兜底模型。例如带 mode 头的调用curl -X POST https://api.kilo.ai/api/gateway/chat/completions \ -H Authorization: Bearer $KILO_API_KEY \ -H x-kilocode-mode: plan \ -H Content-Type: application/json \ -d {model: kilo-auto/efficient, messages: [{role: user, content: Design a database schema}]}深入底层网关 SDK 如何工作如果你想把 Kilo 网关能力直接集成进自己的 CLI 或 Agent 工具仓库里的 kilo-gateway 包提供了完整的实现参考Provider 封装provider.ts 中的createKilo(options)返回一个KiloProvider其内部统一配置baseURL、apiKey与自定义请求头再分别实例化 OpenRouter、Anthropic、OpenAI 与 OpenAI-Compatible 四个 SDK通过languageModel(modelId)、anthropic(modelId)、openai(modelId)、openaiCompatible(modelId)暴露。它还通过自定义fetch包装器动态附加Authorization: Bearer apiKey头并支持匿名场景ANONYMOUS_API_KEY anonymous。请求体变换responses.ts 的transformRequestBody会在调用/responses端点时剔除输入中的item_reference与冗余id字段并支持注入provider.data_collection数据采集开关用于兼容不同上游接口。网关路由server/routes.ts 展示了网关侧的完整 API 面——/profile用户与组织信息、/organization切换组织、/modes组织自定义模式、/fim填空补全、/editNext Edit 补全、/audio/transcriptions语音转写、/models/images与/image/generations图像生成、/notifications、/cloud/session/*云会话同步等全部通过 Hono zod 描述并校验。你可以借此理解网关不只是「聊天补全」还覆盖了编码代理所需的全套能力。继续深入认证与 API Key 管理 — 掌握 API Key、组织令牌、匿名访问与 BYOK模型与提供商 — 浏览可用模型与kilo-auto路由机制流式响应 — 实现实时流式输出、取消与错误处理SDK 与框架集成 — 在 LangChain、LlamaIndex、Haystack 等框架中接入网关API 参考 — 完整的请求与响应 Schema网关 SDK 源码 — 深入阅读 Provider、认证与路由实现至此你已经掌握了用四种方式Vercel AI SDK、OpenAI SDK TypeScript、OpenAI SDK Python、cURL发起 Kilo AI Gateway 首次请求的完整流程并理解了其认证、模型路由与底层 SDK 封装原理——足以在自己的项目中直接落地。【免费下载链接】kilocodeKilo is the all-in-one agentic engineering platform. Build, ship, and iterate faster with the most popular open source coding agent.项目地址: https://gitcode.com/GitHub_Trending/ki/kilocode创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表