Cleaning API JSON Response to content only

I’m a new developer, and I’ve just started working with the OpenAI API. I’ve gotten the API to work and generate a JSON output, but how can I clean it to only give me the content portion of the JSON output? Thanks!

import openai

openai.api_key = 'xxx'

###userInput = input("Welcome to CDA! How can we help you today? ") 
response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Do as prompted"},
        {"role": "user", "content": "Say, 'Hello, World!'"}
    ]
)

print(response) 

Welcome to the community!

What’s the output of your print statement? It should be fairly easy to navigate.

Additionally, you can look at examples in the docs :slight_smile:

https://platform.openai.com/docs/api-reference/chat/create?lang=python

This is the output.

ChatCompletion(id='chatcmpl-9hg9DZxg3ivUzkhc7hvtv5pjq6RB9', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='Hello, World!', role='assistant', function_call=None, tool_calls=None))], created=1720197147, model='gpt-4-0613', object='chat.completion', service_tier=None, system_fingerprint=None, usage=CompletionUsage(completion_tokens=4, prompt_tokens=21, total_tokens=25))

I can see the content portion in there, I’m wondering if there’s a way to only print that part.

https://platform.openai.com/docs/api-reference/chat/create?lang=python

image

you called completion response, so switch that as appropriate, and then

just add .content :slight_smile:

I got it working with this:

import openai

openai.api_key = 'sk-proj-xxx'


completion = openai.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Do as prompted"},
        {"role": "user", "content": "Say, 'Hello, World!"}
    ]
)

print(completion.choices[0].message.content)  

Thank you!

1 Like

Interesting, it looks like they put back non-instantiated operation in recent openai python:

image

The response object is still a new Pydantic model, with attributes and inner objects, needing new parsing.

q.choices[0].message.__class__
<class 'openai.types.chat.chat_completion_message.ChatCompletionMessage'>