Agent state with typeddict

The AgentState is the heart of our system. It's a TypedDict that carries all information between agents - the question, generated SQL, results, errors, and more.

State flows through agents

How AgentState groups fields by purpose

text2sql_agent.py
python
from typing import TypedDict

class AgentState(TypedDict):
    """State of the agent workflow"""
    # Core fields for the main data pipeline
    question: str        # Input from user
    sql_query: str       # Generated SQL
    sql_reason: str      # Why this SQL was chosen
    query_result: str    # Database results
    final_answer: str    # Human-readable answer

The core fields follow the main data flow: question in, SQL generated, results fetched, answer out. Every agent reads from and writes to this shared state.

Beyond the core data pipeline, AgentState also tracks errors for retry logic, visualization preferences, and guardrail decisions. These fields let agents coordinate without talking to each other directly.

The iteration field counts how many times the SQL Agent has retried after an error. Without it, a bad query could loop forever. We cap retries at 3, so the system always terminates even if the LLM cannot fix the SQL.

text2sql_agent.py
python
    # (continued from AgentState)

    # Error tracking and retries
    error: str
    iteration: int       # For retry tracking (max 3)

    # Visualization
    needs_graph: bool
    graph_type: str      # bar, line, pie, scatter
    graph_json: str      # Plotly figure as JSON
    graph_reason: str    # Why a graph was/wasn't needed

    # Guardrails
    is_in_scope: bool
    guardrails_reason: str

Tracking fields enable error recovery (iteration count), automatic chart generation (graph fields), and input filtering (guardrails fields).

Fill in the blanks: Complete the agentstate typeddict

Loading practice…

Each agent reads from and writes to this state. For example, the SQL Agent reads 'question' and writes 'sql_query'. The Executor reads 'sql_query' and writes 'query_result' or 'error'.

Flashcards: Flashcards

Loading practice…

Checkpoint: Agent state knowledge check

Loading practice…

The AgentState gives every agent a shared, typed data structure to read from and write to. Next, we will define each agent's personality and system prompt.