Trying to update a textarea with string from an OpenAI request

2024-09-01 07:52

本文主要是介绍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.

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

这篇关于Trying to update a textarea with string from an OpenAI request的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1126364

相关文章

如何解决mysql出现Incorrect string value for column ‘表项‘ at row 1错误问题

《如何解决mysql出现Incorrectstringvalueforcolumn‘表项‘atrow1错误问题》:本文主要介绍如何解决mysql出现Incorrectstringv... 目录mysql出现Incorrect string value for column ‘表项‘ at row 1错误报错

java String.join()的使用小结

《javaString.join()的使用小结》String.join()是Java8引入的一个实用方法,用于将多个字符串按照指定分隔符连接成一个字符串,本文主要介绍了javaString.join... 目录1. 方法定义2. 基本用法2.1 拼接多个字符串2.2 拼接集合中的字符串3. 使用场景和示例3

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

C# string转unicode字符的实现

《C#string转unicode字符的实现》本文主要介绍了C#string转unicode字符的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1. 获取字符串中每个字符的 Unicode 值示例代码:输出:2. 将 Unicode 值格式化

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

在MySQL执行UPDATE语句时遇到的错误1175的解决方案

《在MySQL执行UPDATE语句时遇到的错误1175的解决方案》MySQL安全更新模式(SafeUpdateMode)限制了UPDATE和DELETE操作,要求使用WHERE子句时必须基于主键或索引... mysql 中遇到的 Error Code: 1175 是由于启用了 安全更新模式(Safe Upd

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

string字符会调用new分配堆内存吗

gcc的string默认大小是32个字节,字符串小于等于15直接保存在栈上,超过之后才会使用new分配。

Vue3上传图片报错:Current request is not a multipart request

当你看到错误 "Current request is not a multipart request" 时,这通常意味着你的服务器或后端代码期望接收一个 multipart/form-data 类型的请求,但实际上并没有收到这样的请求。在使用 <el-upload> 组件时,如果你已经设置了 http-request 属性来自定义上传行为,并且遇到了这个错误,可能是因为你在发送请求时没有正确地设置