Node.js SDK 使用指南
ClawdRouter 兼容 OpenAI Node.js SDK 和 Anthropic Node.js SDK,你可以根据需要选择使用。
OpenAI SDK
安装
npm install openai
# 或
yarn add openai
# 或
pnpm add openai
初始化客户端
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.clawdrouter.com/v1",
});
环境变量
建议通过环境变量管理 API Key:
export OPENAI_API_KEY="YOUR_API_KEY"
export OPENAI_BASE_URL="https://api.clawdrouter.com/v1"
// 会自动读取环境变量
const client = new OpenAI();
基础对话
async function main() {
const completion = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "你是一个有用的助手" },
{ role: "user", content: "用简单的话解释什么是机器学习" },
],
});
console.log(completion.choices[0].message.content);
}
main();
流式输出
async function streamChat() {
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;
if (content) {
process.stdout.write(content);
}
}
console.log(); // 换行
}
streamChat();
多轮对话
const messages = [
{ role: "system", content: "你是一个有用的助手" },
];
async function chat(userInput) {
messages.push({ role: "user", content: userInput });
const completion = await client.chat.completions.create({
model: "gpt-4o",
messages,
});
const reply = completion.choices[0].message.content;
messages.push({ role: "assistant", content: reply });
return reply;
}
async function main() {
console.log(await chat("什么是量子计算?"));
console.log(await chat("它和传统计算有什么区别?"));
console.log(await chat("目前有哪些实际应用?"));
}
main();
工具调用 (Function Calling)
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "获取指定城市的天气信息",
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "城市名称,如 北京",
},
},
required: ["city"],
},
},
},
];
async function main() {
const completion = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "user", content: "北京今天天气怎么样?" },
],
tools,
tool_choice: "auto",
});
const message = completion.choices[0].message;
if (message.tool_calls) {
const toolCall = message.tool_calls[0];
console.log(`调用工具: ${toolCall.function.name}`);
console.log(`参数: ${toolCall.function.arguments}`);
}
}
main();
错误处理
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.clawdrouter.com/v1",
});
async function main() {
try {
const completion = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "你好" }],
});
console.log(completion.choices[0].message.content);
} catch (error) {
if (error instanceof OpenAI.AuthenticationError) {
console.error("API Key 无效,请检查配置");
} else if (error instanceof OpenAI.RateLimitError) {
console.error("请求频率超限,请稍后重试");
} else if (error instanceof OpenAI.APIError) {
console.error(`API 错误: ${error.message}`);
} else {
throw error;
}
}
}
main();