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 固定结果 任意数字

相关推荐
cpolar技术支持7 小时前
把 agent-autoloop 装在 Mac 上:用本机 Node 实跑一次「接活—提问—拍板—接着干」,再用 cpolar 把它的状态页开给不在工位的自己
node.js·内网穿透·cpolar·ai agent·agent-autoloop
SEO_juper14 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
木头左2 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能2 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
w3296362714 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔4 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新4 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大5 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行
回眸&啤酒鸭5 天前
【回眸】Node.js 新手从零到一实战指南
node.js
浪遏5 天前
recruitment-cli:让 AI 接手求职招聘,从架构到一次发送超时
架构·typescript·node.js