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

js调用gpt3.5

参考链接:直接在前端调用 GPT-3 API

效果图:
在这里插入图片描述

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>ChatGPT Web Example</title>
  <style>
    body {
      font-family: "Helvetica Neue", Arial, sans-serif;
    }

    h1 {
      margin-bottom: 20px;
      text-align: center;
    }

    #chatbox {
      border: 1px solid gray;
      height: calc(100vh - 180px);
      margin-bottom: 20px;
      overflow-y: scroll;
      padding: 10px;
    }

    .message {
      margin-bottom: 10px;
    }

    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    .user-message {
      color: forestgreen;
      text-align: right;
    }

    .assistant-message {
      color: darkolivegreen;
    }

    .warning-message {
      color: red;
    }

    .chatgpt-message {
      text-align: left;
    }

    #input-container {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-right: 5%;
    }

    #inputbox {
      font-size: 1rem;
      margin-right: 10px;
      padding: 10px;
      width: 100%;
    }

    #submit {
      background-color: cornflowerblue;
      border: none;
      border-radius: 5px;
      box-sizing: border-box;
      color: white;
      cursor: pointer;
      float: right;
      padding: 10px 20px;
      width: 80px;
    }
  </style>
</head>

<body>
  <div id="chatbox">
    <!-- 消息列表 -->
  </div>
  <div id="input-container">
    <textarea id="inputbox" type="text" placeholder="请输入您的问题"  rows="5"></textarea>
    <button id="submit" loading="true">提交</button>
  </div>
</body>
<script>
  /* 官方文档[https://platform.openai.com/docs/guides/chat] */
  const chatboxEl = document.getElementById("chatbox");
  const inputEl = document.getElementById("inputbox");
  const submitEl = document.getElementById("submit");

  const endpoint = "https://api.openai.com/v1/chat/completions"; //如api过时,请查询官网
  const apiKey = "sk-"; //换成自己的API Key
  const delayTime = 60000; // 超时时间为60秒
  const model = "gpt-3.5-turbo";
  const temperature = 1; // 回答随机度
  const max_tokens = 1000;
  const historyMessageNum = 10;
  const historyMessage = [];

  function addMessage(text, sender) {
    historyMessage.push({ role: sender, content: text });
    const messageEl = document.createElement("div");
    const preEl = document.createElement("pre");
    messageEl.classList.add("message");
    messageEl.classList.add(`${sender}-message`);
    preEl.textContent = text;
    messageEl.appendChild(preEl);
    chatboxEl.appendChild(messageEl);
    chatboxEl.scrollTop = chatboxEl.scrollHeight;
  }

  async function getResponseFromAPI() {
    const controller = new AbortController();
    const signal = controller.signal;
    const timeout = setTimeout(() => {
      controller.abort();
    }, delayTime);
    const messages = historyMessage
      .filter((v) => ["system", "user", "assistant"].includes(v.role))
      .slice(-historyMessageNum); // 最近消息
    const response = await fetch(endpoint, {
      signal,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model,
        messages,
        max_tokens,
        n: 1,
        stop: null,
        temperature,
      }),
    });
    clearTimeout(timeout);
    const result = await response.json();
    return result.choices[0].message;
  }

  function init() {
    submitEl.addEventListener("click", async () => {
      const input = inputEl.value;
      addMessage(input, "user");
      inputEl.value = "";

      // 显示加载动画
      submitEl.innerHTML = "等待中...";
      submitEl.setAttribute("disabled", true);
      // 使用 OpenAI API 获取 ChatGPT 的回答
      getResponseFromAPI(input)
        .then((response) => {
          addMessage(response.content, response.role);
        })
        .catch((error) => {
          addMessage(
            error.name === "AbortError" ? "Network Error" : error.message,
            "warning"
          );
        })
        .finally(() => {
          // 隐藏加载动画
          submitEl.innerHTML = "提交";
          submitEl.removeAttribute("disabled");
        });
    });
    document.addEventListener("keydown", function (event) {
      if (event.shiftKey && event.keyCode === 13) {
        submitEl.click();
      }
    });
  }

  init();
</script>

</html>

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

相关文章:

  • ViewService——一种保证客户端与服务端同步的方法
  • 超级实用,解密云原生监控技术,使用prometheus轻松搞定redis监控
  • 【JavaEE】 多线程的风险-线程安全
  • 《程序员成长历程的四个阶段》
  • 关于中级开发工程师常问的面试题
  • CSDN 第三十九期竞赛题解
  • 如何做好数字化知识管理?
  • Linux内核IO基础知识与概念
  • python中pandas模块数据处理小案例
  • Linux内核六大进程通信机制原理
  • 自己动手做chatGPT:向量的概念和相关操作
  • 7个最受瞩目的 Python 库,提升你的开发效率
  • 【Mysql系列】——详细剖析数据库“索引”【上篇】
  • 【排序算法】
  • Tomcat And Servlet (1)
  • 构造函数为什么不能为虚函数?析构函数为什么要为虚函数?
  • Linux内核进程管理几种CPU调度策略
  • 全网最完整,接口测试总结彻底打通接口自动化大门,看这篇就够了......
  • MyBatisPlus+SpringBoot实现乐观锁功能
  • 智能火焰与烟雾检测系统(Python+YOLOv5深度学习模型+清新界面)