OpenAI Completions API: 如何从响应中提取文本?

我在尝试从OpenAI中提取文本,但我需要一些关于正确语法的帮助。

我的代码如下:

_model = "gpt-3.5-turbo-instruct"# 使用AI模型(例如OpenAI的GPT)总结文本try:    summary = openai.completions.create(        model=_model,        prompt=f"Summarize this text: {text}",        max_tokens=150    )except Exception as e:    return f"summary: Exception {e}"_summary = summary.choices[0].message.content#_summary = summary['choices'][0]['text']

我想获取文本的摘要。这是最好的方法吗?

然而,当我调试代码时,我发现文本对象位于summary['choices'][0]的以下结构中:

CompletionChoice(finish_reason='stop', index=0, logprobs=None, text='blah blah blah')

如何在Python代码中从中提取文本?


回答:

通过使用以下方法,意味着您正在使用OpenAI Python SDK >=v1.0.0

openai.completions.create

使用OpenAI Python SDK >=v1.0.0的响应看起来像这样:

{  "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",  "object": "text_completion",  "created": 1589478378,  "model": "gpt-3.5-turbo-instruct",  "system_fingerprint": "fp_44709d6fcb",  "choices": [    {      "text": "\n\nThis is indeed a test",      "index": 0,      "logprobs": null,      "finish_reason": "length"    }  ],  "usage": {    "prompt_tokens": 5,    "completion_tokens": 7,    "total_tokens": 12  }}

这意味着使用OpenAI Python SDK >=v1.0.0提取完成内容的正确方法是:

summary.choices[0].text

Related Posts

L1-L2正则化的不同系数

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

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

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

f1_score metric in lightgbm

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

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

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

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

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

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

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

发表回复

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