示例
JavaScript
在 Node.js 中使用 OpenAI 官方 SDK 调用 CanalAPI。
CanalAPI 与 OpenAI HTTP 协议兼容,可直接使用 openai Node SDK。
安装
npm install openai
# 或
pnpm add openaiHello world
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.CANALAPI_API_KEY,
baseURL: process.env.CANALAPI_BASE_URL,
});
const r = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: '你好' }],
});
console.log(r.choices[0].message.content);异步迭代式流式
const stream = await client.chat.completions.create({
model: 'gpt-4o-mini',
stream: true,
messages: [{ role: 'user', content: '用流式给我写一段短诗。' }],
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}健壮的错误处理
import OpenAI, { APIError } from 'openai';
const client = new OpenAI({
apiKey: process.env.CANALAPI_API_KEY,
baseURL: process.env.CANALAPI_BASE_URL,
});
async function ask(prompt: string, attempt = 0): Promise<string> {
try {
const r = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
});
return r.choices[0].message.content ?? '';
} catch (e) {
if (e instanceof APIError && [429, 500, 502, 503, 504].includes(e.status ?? 0) && attempt < 4) {
const delay = Math.min(1000 * 2 ** attempt, 8000) * (0.75 + Math.random() * 0.5);
await new Promise((r) => setTimeout(r, delay));
return ask(prompt, attempt + 1);
}
throw e;
}
}在 Next.js 中使用
CanalAPI 必须在服务端调用,绝不要在 Client Component 中直接调用。典型做法是 App Router 中的 Route Handler:
// app/api/chat/route.ts
import OpenAI from 'openai';
export const runtime = 'nodejs';
const client = new OpenAI({
apiKey: process.env.CANALAPI_API_KEY,
baseURL: process.env.CANALAPI_BASE_URL,
});
export async function POST(req: Request) {
const { prompt } = await req.json();
const r = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: prompt }],
});
return Response.json({ text: r.choices[0].message.content });
}