Task 6 · 8 tasks

Structured output

Make the agent return a typed Pydantic DepartmentReport instead of a wall of text.

20 minMedium
Alice’s ask

The “Messy Handwriting” problem

Alice asked for a department report and got three paragraphs of prose. Her dashboard needs JSON with a known shape. Time to give the agent a contract.

You

Build it

  1. Return a typed report

    Challenge

    Define a DepartmentReport with a title, a summary, a list of departments and an integer total_employees, and make the agent return one.

    Work in phase1/starter/t6_structured_output.py (look for TODO; an unfinished one prints [starter] TODO …) and run it with uv run bootcamp.py phase1 t6 --starter. The reference solution is phase1/t6_structured_output.py; uv run bootcamp.py phase1 t6 runs it.

    Hint 1

    Strands can validate the final answer against a Pydantic model. See Strands: structured output.

    Hint 2

    Pass structured_output_model=DepartmentReport when you call the agent and read result.structured_output. Field(description=...) tells the model what each field means.

    Solution
    phase1/t6_structured_output.py
    class DepartmentReport(BaseModel):
        """Department report for DataStream Corp."""
    
        title: str = Field(description="Report title")
        summary: str = Field(description="Executive summary")
        departments: list[dict] = Field(description="Department data, one entry per department")
        total_employees: int = Field(description="Total employee count")
    
    
    report = agent(prompt, structured_output_model=DepartmentReport).structured_output
    print(report.model_dump_json(indent=2))
  2. Run it

    terminal · your starter file
    uv run bootcamp.py phase1 t6 --starter "Generate a department report for DataStream Corp"
    terminal · reference solution
    uv run bootcamp.py phase1 t6 "Generate a department report for DataStream Corp"
  3. Experiments

    • Replace list[dict] with a proper Department model (name, headcount, budget). Is the output more consistent?
    • Add a field the data can't support, like customer_satisfaction. What does the model put there? Would Optional plus a clear description help?

Check your work

Phase 1 has no automated test: you check it by running the task and looking for the result below.

The script prints a JSON object with title, summary, departments and an integer total_employees close to the real count.

Under the hood

Strands turns the Pydantic model into a tool schema and asks the model to call it as its final step, then validates the arguments with Pydantic. If validation fails, the error is fed back so the model can retry. You get a real Python object, not text you have to parse.