Having trouble using OpenAI API

news2024/9/21 14:53:12

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2092536.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

java 教程-我的第一个JAVA程序

Java视频教程 我的第一个JAVA程序 以下我们通过一个简单的实例来展示Java编程&#xff0c;本实例输出"编程字典&#xff0c;Java教程&#xff01;"&#xff0c;这也是所有语言入门的第一个实例程序&#xff1a; packagecodingdict.com; publicclassHelloWorld{ publi…

REGTR: End-to-end Point Cloud Correspondences with Transformers 论文解读

目录 一、导言 二、先导知识 1、3DRegNet 2、Kabsch-Umeyama算法 3、InfoNCE损失函数 三、相关工作 1、基于对应关系的配准 2、全局配准工作 3、过滤问题 4、Transformer 四、REGTR网络 1、降采样和特征提取 2、Transformer 交叉编码器 Transformer为什么要用FF…

MySQL高阶练习题2-没有广告的剧集

目录 题目 准备数据 分析数据 实现代码 总结 题目 找出所有没有广告出现过的剧集。 返回结果 无顺序要求 。 准备数据 create database db; use db;Create table If Not Exists Playback(session_id int,customer_id int,start_time int,end_time int); Create table I…

数据结构:(LeetCode 965)相同的树

给你两棵二叉树的根节点 p 和 q &#xff0c;编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同&#xff0c;并且节点具有相同的值&#xff0c;则认为它们是相同的。 示例 1&#xff1a; 输入&#xff1a;p [1,2,3], q [1,2,3] 输出&#xff1a;true示例 2&…

「草莓」即将上线,OpenAI新旗舰大模型曝光,代号「猎户座」

本月初,OpenAI 创始人、CEO 山姆・奥特曼突然在 X 上发了一张照片,勾起了大家强烈的好奇心。 「四个红草莓,其中还有一个未成熟的青色草莓,这不妥妥地是在说下一代 AI 大模型 GPT-5 要来了吗?」奥特曼在回应网友时也在暗示,惊喜马上就来。 据科技媒体 The Information 报…

前胡基因组与伞形科香豆素的进化-文献精读42

The gradual establishment of complex coumarin biosynthetic pathway in Apiaceae 伞形科中复杂香豆素生物合成途径的逐步建立 羌活基因组--文献精读-36 摘要&#xff1a;复杂香豆素&#xff08;CCs&#xff09;是伞形科植物中的特征性代谢产物&#xff0c;具有重要的药用价…

JAVA:文字写入图片、图片插入图片

一、前言 在实际应用中&#xff0c;需要通过Java将目标信息写在图片上&#xff0c;生成小卡片。 二、实现 1.定义一个工具类&#xff0c;代码如下&#xff1a; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.Fil…

C++(1)基础语法

C(1)之基础语法 Author: Once Day Date: 2024年8月29日 一位热衷于Linux学习和开发的菜鸟&#xff0c;试图谱写一场冒险之旅&#xff0c;也许终点只是一场白日梦… 漫漫长路&#xff0c;有人对你微笑过嘛… 全系列文章可参考专栏: 源码分析_Once-Day的博客-CSDN博客 参考文…

使用控制台与键盘进行输入输出

1、控制台简介与初始化 计算机在上电启动后&#xff0c;显示器被默认配置成80x25列的文本显示模式 。其使用从0xb8000开始&#xff0c;一共32KB的显存用于显示。如要在屏幕上指定位置显示特定的字符&#xff0c;则只需找到该位置对应的显存地址&#xff0c;写入2字节的数据&am…

ctfshow之web58~web71

目录 web58 思路一&#xff1a; 思路二&#xff1a; 思路三&#xff1a; web59~web65 web66~web67 web68~web70 web71 web58 if(isset($_POST[c])){$c $_POST[c];eval($c); }else{highlight_file(__FILE__); } PHP eval() 函数介绍 定义和用法 eval() 函数把字符串按…

【Sceneform-EQR】通过filament(gltfio)加载gltf模型动画(Filament使用Animator)

Sceneform-EQR 简介 Sceneform-EQR是EQ基于sceneform&#xff08;filament&#xff09;扩展的一个用于安卓端的三维渲染器。 相关链接 Git仓库 Sceneform-EQR 码云 EQ-Renderer的示例工程 EQ-R相关文档 文档目录CSDN专栏 实现通过filament加载gltf模型动画 运行示例 …

U盘无法访问?揭秘原因与高效恢复策略

一、U盘困境深度剖析 在日常的数字生活中&#xff0c;U盘作为我们存储和传输数据的重要工具&#xff0c;其重要性不言而喻。然而&#xff0c;当U盘突然显示“无法访问”时&#xff0c;这种突如其来的困境往往让人措手不及。U盘无法访问的现象可能由多种原因造成&#xff0c;包…

Question mutiple pdf‘s using openai, pinecone, langchain

题意&#xff1a;使用 OpenAI、Pinecone 和 LangChain 对多个 PDF 文件进行提问。 问题背景&#xff1a; I am trying to ask questions against a multiple pdf using pinecone and openAI but I dont know how to. 我正在尝试使用 Pinecone 和 OpenAI 对多个 PDF 文件进行提…

ssh远程连接服务

1、概述 一种安全访问远程服务器的协议&#xff0c;远程管理工具&#xff0c;通过加密方式管理连接&#xff0c;使服务器更安全。 2、加密算法 对称加密 发送密码前将密码数据加密成密文&#xff0c;然后发送出去 接收方收到密文后&#xff0c;使用同一个密钥将密文解密。…

基于爬山法MPPT和PI的直驱式永磁同步风力发电机控制系统simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 4.1 PMSM 4.2 MPPT 4.3 PI 控制器原理 5.完整工程文件 1.课题概述 基于爬山法最大功率点跟踪 (Maximum Power Point Tracking, MPPT) 和比例积分控制器 (Proportional Integral, PI) 的直驱式永磁同步…

《软件工程导论》(第6版)第5章 总体设计 复习笔记

第5章 总体设计 一、总体设计概念 1&#xff0e;定义 总体设计的基本目的就是回答“系统应该如何实现”这个问题&#xff0c;总体设计又称为概要设计或初步设计。 2&#xff0e;主要任务 &#xff08;1&#xff09;划分出组成系统的物理元素程序、文件、数据库、人工过程…

大模型种草书籍——BERT基础教程:Transformer大模型实战,看完头皮发麻!

《BERT基础教程&#xff1a;Transformer大模型实战》 是一本专注于介绍自然语言处理&#xff08;NLP&#xff09;领域的先进技术——BERT&#xff08;Bidirectional Encoder Representations from Transformers&#xff09;及其应用的教程书籍。 以下是这本书的简要介绍&#…

C++:string类(1)

1.标准库中的string类 1.1 string类(了解) string类的文档介绍在使用string类时&#xff0c;必须包含#include头文件以及using namespace std; 1.2 auto和范围for auto关键字 用auto声明指针类型时&#xff0c;用auto和auto*没有任何区别&#xff0c;但用auto声明引用类型…

gdb 教程

文章目录 GDB启动 GDB 的方法GDB 命令工具参考 GDB GDB是Linux下的调试工具&#xff0c;可以调试C、C、Go、java等语言 GDB提供了以下四个功能&#xff1a; 程序启动时&#xff0c;可以按照自定义的要求运行程序&#xff0c;如设置参数和环境变量可以让被调试的程序在所指定…

Netflix Feign:微服务HTTP调用如何简化?

Netflix Feign&#xff1a;微服务HTTP调用如何简化&#xff1f; 1、什么是Netflix Feign&#xff1f;2、Feign的优点3、示例4、总结 &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 1、什么是Netflix Feign&#xff1f; Feign是一个声明式的…