要点
- 运行 npm install openai,然后将 baseURL 设置为 https://api.gemininsfw.cc/v1.
- 流式输出使用 for await 遍历响应;使用情况在末尾显示。
- 工具调用在消息中返回,结果以 role tool 的形式传入。
- 遇到 HTTP 429 时,在重试前读取错误代码和 Retry-After 头。
llm api node 项目快速配置
这是 llm api node 集成的快速路径。你需要 Node 18 或更新版本、使用 ES 模块的项目,以及来自 密钥页面的 API 密钥。
mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="your-key-here"
创建 index.js:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
});
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [
{ role: "system", content: "You are a concise assistant." },
{ role: "user", content: "Give me three names for a fantasy tavern." },
],
temperature: 0.8,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);
使用 node index.js 运行它。该包将密钥作为 Authorization: Bearer 头发送,因此无需手动设置。
无 SDK:原生 fetch
如果你偏好零依赖,Node 18 内置了 fetch。该接口有两个方法,POST /v1/chat/completions 和 GET /v1/models,因此编写一个轻量级包装器很容易。
async function chat(messages) {
const res = await fetch("https://api.gemininsfw.cc/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "uncensored", messages }),
});
if (res.ok === false) {
const err = await res.text();
throw new Error(`HTTP ${res.status}: ${err}`);
}
return res.json();
}
const data = await chat([{ role: "user", content: "Hello" }]);
console.log(data.choices[0].message.content);
一旦需要流式辅助功能、类型化响应和内置重试,SDK 是更好的选择。原始版本适合小型脚本或包大小重要的无服务器函数。
Node 中的流式输出
设置 stream: true 并使用 for await 遍历结果。Token 会在到达时即时输出,使用情况在流结束时报告。
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Tell a two-paragraph story about a lighthouse." }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
if (chunk.usage) console.log("\n", chunk.usage);
}
要将流转发到浏览器,Express 处理程序可以设置 Content-Type: text/event-stream 并将每个增量写入 SSE data: 行。记住一条规则:流式请求在其流结束前占用并发槽位。如果浏览器断开连接,请停止读取上游流以释放槽位。使用 SDK 时,调用 stream.controller.abort()。
工具调用和 JSON 模式
工具
传递 tools 和可选的 tool_choice。当模型需要函数时,回复包含 tool_calls。你运行该函数并将输出作为 role: "tool" 消息返回。
const tools = [{
type: "function",
function: {
name: "roll_dice",
description: "Roll an n-sided die",
parameters: {
type: "object",
properties: { sides: { type: "integer" } },
required: ["sides"],
},
},
}];
const messages = [{ role: "user", content: "Roll a d20 for me." }];
const first = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
const call = msg.tool_calls[0];
const { sides } = JSON.parse(call.function.arguments);
const result = 1 + Math.floor(Math.random() * sides);
messages.push(msg, {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify({ result }),
});
const final = await client.chat.completions.create({
model: "uncensored", messages, tools,
});
console.log(final.choices[0].message.content);
}
JSON 模式
添加 response_format: { type: "json_object" } 并在提示词中要求 JSON。将 JSON.parse 包裹在 try/catch 中,以防输出被截断。
小型聊天服务器的项目布局
对于真实应用,请将客户端保留在一个模块中并在需要时导入。这样 base URL、密钥和重试设置就集中在一个地方。
// llm.js
import OpenAI from "openai";
export const llm = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
maxRetries: 2,
});
export async function complete(messages, opts = {}) {
const r = await llm.chat.completions.create({
model: "uncensored",
messages,
...opts,
});
return r.choices[0].message.content;
}
然后你的路由处理程序调用 complete() 且不再触碰密钥。在服务器上按会话存储对话历史,并在历史记录增长时修剪旧轮次。由于 API 是无状态的,每个请求必须携带模型要查看的每条消息。
错误、重试和限制
SDK 会抛出带有 status 字段的 OpenAI.APIError 子类。完整密钥允许 8 个并发请求和每分钟 300 个;试用密钥允许 2 个和 60 个。超过限制时,你会收到带有代码 rate_limited 或 concurrency 的 HTTP 429。在短暂过载期间,API 会发送带有 Retry-After: 5 的 429。
const client = new OpenAI({
baseURL: "https://api.gemininsfw.cc/v1",
apiKey: process.env.API_KEY,
maxRetries: 3,
timeout: 120_000,
});
async function safeAsk(prompt) {
try {
const r = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: prompt }],
});
return r.choices[0].message.content;
} catch (e) {
if (e.status === 429) {
console.error("limited, retry-after:", e.headers?.["retry-after"]);
}
throw e;
}
}
对于批量处理,不要使用 Promise.all 一次性发出所有请求。使用具有固定数量 worker 的小队列,例如 6 个,这样你永远不会超过完整密钥的 8 个并发槽位。请求体限制为 8 MB,上下文窗口为 100,000 token,包含提示词和回答。
成本和后续步骤
价格为每 1M 输入 token $0.15,每 1M 输出 token $0.50。一次包含 3,000 提示词 token 和 600 回复 token 的聊天轮次成本为 3,000 x $0.15 / 1M = $0.00045 加上 600 x $0.50 / 1M = $0.0003,总计 $0.00075。一千次这样的轮次总计 $0.75。失败或被拒绝的请求不收费,响应头 X-Balance-USD 告诉你剩余余额。
新用户可以在密钥页面领取 $0.50 试用额度,定价页面 列出了从 $20 到 $500 的充值选项。有关请求格式的更多详细信息,请参阅 文档。此服务仅处理文本,因此图像、音频和嵌入调用将不起作用。
