I am attempting to extract text from OpenAI, but I need some help with the correct syntax.
My code:
_model = "gpt-3.5-turbo-instruct"
# Summarize the text using an AI model (e.g., OpenAI's 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']
I want to get a summary of the text. Is this the best way?
However, I find when I debug the code that the text object is located in the following structure within summary['choices'][0]
:
CompletionChoice(finish_reason='stop', index=0, logprobs=None, text='blah blah blah')
How do I extract the text from this in Python code?
By using the following method, it means that you're using the OpenAI Python SDK >=v1.0.0
:
openai.completions.create
The response using the OpenAI Python SDK >=v1.0.0
looks like this:
{
"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
}
}
Which means that the following is the correct way to extract the completion using the OpenAI Python SDK >=v1.0.0
:
summary.choices[0].text