Executor agent

The Executor Agent runs the generated SQL against our SQLite database. It handles multiple queries and formats results as JSON for the Analysis Agent.

SQL execution states

How the executor agent handles SQL execution with error recovery

text2sql_agent.py
python
def execute_sql(state: AgentState) -> AgentState:
    """Execute the generated SQL query"""
    sql_query = state["sql_query"]

    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()

        # Split multiple SQL statements
        sql_statements = [stmt.strip() for stmt in sql_query.split(';') if stmt.strip()]
        all_results = []

        for i, statement in enumerate(sql_statements):
            cursor.execute(statement)
            results = cursor.fetchall()

            if results:
                column_names = [desc[0] for desc in cursor.description]
                formatted_results = [
                    dict(zip(column_names, row))
                    for row in results[:100]  # Limit to 100 rows
                ]
                all_results.extend(formatted_results)

        conn.close()

        state["query_result"] = json.dumps(all_results, indent=2) if all_results else "No results found."
        state["error"] = ""

    except Exception as e:
        state["error"] = f"SQL Execution Error: {str(e)}"
        state["query_result"] = ""

    return state

The Executor handles SQL execution and error capture.

Ordering exercise: Order the executor steps

Loading practice…

Quiz: Quiz

Loading practice…

The Executor safely runs SQL and captures results or errors. Next, we will build the Error Recovery Agent that fixes broken queries automatically.