Skip to main content

Implementation

Session state, tool definitions, and loop prevention


Session state​

A ReAct agent without explicit state management will re-run validation on every turn β€” expensive and unsafe in a multi-turn correction session. Five fields cover everything the agent needs:

FieldTypePurpose
file_refstringPath or ID of the uploaded file
validation_scopelist of stringsColumns the user asked to check
findingsdict keyed by columnPer-column error list from validate_sheet
correction_statusdict keyed by columnOne of: pending, previewed, confirmed, applied
exportedboolWhether the corrected file has been returned

correction_status per column is the key one β€” it's what prevents re-applying a correction that already ran and gives the HITL gate its memory.

State machine​

Each column moves through states in one direction only.

Where state lives​

State is injected as a YAML block at the end of each system prompt and updated after each tool call. This is in-context memory β€” the agent's working memory for the current session, held in the active prompt rather than an external store. β†’ Memory Management β€” in-context type

file_ref: uploads/vendor_q2.csv
validation_scope: [product_code, sku_variant]
findings:
product_code: 47 mismatches
sku_variant: 12 nulls
correction_status:
product_code: confirmed
sku_variant: pending
exported: false
tip

For multi-session use, serialise this block to a JSON record keyed by session ID. The schema stays the same β€” only the persistence layer changes from in-context to external (episodic) memory.


Tool ordering​

Not all tools are interchangeable. Some have hard dependencies; others can run in parallel.

ConstraintRule
parse_sheet firstAll other tools depend on the parsed file
validate_sheet βˆ₯ lookup_reference_dataIndependent β€” agent emits both as a single parallel tool call to halve validation latency
preview_correction before apply_correctionsHard requirement β€” no skipping
apply_corrections only after confirmationHITL gate β€” enforced by prompt + status check
danger

The agent must never call apply_corrections for a column unless correction_status[column] == "confirmed". Enforce this in two places: the system prompt (instruction) and the state check (mechanism). The prompt alone is not enough.

Handling ambiguous scope β€” if the user says "check the product data" without specifying columns, call parse_sheet first, surface the column list, and confirm scope before calling validate_sheet. Calling on all columns by default produces noisy, wasteful responses.


Tool definitions​

parse_sheet​

Parses an uploaded file into a structured format the agent can reason about. Call once per session immediately after upload.

ParameterTypeDescription
Infile_refstringPath or ID of the uploaded file
Outcolumnslist of stringsColumn names in the file
row_countintNumber of data rows
samplelist of dictsFirst 5 rows

validate_sheet​

Runs validation rules against specified columns. Can run in parallel with lookup_reference_data.

ParameterTypeDescription
Infile_refstringParsed file reference
columnslist of stringsColumns to validate
rulesdictOptional rule overrides (e.g. skip DRAFT rows)
Outfindingsdict{column: [{row, value, error_type}]}
summarydict{column: error_count} β€” for plain-English summaries

lookup_reference_data​

Queries BigQuery for valid reference values. Can run in parallel with validate_sheet.

ParameterTypeDescription
Incolumnslist of stringsColumns needing reference data
Outreferencedict{column: [valid_values]}
table_namesdictWhich BQ table each column was looked up from

preview_correction​

Computes what apply_corrections would change β€” without writing anything. One column at a time.

ParameterTypeDescription
Infile_refstringParsed file reference
columnstringSingle column to preview
findingslistError list for this column
referencelistValid values for this column
Outdifflist of dicts{row, old_value, new_value}
change_countintRows that would change
unchanged_countintRows that couldn't be auto-corrected

apply_corrections​

Writes corrections to the file. Irreversible within the session. Only callable when correction_status[column] == "confirmed".

ParameterTypeDescription
Infile_refstringParsed file reference
columnstringColumn to correct
difflist of dictsThe exact diff from preview_correction
Outupdated_file_refstringReference to the corrected file
applied_countintRows actually changed

Schema design notes​

Keep summaries separate from details. validate_sheet returns both findings (full list) and summary (counts). The agent uses summary for user responses and passes findings to downstream tools β€” don't force the agent to compute counts from a raw list.

One column at a time for write-path tools. preview_correction and apply_corrections take a single column. This keeps the HITL checkpoint unambiguous β€” each approval covers exactly one column β€” and the correction_status state machine simple. β†’ HITL

Pass diffs by value. apply_corrections receives the full diff, not a "apply the preview" instruction. This guarantees exactly what was shown to the user is what gets written β€” an action-gating guardrail at the tool interface level. β†’ Guardrails β€” action gating


Loop prevention​

Loop patternCauseFix
Re-validating validated columnsAgent can't tell what's already been checkedCheck findings in state before calling validate_sheet β€” use cached result if present
Re-previewing after rejectionAgent calls preview_correction again with same inputsOn rejection, set status back to pending and ask what to change before re-previewing
Applying without confirmationAgent treats "yes" (to a summary question) as write confirmationSystem prompt must specify: confirmation only counts after a diff has been shown in the current turn

The "re-validating" loop is a memory management problem β€” caching findings in session state is exactly what in-context memory is for. Without it, the agent has no way to know validation already ran and will repeat expensive tool calls. β†’ Memory Management

warning

apply_corrections is not idempotent β€” calling it twice on the same column will attempt to re-correct an already-corrected file. Once correction_status[column] == "applied", block further calls at the state layer regardless of user input. If a user asks to redo an applied correction, offer to start a new session with the corrected file as input.