全部文章

AI API 接入指南

OpenAI、Claude、Gemini 等主流 AI API 的接入方式、SDK 使用与费用优化

目录 21 节

AI API 接入指南

这页适合作为“把模型能力真正接进应用”的起点。API 接入的重点不只是调通一次请求,而是把密钥管理、模型选型、流式输出、重试、成本控制和日志观测一起做稳。

先按产品形态选接法

  • 只做单轮问答或简单接口封装:直接用官方 SDK
  • 要在多个模型厂商间切换:考虑统一 SDK 或抽象层
  • 要做聊天应用:优先设计消息结构、上下文裁剪和流式返回
  • 要做 Agent / 工具调用:先把工具协议和错误处理定义清楚
  • 要做企业或团队产品:先规划密钥、配额、日志、审计和回退策略

OpenAI API

安装

pnpm add openai

基础调用

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// Chat Completion
const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: "你是一位 TypeScript 专家" },
    { role: "user", content: "解释 infer 关键字" },
  ],
  temperature: 0.7,
  max_tokens: 1000,
});

console.log(response.choices[0].message.content);

流式输出

const stream = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "写一首诗" }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content || "";
  process.stdout.write(content);
}

Function Calling

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "北京今天天气怎么样?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "获取指定城市的天气",
        parameters: {
          type: "object",
          properties: {
            city: { type: "string", description: "城市名" },
          },
          required: ["city"],
        },
      },
    },
  ],
});

// 检查是否需要调用函数
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
  const args = JSON.parse(toolCall.function.arguments);
  const weather = await getWeather(args.city);
  // 将结果返回给模型继续对话...
}

接入最小流程

比较稳的接入流程通常是:

  1. 先在本地用最小示例调通
  2. 再把 API Key 放进环境变量
  3. 再补超时、重试和错误日志
  4. 再补流式输出和上下文管理
  5. 最后才做多模型切换、缓存和成本优化

不要一开始就同时接很多厂商和很多能力,先让一条主链路稳定最重要。

Anthropic Claude API

pnpm add @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const response = await client.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  system: "你是一位资深开发者",
  messages: [{ role: "user", content: "比较 React 和 Vue 的优缺点" }],
});

console.log(response.content[0].text);

流式输出

const stream = client.messages.stream({
  model: "claude-sonnet-4-20250514",
  max_tokens: 1024,
  messages: [{ role: "user", content: "你好" }],
});

for await (const event of stream) {
  if (
    event.type === "content_block_delta" &&
    event.delta.type === "text_delta"
  ) {
    process.stdout.write(event.delta.text);
  }
}

Google Gemini API

pnpm add @google/generative-ai
import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });

const result = await model.generateContent("解释量子计算");
console.log(result.response.text());

AI SDK(Vercel)

统一的 AI SDK,支持多个提供商。

pnpm add ai @ai-sdk/openai @ai-sdk/anthropic
import { generateText, streamText } from "ai";
import { openai } from "@ai-sdk/openai";
import { anthropic } from "@ai-sdk/anthropic";

// 统一接口,切换模型只需改一行
const result = await generateText({
  model: openai("gpt-4o"),
  // model: anthropic('claude-sonnet-4-20250514'),
  prompt: "你好",
});

// 流式
const stream = streamText({
  model: openai("gpt-4o"),
  messages: [{ role: "user", content: "写一个排序算法" }],
});

for await (const text of stream.textStream) {
  process.stdout.write(text);
}

中转 API / 代理

国内访问 OpenAI 等 API 可使用兼容的中转服务:

const client = new OpenAI({
  baseURL: "https://your-proxy.com/v1",
  apiKey: "your-key",
});

常见兼容 API 提供商:

费用优化

  • 选择合适的模型:简单任务用小模型(GPT-4o-mini、Haiku)
  • 控制 max_tokens:避免不必要的长输出
  • 缓存常见请求的结果
  • 使用 system 消息精简上下文
  • 批量请求使用 Batch API(OpenAI 半价)
  • 监控用量:设置 API 用量上限

接口设计建议

  • 把模型名、温度、最大输出长度做成可配置项
  • 区分用户输入、系统指令和工具结果
  • 为失败请求保留请求 ID、错误码和耗时日志
  • 给外部调用方返回更稳定的业务错误,而不是直接透传上游异常

常见问题

本地能调通,线上报鉴权错误

优先检查:

  • 环境变量是否真的注入到运行环境
  • 是否把客户端调用误写成了服务端调用
  • 不同环境是否用了不同 Key 或 Base URL

输出太贵、太慢

高频处理思路:

  • 换更小模型
  • 裁剪上下文
  • 限制输出长度
  • 对稳定内容做缓存

多厂商接入后逻辑越来越乱

更稳的做法是抽一层统一接口,把这些差异收口:

  • 模型名
  • 请求参数
  • 错误结构
  • 流式事件格式

风险提醒

  • 不要把密钥暴露到前端公开环境变量
  • 不要默认把完整用户隐私数据直接发给第三方模型
  • 中转 API 很方便,但要额外评估稳定性、日志留存和数据边界
  • 先做成本上限与监控,再放给真实用户大规模使用

延伸阅读

参考链接

阅读建议
  • - 先读标题和摘要,再结合目录决定从哪个章节开始精读。
  • - 看到具体命令、配置或步骤时,尽量在自己的环境里同步验证。
  • - 如果你只是快速查资料,可先看目录和相关文档,再决定是否深入全文。
适合谁看
  • - 希望把零散经验整理成长期可复用工作流的人
  • - 正在使用 AI 工具、Agent 或自动化工作流的人
  • - 希望阅读时顺手建立自己的操作清单或收藏体系的人
执行前检查
  • - 先浏览标题、摘要和目录,带着问题阅读会更高效
  • - 确认模型供应商、API Key、CLI 工具链与本地资源是否已准备好
  • - 如果页面里提到相关文档,尽量一起打开对照,效果通常更完整
同类内容
← 上一篇AI 终端代理与自主工具