使用OpenAI API遇到问题

我在使用这段代码时遇到了问题。我想在我的React.js项目中使用OpenAI API来实现AI功能,但似乎无法找出问题所在。我在项目中的搜索栏中提问,它显示“AI无响应”。问题可能不止这些,但这是我认为有问题的部分。

//LandingPage.jsimport React, { useState, useEffect } from 'react';import { FaSearch } from 'react-icons/fa';import './App.css';import { EntryForm } from './EntryForm';function LandingPage() {  // 与健康创新功能相关的状态  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); // 调试:在渲染前检查结构    const createNewChat = () => {    // 清除聊天记录以开始新的对话    setChatInput('');    setCurrentTitle(null)    // 在此上下文中不需要setCurrentTitle  };  const renderChatHistory = () =>  chatHistory.map((chat, index) => (      <div key={index} className="chat-history">          <p>角色: {chat.role}</p>          {/* 检查chat.content是否为字符串;如果不是,适当处理 */}          <p>消息: {chat.content}</p>      </div>  ));  const handleSearchChange = (e) => {    const inputValue = e.target.value;    setChatInput(inputValue); // 更新chatInput而不是search状态。    setShowSuggestions(inputValue.length > 0); // 如果有输入则显示建议  };  const renderDynamicRecommendations = () => {    // 根据搜索输入过滤建议    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";  // 获取消息函数和其他逻辑保持不变,确保使用chatInput来管理输入值  // 调整getMessages函数以正确处理服务器响应  const getMessages = async () => {    if (!chatInput.trim()) return; // 避免发送空消息    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错误!状态: ${response.status}`);      }        const data = await response.json();      const aiResponse = data.choices && data.choices.length > 0        ? data.choices[0].message        : "AI无响应。";       // 更新聊天记录      setChatHistory(prev => [...prev, { role: 'user', content: chatInput }, { role: 'ai', content: aiResponse }]);      setChatInput(''); // 清除输入字段    } catch (error) {      console.error('获取错误:', error);      setChatHistory(prev => [...prev, { role: 'user', content: chatInput }, { role: 'ai', content: "与AI通信错误。" }]);    } finally {      setIsLoading(false);    }  };
//server.js const PORT = 8000const 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_KEYapp.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) {            // 根据OpenAI响应的实际结构调整此路径            res.json({ message: data.choices[0].message.content });        } else {            throw new Error("OpenAI API响应结构无效。");        }    } catch (error) {        console.error("服务器错误:", error);        res.status(500).json({ message: "无法获取AI响应。" });    }});app.listen(PORT, () => console.log('您的服务器正在运行于PORT'+ PORT))

.env文件: 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("OpenAI API响应结构无效。");  }

这将产生JSON响应 { message: "来自OpenAI的响应" }

然而,前端似乎认为后端直接返回了来自OpenAI API的原始响应

   const data = await response.json();   const aiResponse = data.choices && data.choices.length > 0     ? data.choices[0].message     : "AI无响应。"; 

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

   const { message } = await response.json();   const aiResponse = message || "AI无响应。";

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注