Trying to update a textarea with string from an OpenAI request

embedded/2024/9/24 17:23:07/
aidu_pl">

题意:把从 OpenAI 请求中得到的字符串更新到一个文本区域中。

问题背景:

Can anyone assist me with an issue I'm facing. I'm trying to append a string received back from an OpenAI request to an exisitng textarea element. The requested string is received and stored in the back end in an array called response.data.choices[0].text. I'm currently trying to append the {response} string into an existing textarea in the front end using the code <textarea id="textarea">{response}</textarea>. The issue seems to be that code: <textarea id="textarea">{response}</textarea> is creating the textarea on screen (on launch) prior to string data being received/stored into the response array as there is significant latency with respect to the response time between the back end request and what is received from OpenAI. I'm unsure how to overcome this issue do i need to have some sort of thread to constantly check for changes in the array than delete and recreate the textarea element? I honestly have no clue how to bypass this issue any help would be so greatly appreciated. Thanks again for your time.

我遇到一个问题,希望有人能帮忙。我正在尝试将从 OpenAI 请求中接收到的字符串追加到现有的文本区域元素中。请求的字符串已接收到并存储在后端的数组 `response.data.choices[0].text` 中。目前,我尝试使用代码 `<textarea id="textarea">{response}</textarea>` 将 `{response}` 字符串追加到前端的现有文本区域中。问题是代码 `<textarea id="textarea">{response}</textarea>` 会在页面加载时创建文本区域元素,但此时字符串数据尚未接收到并存储到 `response` 数组中,因为后端请求与 OpenAI 之间的响应时间存在显著延迟。我不确定如何解决这个问题。是否需要某种线程来不断检查数组中的变化,然后删除并重新创建文本区域元素?我真的不知道如何绕过这个问题,任何帮助都会非常感激。再次感谢您的时间。

It's really important that the textarea is to appear before the response is received.

关键是文本区域必须在接收到响应之前出现。

APP.JS (Front End)        前端

javascript">import React, { useState } from 'react';function App() {const [message, setMessage] = useState('');const [response, setResponse] = useState('');const handleSubmit = (e) => {e.preventDefault();fetch('http://localhost:3001/', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({ message }),}).then((res) => res.json()).then((data) => setResponse(data.message));};return (<body><div className="App"><form onSubmit={handleSubmit}> <div class="section"></div>//User inputs there question to OpenAI<input type="text" class="topic" placeholder="Interest Rates, Quantum Mechanics, Team Management"value={message}onChange={(e) => setMessage(e.target.value)}></input>//Submits user input to back end<div> <button id="generate" type="submit">Generate</button> </div>//Attempting to write the response from back end to textarea (cannot due to latency)<textarea id="textarea">{response}</textarea><div class="break"></div></form>//prints back end response from OpenAI (for refference only)<h4>{response}</h4></div></body>);
}export default App

INDEX.JS (Back End)        后端代码

javascript">const OpenAI = require('openai');
const { Configuration, OpenAIApi } = OpenAI;const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3001;const configuration = new Configuration({organization: "org-kEBxx4hVwFZZeA",apiKey: "sk-jmYuTSCZvxCjidnbTpjFT3BlbkFJ9nFcGxbH4V",
});
const openai = new OpenAIApi(configuration);app.use(bodyParser.json());
app.use(cors());app.post('/', async (req, res) => {const { message } = req.body;const response = await openai.createCompletion({model: "text-davinci-003",prompt: `${message}`,max_tokens: 100,temperature: 0,});console.log(response.data)if(response.data.choices[0].text){res.json({message: response.data.choices[0].text})}});app.listen(port, () => {console.log("Listening...")
});

问题解决:

I would check out this link for more information on textareas. The short of it is you should replace

我建议你查看[这个链接](#)获取有关文本区域的更多信息。简而言之,你应该替换以下内容:

被替换语句

javascript"><textarea id="textarea">{response}</textarea>

with        替换语句

javascript"><textarea id="textarea" value={response} />

Although, if the user is not going to be editing the response from OpenAI, I would consider just using a styled text element like <p> or <h4> like you have below. Textarea's big benefit is allowing use to edit multiline inputs, which perhaps doesn't seem necessary for it's use here.

不过,如果用户不会编辑从 OpenAI 接收到的响应,我建议考虑使用像 `<p>` 或 `<h4>` 这样的样式化文本元素,就像你下面使用的一样。文本区域的主要优点是允许用户编辑多行输入,但在这里的用途上似乎并不必要。

As a second note, it sounds like you don't want the textarea to appear until the response is received. For that, you can do something like

第二点是,听起来你希望文本区域在接收到响应后才出现。为此,你可以这样做:

javascript">{response.length > 0 && <textarea id="textarea" value={response} />}

which will refrain from displaying the element until the response is not empty. You might also choose to instead track the status of the backend using a boolean for readability.

这样做可以避免在响应为空之前显示该元素。你还可以选择使用布尔值来跟踪后端的状态,以提高代码的可读性。


http://www.ppmy.cn/embedded/103845.html

相关文章

HTML实现俄罗斯方块

本篇文章主要讲使用HTML、CSS和JavaScript实现一个简单的俄罗斯方块游戏&#xff0c;包含基本的游戏逻辑、行消除功能以及暂停和继续游戏的控制。 使用工具 本篇文章有用到ChatGPT-4o代码纠错&#xff0c;国内免翻且稳定&#xff0c;感兴趣的大佬试试。 传送门&#xff1a;36…

XR-Frame 实现 始终朝向屏幕(相机)的面片与模型

wxml&#xff0c;xr-frame中plane平面默认是趴在场景中的&#xff0c;需要先绕x轴渲染90度&#xff0c; // 面片 <xr-node id"l" position"-3.0 0 0.0"><xr-mesh rotation"90 0 0" geometry"plane" uniforms"u_base…

VIVO 相机HDR拍照流程拆解

和你一起终身学习&#xff0c;这里是程序员Android 经典好文推荐&#xff0c;通过阅读本文&#xff0c;您将收获以下知识点: HDR 场景下发 3 帧拍照请求HDR 3帧拍照请求帧&#xff08;478,479 480&#xff09;HDR 3帧 result callback帧HDR 算法处理5.算法编解码处理HDR 拍照lo…

5G SPS配置

‌SPS配置‌是一种技术&#xff0c;用于管理和优化数据传输&#xff0c;特别是在无线通信领域。它涉及到为特定的数据传输需求确定最佳的参数配置&#xff0c;以满足不同的传输需求。SPS配置的参数包括时域资源分配、调制编码方式、频域资源分配、虚拟资源块到物理资源块的映射…

使用 streamlink 把 m3u8 转为 mp4

问题描述&#xff0c; 背景&#xff0c; 来源&#xff1a; 下载 m3u8 ts —> 转为mp4, 按照以往的做法&#xff0c; 就是使用 python requests 一步一步地下载 m3u8, ts&#xff0c; 然后转换。 但是个人写的东西&#xff0c;毕竟问题比较多。 而且&#xff0c; 但是&…

Python知识点:如何使用Elasticsearch与Elasticsearch-py进行全文检索

使用Elasticsearch与elasticsearch-py库进行全文检索可以分为以下几个步骤&#xff1a; 1. 安装elasticsearch-py 首先&#xff0c;确保你已经安装了elasticsearch-py库。你可以使用pip来安装它&#xff1a; pip install elasticsearch2. 连接到Elasticsearch实例 使用elas…

2 Python开发工具:PyCharm的安装和使用

本文是 Python 系列教程第 2 篇&#xff0c;完整系列请查看 Python 专栏。 1 安装 官网下载地址https://www.jetbrains.com.cn/pycharm/&#xff0c;文件比较大&#xff08;约861MB&#xff09;请耐心等待 双击exe安装 安装成功后会有一个30天的试用期。。。本来想放鸡火教程&…

React滚动加载(无限滚动)功能实现

在用户滚动到接近页面底部时自动加载更多内容 &#xff1a;可以将事件绑定在antd的Table组件中的onScroll中 &#xff1a;也可以将事件绑定在外层的div的onScroll中 const handleScroll (e) > {const { scrollTop, scrollHeight, clientHeight } e.target;if (scrollTo…