OpenAI响应文本提取

我正在尝试修复Open AI GPT 3 davinci-text-002给我的响应。在控制台中,我得到了以下响应文本:

{  "id": "cmpl-61dshxu43ecbrqir187yilz9mdhsj",  "object": "text_completion",  "created": 1665749707,  "model": "text-davinci-002",  "choices": [{    "text": "?\n\nthere is no simple answer to these questions. each person's individual experiences and perspectives will shape their understanding of who they are and what life is. in general, however, people often think of themselves as unique individuals with specific talents, interests, and goals. they may also think of life as a journey full of challenges and opportunities for growth.",    "index": 0,    "logprobs": null,    "finish_reason": "stop"  }],  "usage": {    "prompt_tokens": 7,    "completion_tokens": 71,    "total_tokens": 78  }}

文本似乎从\n\n开始,到","index"结束。要提取这段文本作为输出,最好的方法是什么?这是我目前的代码:

let open_ai_response;openai_test();async function openai_test() {  var prompt_text = "who am i?"  var prompt_text2 = "what is life"  var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";  var xhr = new XMLHttpRequest();  xhr.open("POST", url);  xhr.setRequestHeader("Content-Type", "application/json");  xhr.setRequestHeader("Authorization", "Bearer sk-00x0x0x0x0x0x0x0x0x0x0x0x0x");  xhr.onreadystatechange = function() {    if (xhr.readyState === 4) {      console.log(xhr.status);      console.log(xhr.responseText);      var open_ai_response = xhr.responseText;      console.log(open_ai_response);      var edit = open_ai_response[0].toUpperCase() + open_ai_response.slice(1).toLowerCase();      console.log(edit)    }  };  var data = `{    "prompt": "${prompt_text + prompt_text2}",    "temperature": 0.7,    "max_tokens": 256,    "top_p": 1,    "frequency_penalty": 0.75,    "presence_penalty": 0  }`;  xhr.send(data);}


回答:

你收到的响应是JSON格式的。你需要在onreadystatechange处理程序中使用JSON.parse(xhr.responseText)来解析它,然后可以通过访问choices[0].text属性来获取文本。

xhr.onreadystatechange = function() {  if (xhr.readyState === 4) {    var response = JSON.parse(xhr.responseText);    let text = response.choices[0].text    console.log(text);      }};

请注意,这仅读取choices数组中第一个元素的text。如果你想处理该数组中的所有内容,可以修改上述逻辑以遍历它们。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注