Lab 3 of 8 · Prompts and structured output
Turn support emails into checked JSON
Classify customer emails into a fixed set of categories and return validated JSON, with a retry when the model gets the format wrong.
- Time
- 45–60 minutes
- Cost
- A fraction of a cent of API credit.
What you learn
Apps need data they can use, not paragraphs. Clear instructions, examples and a schema turn a model's answer into JSON your code can check.
- Writing clear, specific instructions
- Giving examples (few-shot prompting)
- Asking for JSON and validating it with Pydantic
- Retrying when the output is not valid
In the AI era: Never trust model output blindly. Validating it against a schema is the difference between a demo and a product.
Before you start
Finish lab 2.
Step by step
1 Describe the shape you want
Pydantic checks that the data has exactly these fields and values.
Literallimits the category to four allowed words.import json from typing import Literal from pydantic import BaseModel, Field, ValidationError from llm import MODEL, client, text_of class Ticket(BaseModel): category: Literal["refund", "shipping", "account", "other"] urgent: bool summary: str = Field(max_length=120) INSTRUCTIONS = """Classify the customer email. Reply with only a JSON object with these keys: - "category": one of "refund", "shipping", "account", "other" - "urgent": true if the customer is blocked or very upset, otherwise false - "summary": one short sentence Example: Email: My parcel says delivered but it is not here. JSON: {"category": "shipping", "urgent": true, "summary": "Parcel marked delivered but missing."}""" def triage(email: str, attempts: int = 2) -> Ticket: messages = [{"role": "user", "content": f"{INSTRUCTIONS}\n\nEmail: {email}\nJSON:"}] for _ in range(attempts): message = client().messages.create(model=MODEL, max_tokens=200, messages=messages) raw = text_of(message).strip() try: return Ticket.model_validate(json.loads(raw)) except (json.JSONDecodeError, ValidationError) as error: # Show the model its mistake and ask again. messages += [ {"role": "assistant", "content": raw}, {"role": "user", "content": f"That was not valid: {error}. Reply with only the JSON."}, ] raise ValueError("The model did not return valid JSON") if __name__ == "__main__": emails = [ "I was charged twice for my order and need my money back today!", "How do I change the email address on my account?", "Do you sell decaf?", ] for email in emails: print(triage(email).model_dump_json())2 Run it
Each email becomes a small JSON object your app could store or route.
python triage.pyYou should see:Three JSON lines, with categories
refund,accountandother, and only the first marked urgent.3 Test the validation without calling the model
Your checks should be tested on their own. These tests prove a bad category is rejected.
import pytest from pydantic import ValidationError from triage import Ticket def test_accepts_a_valid_ticket() -> None: ticket = Ticket.model_validate({"category": "refund", "urgent": True, "summary": "Charged twice."}) assert ticket.category == "refund" def test_rejects_an_unknown_category() -> None: with pytest.raises(ValidationError): Ticket.model_validate({"category": "pizza", "urgent": False, "summary": "?"})4 Run the tests
The empty
__init__.pyandconftest.pyfiles let pytest import your modules from the project folder.touch tests/__init__.py conftest.py python -m pytest -qYou should see:2 passed.5 Commit and push
You now have your first tested AI feature.
git add triage.py tests conftest.py git commit -m "Classify emails into validated JSON" git push
You are done when
Each email becomes valid JSON with an allowed category.
Two tests pass without any API call.
You can explain why the retry shows the model its own mistake.
We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.