题意:"使用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.";

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部