当前位置: 首页 > article >正文

在 JavaScript 中调用 OpenAI 的接口初识

在 JavaScript 中调用 OpenAI API 也非常简单,下面我将结合具体代码示例以及使用场景,详细讲解如何使用 JavaScript 调用 OpenAI API。

文章目录

      • 1. 安装 OpenAI 官方库(可选)
      • 2. 准备 API Key
      • 3. 使用 JavaScript 调用 OpenAI API
        • **基本示例:使用 `fetch` 调用 ChatGPT API**
          • **代码示例(浏览器环境):**
        • **运行结果:**
      • 4. 高级使用场景:
        • **场景 1:生成文本(例如文章、博客等)**
          • **代码示例:**
        • **场景 2:创建问答机器人**
          • **代码示例:**
        • **场景 3:批量处理多个请求**
          • **代码示例:**
      • 5. 运行时优化和注意事项:

在这里插入图片描述

1. 安装 OpenAI 官方库(可选)

如果你使用 Node.js 环境,可以通过 npmyarn 安装 OpenAI 的官方 SDK。这样你可以更方便地与 API 进行交互。

npm install openai

如果你在浏览器环境中使用 fetch 来调用 API,则不需要安装任何库。


2. 准备 API Key

和 Python 一样,你需要在 OpenAI 账户 中获取 API Key,并将其用于请求中。


3. 使用 JavaScript 调用 OpenAI API

基本示例:使用 fetch 调用 ChatGPT API
代码示例(浏览器环境):
// 获取 OpenAI API Key(请确保此密钥安全)
const apiKey = 'your_openai_api_key';

// 请求的 API URL
const url = 'https://api.openai.com/v1/chat/completions';

// 定义请求体
const requestBody = {
  model: "gpt-3.5-turbo",  // 可以是 gpt-4 或其他模型
  messages: [
    { role: "system", content: "你是一个乐于助人的AI助手。" },
    { role: "user", content: "帮我写一个Python计算两个数之和的函数。" }
  ],
  temperature: 0.7,  // 控制生成内容的随机性,范围 0-1
  max_tokens: 150,   // 控制生成内容的最大长度
};

// 发送请求到 OpenAI API
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiKey}`,
  },
  body: JSON.stringify(requestBody),
})
  .then(response => response.json())
  .then(data => {
    console.log(data.choices[0].message.content);  // 输出生成的内容
  })
  .catch(error => {
    console.error('Error:', error);
  });
运行结果:
def add_numbers(a, b):
    return a + b

4. 高级使用场景:

场景 1:生成文本(例如文章、博客等)
代码示例:
const generateContent = async (userInput) => {
  const apiKey = 'your_openai_api_key';
  const url = 'https://api.openai.com/v1/chat/completions';
  
  const requestBody = {
    model: "gpt-4",  // 选择合适的模型
    messages: [
      { role: "system", content: "你是一名专业的文案编辑。" },
      { role: "user", content: userInput }
    ],
    temperature: 0.6,
    max_tokens: 200,
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify(requestBody),
    });

    const data = await response.json();
    console.log(data.choices[0].message.content);  // 输出生成的文案
  } catch (error) {
    console.error('Error:', error);
  }
};

// 用户输入
generateContent("帮我写一段关于AI教育工具的产品介绍。");
场景 2:创建问答机器人
代码示例:
const chatbotResponse = async (userInput) => {
  const apiKey = 'your_openai_api_key';
  const url = 'https://api.openai.com/v1/chat/completions';
  
  const requestBody = {
    model: "gpt-3.5-turbo",  // 使用 ChatGPT 模型
    messages: [
      { role: "system", content: "你是一个智能问答机器人,可以回答各种问题。" },
      { role: "user", content: userInput }
    ],
    temperature: 0.7,
    max_tokens: 150,
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify(requestBody),
    });

    const data = await response.json();
    return data.choices[0].message.content;  // 返回生成的回复
  } catch (error) {
    console.error('Error:', error);
    return "发生错误,请稍后再试。";
  }
};

// 用户输入
const userQuery = "如何用Python读取JSON文件?";
chatbotResponse(userQuery).then(response => {
  console.log(response);  // 输出问答机器人回复
});
场景 3:批量处理多个请求
代码示例:
const batchProcess = async (texts) => {
  const apiKey = 'your_openai_api_key';
  const url = 'https://api.openai.com/v1/chat/completions';

  const responses = [];
  for (const text of texts) {
    const requestBody = {
      model: "gpt-3.5-turbo",
      messages: [
        { role: "user", content: text }
      ],
      temperature: 0.6,
      max_tokens: 100,
    };

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`,
        },
        body: JSON.stringify(requestBody),
      });

      const data = await response.json();
      responses.push(data.choices[0].message.content);
    } catch (error) {
      console.error('Error:', error);
      responses.push('错误:无法生成回复');
    }
  }

  return responses;
};

// 批量处理文本
const texts = [
  "帮我总结这段话的重点:Python是一种非常流行的编程语言。",
  "帮我翻译这句话:Hello, how are you?",
  "生成一句关于人工智能未来发展的预测。"
];

batchProcess(texts).then(responses => {
  console.log(responses.join('\n'));
});

5. 运行时优化和注意事项:

  1. API 限制和错误处理:

    • 在高频请求的情况下,确保处理 429 Too Many Requests 错误。
    • 可以实现重试机制,例如在遇到限流错误时延时一段时间后再发起请求。
  2. API Key 安全:

    • 切勿在前端代码中暴露 API Key,尤其是公开的前端应用。
    • 推荐使用环境变量或服务器代理来隐藏 API Key。
  3. 费用控制:

    • OpenAI 的 API 按照生成的 tokens(字符数量)进行计费。根据 max_tokens 来控制生成的文本长度,避免产生不必要的费用。
  4. API 调用频率:

    • 如果在短时间内发送大量请求,可以通过添加适当的 delaydebounce 来避免频繁调用。

通过以上示例,你可以在 JavaScript 环境中灵活调用 OpenAI API 来完成多种任务。如果你有更多的场景需求或问题,可以继续提问! 😊


http://www.kler.cn/a/519929.html

相关文章:

  • 3-scala的类
  • 自定义数据集使用框架的线性回归方法对其进行拟合
  • 第30章 测试驱动开发中的设计模式解析(Python 版)
  • 三年级数学知识边界总结思考-下册
  • GSI快速收录服务:让你的网站内容“上架”谷歌
  • 从Spring请求处理到分层架构与IOC:注解详解与演进实战
  • MYSQL数据库 - 启动与连接
  • 入门 Canvas:Web 绘图的强大工具
  • C#,入门教程(05)——Visual Studio 2022源程序(源代码)自动排版的功能动画图示
  • rust学习-rust中的格式化打印
  • 深度解读:近端策略优化算法(PPO)
  • 浅谈在AI时代GIS的发展方向和建议
  • Elasticsearch 性能测试工具 Loadgen 之 004——高级用法示例
  • c语言函数(详解)
  • Vue.js 高级组件开发
  • 任务一:Android逆向
  • 泷羽Sec-Powershell3
  • 设计模式思想的元规则
  • Python从0到100(八十五):神经网络与迁移学习在猫狗分类中的应用
  • 数据结构day02