Having trouble using OpenAI API

news/2024/9/20 6:54:33/ 标签: ai, reactjs, node.js, openai api
aidu_pl">

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


http://www.ppmy.cn/news/1518913.html

相关文章

大语言模型数据增强与模型蒸馏解决方案

背景 在人工智能和自然语言处理领域&#xff0c;大语言模型通过训练数百亿甚至上千亿参数&#xff0c;实现了出色的文本生成、翻译、总结等任务。然而&#xff0c;这些模型的训练和推理过程需要大量的计算资源&#xff0c;使得它们的实际开发应用成本非常高&#xff1b;其次&a…

线程间数据传递之ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal

线程间数据传递之ThreadLocal、InheritableThreadLocal、TransmittableThreadLocal 1、ThreadLocal介绍 spring 中基于 ThreadLocal 来实现事务。 多线程 访问同一个共享变量的时候容易出现并发问题&#xff0c;ThreadLocal是除了加锁这种同步方式之外的一种保证 规避多线程…

【bug记录7】导入Lottie的json格式动画,获取不到相对路径下的图片

一、问题背景 在vue3项目中&#xff0c;想把Lottie依赖的图片放在其相对路径下&#xff0c;但是发现即使修改其中的u参数&#xff0c;也无法拿到其相对路径中的图片。因为json解析绝对路径&#xff0c;只能将图片放在项目根目录下的public文件夹应急。 二、解决方法 将Lottie…

Lua 代码编码规范

lua代码格式 vscode stylua 插件 配置文件stylua.toml column_width 240 line_endings “Unix” indent_type “Spaces” --使用空格 很重要&#xff0c;保证不同编辑器打开是一样的 indent_width 4 quote_style “AutoPreferDouble” --字符串引号样式双引号 call_paren…

c++关于字符串的练习

提示并输入一个字符串&#xff0c;统计该字符串中字母个数、数字个数、空格个数、其他字符的个数 #include <iostream> #include<string> using namespace std;int main() {string s1;int letter0,digit0,space0,other0;cout<<"请输入一个字符串:"…

ISO C++ 和 GNU C++ 的区别

C 的 ios 标准和 gnu 标准是两种编译器标准或模式&#xff0c;主要由编译器在编译 C 代码时所遵循的规范决定。它们之间的区别主要在于是否包含标准之外的扩展以及对特定功能的支持。 1. ISO C 标准 (-stdc11, -stdc14, -stdc17, 等) 定义: ISO C 标准是由国际标准化组织 (IS…

3D打印透气钢与传统透气钢的差异

透气钢作为一种集金属强度与透气性能于一体的特殊材料&#xff0c;在注塑模具领域扮演着关键角色&#xff0c;通过有效排除模具内困气&#xff0c;显著提升制品成型质量与生产效率。当前&#xff0c;市场上主流的透气钢产品多源自日本、美国&#xff0c;其高昂成本与技术壁垒限…

Java算法之选择排序(Selection Sort)

简介 选择排序是一种简单直观的排序算法&#xff0c;它的工作原理是每次从待排序的数据元素中选出最小&#xff08;或最大&#xff09;的一个元素&#xff0c;然后放到序列的起始位置。通过重复这个过程&#xff0c;直到所有元素都被排序。 算法步骤 在未排序序列中找到最小…

【Vue】Echart图表中的属性

目录 背景属性介绍1. title2. tooltip3. legend4. toolbox5. color6. grid7. xAxis / yAxis8. series9. visualMap10. dataZoom 示例 背景 最近Echart用的比较多&#xff0c;改动的展示效果其实也就那么些&#xff0c;而且很多案例、展示效果在Echart官网写的都很丰富&#xf…

数字化转型中的数据应用:挑战、机遇与追赶之路

在数字化时代的大潮中&#xff0c;数据已悄然从企业的边缘资源跃升为最宝贵的核心资产。然而&#xff0c;这场数据盛宴并未带来普遍的数据应用成熟&#xff0c;反而揭示了企业在数据利用上的巨大鸿沟。即便是全球500强企业&#xff0c;在数据应用的征途上&#xff0c;也仅仅是比…

android 14及android15 READ_EXTERNAL_STORAGE跟相册,视频权限的适配

最近在做Android15的适配&#xff0c;发现WRITE_EXTERNAL_STORAGE跟READ_EXTERNAL_STORAGE无法使用了&#xff0c;被弃用了 在android 13添加了外部细分权限&#xff0c;READ_MEDIA_IMAGES跟READ_MEDIA_VIDEO及 READ_MEDIA_AUDIO权限&#xff0c;而在应用内部的文件管理则不需要…

TCP与UDP对比

这两个都是运输层的协议&#xff0c;UDP是无连接不可靠的&#xff0c;而TCP是面向连接可靠的&#xff0c;相较而言&#xff0c;UDP要简单许多。两者对比做一个简要概述。 连接方式 1.UDP是无连接的&#xff0c;就是通信双方无需建立连接就可以随时发送数据。 2.而TCP在发送数…

基于Python的机器学习系列(18):梯度提升分类(Gradient Boosting Classification)

简介 梯度提升&#xff08;Gradient Boosting&#xff09;是一种集成学习方法&#xff0c;通过逐步添加新的预测器来改进模型。在回归问题中&#xff0c;我们使用梯度来最小化残差。在分类问题中&#xff0c;我们可以利用梯度提升来进行二分类或多分类任务。与回归不同&#xf…

2024.8.31 Python,合并区间,用sort通过列表第一个元素给列表排序,三数之和,跳跃游戏

1.合并区间 以数组 intervals 表示若干个区间的集合&#xff0c;其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间&#xff0c;并返回 一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中的所有区间 。 示例 1&#xff1a; 输入&#xff1a;inter…

ARCGIS 纸质小班XY坐标转电子要素面(2)

本章用于说明未知坐标系情况下如何正确将XY转要素面 背景说明 现有资料&#xff1a;清除大概位置&#xff0c;纸质小班图&#xff0c;图上有横纵坐标&#xff0c;并已知小班XY拐点坐标&#xff0c;但未知坐标系。需要上图 具体操作 大部分操作同这边文章ARCGIS 纸质小班XY…

Java | Leetcode Java题解之第387题字符串中的第一个唯一字符

题目&#xff1a; 题解&#xff1a; class Solution {public int firstUniqChar(String s) {Map<Character, Integer> position new HashMap<Character, Integer>();Queue<Pair> queue new LinkedList<Pair>();int n s.length();for (int i 0; i …

模型 错位竞争(战略规划)

系列文章 分享 模型&#xff0c;了解更多&#x1f449; 模型_思维模型目录。与其更好&#xff0c;不如不同。 1 错位竞争的应用 1.1 美团的错位竞争策略 美团&#xff0c;作为中国领先的电子商务平台&#xff0c;面临着阿里巴巴等电商巨头的竞争压力。为了在市场中获得独特的…

MATLAB虫害检测预警系统

一、课题介绍 本课题是基于MATLAB颜色的植物虫害检测识别&#xff0c;可以辨析植物叶子属于是轻度虫害&#xff0c;中度虫害&#xff0c;严重虫害&#xff0c;正常等四个级别。算法流程&#xff1a;每种等级叶子分别放在同一个文件夹&#xff0c;训练得到每个文件夹每个叶…

续:MySQL的gtid模式

为什么要启用gtid? master端和slave端有延迟 ##设置gtid master slave1 slave2 [rootmysql1 ~]# vim /etc/my.cnf [rootmysql1 ~]# cat /etc/my.cnf [mysqld] datadir/data/mysql socket/data/mysql/mysql.sock symbolic-links0 log-binmysql-bin server-id1 slow_query_lo…

AI学习指南深度学习篇-门控循环单元中的门控机制

AI学习指南深度学习篇-门控循环单元中的门控机制 引言 深度学习是当前人工智能领域的一个重要方向&#xff0c;而循环神经网络&#xff08;RNN&#xff09;在处理序列数据方面展现出了强大的能力。然而&#xff0c;标准的RNN在处理长序列时存在长期依赖问题&#xff0c;容易导…