工具与客户端
JavaScript / Node.js 接入
在服务端项目中读取环境变量并处理流式结果。
安装与配置
使用 Node.js 官网当前 LTS 版本。在自己的项目目录中安装 SDK;若项目还没有 package.json,可先运行 npm init -y。
npm install openai设置首个请求中的三个环境变量。将下面的文件保存为 .mjs,即可使用 ES Module 语法。
一个可复制的流式示例
import OpenAI from "openai";
for (const key of ["SOTAAI_API_KEY", "SOTAAI_BASE_URL", "SOTAAI_MODEL"]) {
if (!process.env[key]) throw new Error(`Missing environment variable: ${key}`);
}
const client = new OpenAI({
apiKey: process.env.SOTAAI_API_KEY,
baseURL: process.env.SOTAAI_BASE_URL.replace(/\/$/, "") + "/v1",
timeout: 120_000,
maxRetries: 0,
});
const stream = await client.responses.create({
model: process.env.SOTAAI_MODEL,
input: "Reply with exactly OK.",
stream: true,
store: false,
});
let completed = false;
for await (const event of stream) {
if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
if (event.type === "response.completed") completed = true;
if (["error", "response.failed", "response.incomplete"].includes(event.type)) {
throw new Error(`Stream ended with ${event.type}`);
}
}
if (!completed) throw new Error("Stream ended without response.completed");
process.stdout.write("\n");node sota-example.mjs网页应用应该怎么接
浏览器调用你自己的后端,由后端持有本站密钥并转发请求。不要把密钥放进 VITE_、NEXT_PUBLIC_ 等会打包到浏览器的公开环境变量。
同时为你自己的用户增加身份校验、费用限制和访问控制,避免后端成为任何人都能使用的付费接口。
发现内容有误,或有未解答的问题?反馈文档问题 ↗