#Does json mode return json object?

1 messages · Page 1 of 1 (latest)

lyric kelp
#

I'm using python and completions api, in json mode. is my response a json string or python dict

wicked trellisBOT
#

Hi @lyric kelp. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, when you use JSON mode in the OpenAI API, the model is instructed to generate a response that is a valid JSON object. This is done by setting the response_format to { "type": "json_object" } when making the API call.

However, when you're using the OpenAI Python client, the response you receive from the API is automatically parsed into a Python object (specifically, a dictionary). This means that you can interact with the response as you would with any other Python dictionary.

Here's an example of how you might use JSON mode with the OpenAI Python client:

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
  model="gpt-3.5-turbo-0125",
  response_format={ "type": "json_object" },
  messages=[
    {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
    {"role": "user", "content": "Who won the world series in 2020?"}
  ]
)

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

In this example, response.choices[0].message.content would be a string that contains a valid JSON object. You can convert this string into a Python dictionary using json.loads().

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: