AI Engineering: Agents and Applications › AI Agents › Day 292

Hands-on lab — Day 292: Agent Frameworks and When to Use Them

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/state_graph.py

Test

bash tests/run_tests.sh

File tree

examples/state_graph.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/state_graph.py
tests/run_tests.sh
tests/test_state_graph.py
troubleshooting.md

Lab README

Day 292 Lab: Agent Frameworks and When to Use Them

Lesson

Purpose

Construct a Directed Cyclic State Graph engine with nodes, conditional edges, state reducers, persistent checkpointing, and human-in-the-loop approval gates.

Learning objectives

  • Model iterative agent workflows as Directed Cyclic State Graphs.
  • Implement state reducers for clean dictionary updates.
  • Build durable state checkpoints and pause-and-resume human gates.
  • Verify cyclic retry transitions and maximum step bounds.

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/state_graph.py: Starter implementation skeleton
  • examples/state_graph.py: Verified reference implementation
  • tests/test_state_graph.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/state_graph.py

What the commands do

  • Executes agent runtime algorithms and logs state transitions to stdout.

Expected output

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Core state transitions and algorithm logic
  • Error observation handling and recovery
  • Edge cases and bounds enforcement

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Verify Python version is >= 3.10 and environment variables are set.

Security notes

Runs completely offline on local CPU without network calls or API keys.

Extension exercises

Implement async execution or enhanced caching strategies.

Day number: 292 of 365

Expected output

FIELDS.md

# Measured Values
- `nodes_count`: 4
- `checkpoints_saved`: 4

examples-run.txt


measured-values.txt

nodes_count=4
checkpoints_saved=4

run-output.txt


starter-run.txt

An untouched starter fails the suite. Captured from a real run:


self = <examples.state_graph.StateGraphEngine object at 0x10af3de00>
name = 'infinite_loop'
func = <function test_max_steps_guard.<locals>.<lambda> at 0x10af694e0>

    def add_node(self, name: str, func: Callable[[Dict[str, Any]], Dict[str, Any]]):
>       raise NotImplementedError('TASK 1: implement add_node.')
E       NotImplementedError: TASK 1: implement add_node.

examples/state_graph.py:20: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_state_graph.py::test_linear_graph_execution - NotImplemente...
FAILED tests/test_state_graph.py::test_max_steps_guard - NotImplementedError:...
ERROR tests/test_state_graph.py::test_cyclic_retry_and_pause - NotImplemented...
ERROR tests/test_state_graph.py::test_resume_after_approval - NotImplementedE...
========================= 2 failed, 2 errors in 0.04s ==========================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-292-agent-frameworks-and-when-to-use
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 4 items

tests/test_state_graph.py::test_cyclic_retry_and_pause PASSED            [ 25%]
tests/test_state_graph.py::test_resume_after_approval PASSED             [ 50%]
tests/test_state_graph.py::test_linear_graph_execution PASSED            [ 75%]
tests/test_state_graph.py::test_max_steps_guard PASSED                   [100%]

============================== 4 passed in 0.01s ===============================

test-run.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-292-agent-frameworks-and-when-to-use
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 4 items

tests/test_state_graph.py::test_cyclic_retry_and_pause PASSED            [ 25%]
tests/test_state_graph.py::test_resume_after_approval PASSED             [ 50%]
tests/test_state_graph.py::test_linear_graph_execution PASSED            [ 75%]
tests/test_state_graph.py::test_max_steps_guard PASSED                   [100%]

============================== 4 passed in 0.01s ===============================

Source files

examples/state_graph.py (2447 bytes)
from typing import Dict, Any, Callable, List, Optional, Tuple

class StateGraphEngine:
    def __init__(self):
        self.nodes: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {}
        self.edges: Dict[str, str] = {}
        self.conditional_edges: Dict[str, Tuple[Callable[[Dict[str, Any]], str], Dict[str, str]]] = {}
        self.entry_point: Optional[str] = None
        self.checkpoints: List[Dict[str, Any]] = []
        
    def add_node(self, name: str, func: Callable[[Dict[str, Any]], Dict[str, Any]]):
        self.nodes[name] = func
        
    def set_entry_point(self, name: str):
        self.entry_point = name
        
    def add_edge(self, start_node: str, end_node: str):
        self.edges[start_node] = end_node
        
    def add_conditional_edges(self, source_node: str, router_fn: Callable[[Dict[str, Any]], str], route_map: Dict[str, str]):
        self.conditional_edges[source_node] = (router_fn, route_map)
        
    def run(self, initial_state: Dict[str, Any], max_steps: int = 10) -> Dict[str, Any]:
        state = dict(initial_state)
        current_node = self.entry_point
        step = 0
        
        while current_node and current_node != "END":
            step += 1
            if step > max_steps:
                state["error"] = "Max graph execution steps exceeded."
                break
                
            node_fn = self.nodes[current_node]
            update = node_fn(state)
            state.update(update)
            
            # Save checkpoint snapshot
            self.checkpoints.append({
                "step": step,
                "node": current_node,
                "state_snapshot": dict(state)
            })
            
            # Human approval check
            if state.get("requires_human_approval", False) and not state.get("is_approved", False):
                state["status"] = "PAUSED_FOR_HUMAN_APPROVAL"
                state["paused_at_node"] = current_node
                break
                
            # Routing
            if current_node in self.conditional_edges:
                router, rmap = self.conditional_edges[current_node]
                decision = router(state)
                current_node = rmap.get(decision, "END")
            elif current_node in self.edges:
                current_node = self.edges[current_node]
            else:
                current_node = "END"
                
        return state
metadata.yml (398 bytes)
lesson_id: D292
day: 292
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/state_graph.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/state_graph.py (1451 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

from typing import Dict, Any, Callable, List, Optional, Tuple

class StateGraphEngine:

    def __init__(self):
        self.nodes: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {}
        self.edges: Dict[str, str] = {}
        self.conditional_edges: Dict[str, Tuple[Callable[[Dict[str, Any]], str], Dict[str, str]]] = {}
        self.entry_point: Optional[str] = None
        self.checkpoints: List[Dict[str, Any]] = []

    def add_node(self, name: str, func: Callable[[Dict[str, Any]], Dict[str, Any]]):
        raise NotImplementedError('TASK 1: implement add_node.')

    def set_entry_point(self, name: str):
        raise NotImplementedError('TASK 2: implement set_entry_point.')

    def add_edge(self, start_node: str, end_node: str):
        raise NotImplementedError('TASK 3: implement add_edge.')

    def add_conditional_edges(self, source_node: str, router_fn: Callable[[Dict[str, Any]], str], route_map: Dict[str, str]):
        raise NotImplementedError('TASK 4: implement add_conditional_edges.')

    def run(self, initial_state: Dict[str, Any], max_steps: int=10) -> Dict[str, Any]:
        raise NotImplementedError('TASK 5: implement run.')
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_state_graph.py (2649 bytes)
import pytest
from examples.state_graph import StateGraphEngine

def node_planner(state):
    retries = state.get("retries", 0)
    if retries == 0:
        return {"plan": "INVALID_SQL", "retries": 1}
    return {"plan": "SELECT * FROM users;", "retries": retries + 1}

def node_validator(state):
    plan = state.get("plan", "")
    is_valid = plan.startswith("SELECT")
    return {"is_valid": is_valid}

def router_validator(state):
    return "VALID" if state.get("is_valid") else "INVALID"

def node_approval(state):
    return {"requires_human_approval": True}

def node_executor(state):
    return {"status": "EXECUTED_SUCCESSFULLY", "result": [1, 2, 3]}

@pytest.fixture
def workflow():
    g = StateGraphEngine()
    g.add_node("planner", node_planner)
    g.add_node("validator", node_validator)
    g.add_node("approval", node_approval)
    g.add_node("executor", node_executor)
    
    g.set_entry_point("planner")
    g.add_edge("planner", "validator")
    g.add_conditional_edges(
        "validator",
        router_validator,
        {"VALID": "approval", "INVALID": "planner"}
    )
    g.add_edge("approval", "executor")
    g.add_edge("executor", "END")
    return g

def test_cyclic_retry_and_pause(workflow):
    res = workflow.run({"goal": "Query users", "is_approved": False})
    # Should loop once on invalid SQL, then pause at approval gate
    assert res["status"] == "PAUSED_FOR_HUMAN_APPROVAL"
    assert res["is_valid"] is True
    assert res["retries"] == 2
    assert len(workflow.checkpoints) >= 3

def test_resume_after_approval(workflow):
    # First run pauses
    res = workflow.run({"goal": "Query users", "is_approved": False})
    assert res["status"] == "PAUSED_FOR_HUMAN_APPROVAL"
    
    # Resume with approval
    res["is_approved"] = True
    workflow.set_entry_point("executor")
    res_final = workflow.run(res)
    assert res_final["status"] == "EXECUTED_SUCCESSFULLY"
    assert res_final["result"] == [1, 2, 3]

def test_linear_graph_execution():
    g = StateGraphEngine()
    g.add_node("step1", lambda s: {"count": s.get("count", 0) + 1})
    g.add_node("step2", lambda s: {"count": s.get("count", 0) * 10})
    g.set_entry_point("step1")
    g.add_edge("step1", "step2")
    g.add_edge("step2", "END")
    
    res = g.run({"count": 5})
    assert res["count"] == 60
    assert len(g.checkpoints) == 2

def test_max_steps_guard():
    g = StateGraphEngine()
    g.add_node("infinite_loop", lambda s: s)
    g.set_entry_point("infinite_loop")
    g.add_edge("infinite_loop", "infinite_loop")
    
    res = g.run({}, max_steps=4)
    assert "Max graph execution steps exceeded" in res["error"]

Troubleshooting

Troubleshooting - Day 292

  1. Unregistered Node in Route Map: Ensure all router targets exist in self.nodes or equal "END".
  2. Max Steps Exceeded: Check that conditional loop edges have an exit condition.

Security notes

Security Considerations - Day 292

  1. Approval Gates: High-risk operations pause for explicit human confirmation, preventing unauthorized autonomous mutations.
  2. State Isolation: Deep-copying state snapshots ensures that checkpoints remain immutable and tamper-proof.