SDK 与集成
Node.js SDK
用 OpenAI Node.js SDK 接入 CokeAPI,服务端调用 chat / images / video 接口。
CokeAPI 与 OpenAI 协议兼容,用 OpenAI 官方 Node.js SDK 即可。
安装
npm install openai
# 或
pnpm add openai
yarn add openai基础用法
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://cokeapi.com/v1",
apiKey: process.env.COKEAPI_KEY,
});
// 文本
const resp = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "用一句话介绍 CokeAPI" }],
});
console.log(resp.choices[0].message.content);流式
const stream = await client.chat.completions.create({
model: "grok-4.20-fast",
messages: [{ role: "user", content: "讲个三句的笑话" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}TypeScript 类型
OpenAI SDK 自带完整类型,直接用即可:
import OpenAI, { type ChatCompletionMessageParam } from "openai";
const messages: ChatCompletionMessageParam[] = [
{ role: "system", content: "你是简洁的助手" },
{ role: "user", content: "用一句话介绍 CokeAPI" },
];
const resp = await client.chat.completions.create({
model: "gpt-4o-mini",
messages,
});错误处理
import OpenAI, { RateLimitError, APIError } from "openai";
try {
await client.chat.completions.create({...});
} catch (err) {
if (err instanceof RateLimitError) {
console.log("限流,稍后重试");
} else if (err instanceof APIError) {
console.log(`code=${err.error?.code} trace_id=${err.error?.trace_id}`);
}
}