我在这个代码上遇到了麻烦.我想在我的React.js项目中使用OpenAI API实现人工智能,但我似乎不知道问题是什么.我在我的项目中的搜索栏中问它一个问题,它说"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))

. inf文件:API_KEY ="api key"

我试过改变变量,也看到如果我有一切下载,我做.

推荐答案

后端返回的响应格式与前端期望的不同.

关于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.");
  }

这将产生json响应{ message: "response from openai" }

然而,在前端,就好像后端直接从openai api返回原始响应,

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

以下是前端代码的修复,以匹配后端的响应形状:

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

Node.js相关问答推荐

我的 MERN 网站一直告诉我我的一个函数不是一个函数

运行本地移动自动化测试时,在onPrepare钩子中,ERROR @wdio/cli:utils: A service failed in the 'onPrepare'

如何在带有 JS 的 Nodejs 中使用没有 Async 方法的 Await

如何在 Docker 容器中 SSO 登录 AWS(使用 aws-sdk v3)

对 google api v3 的 Axios 请求返回加密(?)数据

无法关闭 node.js 中的mongoose 连接

更新文档数组中的文档 Mongoose

来自 child_process.exec 的错误没有这样的设备或地址,管道有帮助.为什么?

无服务器无法获取所有记录事件对象验证失败?

使用 node.js 执行一个 exe 文件

使用 nvm-windows 时更新 npm

Passport 登录和持久会话

安装 node.JS 时,node.js 运行时和 npm 包管理器选项有什么区别?

Nodejs续集批量更新

npm 出现无法读取依赖项错误

nodejs - 如何读取和输出 jpg 图像?

在 Node 中连接和缩小 JS 文件

如何在 NodeJS 中拆分和修改字符串?

如何从 Node.js 应用程序Ping?

Firestore:多个条件 where 子句