Force the AI to respond in structured JSON format.
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...