我在尝试从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