Loading Python for AI Engineering...
Generating deterministic JSON Schemas from Pydantic models (model_json_schema) and enforcing constrained decoding or tool-calling modes in modern LLMs (OpenAI JSON Mode / Anthropic Tool Use).
{
"query": "vector index latency",
"confidence": 0.94,
"is_urgent": true
}“Structured extraction is handing the model a pre-cut wooden puzzle frame: the model can only place tokens that physically fit into the designated shapes.”
Asking the LLM to output valid JSON in the system prompt without passing the formal schema to the API runtime, resulting in markdown code-fence syntax errors (```json).
from pydantic import BaseModel
import json
class EntityExtraction(BaseModel):
entities: list[str]
is_urgent: bool
# Pass schema directly to model tool definitions:
schema = EntityExtraction.model_json_schema()
print(json.dumps(schema, indent=2))
# Model output string -> validated instance:
raw_llm_json = '{"entities": ["Server", "DB"], "is_urgent": true}'
parsed = EntityExtraction.model_validate_json(raw_llm_json)