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

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 featuresconst [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 renderingconst createNewChat = () => {// Clears the chat to start a new conversationsetChatInput('');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 inputconst 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 correctlyconst getMessages = async () => {if (!chatInput.trim()) return; // Avoid sending empty messagessetIsLoading(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 historysetChatHistory(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_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) {// Adjust this path according to the actual structure of OpenAI's responseres.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.";

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • list类底层逻辑实现
  • 设备管理与文件系统
  • 冻死你都觉得简单
  • 石子合并-环(区间dp)c++
  • 什么是in-the-wild image(野生图像)?怎么更好的利用这些图像(通过BLIP)
  • Xilinx高速接口之GTP
  • 如何使用vcftools提取特定的染色体
  • idea付费插件,SequenceDiagram有哪些优点
  • 第三章 数组(3)
  • 看github源码必备的chrome插件
  • 瀑布流布局 vue
  • 数据源10min自动断开连接导致查询抛异常(未获取可用连接)
  • Fast-BEV: A Fast and Strong Bird’s-Eye ViewPerception Baseline
  • 安防视频汇聚平台EasyCVR启动后无法访问登录页面是什么原因?
  • Unity | 基础知识
  • 《微软的软件测试之道》成书始末、出版宣告、补充致谢名单及相关信息
  • 【从零开始安装kubernetes-1.7.3】2.flannel、docker以及Harbor的配置以及作用
  • 2017 年终总结 —— 在路上
  • FastReport在线报表设计器工作原理
  • Idea+maven+scala构建包并在spark on yarn 运行
  • iOS筛选菜单、分段选择器、导航栏、悬浮窗、转场动画、启动视频等源码
  • PAT A1092
  • python3 使用 asyncio 代替线程
  • Sublime text 3 3103 注册码
  • VUE es6技巧写法(持续更新中~~~)
  • windows下如何用phpstorm同步测试服务器
  • 给新手的新浪微博 SDK 集成教程【一】
  • 基于游标的分页接口实现
  • 技术发展面试
  • 前端临床手札——文件上传
  • 什么软件可以剪辑音乐?
  • 阿里云重庆大学大数据训练营落地分享
  • ​二进制运算符:(与运算)、|(或运算)、~(取反运算)、^(异或运算)、位移运算符​
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • ###项目技术发展史
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (12)目标检测_SSD基于pytorch搭建代码
  • (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
  • (Note)C++中的继承方式
  • (顶刊)一个基于分类代理模型的超多目标优化算法
  • (附源码)spring boot公选课在线选课系统 毕业设计 142011
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (六)DockerCompose安装与配置
  • (四)c52学习之旅-流水LED灯
  • (四)汇编语言——简单程序
  • (原創) 如何將struct塞進vector? (C/C++) (STL)
  • .net core 调用c dll_用C++生成一个简单的DLL文件VS2008
  • .net core 依赖注入的基本用发
  • .NET delegate 委托 、 Event 事件
  • .net 程序发生了一个不可捕获的异常
  • .NET 使用 XPath 来读写 XML 文件
  • .net 使用ajax控件后如何调用前端脚本
  • .netcore如何运行环境安装到Linux服务器
  • .Net多线程总结
  • .NET国产化改造探索(三)、银河麒麟安装.NET 8环境