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

相关推荐
千寻girling3 小时前
被内推的面试 , 第一次
java·前端·python·面试·职场和发展·typescript·node.js
炽烈小老头8 小时前
Express Routing(路由系统)
node.js·express
zhensherlock1 天前
Protocol Launcher 系列:Overcast 一键订阅播客
前端·javascript·typescript·node.js·自动化·github·js
Bigger1 天前
🚀 mini-cc:打造你的专属轻量级 AI 编程智能体
前端·node.js·claude
算是难了1 天前
TypeORM vs Prisma
数据库·typescript·node.js
xxjj998a1 天前
如何安装linux版本的node.js
linux·运维·node.js
青花瓷2 天前
Windows下Node.js的安装
node.js
暮雪倾风3 天前
【JS-Node】node.js环境安装及使用
开发语言·javascript·node.js
冴羽3 天前
请愿书:Node.js 核心代码不应该包含 AI 代码!
前端·javascript·node.js