How do I clean the response from the API in Python?

I know this a really silly question, but I’m still a little new to Python and I’ve been trying all day to find a way to clean the API response to just the “text” value attribute.

Would anyone of you happen to know how to do this and can post a quick example of the code so I can learn?

Thanks a ton for your time! :blush:

2 Likes

Yes.

From the response, you want only response["choices"][0]["text"]. It gives you a full-text response without any other data. I think it’s the same for every OpenAI model.

This is the quickest example I have: Just install json and openai with Python PIP. After that, replace openai.api_key with your OpenAI secret key, which is here.

Finally execute the code in your terminal, when it requests you text, you can give it the first paragraph of the Earth Wikipedia article. Just copy and paste it. When you press Enter, it will give you only the text response (in this case, is the summarized paragraph).

import json
import openai

openai.api_key = "Replace this string with your OpenAI API secret key"

text_input = str(input('Enter your text: '))
text_input = text_input.strip()

response = openai.Completion.create(
        engine="davinci",
        prompt="My second grader asked me what this passage means:\n\"\"\"\n" + text_input + "\n\"\"\"\nI rephrased it for him, in plain language a second grader can understand:\n\"\"\"\n",
        temperature=0.5,
        max_tokens=100,
        top_p=1,
        frequency_penalty=0.2,
        presence_penalty=0,
        stop=["\"\"\""]
)

# This is the response
print("The summarized text is:"
print(response["choices"][0]["text"])

It will work like that:

This piece of code was modified and extracted from one of my projects: Summer, it summarizes complex text.

Regards!

1 Like

Thanks so much for the help and I really liked your example! :grin:

2 Likes