How to Parse Chat Completion JSON in Python
Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.
Python code
31 linesimport json
def parse_chat_response(raw: str) -> dict:
data = json.loads(raw)
choice = data["choices"][0]
return {
"content": choice["message"]["content"],
"finish_reason": choice["finish_reason"],
"model": data["model"],
}
if __name__ == "__main__":
mock_response = '''
{
"id": "chatcmpl-123",
"object": "chat.completion",
"model": "gpt-3.5-turbo",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?"
},
"finish_reason": "stop"
}
]
}
'''
result = parse_chat_response(mock_response)
print(json.dumps(result, indent=2))
Output
{
"content": "Hello! How can I help you today?",
"finish_reason": "stop",
"model": "gpt-3.5-turbo"
}
How it works
The json.loads call converts the raw JSON string into a Python dictionary, letting you access nested fields with bracket notation. The choices list is indexed first, because each response can contain multiple choices and you want the first one. The message object nested inside holds the assistant's reply content. Extracting finish_reason and model gives you metadata for logging or branching logic. This pattern mirrors what you'd do with real API responses, just with dummy data for testing.
Common mistakes
- Assuming `choices` list always has an element — always guard against empty responses.
- Forgetting that the content field may be null for tool calls or function invocations.
- Using `json.load` instead of `json.loads` when reading from a string instead of a file.
Variations
- Use `choice["message"].get("content")` to safely handle missing content.
- Use `json.loads(raw)["choices"][0]["message"]["content"]` for a one-liner when you don't need the other fields.
Real-world use cases
- Extracting assistant replies from an OpenAI API response in a chatbot backend.
- Logging finish reasons to detect truncated or stopped completions in production.
- Testing prompt logic with mock responses before wiring up real API calls.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.