Skip to content
AgenticAIWiki
  1. Learn
  2. Part 12
  3. 66. Governance and compliance
  4. 66.1

Lesson 66.1 · 1 of 7 · 5 min read · Reviewed 24 Nov 2026

Audit logs for agent reasoning and actions

By the end, you can

  • Explain how an audit log differs from a debug trace.
  • Design an audit record for an agent action, including denied and approved actions.

An agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. that can refund money, change records or send email is acting for your organisation. Sooner or later someone will ask: why did it do that, and who allowed it? A traceTrace: A record of everything that happened during one request or agent run, as a tree of timed steps. (67.1) is built for engineers fixing bugs. An audit logAudit trail: A tamper-resistant record of who did what, when, and with which model and prompt version. is built to answer that question months later, possibly for a regulator or a court.

Trace or audit log?

Debug trace Audit log
Purpose Find slow or broken steps Prove what happened and under what authority
Readers Engineers Security, compliance, auditors, sometimes customers
Content Timings, tokens, prompts, tool results Actor, action, target, policy decision, approver, outcome
Sampling Often sampled Never sampled: every consequential action
Changes Can be deleted or rewritten freely Append-only, tamper-evident
Retention Days or weeks Set by policy, often much longer

Keep them linked: the audit entry carries the trace id, so an investigator can jump from “refund issued” to the full run.

What goes in an audit record

A worked example for one agent action:

{
  "seq": 48211,
  "time": "2026-11-24T10:42:07Z",
  "actor": {"agent": "refund-agent", "version": "prompt v14 + tools v6"},
  "on_behalf_of": {"user": "u_1932", "tenant": "acme"},
  "action": "issue_refund",
  "target": "order_88412",
  "args": {"amount_credits": 450},
  "policy": {"rule": "refunds_over_300_need_approval", "result": "needs_approval"},
  "approval": {"by": "staff_207", "result": "approved"},
  "outcome": "succeeded",
  "trace_id": "4bf92f35...",
  "prev_hash": "9c1e..."
}

Rules of thumb:

  • Log the decision, not just the action. Denied actions and blocked tool calls matter as much as successful ones: they show your guardrailsGuardrail: A control that keeps an AI system within safe and allowed behaviour, such as input checks, tool limits or output filters. worked (chapter 64).
  • Log who approved. If a human approved the step, record who and when.
  • Log the versions of prompt, tools and model (72.1), so behaviour can be tied to a release.
  • Keep secrets and raw personal dataPII: Personally identifiable information: data that can identify a person, such as name, email, address or ID numbers. out. Store ids and references; the trace store, with its shorter retention, holds the text (67.3).

Reasoning: record it, but don’t overtrust it

You can store the agent’s stated plan or rationale next to the action. It helps reviewers. But a model’s explanation is generated text: it may not reflect how the model actually reached the action. The evidence is the record of inputs the agent saw, the policy decision and the action taken. Treat the rationale as a note, not a confession.

Making it tamper-evident

  • Append-only storage: write-once buckets or a table where the application role can insert but not update or delete.
  • Hash chaining: each entry stores a hash of the previous entry. Changing or removing an old entry breaks every hash after it, so tampering shows.
  • Separate access: the agent and its operators can write; only a small audit role can read; nobody can edit.
  • Reliable time: synchronised clocks, and a sequence number so order is clear even if two entries share a timestamp.

Common mistakes

  • Logging only successes, so nobody can see what the agent tried and was stopped from doing.
  • Writing audit entries from the model’s output (“I have refunded the order”) instead of from the tool that actually ran.
  • Keeping the audit log in the same database the agent can modify.
  • SamplingSampling: Choosing the next token from the model’s probability distribution, rather than always taking the most likely one. audit events to save storage.

This lesson is general engineering guidance, not legal advice. What you must record, and for how long, depends on your sector and the laws that apply to you.

Key points

  • Traces help engineers debug; an audit log lets someone later prove who did what, on whose behalf, with what authority and with what result.
  • Record every consequential action, including denials and human approvals, with the inputs and policy decision that led to it.
  • Make the log append-only and tamper-evident, with its own access rules and retention period.
  • A model's written rationale is useful context but not proof of why it acted; the recorded inputs, decision and action are the evidence.
Hands-on labRuns in the Playground

Hash-chain an agent's audit log

Write an audit record for every refund attempt, including denials and approvals, and make tampering visible.

You will have: An audit() function that writes chained records and a verify() that finds the first edited entry.

Steps

  1. Run the starter: only the successful refund is logged.
  2. Write an entry for every attempt, with outcome blocked when the tool did not run.
  3. Record who answered each approval request and what they said.
  4. Add prev_hash and hash to each entry, then write verify() to walk the chain.
  5. Read the last line: edit one old entry and see where the chain breaks.

Done when

  • The log has 4 entries, 2 of them blocked.
  • Both approval requests name staff_207 and the answer given.
  • verify() reports chain OK, and seq 2 after the edit.

Open in the Playground No API key needed.

Starter code (Python)
# Write an audit record for every agent action (allowed, approved or blocked), chain them with hashes,
# and show that editing an old entry is detected.
import copy
import hashlib
import json

log = []


def entry_hash(e):
    body = {k: v for k, v in e.items() if k != "hash"}
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()


def policy(amount):
    if amount > 1000:
        return {"rule": "refunds_over_1000_denied", "result": "denied"}
    if amount > 300:
        return {"rule": "refunds_over_300_need_approval", "result": "needs_approval"}
    return {"rule": "refunds_up_to_300_allowed", "result": "allowed"}


def audit(user, order, amount, decision, approval, outcome, trace_id):
    e = {
        "seq": len(log) + 1,
        "time": f"2026-11-24T10:{len(log):02d}:00Z",
        "actor": {"agent": "refund-agent", "version": "prompt v14 + tools v6"},
        "on_behalf_of": {"user": user, "tenant": "acme"},
        "action": "issue_refund",
        "target": order,
        "args": {"amount_credits": amount},
        "policy": decision,
        "approval": approval,
        "outcome": outcome,
        "trace_id": trace_id,
    }
    # TODO 3: add prev_hash (the previous entry's hash, or "genesis"), then set e["hash"] = entry_hash(e)
    e["hash"] = ""
    log.append(e)


def verify(entries):
    # TODO 4: walk the entries; return the seq of the first one whose prev_hash or hash does not match
    return None


# Tool calls the agent tried: (user, order, amount, approver's answer if asked)
ATTEMPTS = [
    ("u_1932", "order_88410", 120, None),
    ("u_1932", "order_88412", 450, ("staff_207", "approved")),
    ("u_2210", "order_88501", 1500, None),
    ("u_3051", "order_88533", 600, ("staff_207", "rejected")),
]
for i, (user, order, amount, answer) in enumerate(ATTEMPTS):
    decision = policy(amount)
    approval = None
    # TODO 2: when the policy says needs_approval, record who answered and what: {"by": ..., "result": ...}
    ran = decision["result"] == "allowed"
    # TODO 1: audit blocked attempts too. Today only successes are written, so denials leave no trace.
    if ran:
        audit(user, order, amount, decision, approval, "succeeded", f"trace_{i + 1:04d}")

for e in log:
    who = f" by {e['approval']['by']} ({e['approval']['result']})" if e["approval"] else ""
    print(f"seq {e['seq']} {e['target']} {e['args']['amount_credits']:>5} credits -> {e['policy']['result']}{who} / {e['outcome']}")
blocked = sum(e["outcome"] == "blocked" for e in log)
print(f"entries: {len(log)} ({blocked} blocked)")
print("chain OK" if verify(log) is None else f"chain broken at seq {verify(log)}")

tampered = copy.deepcopy(log)
tampered[-1]["args"]["amount_credits"] = 45  # someone quietly edits an old entry
print(f"after editing seq 2: chain broken at seq {verify(tampered)}")
Show a solution
# Write an audit record for every agent action (allowed, approved or blocked), chain them with hashes,
# and show that editing an old entry is detected.
import copy
import hashlib
import json

log = []


def entry_hash(e):
    body = {k: v for k, v in e.items() if k != "hash"}
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()


def policy(amount):
    if amount > 1000:
        return {"rule": "refunds_over_1000_denied", "result": "denied"}
    if amount > 300:
        return {"rule": "refunds_over_300_need_approval", "result": "needs_approval"}
    return {"rule": "refunds_up_to_300_allowed", "result": "allowed"}


def audit(user, order, amount, decision, approval, outcome, trace_id):
    e = {
        "seq": len(log) + 1,
        "time": f"2026-11-24T10:{len(log):02d}:00Z",
        "actor": {"agent": "refund-agent", "version": "prompt v14 + tools v6"},
        "on_behalf_of": {"user": user, "tenant": "acme"},
        "action": "issue_refund",
        "target": order,
        "args": {"amount_credits": amount},
        "policy": decision,
        "approval": approval,
        "outcome": outcome,
        "trace_id": trace_id,
        "prev_hash": log[-1]["hash"] if log else "genesis",
    }
    e["hash"] = entry_hash(e)
    log.append(e)


def verify(entries):
    prev = "genesis"
    for e in entries:
        if e["prev_hash"] != prev or entry_hash(e) != e["hash"]:
            return e["seq"]
        prev = e["hash"]
    return None


# Tool calls the agent tried: (user, order, amount, approver's answer if asked)
ATTEMPTS = [
    ("u_1932", "order_88410", 120, None),
    ("u_1932", "order_88412", 450, ("staff_207", "approved")),
    ("u_2210", "order_88501", 1500, None),
    ("u_3051", "order_88533", 600, ("staff_207", "rejected")),
]
for i, (user, order, amount, answer) in enumerate(ATTEMPTS):
    decision = policy(amount)
    approval = None
    if decision["result"] == "needs_approval":
        approval = {"by": answer[0], "result": answer[1]}
    ran = decision["result"] == "allowed" or (approval and approval["result"] == "approved")
    # The outcome comes from the tool that ran (or did not), never from the model's own text.
    audit(user, order, amount, decision, approval, "succeeded" if ran else "blocked", f"trace_{i + 1:04d}")

for e in log:
    who = f" by {e['approval']['by']} ({e['approval']['result']})" if e["approval"] else ""
    print(f"seq {e['seq']} {e['target']} {e['args']['amount_credits']:>5} credits -> {e['policy']['result']}{who} / {e['outcome']}")
blocked = sum(e["outcome"] == "blocked" for e in log)
print(f"entries: {len(log)} ({blocked} blocked)")
print("chain OK" if verify(log) is None else f"chain broken at seq {verify(log)}")

tampered = copy.deepcopy(log)
tampered[1]["args"]["amount_credits"] = 45  # someone quietly edits an old entry
print(f"after editing seq 2: chain broken at seq {verify(tampered)}")
Quick checkAn auditor asks why an agent was allowed to issue a large refund last month. Which record answers that best?
How sure are you?
Pick an answer and how sure you are