OpenAI converting API code from GPT-3 to chatGPT-3.5

题意:将OpenAI API代码从GPT-3转换为ChatGPT-3.5

问题背景:

Below is my working code for the GPT-3 API. I am having trouble converting it to work with chatGPT-3.5.

以下是我用于GPT-3 API的工作代码。我在将其转换为适用于ChatGPT-3.5时遇到了困难

php 复制代码
<?php include('../config/config.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chatbot</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="container py-5">
  <h1 class="mb-5 text-center">
    <div class="logo"> <img src="/images/Logo-PocketAI.svg" height="80" width="210" aria-label="PocketAI.Online Logo" title="PocketAI.Online Logo" alt="SPocketAI.Online Logo" class="img-fluid"> </div>
  </h1>
  <div class="form-floating mb-3">
    <select class="form-select" id="tab-select" aria-label="Select your purpose">
      <option value="exam" selected>Exam</option>
      <option value="feedback">Feedback</option>
    </select>
    <label for="tab-select">Select your purpose:</label>
  </div>
  <div class="input-group mb-3">
    <div class="form-floating">
      <textarea class="form-control" placeholder="Enter your question or comment here" id="prompt"></textarea>
      <label for="prompt">Enter your question or comment here</label>
    </div>
    <div class="input-group-append username w-100 mt-3 mb-4">
      <button class="btn btn-outline-primary w-100" type="button" id="send-button">Send</button>
    </div>
  </div>
  <div id="output" class="mb-3" style="height: 300px; overflow: auto; border: 1px solid lightgray; padding: 10px;"></div>
  <div id="exam-instructions" class="mb-3" style="display: block;">
    <h3>Exam</h3>
    <p>PocketAI can create multiple choice and true false questions in a format that enables import into Brightspace D2L quizzes using Respondus. Place PocketAI output into a Word document before importing with Respondus. Ask PocketAI questions like the following: <br>
      <br>
      Create 3 multiple choice questions about carbohydrates for a freshman Nutrition online college course.<br>
      Create 2 true false questions about business for a sophomore Business face to face college course.</p>
  </div>
  <div id="feedback-instructions" class="mb-3" style="display: none;">
    <h3>Feedback</h3>
    <p>Enter text to receive writing feedback.</p>
  </div>
</div>
<script>
const previousPrompts = [];
const userName = "<strong>User</strong>";
const chatbotName = "<strong>PocketAI</strong>";

const selectDropdown = document.getElementById("tab-select");

selectDropdown.addEventListener("change", function() {
  const activeTabId = this.value;
  
  // hide all instruction sections
  document.querySelectorAll("[id$='-instructions']").forEach(function(instructionSection) {
    instructionSection.style.display = "none";
  });
  
  // show the instruction section for the active tab
  document.getElementById(`${activeTabId}-instructions`).style.display = "block";
});

document.getElementById("send-button").addEventListener("click", function() {
  const prompt = document.getElementById("prompt").value;
  const activeTabId = selectDropdown.value;

  const endpoint = "https://api.openai.com/v1/completions";
  const apiKey = "<?=$OPEN_AI_KEY;?>";

  document.getElementById("send-button").innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Sending...';

  let promptText = "";
  
  switch (activeTabId) {
    case "exam":
        promptText = "Create quiz questions in the following format: Begin each question with a number followed by a period, and then include the question wording. For each question, include four answer choices listed as letters (A, B, C, D) followed by a period and at least one space before the answer wording. Designate the correct answer by placing an asterisk (*) directly in front of the answer letter (do not put a space between the asterisk and the answer choice). Place the asterisk in front of the answer letter, only the front. It is important that correct answers are identified. Don't make up answers, only select factual answers. For example formatting (don't use this specific example), \"1. What is the recommended daily intake of dietary fiber? A. 10 grams B. 25 grams *C. 50 grams D. 75 grams\". Format true false questions the same way. If you are unsure of the correct answer, don't create the question. Every quiz question and answer must be 100% correct and factual. Do not make up answers. All answers must be correct.";
      break;
     case "feedback":
      promptText = "Can you provide feedback on the writing, grammar, sentence structure, punctuation, and style of this student's paper? The paper should be analyzed for its strengths and weaknesses in terms of written communication. Please provide suggestions for improvement and examples to help the student understand how to make the writing better. The feedback should be specific and provide actionable steps that the student can take to improve their writing skills. Please include at least three examples of areas that could be improved and specific suggestions for how to improve them, such as correcting grammar errors, restructuring sentences, or improving the use of punctuation.";
      break;
  }
  
  const requestData = {
    prompt: previousPrompts.join("\n") + promptText + "\n" + prompt,
    max_tokens: 400,
      model: "text-davinci-003",
    n: 1,
    stop: "",
    temperature: 0.5,
      top_p: 0.0,
      frequency_penalty: 0.0,
      presence_penalty: 0
  };
        
  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${apiKey}`,
    },
    body: JSON.stringify(requestData),
  };
  
  fetch(endpoint, requestOptions)
    .then(response => response.json())
    .then(data => {
      const reply = data.choices[0].text;
      
      // Add the user message to the chat history
      const userMessage = `<div class="message-container">
        <div class="username">${userName}:&nbsp;</div>
        <div class="user-message">${prompt}</div>
      </div>`;
      document.getElementById("output").innerHTML += userMessage;
      
      const chatbotMessage = `<div class="message-container">
  <div class="username">${chatbotName}:&nbsp;</div>
  <div class="chatbot-message" style="white-space: pre-wrap">${reply}<i class="bi bi-clipboard-check copy-button" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Copy to clipboard" data-text="${reply}" style="cursor: pointer;"></i></div>
</div>`; 
document.getElementById("output").innerHTML += chatbotMessage;

// Add an event listener to each "Copy to Clipboard" button
document.addEventListener("click", function(event) {
  if (event.target.classList.contains("copy-button")) {
    const textToCopy = event.target.dataset.text;
    navigator.clipboard.writeText(textToCopy);
  }
});
     // Scroll to the bottom of the chat history
      document.getElementById("output").scrollTop = document.getElementById("output").scrollHeight;
    
      // Clear the user input field
      document.getElementById("prompt").value = "";
    
      previousPrompts.push(prompt);
      // Clear the spinner and show the "Send" button again
      document.getElementById("send-button").innerHTML = 'Send';
    })
    .catch(error => {
      console.error(error);
    
      // Hide the spinner and show the "Send" button again
      document.getElementById("send-button").innerHTML = 'Send';
    });
});

document.getElementById("prompt").addEventListener("keydown", function(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    document.getElementById("send-button").
click();
  }
});
</script>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>

I have read https://openai.com/blog/introducing-chatgpt-and-whisper-apis and referred to this - OpenAI ChatGPT (gpt-3.5-turbo) API: How to access the message content? but still can't make it work.

我已经阅读了https://openai.com/blog/introducing-chatgpt-and-whisper-apis并参考了这个 - OpenAI ChatGPT (gpt-3.5-turbo) API: 如何访问消息内容?但仍然无法使其正常工作

I've tried changing the requestData to this, but no luck:

我尝试将 requestData 更改为如下,但仍然没有成功

复制代码
const requestData = {
    model: "gpt-3.5-turbo",
    messages: [
      { role: "user", content: prompt }
    ],
    max_tokens: 400,
    temperature: 0.5,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0
  };

Any help will be greatly appreciated!

任何帮助将不胜感激

问题解决:

better check your requestData object, the GPT 3.5 turbo doesn't need these props

最好检查一下你的 requestData 对象,GPT-3.5 turbo 不需要这些属性

max_tokens,temperature,top_p: 1,frequency_penalty,presence_penalty

I made the same mistake too, GPT 3.5 turbo is way easier to use than I expected. Here's OpenAI sample:

我也犯了同样的错误,GPT-3.5 turbo 比我预期的要简单得多。这里是 OpenAI 的示例

javascript 复制代码
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const completion = await openai.createChatCompletion({
  model: "gpt-3.5-turbo",
  messages: [{role: "user", content: "Hello world"}],
});
console.log(completion.data.choices[0].message);
相关推荐
archko5 分钟前
语音识别-3,添加ai问答
android·人工智能
zm1 小时前
TCP 粘包
服务器·网络·php
Bowen_CV2 小时前
AI 赋能防艾宣传:从创意到实践,我的 IP 形象设计之旅
人工智能·3d建模·豆包·造好物·腾讯混元 3d
你是一个铁憨憨2 小时前
使用深度学习预训练模型检测物体
人工智能·深度学习·arcgis·影像
AI算法工程师Moxi3 小时前
什么时候可以开始学习深度学习?
人工智能·深度学习·学习
好评笔记3 小时前
Meta的AIGC视频生成模型——Emu Video
人工智能·深度学习·机器学习·aigc·transformer·校招·面试八股
思通数据5 小时前
AI全域智能监控系统重构商业清洁管理范式——从被动响应到主动预防的监控效能革命
大数据·人工智能·目标检测·机器学习·计算机视觉·数据挖掘·ocr
flex88885 小时前
FramePack - 开源 AI 视频生成工具
人工智能·开源·音视频
Le_ee6 小时前
sqli-labs靶场第七关——文件导出注入
数据库·sql·网络安全·php·sql注入·sqli—labs
jndingxin6 小时前
OpenCV CUDA模块中矩阵操作------范数(Norm)相关函数
人工智能·opencv