Trying to update a textarea with string from an OpenAI request

news/2024/9/16 17:35:30/ 标签: ai, javascript, reactjs, react native, react hooks
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/news/1521769.html

相关文章

设计之道:ORM、DAO、Service与三层架构的规范探索

引言&#xff1a; 实际开发中&#xff0c;遵守一定的开发规范&#xff0c;不仅可以提高开发效率&#xff0c;还可以提高项目的后续维护性以及项目的扩展性&#xff1b;了解一下本博客的项目设计规范&#xff0c;对项目开发很有意义 一、ORM思想 ORM&#xff08;Object-Relation…

P0.9/P1.25全倒装共阴节能COB超微小间距LED显示屏已抢占C位

COB&#xff08;Chip on Board&#xff09;技术最早发源于上世纪60年代&#xff0c;是将LED芯片直接封装在PCB电路板上&#xff0c;并用特种树脂做整体覆盖。COB实现“点” 光源到“面” 光源的转换。点间距有P0.3、P0.4、P0.5、P0.6、P0.7、P0.9、P1.25、P1.538、P1.5625、P1.…

pytorch计算张量中三维向量的欧式距离

如果 X 是一个包含多个三维向量的张量&#xff0c;形状为 [b, n, 3]&#xff0c;其中 b 是批次大小&#xff0c;n 是每个批次中的向量数量&#xff0c;那么可以使用类似的广播机制来计算同一批次内不同位置的三维向量之间的欧式距离。 以下是具体实现步骤&#xff1a; 扩展张量…

时序预测 | 基于DLinear+PatchTST多变量时间序列预测模型(pytorch)

目录 效果一览基本介绍程序设计参考资料 效果一览 基本介绍 DLinearPatchTST多变量时间序列 dlinear,patchtst python代码&#xff0c;pytorch架构 适合功率预测&#xff0c;风电光伏预测&#xff0c;负荷预测&#xff0c;流量预测&#xff0c;浓度预测&#xff0c;机械领域预…

Java 基于微信小程序的小区服务管理系统,附源码

博主介绍&#xff1a;✌stormjun、8年大厂程序员经历。全网粉丝15w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;&…

websocket和轮询的区别?

问&#xff1a; websocket和轮询的区别&#xff1f; 回答&#xff1a; WebSocket 和定时轮询&#xff08;每隔几秒发送一次请求&#xff09;是两种不同的实时通信方法&#xff0c;各有优缺点&#xff0c;适用于不同的场景。以下是它们的主要区别及适用场景&#xff1a; WebSo…

Node.js sqlite3事件深入解析:trace、profile、change、error、open

在Node.js环境中&#xff0c;sqlite3库不仅提供了丰富的API用于数据库操作&#xff0c;还定义了一系列的事件&#xff0c;使得开发者能够监听和响应数据库操作过程中的各种状态变化。本文将深入解析sqlite3库中的trace、profile、change、error、open这五个事件&#xff0c;包括…

0903,LIST(merge,splice,sort,unique),SET(insert,erase)

目录 03_vector_delete.cc 04_vector_shrink.cc 05_vec_emplace_back.cc 06_listspec_splice.cc 07_classstruct.cc 08_set.cc 09_setErase.cc 作业 01 STL中的容器包括哪些&#xff1f;各自具有哪些特点&#xff1f; 02 题目&#xff1a;编写代码&#xff1a;将…

Android Camera系列(一):SurfaceView+Camera

心行慈善&#xff0c;何需努力看经—《西游记》 Android Camera系列&#xff08;一&#xff09;&#xff1a;SurfaceViewCamera Android Camera系列&#xff08;二&#xff09;&#xff1a;TextureViewCamera Android Camera系列&#xff08;三&#xff09;&#xff1a;GLSur…

20240902软考架构-------软考96-100答案解析

每日打卡题96-100答案 96、【2018年真题】 难度&#xff1a;难 CORBA服务端构件模型中&#xff0c; 是CORBA对象的真正实现&#xff0c;负责完成客户端请求。 A.伺服对象&#xff08;Servant&#xff09; B.对象适配器&#xff08;Object Adapter&#xff09; C.对象请求代理&…

回溯——7.子集II

力扣题目链接 给定一个可能包含重复元素的整数数组 nums&#xff0c;返回该数组所有可能的子集&#xff08;幂集&#xff09;。 说明&#xff1a;解集不能包含重复的子集。 示例: 输入: [1,2,2]输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] 解题思路总结&#xff1a; …

AIStarter改进计划:功能优化与内测预告【欢迎吐槽】

随着技术的不断进步&#xff0c;AIStarter也在持续进化&#xff0c;以更好地满足用户的需求。本文将探讨AIStarter的改进计划&#xff0c;包括应用版本号、市场排序、描述和筛选功能的优化&#xff0c;并预告即将到来的内测消息。此外&#xff0c;还将介绍AIStarter在网络加速、…

东南大学研究生-数值分析上机题(2023)Python 3 线性代数方程组数值解法

列主元Gauss消去法 3.1 题目 对于某电路的分析&#xff0c;归结为就求解线性方程组 R I V \pmb{RIV} RIV&#xff0c;其中 R [ 31 − 13 0 0 0 − 10 0 0 0 − 13 35 − 9 0 − 11 0 0 0 0 0 − 9 31 − 10 0 0 0 0 0 0 0 − 10 79 − 30 0 0 0 − 9 0 0 0 − 30 57 − 7 …

【2024-2025源码+文档+调试讲解】微信小程序的城市公交查询系统

摘 要 当今社会已经步入了科学技术进步和经济社会快速发展的新时期&#xff0c;国际信息和学术交流也不断加强&#xff0c;计算机技术对经济社会发展和人民生活改善的影响也日益突出&#xff0c;人类的生存和思考方式也产生了变化。传统城市公交查询管理采取了人工的管理方法…

怎么摆脱非自然链接?

什么是非自然链接&#xff1f; 非自然链接是人为创建的链接&#xff0c;用于操纵网站在搜索引擎中的排名。非自然链接违反了Google 的准则&#xff0c;网站可能会因此受到惩罚。 它们不是由网站所有者编辑放置或担保的。示例包括带有过度优化锚文本的链接、通过 PR 的广告、嵌…

Nginx部署前端VUE项目

要部署一个Vue项目&#xff0c;可以使用nginx作为web服务器。下面是一些步骤&#xff1a; 确保你已经在本地机器上安装了nginx。如果没有安装&#xff0c;请按照官方文档进行安装。 将Vue项目构建为静态文件。在项目根目录下运行以下命令&#xff1a; npm run build这将在项…

如何在Excel中创建一个VBA宏,并设置一个按钮来执行这个宏

下面是一个详细的步骤指南 步骤1&#xff1a;创建VBA宏 1. 打开Excel并按 Alt F11 打开VBA编辑器。 2. 在VBA编辑器中&#xff0c;选择 Insert > Module 来插入一个新的模块。 3. 将以下代码粘贴到模块中&#xff1a; vba Sub CreateNewSheet() 声明一个工作表对象Dim …

【STM32项目设计】STM32F411健康助手--MPU6050陀螺仪驱动(6)

硬件设计 软件设计 此项目使用的是软件I2C&#xff0c;MPU6050的SCL连接到STM32的PB10&#xff0c;SDA连接到STM32的PB9 mpuiic.c #include "mpuiic.h" #include "delay.h"//MPU IIC 延时函数 void MPU_IIC_Delay(void) {delay_us(2); }//初始化IIC voi…

AWS账号关闭后的影响:您需要知道的一切

亚马逊网络服务&#xff08;AWS&#xff09;作为全球领先的云计算平台&#xff0c;为众多企业和个人提供了便捷、高效的云服务。然而&#xff0c;当用户决定关闭其AWS账号时&#xff0c;可能会对其现有的服务和资源产生重大影响。我们九河云将通过本文将深入探讨AWS账号关闭后的…

SQLite 创建表:一场数据库里的“造物运动”

嘿&#xff0c;各位数据库的“造物主”们&#xff01;今天咱们来聊聊SQLite里的一场有趣活动——创建表。没错&#xff0c;就像上帝创造了世界&#xff0c;我们也可以在SQLite数据库里创造属于我们自己的“小世界”。 一、创建表的“魔法咒语” 在SQLite这个“魔法世界”里&a…