OpenAI NodeJs版使用案列

Node.js 模板 + 最实用参数配置,包含:

  1. 基础聊天(最常用)
  2. 流式输出(前端实时打字效果)
  3. JSON 格式输出(接口必用)
  4. 函数调用(工具调用)
  5. 文本嵌入 Embeddings
  6. 统一错误处理

你只需要替换 apiKey 即可使用。


一、安装依赖

bash 复制代码
npm install openai
# 或
yarn add openai

二、统一客户端初始化(推荐)

javascript 复制代码
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: '你的 sk-xxx 密钥',
  // baseURL: 'https://你的代理地址/v1', // 国内必须加代理
  timeout: 2 * 60 * 1000,
  maxRetries: 2,
});

export default openai;

三、场景 1:基础聊天(最常用)

javascript 复制代码
async function chatBasic() {
  try {
    const res = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo', // 或 gpt-4o-mini / gpt-4o

      // 对话上下文
      messages: [
        { role: 'system', content: '你是一个专业的技术助手,回答简洁、准确、不啰嗦' },
        { role: 'user', content: '用 Node.js 调用 OpenAI 最好的参数配置是什么?' },
      ],

      // 核心参数
      temperature: 0.7,      // 0=严谨 1=平衡 2=天马行空
      max_tokens: 1024,      // 最大生成长度
      top_p: 1,
      frequency_penalty: 0,  // 减少重复
      presence_penalty: 0,   // 减少跑题

      // 可选
      // stop: ['\n\n', '用户:'], // 遇到这些字符自动停止
      // seed: 123, // 固定结果可复现
    });

    console.log(res.choices[0].message.content);
    return res;
  } catch (err) {
    console.error('OpenAI 请求失败', err);
  }
}

chatBasic();

四、场景 2:流式输出(前端实时打字)

javascript 复制代码
async function chatStream() {
  const stream = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [
      { role: 'system', content: '你是一个温柔的助手' },
      { role: 'user', content: '讲一个很短的故事' },
    ],
    stream: true, // 开启流式
    temperature: 0.7,
  });

  // 逐字输出
  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content || '';
    process.stdout.write(content); // 控制台实时打印
  }
}

chatStream();

五、场景 3:强制返回 JSON(接口神器)

javascript 复制代码
async function chatJSON() {
  const res = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo-1106', // 必须用支持 JSON 的模型
    messages: [
      {
        role: 'system',
        content: '你只返回合法 JSON,不要任何多余解释、markdown、注释',
      },
      {
        role: 'user',
        content: '提取这句话里的用户名和年龄:小明今年25岁,喜欢编程',
      },
    ],
    response_format: { type: 'json_object' }, // 关键
    temperature: 0.1, // JSON 尽量低
  });

  const json = JSON.parse(res.choices[0].message.content);
  console.log(json);
  return json;
}

chatJSON();

六、场景 4:函数调用(工具调用)

4.1 定义函数

javascript 复制代码
// 模拟一个查询天气函数
async function getWeather({ city }) {
  return { city, weather: '晴天', temperature: '25℃' };
}

4.2 调用函数

javascript 复制代码
async function chatWithTools() {
  const res = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: '北京天气怎么样' }],

    // 定义工具
    tools: [
      {
        type: 'function',
        function: {
          name: 'getWeather',
          description: '获取城市天气',
          parameters: {
            type: 'object',
            properties: {
              city: { type: 'string', description: '城市名' },
            },
            required: ['city'],
          },
        },
      },
    ],

    tool_choice: 'auto', // auto / required / none
  });

  const toolCall = res.choices[0].message.tool_calls?.[0];
  if (toolCall) {
    const funcName = toolCall.function.name;
    const args = JSON.parse(toolCall.function.arguments);

    if (funcName === 'getWeather') {
      const weather = await getWeather(args);
      console.log('天气结果:', weather);
    }
  }
}

chatWithTools();

七、场景 5:Embedding 文本嵌入(向量库)

javascript 复制代码
async function createEmbedding(text) {
  const res = await openai.embeddings.create({
    model: 'text-embedding-3-small', // 便宜好用
    input: text,
    // dimensions: 512, // 可自定义维度(3-large 支持)
    encoding_format: 'float',
  });

  const vector = res.data[0].embedding;
  console.log('向量长度:', vector.length);
  return vector;
}

createEmbedding('我想把这句话转成向量');

八、通用错误处理模板(生产环境必备)

javascript 复制代码
async function safeChat() {
  try {
    const res = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: '你好' }],
    });
    return res.choices[0].message.content;

  } catch (err) {
    if (err instanceof OpenAI.APIError) {
      console.error('状态码:', err.status);
      console.error('错误信息:', err.error);
    }

    if (err instanceof OpenAI.AuthenticationError) console.log('密钥错误');
    if (err instanceof OpenAI.RateLimitError) console.log('限流了');
    if (err instanceof OpenAI.TimeoutError) console.log('请求超时');

    throw err;
  }
}

九、最实用参数速查表(直接背)

参数 作用 推荐值
temperature 创造力 对话 0.7 / 业务 0.1 / JSON 0
max_tokens 最长输出 512 / 1024 / 2048
top_p 多样性 1
frequency_penalty 减少重复 0~0.3
presence_penalty 减少跑题 0~0.3
stream 流式输出 true(前端必开)
response_format JSON 输出 { type: 'json_object' }
stop 自动停止 '\\n\\n', '结束'
seed 固定结果 任意数字

相关推荐
king13598745506 小时前
AI Agent 端云协同选型:Node.js 任务成本算例与权限检查清单(2027—2028 展望)
人工智能·ai·node.js·ai agent
居里先生7529 小时前
PDF 批注到底存在文件的哪里?从 /Annots 讲到导出验证
node.js
MasonYyp1 天前
安装npm依赖仓库Verdaccio
前端·npm·node.js
编程的一拳超人3 天前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
lucas_AI3 天前
今年 2 月就修好的漏洞,10 月才炸:HTTP2Shell 把 Node、Python 一锅端
node.js
SEO_juper3 天前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
孟陬4 天前
解决动态 import 类型 Any 痼癖
typescript·node.js·bun
Dumbness4 天前
后台管理员把自己锁在门外:RBAC 里「自己的权限只能由别人来减」
安全·node.js
攻城狮白玉4 天前
Node.js 发布紧急安全更新:10 个漏洞,8 枚危险证书被拉黑。附AI修复提示词
node.js
Json____5 天前
用 FastAPI + Vue3 打造一套完整的在线考试系统:从组卷到阅卷的业务闭环实践
后端·node.js·fastapi·it学习·wwwoop.com