Audit logging for a deployed AI agent
An agent that can issue refunds or change records owes the same answers a person does: who acted, on whose behalf, with what, and why. Santati's AI agents pack supplies the actions for the agent's own lifecycle, and this guide shows the code that emits them.
The outcome: runs, tool calls, refusals, approvals and the stated reasoning on a trail you can
query and verify. The pack covers the agent's lifecycle, runs, tools, approvals, guardrails and
knowledge sources; ordinary business actions stay ordinary events, with the agent as the actor.
Before you start: a trail named agents and a write key in
SANTATI_API_KEY (Quickstart), Python 3.10+, and pip install santati.
What to record
| Moment | Action | Notes |
|---|---|---|
| A run starts | agent.run.started | trigger is user, schedule, webhook, agent or api |
| A run ends | agent.run.completed, agent.run.failed, agent.run.canceled | On a failure, say why in reason |
| The agent calls a tool | agent.tool.called | result is success or error |
| A tool call is blocked | agent.tool.denied | By policy or a missing permission |
| A person must approve | agent.approval.requested, then agent.approval.granted, agent.approval.denied or agent.approval.expired | The answer's actor is the person |
| A guardrail fires | agent.guardrail.triggered | guardrail and outcome are required |
| A run hits a budget | agent.budget.exceeded | budget is tokens, cost, steps or time |
| The agent hands a run off | agent.run.handed_off | handoff_to is human or agent |
| The agent's setup changes | agent.updated, agent.deployed, agent.tool_access_changed | Emitted by whoever changed it |
When the agent performs an ordinary business action, emit the ordinary event with the agent as
actor: the pack covers the agent's own lifecycle, and
agents acting for someone is a convention, not an action
of the pack. The pack also covers knowledge sources (knowledge_source.connected,
knowledge_source.synced, knowledge_source.removed) and stored memory
(agent.memory.deleted). AI agents lists every action's fields.
Who acted: the agent and the person behind it
{
"actor": {
"type": "agent",
"id": "agt_support",
"name": "Support assistant",
"metadata": {"on_behalf_of_type": "user", "on_behalf_of_id": "usr_123"}
},
"targets": [
{"type": "agent", "id": "agt_support", "name": "Support assistant"},
{"type": "agent_run", "id": "run_8f2c41d09b7e"},
{"type": "tool", "id": "tool_search_invoices", "name": "search_invoices"}
]
}
actor.type is agent. on_behalf_of_type and on_behalf_of_id name the person or service
the agent acts for, and they go together: the standard schemas refuse one without the other with
schema_validation_failed. The targets identify the agent, the run and the tool, so each can be
filtered on. actor.metadata is subject to the same limits as event metadata: a flat
string-to-string map.
Record runs and tool calls
import logging
import time
import uuid
from contextlib import contextmanager
import santati
logger = logging.getLogger(__name__)
def _elapsed_ms(started: float) -> str:
return str(int((time.monotonic() - started) * 1000))
class AgentAudit:
"""Records one run of one agent with the AI agents pack's actions."""
def __init__(self, client, *, organization_id, agent_id, agent_name, user_id):
self.client = client
self.organization_id = organization_id
self.run_id = f"run_{uuid.uuid4().hex}"
self.actor = {
"type": "agent",
"id": agent_id,
"name": agent_name,
"metadata": {"on_behalf_of_type": "user", "on_behalf_of_id": user_id},
}
self.targets = [
{"type": "agent", "id": agent_id, "name": agent_name},
{"type": "agent_run", "id": self.run_id},
]
def emit(self, event, *, targets=(), metadata=None, data=None):
try:
self.client.events.emit(
event,
organization_id=self.organization_id,
actor=self.actor,
targets=[*self.targets, *targets],
metadata=metadata,
data=data,
)
except santati.SantatiError:
logger.warning("audit event %s not recorded", event, exc_info=True)
@contextmanager
def run(self, *, trigger, model, conversation_id):
started = time.monotonic()
self.emit(
"agent.run.started",
metadata={
"trigger": trigger,
"gen_ai.request.model": model,
"gen_ai.conversation.id": conversation_id,
},
)
try:
yield self
except Exception as error:
self.emit(
"agent.run.failed",
metadata={
"duration_ms": _elapsed_ms(started),
"error.type": type(error).__name__,
"reason": str(error)[:500] or type(error).__name__,
},
)
raise
self.emit("agent.run.completed", metadata={"duration_ms": _elapsed_ms(started)})
def tool(self, name, fn, arguments, *, call_id, reasoning=None):
started = time.monotonic()
tool = {"type": "tool", "id": f"tool_{name}", "name": name}
metadata = {
"gen_ai.tool.name": name,
"gen_ai.tool.call.id": call_id,
"gen_ai.tool.type": "function",
}
data = {"arguments": arguments}
if reasoning:
data["reasoning"] = reasoning
try:
result = fn(**arguments)
except Exception as error:
self.emit(
"agent.tool.called",
targets=[tool],
metadata={**metadata, "result": "error", "duration_ms": _elapsed_ms(started)},
data={**data, "error": f"{type(error).__name__}: {error}"},
)
raise
self.emit(
"agent.tool.called",
targets=[tool],
metadata={**metadata, "result": "success", "duration_ms": _elapsed_ms(started)},
data=data,
)
return result
def tool_denied(self, name, *, reason):
self.emit(
"agent.tool.denied",
targets=[{"type": "tool", "id": f"tool_{name}", "name": name}],
metadata={"gen_ai.tool.name": name, "reason": reason},
)
import os
import santati
from agent_audit import AgentAudit
client = santati.Santati(os.environ["SANTATI_API_KEY"], trail="agents")
audit = AgentAudit(
client,
organization_id=tenant.id,
agent_id="agt_support",
agent_name="Support assistant",
user_id=user.id,
)
with audit.run(trigger="user", model="gpt-4o", conversation_id=conversation.id):
for call in next_tool_calls(): # your agent loop
if call.name not in ALLOWED_TOOLS:
audit.tool_denied(call.name, reason="not in this agent's tool list")
continue
audit.tool(
call.name,
TOOLS[call.name],
call.arguments,
call_id=call.id,
reasoning=call.rationale,
)
Every metadata value is a string, hence the string durations. trigger is required on
agent.run.started; reason is optional metadata on every action in the pack, and on a failed
run it is where you say why. The keys beginning gen_ai. are
OpenTelemetry attribute names (the catalog lists them),
so audit events and traces join on them. result is success or error, and error.type is
an OpenTelemetry attribute too. A blocked call is
agent.tool.denied with a reason, not a failed agent.tool.called. A failed emit is logged,
never raised into the agent.
Record the reasoning
Put the rationale the model gave for an action in data.reasoning on the event it explains, as
agent_audit.py does for tool calls. Metadata values stop at 500 characters and exist for filtering;
data is stored verbatim and no schema constrains it. Record the stated rationale or a summary,
not the whole transcript, and keep gen_ai.conversation.id in metadata to find the transcript
in your own store.
Reasoning and tool arguments can hold personal data and secrets. A team administrator adds
rules under Audit Log → Redaction that mask, hash or drop a path such as data.reasoning or
data.arguments.card_number before the event is stored.
Approvals, guardrails and budgets
approval = {"type": "approval", "id": f"apr_{uuid.uuid4().hex}"}
audit.emit(
"agent.approval.requested",
targets=[approval],
metadata={"gen_ai.tool.name": "refund_invoice", "reason": "refund above 100.00"},
data={"arguments": {"invoice_id": "inv_555", "amount_cents": 42000}},
)
# Later, in the request handler where a person answers. The actor is that person, not the agent.
client.events.emit(
"agent.approval.granted",
organization_id=tenant.id,
actor={"type": "user", "id": approver.id, "name": approver.name},
targets=[*audit.targets, approval],
)
audit.emit("agent.guardrail.triggered", metadata={"guardrail": "prompt_injection", "outcome": "blocked"})
audit.emit("agent.budget.exceeded", metadata={"budget": "steps", "limit": "25"})
The agent emits the request; the answer is emitted where the person answers, with that person as
the actor. An unanswered request ends as agent.approval.expired, and a refusal as
agent.approval.denied; the request and its answer target the same approval, so they link.
guardrail names what fired (prompt_injection, pii, content); outcome is
blocked, redacted or flagged; budget is tokens, cost, steps or time.
Shortcut: framework integrations
The Python SDK ships callbacks that record tool calls for LangChain and LangGraph
(SantatiCallbackHandler), the OpenAI Agents SDK (SantatiRunHooks), Pydantic AI
(SantatiCapability) and the Claude Agent SDK (santati_hooks):
pip install "santati[langchain]"
from santati.integrations.langchain import SantatiCallbackHandler
handler = SantatiCallbackHandler(client, organization_id=tenant.id)
agent.invoke({"messages": messages}, config={"callbacks": [handler]})
The integrations record agent.tool_call.succeeded and agent.tool_call.failed with a system
actor, not the pack's agent.tool.called. A team that has event definitions must define those
two actions, or pass succeeded_event= and failed_event= naming actions it has defined;
otherwise the events are refused with unknown_action and the integration only logs a warning.
See the framework integrations README
for per-framework caveats, and Python SDK for the client. The adapters fix
organization_id and actor per instance, so a multi-tenant app builds one per request, and
they use a fixed idempotency key per event, so a dispatcher's retry replays instead of
double-recording.
Enforce the shape
Team administrators open Actions & Schemas → Add standard events and tick "AI agents", or
call POST /api/v0/standard-events/install/ with {"packs": ["agents"]} and a manage key
(reference).
On a team with no definitions this turns enforcement on, and every action outside the catalog
is then refused with unknown_action (Event definitions).
Installed actions also enforce their target types: an extra type is refused with
schema_validation_failed on targets.<i>.type. Installing a pack copies each schema into
your catalog as its own published v1; from then on it is yours, and you edit it like any custom
schema.
Read a run back
for event in client.events.iterate(target_type="agent_run", target_id=audit.run_id):
print(event.created_at, event.event)
Events come back newest first; iterate pages through every result with limit defaulting to
100 and capped at 1000. The same filter vocabulary works from curl:
curl -G https://api.santati.io/api/v0/events/ \
-H "Authorization: Api-Key $SANTATI_API_KEY" \
--data-urlencode "trail=agents" \
--data-urlencode "event=agent.tool.denied" \
--data-urlencode "organization_id=org_acme" \
--data-urlencode "created_after=2026-11-01"
Next steps
MCP servers for the server an agent's tools run on, Chain verification to make the trail tamper-evident, and AI agents for every action's fields.