Agent Inspector: Building a Black-Box Recorder for AI Agents
A deep dive into a different repo component, serverless AWS platform that answers the one question every team shipping AI agents eventually gets asked: “what did it actually do, and can you prove it?”
The question every agent eventually has to answer :
Every AI agent demo looks great until someone in a room asks: “Why did it do that?”
Not “why did the LLM say that” — that’s a prompting question. I mean the operational question: which tool did it call, which of three candidate routes did it pick, what confidence did it have, what was the exact input it reasoned over, and — six months later, when a customer disputes a decision — can you show an audit trail that hasn’t been quietly edited since?
Most teams answer this with a mix of `print()` statements, LLM provider logs, and whatever their observability vendor captures for latency and cost. That’s fine for debugging. It’s not fine for governance. Logs can be overwritten. Traces expire. Nothing chains one decision to the next in a way you could hand to a compliance auditor and say “here, verify it yourself.”
So I built Agent Inspector — not a logging library, a governance and audit platform. It captures every meaningful decision an agent makes as a structured, hash-chained event, ships it out of the agent’s own AWS account with zero infrastructure burden on the team running the agent, and projects it into a purpose-built data store that two very different audiences — automated partner systems and human auditors — can query independently.
What Agent Inspector actually is
For this decision, what did the agent see, what did it choose, why, and can I prove the record wasn’t tampered with afterward?
It does that in three moves:
1. Instrument — a lightweight Python SDK drops into any agent (LangChain, Bedrock, LlamaIndex, or a bare LLM loop). It turns “the agent picked route X over Y” into a structured, hash-chained `DecisionEvent` and writes it to S3. The only infrastructure requirement in the agent’s own AWS account is a bucket and a write role.
2. Ingest — a serverless pipeline in a central AWS account validates, links, and projects those raw events into a DynamoDB data model built for two very different access patterns: “show me this trace end-to-end” and “show me every violation for this team this week.”
3. Serve — two independent read surfaces sit on top of the same data: a governed REST API for machine-to-machine / partner consumption, and a dashboard API + React SPA for human investigators.
It’s deliberately built as five independent git repositories (plus a reference agent), each its own deployable unit (mostly AWS SAM), so a platform team can version, deploy, and reason about ingestion, storage, and the two read paths on entirely separate release cadences.
Why this needed to exist (the significance bit)
A few things became clear once agents started making real decisions instead of answering chat prompts:
- Observability tools answer “what happened,” not “what was decided.” APM traces tell you a Lambda ran for 340ms. They don’t tell you an agent considered `billing`, `technical_support`, and `general`, picked `billing` at 0.91 confidence, and why.
- Trust requires tamper-evidence, not just storage. A log line sitting in CloudWatch can be edited by anyone with write access to CloudWatch. An audit record needs a way to prove it wasn’t altered after the fact — that’s a hashing and chaining problem, not a storage problem.
- Governance and product engineering shouldn’t share a blast radius. The team running the agent shouldn’t need to provision anything beyond an S3 bucket. The team running the audit platform shouldn’t need write access into a customer’s account. That single constraint — the SDK needs zero infrastructure inside the agent’s own account beyond a bucket — shaped almost every other design decision downstream.
- Auditors and automation systems want different things from the same data. A compliance reviewer wants a browser, a trace timeline, and a “click here to see everything about this run.” A partner system wants a stable, IAM-authenticated REST contract it can poll. Building one API to serve both usually means building an API that serves neither well.
High-level design

The end-to-end flow, step by step
1. Instrument: An engineering team calls `sdk.configure(…)` once at process start, then `sdk.decision(…)` at each meaningful decision point — a tool call, a routing choice, a retrieval selection, a final answer.
2. Capture & hash: Each call builds a canonical `DecisionEvent`, computes a SHA-256 hash over it, chained to the previous event’s hash within that process, and enqueues it in memory.
3. Buffer & ship: A background thread flushes the queue to S3 every `flush_interval_s` seconds (default 5), or immediately on `sdk.flush()` / process exit. Keys are partitioned by org/env/day/agent.
4. Detect: The central account’s bucket emits an `Object Created` event; an EventBridge rule filtered to the `events/` prefix routes it to SQS.
5. Fan out: An EventBridge Pipe (batch size 1, fire-and-forget) starts one Step Functions execution per message.
6. Validate, link, project: The state machine reads the object, validates it, and per record: writes an operational span, upserts the trace summary, and conditionally writes decision/violation records.
7. Finalize: The object moves to a `processed/` or `failed/` prefix in the same bucket — a permanent audit trail of what was ingested and how it resolved.
8. Serve: Two independent read paths sit on the same DynamoDB tables: a governed REST API for machines, a dashboard API + SPA for humans.
Now let’s go through each piece with the actual code.
The shared contract: one schema every agent speaks
Every
DecisionEvent — whether it came from a LangChain agent, a bare Bedrock loop, or something that hasn't been built yet — is validated against the same JSON Schema ( schema.json , draft 2020-12). That's not an implementation detail; it's the thing that makes "any framework" in the opening claim true rather than aspirational. A LangChain integration and a raw boto3 + Bedrock loop produce byte-for-byte the same ten top-level sections — identity , temporal , model , context , input , reasoning , tool_calls , decision_points , output , governance — because both go through the same create_decision_event() call, not because two teams happened to agree on a convention.Two things about how the schema is shaped are deliberate:
- Every section is closed, with one escape hatch. Each section sets
additionalProperties: false— you can't bolt an arbitrary field ontoidentityorgovernance— but every section also carries anadditional_fieldsmap, gated by its own sub-schema: keys must be namespaced (prefix.key), andsystem,governance, andagent_inspectorare reserved prefixes no caller can write into (RESERVED_PREFIXESin_schema.py). That's how a framework-specific detail — a LangChain run ID, say — rides along without turning into a schema fork every time a new integration wants to record something the core schema didn't anticipate.
-
schema_versionis the forward-compat lever, not decoration. Every event carries it ("1.0"today, fromAgentConfig.schema_version), so a consumer reading events written by different SDK versions can branch on shape instead of guessing.
Worth flagging plainly, in the same spirit as the other gaps in this post: the Lambda named
ReadAndValidateFunction — the first step in the ingestion state machine — doesn't actually validate incoming records against schema.json today. Reading its source, "validate" currently means "parse the S3 event notification envelope and unwrap the record(s) inside it," not "check the record conforms to the DecisionEvent schema."The schema is real, it's enforced by construction on the write side (
create_decision_event can't produce a non-conforming event), but nothing on the read side currently rejects a malformed or hand-crafted event that skipped the SDK entirely. That's a closable gap — wire a jsonschema validation call into that Lambda against the existing schema.json — not a design flaw, but it's not there yet.Component 1:`agent-inspector-sdk`: the only thing that runs in the customer’s process
This is the one component that lives inside someone else’s agent. Its only production dependency is `boto3`, and its entire public surface is three functions: `configure()`, `decision()`, `flush()`.

Configuring it is a one-time call, usually at process start:
import agent_inspector_sdk as sdk
sdk.configure(
s3_bucket="my-org-audit-bucket",
org_id="org-demo",
team_id="platform",
agent_id="langgraph-support-agent",
env="prod",
compliance_mode="best_effort", # or "strict"
flush_interval_s=5,
)Recording a decision is one call at each point where the agent chooses between options:
span_id = sdk.decision(
action="classify_request",
options_considered=["billing", "technical_support", "general"],
selected_option="billing",
selection_reason="Detected billing-related keywords in the request.",
confidence=0.91,
metadata={
"audit_trace_id": trace_id,
"prompt": classification_prompt,
"model_name": "anthropic.claude-...",
"model_provider": "aws_bedrock",
},
)That’s the entire integration cost. No agent-side infrastructure, no schema to hand-roll, no separate audit database to stand up.
What happens under the hood is the interesting part. Every event is hash-chained to the one before it, within the same SDK process:
def decision(action: str, *, ..., parent_span_id: str | None = None) -> str:
with _last_event_hash_lock:
prev_hash = _last_event_hash
span_id = str(uuid.uuid4())
event = create_decision_event(
config=_config_obj,
action=action,
span_id=span_id,
decision_seq=_next_decision_seq(),
...,
prev_event_hash_sha256=prev_hash,
)
with _last_event_hash_lock:
_last_event_hash = event.governance.event_hash_sha256
_flush.enqueue(event.to_dict())
return span_idAnd the hash itself is a canonical SHA-256 over the whole event, deliberately excluding the `governance` section (which holds the hash and the pointer to the previous one — you can’t include a field in its own hash):
def compute_event_hash(event_dict: dict[str, Any]) -> str:
payload = {k: v for k, v in event_dict.items() if k != "governance"}
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()Sorted keys and compact separators matter here — canonical JSON serialization is what makes the hash reproducible by anyone re-verifying the event later, not just the process that wrote it.
There’s a second detail worth calling out: large payloads don’t get inlined. Prompts and conversation histories over 4KB get swapped for a pointer and a hash of the original content instead of being embedded in the event:
def _inline_or_pointer(content, label):
if content is None:
return None, None, None
raw = content.encode("utf-8")
if len(raw) <= INLINE_THRESHOLD_BYTES: # 4096
return content, None, None
content_hash = hashlib.sha256(raw).hexdigest()
pointer = f"{label}://{uuid.uuid4()}"
return None, pointer, content_hash
Worth being honest about: the SDK reserves this shape but doesn’t yet persist the oversized content anywhere retrievable. Today, content above the threshold simply isn’t carried in the event — the pointer and hash exist so a future large-object store can be wired in without a schema change. I’d rather ship the shape now and be upfront about the gap than pretend it’s finished.
The flush engine is what makes `sdk.decision()` non-blocking. Events land in a bounded in-memory queue; a daemon thread drains it on a timer:
- `best_effort` mode: if S3 is unreachable, failed writes fall back to a local temp-file buffer and retry next cycle. The agent never stalls because the audit pipe is down.
- `strict` mode: an unrecoverable write raises `InspectorWriteError` and halts the flush loop entirely — appropriate when “silently dropped audit event” is the worse failure mode than “agent call fails loudly.”
That’s a per-deployment policy choice, not a code fork — exactly the kind of knob a governance platform should expose rather than hard-code.
Component 2 — `agent-inspector-ingestion-pipeline`: the ETL that turns raw JSON into a queryable graph
This is where an S3 object becomes rows in five DynamoDB tables. The trigger chain is standard serverless plumbing — EventBridge rule on `Object Created`, filtered to the `events/` prefix, into an SQS queue with a 5-retry redrive to a DLQ that’s kept for 14 days as a forensic record of failed ingests — but the interesting part is the state machine itself:

{
"StartAt": "WrapInput",
"States": {
"ReadAndValidate": { "Type": "Task", "Next": "ForEachRecord" },
"ForEachRecord": {
"Type": "Map",
"ItemsPath": "$.read.records",
"MaxConcurrency": 10,
"Iterator": {
"StartAt": "RouteRecord",
"States": {
"RouteRecord": { "Type": "Task", "Next": "WriteAgentInvocation" },
"WriteAgentInvocation": { "Type": "Task", "Next": "UpsertAuditTrace" },
"UpsertAuditTrace": { "Type": "Task", "Next": "HasDecision" },
"HasDecision": {
"Type": "Choice",
"Choices": [{ "Variable": "$.route.should_write_decision", "BooleanEquals": true, "Next": "WriteDecisionEvent" }],
"Default": "HasViolation"
},
"HasViolation": {
"Type": "Choice",
"Choices": [{ "Variable": "$.route.should_write_violation", "BooleanEquals": true, "Next": "WriteGovernanceViolation" }],
"Default": "RecordDone"
}
}
},
"Next": "FinalizeFile"
}
}
}
One S3 object can contain multiple events; the `Map` state fans each record out through its own write path with bounded concurrency, and two `Choice` states decide — per record — whether it also deserves a row in `DecisionEventTable` or `GovernanceViolationTable`. `RouteRecordFunction` is the thing making that call, and it’s intentionally small:
def handler(event, context):
record = event.get("record", {})
return {
"should_write_decision": bool(record.get("decision_points")),
"should_write_violation": bool(record.get("violations")),
}The write functions each carry a `DynamoDBCrudPolicy` scoped to exactly one table — least-privilege at the function level, not the stack level. And the invocation writer uses a conditional put to make ingestion idempotent, which matters because SQS gives you at-least-once delivery, not exactly-once:
table.put_item(
Item={
"pk": f"{org_id}#{audit_trace_id}",
"sk": span_id,
"audit_trace_id": audit_trace_id,
"event_time_utc": event_time_utc,
"decision_seq": decision_seq,
"agent_id": agent_id,
...
},
ConditionExpression="attribute_not_exists(pk) AND attribute_not_exists(sk)",
)If the same S3 object gets processed twice — a retried Lambda, a redelivered SQS message — the second write fails the condition and is dropped rather than silently duplicating a span.
Where the current code is honestly incomplete, and I’d rather flag this than gloss over it: the design docs describe a “TraceLinker” step that buffers a child span in `PendingParentTable` when its parent hasn’t arrived yet, and resolves it once the parent shows up. `PendingParentTable` exists in the data layer, complete with a TTL for auto-expiry — but no Lambda in the pipeline currently has IAM access to it or logic to use it. `RouteRecordFunction` today is a two-flag router, not the parent-linking step the design intends. It’s provisioned but not wired — a good example of infrastructure shipping slightly ahead of the code that uses it.
Component 3— agent-inspector-data-store : the schema everything else agrees on
Pure DynamoDB, on-demand billing, no compute — this stack’s only job is to define the shape of the data and export table names via CloudFormation for the ingestion pipeline to import.

- AgentInvocationTable: One item per span — the primary operational store (
TraceIndex,TransactionIndex,AgentTimeIndex,SessionIndex,OrgTeamIndex)
- AuditTraceTable: One trace-level summary per agent trigger — the “single-click full flow” entry point (
TransactionTraceIndex,StatusIndex)
- DecisionEventTable: Explicit decision points, for decision analytics (TraceDecisionIndex,
OrgEnvDecisionIndex)
- GovernanceViolationTable: Timeouts, broken hash chains, schema breaks (
ViolationTypeIndex,TeamViolationIndex)
- PendingParentTable: Out-of-order span buffer (TTL-based, not PITR) ( provisioned, not yet wired into the pipeline)
Four of the five tables have Point-in-Time Recovery on;
PendingParentTable deliberately doesn't, because it's a transient buffer that self-expires via TTL, not a system of record.Component 4— agent-inspector-external-api : the governed door for machines
Built for automation and partner systems that need programmatic, cross-account access — think a compliance system polling for new violations, or a partner platform pulling traces tied to a transaction ID.
The auth model is deliberately heavier than the dashboard’s:
AWS_IAM (SigV4-signed requests) and an API key. Callers assume a named IAM role ( AllowedCallerRoleArn ) to sign requests, then also present a key tied to a usage plan — two independent gates, appropriate for cross-account machine access where you want both an identity and a throttle-able contract.Four Lambdas, each scoped to one table:
- AuditTraceFunction: This function points to Dynamodb table AuditTraceTable and exposed endpoint
:AuditTraceTableGET /audit-traces/{trace_id}
-
InvocationFunctionAgentInvocationTableGET /invocations/by-trace/{trace_id}
-
DecisionFunctionDecisionEventTableGET /decisions/by-org-env/{org_id}/{env}
-
ViolationFunctionGovernanceViolationTableGET /violations/by-team/{org_id}/{team_id}
Every route here is
GET -only in practice, though the IAM policy attached is DynamoDBCrudPolicy — broader than the read-only reality. That's a known tightening item (the dashboard backend, built later, gets this right — more below), and it's the kind of thing worth calling out in a blog post rather than only in a backlog: shipping the looser policy first and narrowing it is a normal sequence, but it's still a gap until it's closed.Component 5— agent-inspector-dashboard : the human-facing "one click, full trace" view
This is two genuinely independent deployable units — a FastAPI backend and a React SPA — that deliberately do not call
agent-inspector-external-api . They share nothing but a convention: the same DynamoDB schema.Why not just point the browser at the external API? Two reasons. First, that API requires SigV4 on top of an API key — a browser SPA can’t produce that without standing up a Cognito Identity Pool, which is a lot of infrastructure just to render a page. Second, and more importantly, the external API has no single endpoint that returns a joined “trace + spans + decisions + violations” view — a UI built on it would need several round trips stitched together client-side, on every page load, for every investigator.
So the dashboard backend does the stitching server-side, in one endpoint. This is the piece I’d point to as the clearest expression of “build for the reader, not the writer” in the whole platform:
@router.get("/traces/{trace_id}/flow")
def get_trace_flow(trace_id: str, org_id: str = Query(...)):
trace = db.audit_trace_table().get_item(Key={"pk": org_id, "sk": trace_id}).get("Item")
if not trace:
raise HTTPException(status_code=404, detail="Audit trace not found")
spans = db.query_all_pages(
db.agent_invocation_table(),
index_name="TraceIndex",
key_condition=Key("audit_trace_id").eq(trace_id),
scan_forward=True,
)
decisions = db.query_all_pages(
db.decision_event_table(),
index_name="TraceDecisionIndex",
key_condition=Key("audit_trace_id").eq(trace_id),
scan_forward=True,
)
violations = db.query_all_pages(
db.governance_violation_table(),
key_condition=Key("pk").eq(org_id),
filter_expression=Attr("audit_trace_id").eq(trace_id),
)
span_ids = {s.get("span_id") for s in spans if s.get("span_id")}
span_links = [
{
"span_id": s.get("span_id"),
"parent_span_id": s.get("parent_span_id"),
"is_root": not s.get("parent_span_id"),
"parent_missing": bool(s.get("parent_span_id")) and s.get("parent_span_id") not in span_ids,
}
for s in spans
]
return {"trace": trace, "spans": spans, "decisions": decisions, "violations": violations, "span_links": span_links}
One call, four table reads, and the chain-integrity check (
parent_missing ) computed server-side so the UI never has to re-derive "is this trace's span tree actually intact?" on the client. That last part matters more than it looks: it means the browser never has to know how hash-chain integrity is verified — it just renders a flag.A few other deliberate choices here:
- The Lambda uses
DynamoDBReadPolicy— genuinely read-only, unlike the external API's CRUD grant.
- The whole FastAPI app runs behind one Lambda via Mangum, handling
ANY /{proxy+}— one function, not one-per-route, because a human-facing dashboard's traffic pattern doesn't benefit from per-route isolation the way a partner-facing API might.
- If a
RawEventBucketNameis supplied at deploy time, the backend also gets scopedS3ReadPolicyto serve a raw-event endpoint — for when an investigator needs the full canonical JSON, not just the DynamoDB projection.
- The React SPA fetches its API base URL and API key from a
config.jsonloaded at runtime, so the exact same build artifact ships to dev, staging, and prod — no rebuild, just swap the config file.
Test the Concept: agent-inspector-sample-agent : proving the SDK against a real agent
This repo is deliberately not part of the deployed platform — it’s a reference LangGraph + Bedrock agent kept in its own repo “so the integration stays realistic and reusable,” rather than a toy example bolted onto the SDK’s own tests.
It’s a two-node support-triage graph: classify the request, then draft a response. Each node wraps its work in exactly one
sdk.decision() call:def _classify_request(state: AgentState) -> AgentState:
outcome = _bedrock_route(state["user_input"]) if state.get("use_bedrock") else _mock_route(state["user_input"])
span_id = sdk.decision(
action="classify_request",
options_considered=ROUTES,
selected_option=outcome["route"],
selection_reason=outcome["rationale"],
confidence=outcome["confidence"],
metadata={
"audit_trace_id": state["trace_id"],
"prompt": CLASSIFICATION_PROMPT.format(user_input=state["user_input"]),
"model_name": os.getenv("BEDROCK_MODEL_ID", "mock-router"),
"model_provider": "aws_bedrock" if state.get("use_bedrock") else "mock",
},
)
state.update({"route": outcome["route"], "classify_span_id": span_id, ...})
return stateThe second node (
_draft_response ) passes parent_span_id=state["classify_span_id"] — that's how a two-step decision becomes a linked trace instead of two unrelated events. It runs two ways: a fast local mock (no AWS calls, sub-second dev loop) and a Bedrock-backed mode ( ChatBedrockConverse ) for the real thing, plus AgentCore packaging to actually deploy the demo agent to Bedrock AgentCore. The point of keeping this as a full, deployable agent rather than a unit-test fixture is that it forces the SDK's public API to survive contact with a real framework's control flow, not just a mock harness.
Security, governance, and what “tamper-evident” actually means here
Worth being precise about a term I’ve used loosely so far: this system provides tamper evidence, not tamper prevention. The
event_hash_sha256 on every event, chained via prev_event_hash_sha256 , lets a verifier detect if an event was altered after the fact, or if a link in a chain is missing. It does not stop someone with write access to the tables from altering data — that's what KMS signing (reserved fields, not yet implemented) would add. And today the chain is per-process, not a single global ledger: if an agent runtime restarts, a new chain starts. Being upfront about that distinction is, I think, more useful to a reader than implying stronger guarantees than the system currently makes.The rest of the governance surface:
- Compliance modes (
best_effort/strict) are a per-deployment policy choice atconfigure()time, not a code fork — the same SDK build serves both a "never block the agent" deployment and a "never silently lose an audit event" deployment.
- Auth differs by consumer, by design — SigV4 + API key for cross-account machine consumers, API key alone for the browser-facing dashboard, because forcing every consumer through the same auth model would have meant either weakening the partner API or forcing Cognito onto a simple SPA.
- Forensic retention over deletion — the ingestion DLQ keeps failed messages for 14 days without auto-purge, and
FinalizeFilemoves (never deletes) every processed and failed raw event intoprocessed//failed/prefixes in the same bucket. Nothing in the ingestion path destroys evidence, even evidence of its own failures.
Closing thoughts:
The constraint I’d defend hardest is the simplest one: the SDK needs nothing beyond an S3 bucket in the customer’s account. The five-repo split, the two independent read APIs, and the dashboard’s server-side “one click, full flow” endpoint all follow from taking that seriously — and from asking separately what an auditor needs versus what an automation system needs, instead of building one API for both.
The gaps I’ve flagged along the way — the unwired
PendingParentTable , the CRUD policy that should be read-only, the payload pointer without real storage — aren't surprises. They're what you get when infrastructure lands a step ahead of the code that uses it. Worth naming plainly: this system gives you tamper-evidence, not tamper-prevention, and a hash chain that's per-process, not a global ledger.If you’re instrumenting agents today with little more than log lines, the gap between that and a hash-chained, queryable audit trail is smaller than it looks: three SDK functions, a Step Functions workflow, and a data model built around “give me this trace” as the first-class query. The rest is refinement.
GitHub Repo
Thanks for reading this far — if you made it through the code and not just the diagrams, I appreciate it. Questions, pushback, or “you got this wrong” are all welcome.
Thank you for your time and attention.
“Keep Learning.. Keep growing..”
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article