C.W.K.
Stream
Lesson 09 of 10 · published

Pydantic / Zod / Schemas as Contracts

~14 min · outputs, schema, contracts

Level 0Apprentice
0 XP0/100 lessons0/14 achievements
0/120 XP to next level120 XP to go0% complete

One schema, many consumers

The output schema is consumed by: the prompt (in the JSON Schema export), the validator (Pydantic / Zod), the downstream code (TypeScript / Python types), the test suite (sample fixtures), and the docs (whatever describes the API). One source of truth, many derived artifacts.

How to wire it

  • Author in Pydantic (Python) or Zod (TypeScript).
  • Generate JSON Schema via model_json_schema() or zodToJsonSchema.
  • Inject the JSON Schema into the prompt as a structured-output spec.
  • Validate the response with the same Pydantic / Zod model.
  • Type the consumer with the same type.

The win

When you change the schema, every dependent layer breaks at compile time. You see what needs to change. Without a single source of truth, schema changes silently desync — prompt asks for old shape, code expects new shape, runtime crashes.

Code

Pydantic → JSON Schema → prompt·python
from pydantic import BaseModel, Field
from typing import Literal

class Verdict(BaseModel):
    verdict: Literal["approve", "reject", "hold"]
    reason_codes: list[Literal["low_confidence", "missing_evidence", "policy_block", "ok"]] = Field(min_length=1, max_length=3)

schema = Verdict.model_json_schema()
response_format = {"type": "json_schema", "json_schema": {"name": "verdict", "strict": True, "schema": schema}}

resp = client.chat.completions.create(model="gpt-5.5", messages=msgs, response_format=response_format)
parsed = Verdict.model_validate_json(resp.choices[0].message.content)

External links

Exercise

Take one prompt where the inline output spec is hand-maintained. Replace it with a Pydantic / Zod schema and a generator. Verify the consumer types and the prompt schema are now derived from one source.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.