安装与配置
在项目目录安装 SDK,使用它支持的 Node.js 运行时,生产环境锁定经过测试的版本。
npm install openai按鉴权指南配置 QINGYUN_TOP_API_KEY、QINGYUN_TOP_BASE_URL、QINGYUN_TOP_MODEL。Base URL 为 https://top.qingyuntop.ai/v1。
保存为 app.mjs
import OpenAI from 'openai';
for (const name of ['QINGYUN_TOP_API_KEY', 'QINGYUN_TOP_BASE_URL', 'QINGYUN_TOP_MODEL']) {
if (!process.env[name]) throw new Error(`缺少环境变量:${name}`);
}
const client = new OpenAI({
apiKey: process.env.QINGYUN_TOP_API_KEY,
baseURL: process.env.QINGYUN_TOP_BASE_URL,
timeout: 60_000,
maxRetries: 0,
});
try {
const result = await client.chat.completions.create({
model: process.env.QINGYUN_TOP_MODEL,
messages: [{ role: 'user', content: '请用一句话解释 API' }],
});
console.log(result.choices[0]?.message?.content ?? '返回没有普通文本');
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error({ status: error.status, requestId: error.request_id });
} else {
console.error('网络或运行环境错误,请检查配置');
}
process.exitCode = 1;
}执行 node app.mjs。变量在终端中设置,只对当前进程及其子进程有效;开发服务器或容器需要重新加载对应配置。
Web 项目注意事项
让浏览器调用你自己的已鉴权业务后端,再由后端调用模型。不要开启 SDK 的浏览器密钥选项来绕过保护,也不要把密钥写入公开环境变量。你自己的业务接口应控制调用用户、请求大小和预算,不能成为无限制的匿名转发入口。
先用普通文本成功,再添加流式输出或工具能力;处理非文本回复时参照实际协议字段。