森3Dai助手森3Dai助手

Node.js 调用 AI API 教程

Node.js 18 及以上内置 fetch,无需额外依赖即可调用森3Dai助手的 OpenAI 兼容接口。本文给出 fetch 调用、流式读取与错误处理的完整示例。

一、环境变量

把密钥放进环境变量,避免写进源码:

# macOS / Linux
export SEN_API_KEY="你的密钥"

# Windows PowerShell
$env:SEN_API_KEY="你的密钥"

二、基础调用(fetch)

async function chat(content) {
  const res = await fetch(
    "https://yutongguoji.cn/v1/chat/completions",
    {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.SEN_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: "agnes",
        messages: [{ role: "user", content }],
      }),
    }
  );
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json();
  return data.choices[0].message.content;
}

chat("你好").then(console.log).catch(console.error);

三、流式输出(SSE)

async function chatStream(content) {
  const res = await fetch(
    "https://yutongguoji.cn/v1/chat/completions",
    {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.SEN_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: "agnes",
        messages: [{ role: "user", content }],
        stream: true,
      }),
    }
  );
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    const text = decoder.decode(value);
    for (const line of text.split("\n")) {
      if (line.startsWith("data:") && !line.includes("[DONE]")) {
        const chunk = JSON.parse(line.slice(5).trim());
        process.stdout.write(chunk.choices[0]?.delta?.content || "");
      }
    }
  }
}

四、使用 OpenAI SDK

npm install openai
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://yutongguoji.cn/v1",
  apiKey: process.env.SEN_API_KEY,
});
const resp = await client.chat.completions.create({
  model: "agnes",
  messages: [{ role: "user", content: "你好" }],
});
console.log(resp.choices[0].message.content);

五、错误处理

401 表示密钥缺失或无效;请求格式错误会返回 4xx。排查顺序:确认环境变量已设置、密钥未过期、角色未被删除(删除角色会使 Key 失效)。详见接口文档的错误码部分。

Python 教程 接口文档 常见问题