Skip to content
Blog

Agentic Data Cleaning Pipeline: Validator, Formatter, and Enricher

Build a three-stage Google ADK data cleaning pipeline with a deterministic validator, an LLM formatter, and a tool-equipped enricher sharing session state.

Published on • November 30, 2026

AI Assistant

Every data team has been there: the “simple ETL job” that ships a customer file with "$1,240.00 " in one row, "n/a" in the next, San Francisco CA in one column and SF, California in another — and a downstream model that quietly degrades for three weeks before anyone notices. The traditional fix is ten thousand lines of regex. The tempting fix is “let the LLM clean the whole file.” The first is unmaintainable, the second is slow, expensive, and occasionally invents values that were never in the source.

The workable middle is an agentic pipeline with strict stage discipline: a deterministic Validator that quarantines structurally broken rows, an LLM Formatter that normalizes only genuinely ambiguous human-written text, and a tool-equipped Enricher that adds facts it can look up — each stage connected by session state in Google Agent Development Kit (ADK).


1. Three Questions, Three Stages

Clean data answers three distinct questions, and conflating them is why ad-hoc scripts rot:

  1. Is it valid? (schema, types, required fields, ranges) → rules, not a model.
  2. Is it readable? (messy human strings → canonical form) → model judgment on ambiguous cases.
  3. Is it complete? (missing city, unmapped category, bare domain) → model + lookup tools.
   raw rows ──► ┌───────────┐   clean-ish  ┌───────────┐   canonical ┌───────────┐
                │ VALIDATOR│ ────────────► │ FORMATTER │ ─────────► │ ENRICHER  │
                │ (Python) │              │  (LLM)    │             │ (LLM+tool)│
                └─────┬─────┘              └───────────┘             └─────┬─────┘
                      │ quarantine                                         │
                      ▼                                                    ▼
                 state["quarantine"]                                 state["clean_rows"]

In ADK each stage is a sub-agent, and the pipeline is a SequentialAgent — execution order is fixed by the framework, never by the model, because a formatter running before validation would happily “fix” a structurally invalid file.


2. The Contract: Rows and State Keys

Everything passes through session.state. Fix the shape first; every downstream instruction can then reference stable keys.

from typing import Any, AsyncGenerator, Dict, List
import re

from google.adk.agents import Agent, BaseAgent, SequentialAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events import Event, EventActions
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from pydantic import BaseModel, Field


class Row(BaseModel):
    row_id: str
    name: str = ""
    amount: str = ""
    city: str = ""
    email: str = ""
    category: str = ""


class CleaningBatch(BaseModel):
    rows: List[Row] = Field(description="Raw rows to clean.")


# Seed keys written before the run; stages read and refine them.
#   state["raw_batch"]     -> CleaningBatch as loaded from CSV/CRM export
#   state["quarantine"]    -> rows rejected by the validator
#   state["candidates"]    -> rows eligible for LLM formatting
#   state["clean_rows"]    -> final output

Two conventions keep this maintainable: each stage reads only the key of the stage before it, and rejected data is never deleted — it moves to quarantine so the run is reversible and auditable.


3. Stage 1 — The Deterministic Validator

The validator subclasses BaseAgent and does what code does best: hard checks, zero tokens, reproducible outcomes.

class ValidatorAgent(BaseAgent):
    """Structural validation. Splits rows into candidates vs. quarantine."""

    async def _run_async_impl(
        self, ctx: InvocationContext
    ) -> AsyncGenerator[Event, None]:
        batch: CleaningBatch = ctx.session.state["raw_batch"]
        candidates, quarantine = [], []

        for row in batch.rows:
            errors = []
            if not row.row_id.strip():
                errors.append("missing_row_id")
            if row.email and not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", row.email):
                errors.append("bad_email")
            if row.amount and not re.fullmatch(r"\$?-?[\d,.]+", row.amount.strip()):
                errors.append("bad_amount")
            if not any([row.name.strip(), row.email.strip(), row.city.strip()]):
                errors.append("empty_record")

            if errors:
                quarantine.append({"row_id": row.row_id, "errors": errors,
                                    "raw": row.model_dump()})
            else:
                candidates.append(row.model_dump())

        ctx.session.state["quarantine"] = quarantine
        ctx.session.state["candidates"] = candidates
        ctx.session.state["stats_validated"] = len(batch.rows)

        # state writes are surfaced on the emitted event as actions.state_delta
        yield Event(author=self.name, actions=EventActions())

The validator’s job ends at classification. It does not attempt repair — a malformed amount could be $1,240.00 (repairable) or a spreadsheet error value (poison), and only a downstream stage with more context should make that call.


4. Stage 2 — The Formatter (LLM, on a Leash)

The formatter is an LlmAgent constrained to the candidate rows. Its instruction states the rule that matters most in data work: normalize, never invent.

formatter = Agent(
    name="formatter",
    model="gemini-3.8-flash",
    description="Normalizes messy human-written strings into canonical formats.",
    instruction="""
    You receive candidate rows from state key 'candidates'.
    Normalize ONLY what is present:
    - amount -> plain decimal string ("$1,240.00 " -> "1240.00")
    - city   -> "City, ST" Title Case ("sf ca" -> "San Francisco, CA")
    - name   -> trimmed, consistent capitalization
    Rules:
    - NEVER invent values. If a field is unambiguous garbage, leave it untouched.
    - NEVER drop or add rows. Output a JSON array with every input row_id,
      each row carrying keys: row_id, name, amount, city, email, category.
    - Preserve unknown fields verbatim.
    """,
    output_key="formatted_rows",
)

Deliberately absent: any instruction to fill gaps. Gap-filling is the enricher’s job, and keeping the stages’ responsibilities disjoint is what lets you debug a bad output — you can tell from session.state whether the normalization step or the enrichment step went wrong.

Note also the JSON-array output contract. Since downstream stages are code, ask for machine-readable output explicitly and give the parser a tolerance path (an unparseable response should fall back to the pre-format candidates rather than crash the run).


5. Stage 3 — The Enricher (LLM + Tools)

Enrichment means adding facts the source lacked, which is exactly what tools are for: a lookup returns ground truth, the model decides how to attach it.

def lookup_category(product_line: str) -> Dict[str, Any]:
    """Maps free-text product lines to the internal taxonomy."""
    catalog = {
        "espresso machines": "kitchen_appliances",
        "coffee beans": "grocery",
        "travel mug": "drinkware",
        "barista course": "services",
    }
    return {"category": catalog.get(product_line.strip().lower(), "uncategorized")}


def geocode_city(city: str) -> Dict[str, Any]:
    """Resolves a city string to canonical city/state/coordinates."""
    db = {"san francisco, ca": ("San Francisco", "CA", 37.77, -122.42),
          "austin, tx": ("Austin", "TX", 30.26, -97.74)}
    key = city.strip().lower()
    if key in db:
        c, s, lat, lng = db[key]
        return {"status": "ok", "city": c, "state": s, "lat": lat, "lng": lng}
    return {"status": "not_found"}


enricher = Agent(
    name="enricher",
    model="gemini-3.8-flash",
    description="Adds canonical categories, locations, and derived fields to formatted rows.",
    instruction="""
    Read 'formatted_rows' from session state. For each row:
    - If 'category' is missing or 'uncategorized', call lookup_category with the
      product/name text.
    - If 'city' is present, call geocode_city; keep returned city/state only
      when status is "ok", otherwise leave the row's city unchanged.
    - Add derived key 'record_status': "enriched" when at least one new fact
      was attached, else "clean".
    Output the full JSON array. Never drop rows. Never guess a value a tool
    did not return.
    """,
    tools=[lookup_category, geocode_city],
    output_key="clean_rows",
)

The instruction “never guess a value a tool did not return” is the guardrail that keeps enrichment honest: tools provide the facts, the model only arranges them.


6. Assembling and Running the Pipeline

pipeline = SequentialAgent(
    name="data_cleaning_pipeline",
    sub_agents=[ValidatorAgent(name="validator"), formatter, enricher],
)


async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=pipeline, app_name="cleaner",
                    session_service=session_service)
    session = await session_service.get_or_create(
        app_name="cleaner", user_id="etl_job_118"
    )
    session.state["raw_batch"] = CleaningBatch(rows=[
        Row(row_id="r1", name="  jordan lee", amount="$1,240.00 ",
            city="sf ca", email="jordan@example.com",
            category="espresso machines"),
        Row(row_id="r2", amount="N/A", city="", email="broken@@mail"),
        Row(row_id="r3", name="Sam Ortiz", amount="89.5",
            city="austin, tx", email="sam@example.com",
            category="travel mug"),
    ])

    async for event in runner.run_async(
        session=session, message="Clean today's inbound lead export."
    ):
        if event.actions and event.actions.state_delta:
            delta = event.actions.state_delta
            for key in ("quarantine", "stats_validated", "formatted_rows", "clean_rows"):
                if key in delta:
                    print(f"state[{key}] updated")

    print("quarantined:", len(session.state.get("quarantine", [])))
    print("clean rows :", len(session.state.get("clean_rows", [])))


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Row r2 — no usable fields, malformed email — never reaches the LLM at all; the validator quarantines it, and you pay nothing for it. Rows r1 and r3 get normalized and enriched. The event stream shows one state_delta per stage, which doubles as your pipeline’s run log: stage boundaries, row counts, and failures are all reconstructible from session.events.

Scaling to real batches

The single-batch example extends along two axes that map directly onto ADK primitives:

  • Fan out per file or per shard with a ParallelAgent — branches share session.state, so give each branch distinct keys (candidates_shard_0, …) to avoid write races, then merge.
  • Retries: wrap the enricher in a LoopAgent with max_iterations and escalate from a small custom agent once clean_rows parses as valid JSON — bounded, deterministic, no infinite polishing.

On ADK 2.0, template workflows like SequentialAgent are being superseded by graph-based and dynamic workflows; the stage graph above translates one-to-one (validate → format → enrich, with a quarantine terminal edge), and the validator and other custom BaseAgent stages carry over unchanged.


7. Checklist

  1. Validate with code, not prompts — schema, types, and ranges belong in a custom BaseAgent with unit tests.
  2. Never destroy dirty data; move it to a quarantine state key with machine-readable reasons.
  3. Give the formatter one mandate: normalize what exists, invent nothing, emit JSON.
  4. Give the enricher tools and forbid guessing — every added fact must trace to a tool result.
  5. Pass data between stages via session.state / output_key, one key per stage boundary.
  6. Log event.actions.state_delta — it is your audit trail and your live progress indicator.
  7. Bound every loop (max_iterations) and cap the rows sent to any model, so a bad file cannot turn into an unbounded bill.

With those seven habits, “clean the data” stops being a heroic regex sprint and becomes a pipeline you can rerun, audit, and trust.

Sources