目录 · 5 个章节
想在 Node 项目里同时用上 Claude、GPT 等模型,又不想为每个厂商单独接 SDK 时,可以用 OpenAI 兼容接口:一套 baseURL + apiKey,按 model 切换。
下面按用户视角跟做(文档与端点以官方为准,价格以控制台为准,文中不写死价格)。
1. 准备
- API 文档:https://doc.apixhm.com
- 对话/兼容接口:https://api.apixhm.com
- 生图接口:https://image.apixhm.com
- 在控制台拿到 API Key,本地用环境变量,例如 YUAN_API_KEY,不要提交进仓库。
2. 安装
npm i openai
3. 最小可跑示例(聊天)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.YUAN_API_KEY,
baseURL: "https://api.apixhm.com/v1",
});
const res = await client.chat.completions.create({
model: "gpt-4o-mini", // 也可换成控制台里的 Claude 等兼容模型名
messages: [{ role: "user", content: "用三句话介绍 Node 流式输出" }],
});
console.log(res.choices[0].message.content);
换模型时只改 model;baseURL 仍指向 https://api.apixhm.com 的 OpenAI 兼容路径(具体路径以 https://doc.apixhm.com 为准)。
4. 生图(可选)
需要配图时走 https://image.apixhm.com ,请求格式见 https://doc.apixhm.com ,同样用 Key,勿把 Key 写进前端公开仓库。
5. 小建议
- 先用最小脚本验证 Key 与模型名,再接到业务里。
- 流式场景看文档的 stream 说明;返回 HTTP 200 不等于业务成功,注意错误体。
- 配额与计费以控制台实时显示为准。
欢迎补充你在 Node 里接兼容中转的坑,我也可以按你的框架(Express / Nest 等)改一版示例。