14.1 JSON Mode
response = client.chat.completions.create(
model="gpt-4o",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Extract entity information as JSON."},
{"role": "user", "content": "John Smith is a Senior VP at Acme Corp in NYC."}
]
)
# Output: {"name": "John Smith", "title": "Senior VP", "company": "Acme Corp", "location": "NYC"}
14.2 Function Calling
tools = [{
"type": "function",
"function": {
"name": "search_knowledge_base",
"description": "Search the enterprise knowledge base for relevant documents",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"filters": {
"type": "object",
"properties": {
"department": {"type": "string"},
"date_range": {"type": "string"},
"doc_type": {"type": "string"}
}
},
"top_k": {"type": "integer", "default": 5}
},
"required": ["query"]
}
}
}]
14.3 Structured Outputs with Pydantic
from pydantic import BaseModel
from openai import OpenAI
class EntityExtraction(BaseModel):
entities: list[dict] # name, type, confidence
relationships: list[dict] # source, target, relation
summary: str
response = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[...],
response_format=EntityExtraction
)
Section 14 — Interview Q&A
Q: When would you use JSON mode vs. function calling vs. Pydantic structured outputs? A: JSON mode is the lightest-weight option — it guarantees syntactically valid JSON but doesn’t enforce a specific schema, so it’s suitable for simple extraction tasks where you’ll validate loosely downstream. Function calling is the right choice when the LLM needs to decide whether and which action to take from a set of available tools — the schema describes an invocation contract, not just a data shape. Pydantic-backed structured outputs (or equivalent schema-constrained decoding) are what I use for production data-extraction pipelines where downstream systems require a guaranteed, strongly-typed schema — e.g., extracting entities into a schema that will be inserted directly into a database or knowledge graph, where any schema drift would break downstream consumers.