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

Having trouble using OpenAI API

题意:"使用OpenAI API遇到困难"

问题背景:

I am having trouble with this code. I want to implement AI using OpenAI API in my React.js project but I cannot seem to get what the issue is. I ask it a question in the search bar in my project and it says "No response from AI". There is more to it but this is just what I think is having trouble.

"我在这段代码上遇到了困难。我想在我的React.js项目中使用OpenAI API实现AI功能,但似乎找不到问题所在。我在项目中的搜索栏中输入问题时,它显示‘没有收到AI的响应’。还有更多问题,但这就是我认为出问题的地方。"

//LandingPage.js
import React, { useState, useEffect } from 'react';
import { FaSearch } from 'react-icons/fa';
import './App.css';
import { EntryForm } from './EntryForm';

function LandingPage() {
  // States related to the Healthy Innovations features
  const [search, setSearch] = useState('');
  const [showSuggestions, setShowSuggestions] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [recipeDetails, setRecipeDetails] = useState(null);
  const [showWorkoutQuestion, setShowWorkoutQuestion] = useState(false);
  const [selectedSuggestion, setSelectedSuggestion] = useState(null);
  const [showWorkoutPlan, setShowWorkoutPlan] = useState(false);
  const [showCalorieCalculator, setShowCalorieCalculator] = useState(false);
  const [workoutSplit, setWorkoutSplit] = useState('');
  const [showCalorieQuestion, setShowCalorieQuestion] = useState(false);
  const [chatInput, setChatInput] = useState('');
  const [chatHistory, setChatHistory] = useState([]);
  const [currentTitle, setCurrentTitle]= useState(null)
  
  console.log(chatHistory); // Debugging: Check the structure before rendering
  

  const createNewChat = () => {
    // Clears the chat to start a new conversation
    setChatInput('');
    setCurrentTitle(null)
    // No need for setCurrentTitle in this context
  };

  const renderChatHistory = () =>
  chatHistory.map((chat, index) => (
      <div key={index} className="chat-history">
          <p>Role: {chat.role}</p>
          {/* Check if chat.content is a string; if not, handle it appropriately */}
          <p>Message: {chat.content}</p>
      </div>
  ));

  const handleSearchChange = (e) => {
    const inputValue = e.target.value;
    setChatInput(inputValue); // Update chatInput instead of search state.
    setShowSuggestions(inputValue.length > 0); // Show suggestions if there's input
  };

  const renderDynamicRecommendations = () => {
    // Filter suggestions based on search input
    const filteredSuggestions = staticSuggestions.filter(suggestion =>
      suggestion.toLowerCase().includes(search.toLowerCase())
    ); 

    return (
      <ul>
        {filteredSuggestions.map((suggestion, index) => (
          <li key={index} onClick={() => handleSelectSuggestion(suggestion)} style={{ cursor: 'pointer' }}>
            {suggestion}
          </li>
        ))}
      </ul>
    );
  };

  const SERVER_URL = "http://localhost:8000/completions";
  // Get messages function and other logic remain the same, ensure you're using chatInput for input value management
  // Adjusting the getMessages function to handle server response correctly
  const getMessages = async () => {
    if (!chatInput.trim()) return; // Avoid sending empty messages
    setIsLoading(true);
  
    try {
      const response = await fetch('http://localhost:8000/completions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: chatInput })
      });
  
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
  
      const data = await response.json();
      const aiResponse = data.choices && data.choices.length > 0
        ? data.choices[0].message
        : "No response from AI."; 
      // Update chat history
      setChatHistory(prev => [...prev, { role: 'user', content: chatInput }, { role: 'ai', content: aiResponse }]);
      setChatInput(''); // Clear the input field
    } catch (error) {
      console.error('Fetch error:', error);
      setChatHistory(prev => [...prev, { role: 'user', content: chatInput }, { role: 'ai', content: "Error communicating with AI." }]);
    } finally {
      setIsLoading(false);
    }
  };
//server.js 

const PORT = 8000
const express = require('express')
const cors = require('cors')
require('dotenv').config()
const app = express()
app.use(express.json())
app.use(cors())

const API_KEY = process.env.API_KEY

app.post('/completions', async (req, res) => {
    const options = {
        method: "POST",
        headers: {
            "Authorization": `Bearer ${API_KEY}`, 
            "Content-Type": "application/json" 
        },
        body: JSON.stringify({
            model: "gpt-3.5-turbo",
            messages: [{role: "user", content: req.body.message}],
            max_tokens: 100,
        })
    };
    try {
        const response = await fetch('https://api.openai.com/v1/chat/completions', options);
        const data = await response.json();

        if (data.choices && data.choices.length > 0 && data.choices[0].message) {
            // Adjust this path according to the actual structure of OpenAI's response
            res.json({ message: data.choices[0].message.content });
        } else {
            throw new Error("Invalid response structure from OpenAI API.");
        }
    } catch (error) {
        console.error("Server error:", error);
        res.status(500).json({ message: "Failed to get response from AI." });
    }
});

app.listen(PORT, () => console.log('Your server is running on PORT'+ PORT))

.env file: API_KEY = "api key"

I have tried changing varablies and also seing if I have everything downloaded which I do.

"我尝试过更改变量,也检查了是否已经下载了所有需要的内容,一切都已下载。"

问题解决:

The backend returns a response in a format different from what the frontend expects.

"后端返回的响应格式与前端预期的不一致。"

From server.js

if (data.choices && data.choices.length > 0 && data.choices[0].message) {
    res.json({ message: data.choices[0].message.content });
  } else {
    throw new Error("Invalid response structure from OpenAI API.");
  }

This will produce json response { message: "response from openai" }

However on the frontend act as if backend return raw response straight from the openai api

"然而,前端的行为却好像后端返回的是直接来自OpenAI API的原始响应。"

const data = await response.json();
   const aiResponse = data.choices && data.choices.length > 0
     ? data.choices[0].message
     : "No response from AI."; 

Here is a fix of the frontend code to match response shape from the backend:

"这是前端代码的修复,以匹配后端返回的响应格式:"

const { message } = await response.json();
   const aiResponse = message || "No response from AI.";


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

相关文章:

  • 基于BILSTM及其他RNN序列模型的人名分类器
  • 期权懂|期权新手入门教学:期权合约有哪些要素?
  • 数据分析那些事儿——关于A/B实验
  • 前端入门一之ES6--面向对象、够着函数和原型、继承、ES5新增方法、函数进阶、严格模式、高阶函数、闭包
  • 使用Git工具在GitHub的仓库中上传文件夹(超详细)
  • wordpress实用功能A5资源网同款 隐藏下载框 支付框 需要登录才能查看隐藏的内容
  • 回归预测|基于鹅GOOSE优化LightGBM的数据回归预测Matlab程序 多特征输入单输出 2024年优化算法
  • vue3本地运行错误集
  • 5.3 MySql实战
  • Xilinx FPGA在线升级——升级思路
  • 鸿蒙开发5.0【基于Swiper的页面布局】
  • LeetCode 热题100-9 找到字符串中所有字母异位词
  • vscode 未定义标识符 “uint16_t“C/C++(20) 但是可以顺利编译
  • Java算法—插入排序(Insertion Sort)
  • 一种导出PPT到MP4的方法
  • 大数据测试怎么做,数据应用测试、数据平台测试、数据仓库测试
  • ​T​P​一​面​
  • 系统编程-消息队列
  • 力扣2116.判断一个括号字符串是否有效
  • Qt_信号槽机制
  • 计算机网络概述(网络结构)
  • MYSQL——聚合查询
  • B树及其Java实现详解
  • 续:MySQL的半同步模式
  • APO 新发版支持Skywalking Agent接入
  • unity的问题记录(信息管理)