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

Trying to update a textarea with string from an OpenAI request

题意:把从 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)        前端

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)        后端代码

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

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

被替换语句

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

with        替换语句

<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

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

{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.

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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 使用Python+docx+openpyxl将Word表格转换为Excel表格
  • 如何处理时间序列异常值?理解、检测和替换时间序列中的异常值
  • 掌握Go语言中的Channel:并发编程的核心
  • 集成电路学习:什么是CPU中央处理器
  • 神仙插件 LightFlow!一键复用SD WebUI工作流,AI绘画StableDiffusion抄作业必备神器!
  • 【Python篇】Python 类和对象:详细讲解(上篇)
  • 海外新闻稿发布:企业如何充分利用数字化媒体进行
  • [imx9]DDR test Tool for imx9
  • HarmonyOS鸿蒙开发:在线短视频流畅切换最佳实践
  • 数据结构——队的基本操作
  • MongonDB-索引
  • 集成电路学习:什么是ARM先进精简指令集计算机
  • 旗帜分田(华为od机考题)
  • 探索生活服务 API 接口的神奇之处
  • 国风高铁站可视化:传统文化与现代科技的融合
  • 自己简单写的 事件订阅机制
  • 【挥舞JS】JS实现继承,封装一个extends方法
  • Docker容器管理
  • Fastjson的基本使用方法大全
  • Java 23种设计模式 之单例模式 7种实现方式
  • PHP那些事儿
  • python学习笔记-类对象的信息
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • vue总结
  • webpack项目中使用grunt监听文件变动自动打包编译
  • windows下使用nginx调试简介
  • 复杂数据处理
  • 简单实现一个textarea自适应高度
  • 将 Measurements 和 Units 应用到物理学
  • 免费小说阅读小程序
  • 前端工程化(Gulp、Webpack)-webpack
  • 收藏好这篇,别再只说“数据劫持”了
  • 小程序01:wepy框架整合iview webapp UI
  • 小程序开发中的那些坑
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • #1015 : KMP算法
  • #162 (Div. 2)
  • #if和#ifdef区别
  • $LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
  • %@ page import=%的用法
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (Java入门)抽象类,接口,内部类
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (超详细)2-YOLOV5改进-添加SimAM注意力机制
  • (分类)KNN算法- 参数调优
  • (附源码)spring boot北京冬奥会志愿者报名系统 毕业设计 150947
  • (附源码)ssm跨平台教学系统 毕业设计 280843
  • (亲测有效)推荐2024最新的免费漫画软件app,无广告,聚合全网资源!
  • (三)Kafka 监控之 Streams 监控(Streams Monitoring)和其他
  • (转)C#开发微信门户及应用(1)--开始使用微信接口
  • *setTimeout实现text输入在用户停顿时才调用事件!*
  • .NET Core中Emit的使用
  • .net mvc部分视图
  • .NET 编写一个可以异步等待循环中任何一个部分的 Awaiter
  • .NET 设计模式—简单工厂(Simple Factory Pattern)