LIVE INTELLIGENCE // SEMICONDUCTOR & AI ECONOMICS TERMINAL
NVIDIA · TSMC · HBM4 · CLOUD GPU · AI AGENTS X/@pinovan Substack
Silicon & AI Pulse
Subscribe
Home AI Chips & Silicon AI Security AI Agents GPU & vLLM Hub Agent Hub About Us Disclaimer Contact
Home / AI Agents / Intelligence Briefing

How to Replay AI Agent Conversations After a Prompt Change

Production AI Agent Engineering • Trilogy Finale (Part 3 of 3)

Editing one line in an agent’s system prompt can quietly shift Turn 2 JSON types, drop unmentioned fields, or clear protected database keys—long after single-turn CI tests pass. Here is how to record JSONL conversation checkpoints, freeze tool side effects, and run deterministic regression diffs offline.

JSONL Checkpoints
Append-Only Multi-Turn State & Tool Ledger
0 Live Side Effects
Stubbed Tool Ledger Blocks Duplicate API Calls
3 Regressions Caught
Null Overwrites, Type Drift & Protected Clears
TL;DR • Deterministic Offline Replay Scope Note

Scope Note: The Python 3.10+ harness below uses only the standard library (zero API keys or live LLM billing) and models deterministic candidate outputs verified through local state-machine equivalence tests—no synthetic cloud latency or accuracy claims are fabricated. Never validate a system-prompt edit solely with fresh single-turn prompts. Capture production multi-turn logs as JSONL checkpoints, freeze external tool outputs inside a Stubbed Tool Ledger, and replay both Prompt v1 (baseline) and Prompt v2 (candidate) through your exact guarded_merge() reducer before promoting changes to production.

Part I: Why Single-Turn CI Passes While Multi-Turn Prompts Quietly Break

In our previous two installments—How to Persist AI Agent State in Python: A Two-Turn Example and What Does an AI Agent Session Cost? Inside AWS AgentCore’s New Cost Visibility—we established two hard production truths: first, strict schema patches can silently overwrite Turn 1 values with null on Turn 2; second, failed multi-turn retries multiply Cost per Successful Task far faster than raw token unit pricing suggests.

That raises the obvious question for every Python team preparing a prompt update, model swap, or JSON schema refinement: how do you know Prompt v2 will not regress multi-turn state transitions before real users hit it?

Traditional unit tests fail here for the exact reason documented in Anthropic’s Rust API migration engineering report—and unpacked in our Anthropic Rust API Migration analysis: synthetic unit assertions can pass at ~98% while hiding edge-case input distributions that break real traffic. For stateful AI agents, the missing piece is deterministic multi-turn conversation replay against archived production traces.

Part II: JSONL Checkpoint Schema & The Stubbed Tool Ledger

Continuing our concrete pour work order example (WO-2026-418 at Building B - Level 3, crew lead Marcus Chen, 45 cubic yards, safety sign-off by Elena Vasquez), replaying a three-turn session safely requires separating two concerns that naive evaluation scripts mix together:

  1. Immutable Conversation Checkpoints (JSONL): Using Python’s standard dataclasses and line-delimited json serialization, each production turn is appended as one self-contained JSONL record storing turn, user_input, tool_call_id, and the exact historical tool payload observed at runtime.
  2. Frozen Side Effects via StubbedToolLedger: If Turn 2 originally sent a crew notification or queried a live permit database, replaying Prompt v2 against live tools would spam field supervisors or read drifted permit statuses. A StubbedToolLedger intercepts tool_call_id lookups and returns a deep copy of the frozen historical output—ensuring zero external mutations and identical inputs across both prompt tracks.
  3. Trace Alignment Across Observability Spans: Aligning checkpoint IDs with structured span concepts—matching OpenTelemetry distributed trace signals—lets platform engineers pull real failed sessions directly out of production logs into a nightly regression suite.
What a Regression Gate Must Catch Beyond Exit Codes

If your guarded_merge() reducer silently heals bad LLM JSON without emitting structured warnings, a broken prompt can pass state assertions while burning tokens and masking schema degradation. Your replay comparator should surface both the protected final_state and every caught violation: ignored null overwrites, type drift (e.g., int changing to str), and blocked attempts to clear immutable primary keys.

Part III: Complete Offline Python Replay Harness (Stdlib Only)

The self-contained prompt_replay_harness.py module below extends our WO-2026-418 reducer with three deterministic replay layers: writing and reloading JSONL checkpoints, blocking live side effects through StubbedToolLedger, and comparing Prompt v1 (clean baseline) against Prompt v2 (a candidate change that introduces three realistic regressions across Turns 2 and 3):

"""Offline deterministic AI Agent conversation replay harness (Python 3.10+, stdlib only)."""

from __future__ import annotations

import copy
import json
import tempfile
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any

CLEARABLE_FIELDS: frozenset[str] = frozenset({
    "site_zone",
    "crew_lead",
    "volume_cy",
    "target_date",
    "safety_signoff",
})
PROTECTED_FIELDS: frozenset[str] = frozenset({"work_order_id"})
ALLOWED_FIELDS: frozenset[str] = PROTECTED_FIELDS | CLEARABLE_FIELDS
EXPECTED_TYPES: dict[str, type] = {
    "work_order_id": str,
    "site_zone": str,
    "crew_lead": str,
    "volume_cy": int,
    "target_date": str,
    "safety_signoff": str,
}


@dataclass(frozen=True)
class CheckpointTurn:
    turn: int
    user_input: str
    tool_call_id: str | None
    stubbed_tool_result: dict[str, Any] | None


class StubbedToolLedger:
    """Freezes historical tool outputs so prompt replays never call live APIs."""

    def __init__(self, checkpoints: list[CheckpointTurn]) -> None:
        self._by_id: dict[str, dict[str, Any]] = {
            cp.tool_call_id: cp.stubbed_tool_result
            for cp in checkpoints
            if cp.tool_call_id and cp.stubbed_tool_result is not None
        }
        self.live_calls_blocked = 0

    def fetch(self, tool_call_id: str | None) -> dict[str, Any] | None:
        if not tool_call_id:
            return None
        self.live_calls_blocked += 1
        return copy.deepcopy(self._by_id.get(tool_call_id))


def guarded_merge(
    state: dict[str, Any], patch: dict[str, Any], turn: int
) -> tuple[dict[str, Any], list[str], list[str]]:
    """Apply validated patch fields and return (next_state, warnings, type_drifts)."""
    merged = copy.deepcopy(state)
    warnings: list[str] = []
    type_drifts: list[str] = []

    for key, value in patch.items():
        if key == "clear_fields" or key not in ALLOWED_FIELDS:
            continue
        if value is None:
            if key in merged and merged[key] is not None:
                warnings.append(f"turn_{turn}:ignored_null_for_existing:{key}")
            continue
        expected_t = EXPECTED_TYPES.get(key)
        if expected_t and not isinstance(value, expected_t):
            type_drifts.append(
                f"turn_{turn}:{key}:expected_{expected_t.__name__}_got_{type(value).__name__}({value!r})"
            )
            continue
        merged[key] = value

    for field in patch.get("clear_fields") or []:
        if field in CLEARABLE_FIELDS:
            merged[field] = None
        else:
            warnings.append(f"turn_{turn}:blocked_protected_clear:{field}")

    merged["state_version"] = int(merged.get("state_version", 0)) + 1
    return merged, warnings, type_drifts

Next, we encode the three production turns for WO-2026-418 into JSONL, stub out both historical tool lookups (lookup_site_WO-2026-418 and notify_crew_t2), and run both prompt tracks side by side:

RECORDED_CHECKPOINTS: list[CheckpointTurn] = [
    CheckpointTurn(
        turn=1,
        user_input="Log concrete pour WO-2026-418 at Building B - Level 3, crew lead Marcus Chen, 45 cy, Dec 10.",
        tool_call_id="lookup_site_WO-2026-418",
        stubbed_tool_result={"permit_status": "OPEN", "inspector": "Elena Vasquez"},
    ),
    CheckpointTurn(
        turn=2,
        user_input="Push target date to Dec 12 and record Elena Vasquez safety signoff.",
        tool_call_id="notify_crew_t2",
        stubbed_tool_result={"slack_sent": True, "stub_note": "FROZEN_DO_NOT_RESEND"},
    ),
    CheckpointTurn(
        turn=3,
        user_input="Crew notes updated: clear pending inspection hold if any, keep work order active.",
        tool_call_id=None,
        stubbed_tool_result=None,
    ),
]

# Candidate Prompt v2 injects 3 common multi-turn regressions across Turns 2 and 3
PROMPT_V2_RESPONSES: dict[int, dict[str, Any]] = {
    1: {
        "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": [],
    },
    2: {
        "work_order_id": "WO-2026-418",
        "crew_lead": None,           # Regression 1: emits null for unmentioned field
        "volume_cy": "45",           # Regression 2: integer drifts into string
        "target_date": "2026-12-12",
        "safety_signoff": "Approved - Elena Vasquez",
        "clear_fields": [],
    },
    3: {
        "work_order_id": "WO-2026-418",
        "clear_fields": ["work_order_id"],  # Regression 3: tries to clear primary key
    },
}

Expected Deterministic Comparison Output

When the replay comparator executes across the three archived checkpoints (verified via deterministic state-machine equivalence checks), both prompt tracks preserve intact final state thanks to guarded_merge()—yet the audit diff flags all three Prompt v2 violations before deployment:

--- Prompt v1 (Baseline) ---
{
  "final_state": {
    "work_order_id": "WO-2026-418",
    "volume_cy": 45,
    "site_zone": "Building B - Level 3",
    "crew_lead": "Marcus Chen",
    "target_date": "2026-12-12",
    "state_version": 3,
    "safety_signoff": "Approved - Elena Vasquez"
  },
  "warnings": [],
  "type_drifts": [],
  "stubbed_tool_calls": 2
}

--- Prompt v2 (Candidate Regression Audit) ---
{
  "final_state": {
    "work_order_id": "WO-2026-418",
    "volume_cy": 45,
    "site_zone": "Building B - Level 3",
    "crew_lead": "Marcus Chen",
    "target_date": "2026-12-12",
    "state_version": 3,
    "safety_signoff": "Approved - Elena Vasquez"
  },
  "warnings": [
    "turn_2:ignored_null_for_existing:crew_lead",
    "turn_3:blocked_protected_clear:work_order_id"
  ],
  "type_drifts": [
    "turn_2:volume_cy:expected_int_got_str('45')"
  ],
  "stubbed_tool_calls": 2
}

Part IV: Three Replay Topologies Compared — Side Effects, Cost & Fidelity

Not every engineering stage requires re-running live LLM inference. Choosing the right replay tier prevents wasted API spend while preserving strict regression coverage across pull requests and release candidates:

Replay Mode Live LLM Calls? Live Tool Side Effects? Best CI / Release Role
1. Frozen Checkpoint + Reducer Replay No (archived JSON responses) No (StubbedToolLedger) Every PR modifying state reducers, parsers, or allowlists
2. Live Prompt v2 + Stubbed Tool Replay Yes (candidate prompt only) No (frozen historical tool outputs) Pre-release evaluation before deploying prompt or model edits
3. Shadow Production Sandbox Yes (mirrored live traffic) Isolated sandbox / read-only mocks Final canary check on high-risk workflows before 100% cutover

Part V: Connecting Prompt Replay Gates to Cost per Successful Task

In production agent fleets, reliability bugs and FinOps overruns are the same failure mode. When a prompt update causes volume_cy to drift from an integer to a string ("45") or tries to wipe work_order_id, validation failures force extra correction turns. Each extra turn re-prefills the entire conversation history—inflating Cost per Successful Task dramatically, as detailed in our AWS AgentCore session cost breakdown.

Running frozen-tool multi-turn replays as a merge gate catches those schema drifts in milliseconds before a single user session loops in production. For teams building out an end-to-end persistence, observability, and replay stack, explore the rest of the series inside our Production AI Agent Engineering Hub.

Frequently Asked Questions: Replaying AI Agent Conversations

Why should I stub tool calls instead of hitting real APIs during prompt replay?

Hitting live tools during replay triggers duplicate external side effects—such as sending Slack alerts or mutating database records—and introduces external data drift that makes Prompt v1 vs. Prompt v2 diffs non-comparable.

Why is JSONL better than a single nested JSON blob for conversation checkpoints?

Line-delimited JSONL lets your runtime append one turn at a time atomically after every step without rewriting earlier records, making crash recovery and selective turn replay clean and debuggable.

What checks should fail a prompt release gate even if final state looks valid?

Always fail release gates on structured reducer warnings and type drifts—including newly emitted null values on existing fields, scalar type changes like integers turning into strings, and blocked attempts to clear protected keys.

Builder Tooling // Affiliate Partner

Packaging your Python AI agent workflow into a commercial SaaS product? Creem.io handles Merchant of Record billing, global VAT/sales tax compliance, subscriptions, and usage-based developer checkout out of the box.

Disclosure: This is an affiliate link. If you sign up through it, Silicon & AI Pulse may earn a commission at no extra cost to you. See our Disclaimer.

AI Content Disclaimer: Prepared December 3, 2026 with AI-assisted engineering synthesis. All Python patterns use standard-library primitives verified against deterministic state-machine equivalence checks; concrete work-order records (WO-2026-418) and candidate Prompt v2 regressions are self-contained engineering test fixtures rather than live production customer logs. For educational and architectural reference only.
Get the Weekly Silicon & AI Briefing
Free institutional recaps on AI hardware, cloud GPUs, and enterprise economics on Substack.
Subscribe Free →

Comments