Lesson 11 of 23 · Part 1: API Basics

JSON Output

Force the AI to respond in structured JSON format.

Last time: A while True loop and a growing messages list let our chatbot remember the conversation.
Today: We ask the AI for data in JSON, a neat format that programs can read easily.
Your laptop
→
←
OpenAIwaiting
What is JSON?
{"difficulty": "easy"}
Source Code
1# 3_json_output.py
2from openai import OpenAI
3client = OpenAI()
4
5print("Asking the AI for structured JSON output...")
6
7system_prompt = "You are a helpful assistant that only responds in valid JSON."
8
9user_prompt = "Give me 3 Python interview questions in JSON format. Use the keys: 'question' and 'difficulty'."
10
11response = client.chat.completions.create(
12    model="gpt-4o-mini",
13    messages=[
14        {"role": "system", "content": system_prompt},
15        {"role": "user", "content": user_prompt}
16    ],
17    response_format={ "type": "json_object" }
18)
19
20print("\nAI's JSON Response:")
21print(response.choices[0].message.content)

No output yet...

← Prev
1/0
Next: Few-Shot →