pythonbeginner
OpenAI JSON Mode Responses
Force JSON output from OpenAI models using response_format for reliable structured responses.
pythonPress ⌘/Ctrl + Shift + C to copy
from openai import OpenAI
import json
client = OpenAI()
response = client.chat.completions.create(
model='gpt-4o-mini',
response_format={'type': 'json_object'},
messages=[
{'role': 'system', 'content': 'Return your answer as a JSON object.'},
{'role': 'user', 'content': 'List 3 Python libraries for data science with a one-line description each.'},
],
)
data = json.loads(response.choices[0].message.content)
print(json.dumps(data, indent=2))Use Cases
- structured AI responses
- JSON extraction
- reliable parsing
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai
pythonintermediate
Async OpenAI Client in Python
Use the AsyncOpenAI client with asyncio to run concurrent chat completions without blocking.
Best for: concurrent LLM calls
#openai#async
pythonadvanced
OpenAI Batch API for Cost Reduction
Submit large workloads via the OpenAI Batch API for 50% cost reduction with async processing.
Best for: batch inference
#openai#batch
pythonbeginner
OpenAI DALL-E Image Generation
Generate and save images using the DALL-E 3 API with quality and style control.
Best for: AI image creation
#openai#dall-e