题意:把从 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.
这样做可以避免在响应为空之前显示该元素。你还可以选择使用布尔值来跟踪后端的状态,以提高代码的可读性。