DEV Community

chasewong
chasewong

Posted on Edited on Originally published at aisiliconpulse.com

How to Persist AI Agent State in Python: A Two-Turn Example

Single-turn AI agent demos rarely fail. Turn 2 is where state quietly breaks.

When a structured output schema requires every field to be present and allows unmentioned fields to be null, follow-up turns often emit null for facts established on Turn 1. Calling state.update(model_json) blindly silently wipes earlier fields.

Below is the complete, self-contained replay.py script (python replay.py, Python 3.10+ stdlib only, zero API keys required). It uses simulated structured JSON payloads for a fictitious construction work order (WO-2026-418) so anyone can reproduce the bug offline, verify a real Turn 1 disk write → fresh disk reload → Turn 2 merge, and enforce an application-defined CLEARABLE_FIELDS allowlist.

Complete Single-File replay.py (Single-Writer JSON Solution)

Scope note: state_version here is a simple version counter (it does not perform cross-process compare-and-swap locking), and os.replace() ensures clean file replacement during normal execution; the tests verify a clean disk round-trip rather than power-loss recovery or multi-writer races.

from __future__ import annotations
import copy, json, os, tempfile
from pathlib import Path
from typing import Any

CLEARABLE_FIELDS = frozenset({"site_zone", "crew_lead", "volume_cy", "target_date", "safety_signoff"})
ALLOWED_FIELDS = frozenset({"work_order_id"}) | CLEARABLE_FIELDS

TURN_1_MODEL_JSON = {
    "work_order_id": "WO-2026-418",
    "site_zone": "Building B - Level 3",
    "crew_lead": "Marcus Chen",
    "volume_cy": 45,
    "target_date": "2026-12-10",
    "safety_signoff": None,
    "clear_fields": [],
}

TURN_2_MODEL_JSON = {
    "work_order_id": "WO-2026-418",
    "site_zone": None,
    "crew_lead": None,
    "volume_cy": None,
    "target_date": "2026-12-12",
    "safety_signoff": "Approved - Elena Vasquez",
    "clear_fields": [],
}

def naive_merge(state: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
    merged = copy.deepcopy(state)
    merged.update({k: v for k, v in patch.items() if k != "clear_fields"})
    return merged

def guarded_merge(state: dict[str, Any], patch: dict[str, Any], turn_label: str) -> tuple[dict[str, Any], list[str]]:
    merged = copy.deepcopy(state)
    changed, rejected_clears = [], []
    for key, value in patch.items():
        if key == "clear_fields" or key not in ALLOWED_FIELDS:
            continue
        if value is not None and merged.get(key) != value:
            merged[key] = value
            changed.append(key)
    for field in patch.get("clear_fields") or []:
        if field in CLEARABLE_FIELDS:
            if merged.get(field) is not None:
                merged[field] = None
                changed.append(f"{field}:CLEARED")
        else:
            rejected_clears.append(field)
    merged["state_version"] = int(merged.get("state_version", 0)) + 1
    merged["audit_log"] = list(merged.get("audit_log") or []) + [{"turn": turn_label, "version": merged["state_version"], "updated": changed}]
    return merged, rejected_clears

def atomic_save_json(target_path: Path, state: dict[str, Any]) -> None:
    fd, tmp_name = tempfile.mkstemp(prefix=".state_", suffix=".tmp", dir=str(target_path.parent))
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(state, handle, indent=2)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp_name, target_path)
    except Exception:
        if os.path.exists(tmp_name):
            os.unlink(tmp_name)
        raise

if __name__ == "__main__":
    # 1) Naive merge loses 3 fields
    bad = naive_merge(naive_merge({}, TURN_1_MODEL_JSON), TURN_2_MODEL_JSON)
    assert bad["crew_lead"] is None

    # 2) Turn 1 write -> fresh disk reload -> Turn 2 merge
    path = Path("./wo_2026_418_state.json")
    s1, _ = guarded_merge({}, TURN_1_MODEL_JSON, "turn_1")
    atomic_save_json(path, s1)
    reloaded = json.loads(path.read_text(encoding="utf-8"))
    s2, _ = guarded_merge(reloaded, TURN_2_MODEL_JSON, "turn_2")
    atomic_save_json(path, s2)
    final_state = json.loads(path.read_text(encoding="utf-8"))
    assert final_state["crew_lead"] == "Marcus Chen" and final_state["state_version"] == 2

    # 3) Clear-only patch & protected-key rejection
    s3a, rej_a = guarded_merge(final_state, {"clear_fields": ["crew_lead"]}, "turn_3a")
    assert s3a["crew_lead"] is None and not rej_a
    s3b, rej_b = guarded_merge(s3a, {"clear_fields": ["work_order_id"]}, "turn_3b")
    assert s3b["work_order_id"] == "WO-2026-418" and rej_b == ["work_order_id"]
    print("All replay checks passed.")
Enter fullscreen mode Exit fullscreen mode

Resuming Conversation Context After Restart (case + last_question)

State fields alone aren't enough if a user answers "Approved this morning" after a process restart. Store {"case": ..., "last_question": {"field": ..., "text": ...}} together on disk, validate that last_question targets a still-null field, and replay last_question["text"] as an assistant message on the next boot before sending the user's new reply.

Originally published at Silicon & AI Pulse, with full formatted test output, Anthropic shadow-traffic context, and the backend scaling matrix (JSON vs. SQLite/Postgres optimistic locking).


AI Content Disclaimer: Updated December 2, 2026. The concrete work-order scenario and JSON responses in replay.py are deterministic, offline-reproducible simulated payloads using Python 3.10+ standard libraries without live cloud LLM API calls. Provided for engineering and educational reference only.

Top comments (0)