# How to add audit logging to an existing AI agent: OpenTelemetry vs proxy logs vs provider usage APIs vs your own table

URL: https://www.getpleach.com/blog/add-an-audit-ledger-without-rewriting-your-agent-loop
Published: 2026-10-03 · Updated: 2026-11-03

> You can add LLM call logging to a running agent at four layers: OpenTelemetry GenAI spans, a proxy in front of the provider, the provider's usage API, or a per-call table in your own database. They differ in what each record carries, where it lives, and whether anything runs before the call.

_Drafted by an AI agent, from a research brief, primary sources and the Pleach docs; reviewed by a maintainer before publishing._

_No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. [Package status](https://www.getpleach.com/docs/packages)._

**You can add audit logging to an agent you already run at four layers: OpenTelemetry spans in the process, a proxy in front of the provider, the provider's own usage reports, or a per-call table in your database.** Each layer sees a different slice of the call. Spans and proxy logs need a small code or config change. Provider usage APIs need none, but they report aggregates. A table you write yourself is the only layer that knows your tenant, tool, and turn by default.

Related reading: [hash chain vs append-only table vs OTel traces](/blog/hash-chain-vs-append-only-table-vs-otel-traces) covers tamper evidence, and [attributing subagent cost to the turn](/blog/attributing-subagent-cost-to-the-turn) covers rollups.

## The four layers side by side

These setups aren't like-for-like. A span describes one call inside your process; a provider usage report describes many calls across an organization.

| Property | OpenTelemetry GenAI spans | LLM proxy logs | Provider usage APIs | Your own per-call table |
|---|---|---|---|---|
| Unit of record | One span per operation | One log object per proxied request | Aggregated time bucket | One row per call, as you define it |
| Model and tokens | `gen_ai.request.model`, `gen_ai.usage.input_tokens` / `output_tokens` | `model`, `prompt_tokens`, `completion_tokens`, `response_cost` | Token counts per bucket, grouped by model | Whatever you insert |
| User or tenant | `gen_ai.conversation.id`; tenant via your own attribute | `end_user` and key, team, and user ids in metadata | Project, user, API key (OpenAI); API key, workspace (Anthropic) | Your own tenant and user keys |
| Tool and agent steps | `execute_tool` and `invoke_agent` spans | `mcp_tool_call_metadata` and request metadata | Server-side tool usage (Anthropic) | Your own tool and parent-turn keys |
| Completeness | SDK default samples every root trace | Every request through the proxy | Organization-wide totals | Every call your code writes |
| Where data lives | Your trace backend | Proxy database plus configured callbacks | Provider console and API | Your database |
| Code change | Instrumentation library or SDK hooks | Point the client at the proxy URL | None | A write at each call site |
| Acts before the call | Records only | Budgets, rate limits, `pre_call` guardrails | Reports only | Whatever your code checks |

## What does an OpenTelemetry GenAI span capture?

An OpenTelemetry GenAI inference span captures the provider, the model, and token usage for one model call. The [client inference conventions](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/client-inference.md) say the span name "SHOULD be `{gen_ai.operation.name} {gen_ai.request.model}`."

The requirement levels set what you can count on. `gen_ai.provider.name` is Required. `gen_ai.request.model` is Conditionally Required, if available. `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are Recommended. `gen_ai.conversation.id` is Conditionally Required "if and only if the instrumented library has one readily available."

The inference attribute list identifies the conversation, not a tenant or end user. If your audit questions are keyed by tenant, add that as your own span attribute.

Content is opt-in. `gen_ai.input.messages` and `gen_ai.output.messages` are Opt-In, with the warning that they are "likely to contain sensitive information including user/PII data." For tool spans, the [GenAI spans document](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md) says instrumentations "SHOULD NOT capture them by default, but SHOULD provide an option for users to opt in."

Agent structure has its own span types. A tool call is an `execute_tool {gen_ai.tool.name}` span, and `gen_ai.tool.name` is Required. An agent call is an `invoke_agent` span, named `invoke_agent {gen_ai.agent.name}` when the name is available, per the [agent spans document](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md).

One caveat: all three documents carry **Development** status. Attribute names can still change between releases.

## Are traces a complete record of every call?

Traces are complete under the SDK default and partial under ratio sampling. The [OpenTelemetry trace SDK specification](https://opentelemetry.io/docs/specs/otel/trace/sdk/) states: "The default sampler is `ParentBased(root=AlwaysOn)`."

Teams that want lower trace volume can configure a probability sampler instead. The spec marks `TraceIdRatioBased` deprecated in favor of `ProbabilitySampler`, and recommends ratio sampling for root spans combined with `ParentBased`. Once a probability sampler is in place, the trace store holds that fraction of calls.

That's fine for latency and error analysis. For an audit trail, confirm the sampler on every service that makes model calls.

## What does an LLM proxy log, and what can it enforce?

An LLM proxy logs every request that passes through it, and it can act on a request before forwarding it. This section uses the docs of LiteLLM, an open-source proxy, as the reference.

Each terminal success or failure event carries a `StandardLoggingPayload`. The [payload spec](https://docs.litellm.ai/docs/proxy/logging_spec) lists `id`, `call_type`, `model`, `response_cost`, `prompt_tokens`, `completion_tokens`, `total_tokens`, `status`, and `end_user`. Its metadata carries identity fields such as `user_api_key_team_id`, `user_api_key_user_id`, and `user_api_key_end_user_id`.

Storage splits two ways. The [cost tracking docs](https://docs.litellm.ai/docs/proxy/cost_tracking) write spend to a `LiteLLM_SpendLogs` table, with the key hash, team, end user, model group, spend, and tokens. The [logging docs](https://docs.litellm.ai/docs/proxy/logging) list callback destinations, including OpenTelemetry, S3, Google Cloud Storage, Azure Blob Storage, and Datadog, set under `litellm_settings`.

Message content is configurable. Setting `turn_off_message_logging: True` keeps prompts and responses out of the logs, and the docs note that spend is still tracked.

A proxy can also act first. The [budget docs](https://docs.litellm.ai/docs/proxy/users) say `max_budget` is `null` by default, and that "after the key crosses it's `max_budget`, requests fail." [Guardrails](https://docs.litellm.ai/docs/proxy/guardrails/quick_start) in `pre_call` mode "run before LLM call, on input."

The proxy sees what the request carries. The cost tracking docs advise setting `user_id` on keys to attribute spend to a user reliably. App concepts such as a tool name or a parent turn reach the proxy as request metadata you attach.

## What do provider usage APIs report?

Provider usage APIs report aggregated token usage and cost per time bucket, with no change to your agent. Both major providers expose them through admin credentials.

OpenAI's [completions usage endpoint](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/completions) returns time buckets, each holding "the aggregated completions usage details of the specific time bucket." `bucket_width` accepts `1m`, `1h`, or `1d`, defaulting to `1d`. `group_by` accepts `project_id`, `user_id`, `api_key_id`, `model`, `batch`, `service_tier`, and `api_source`.

Anthropic's [Usage and Cost API](https://platform.claude.com/docs/en/api/usage-cost-api) groups usage by API key, workspace, model, service tier, and other dimensions, in `1m`, `1h`, or `1d` buckets. The docs say data "typically appears within 5 minutes of API request completion." Anthropic now recommends its Usage and Cost Analytics API for new integrations.

These reports are the provider's billing view. They're the right source for reconciling an invoice. They group by the provider's own entities, such as project, workspace, and API key, so a per-tenant view means mapping tenants onto those entities.

## What should your own per-call table record?

Your own table should record one row per model call, keyed so a retry doesn't write it twice. That's the layer where your app's concepts live: tenant, end user, tool, and which turn a subagent call belongs to.

Idempotency is a database feature you already have. PostgreSQL's [`INSERT` reference](https://www.postgresql.org/docs/current/sql-insert.html) says "`ON CONFLICT DO NOTHING` simply avoids inserting a row as its alternative action." Put a unique constraint on your call key and retried writes become no-ops.

The cost is the code. Every call site needs the write, and any call path you miss is missing from the table. Wrapping the provider client once, rather than each call site, keeps that surface small.

## When to use each

- **You already run an OpenTelemetry pipeline:** add GenAI instrumentation, add a tenant attribute, and check the sampler.
- **Many services call several providers:** a proxy gives one log and one place for budgets and `pre_call` guardrails.
- **You need invoice reconciliation, not per-call records:** the provider usage APIs answer it with no code change.
- **Auditors ask which tenant, tool, and turn caused a call:** write a per-call row in your own database.
- **A single-shot bot with no tools or subagents:** provider usage reports are often enough.

## How Pleach does it

Pleach takes the per-call-table approach without a loop rewrite. You wrap your provider client, database, and tools as adapters under `@pleach/core`, and core drives the turn over your code. With an audit emitter registered, every model call writes one `AuditableCall` row to your own Postgres. See [adoption paths](/docs/adoption-paths) for the options and [packages](/docs/packages) for each package's current status.

### Wrapping what you already run

You implement two small interfaces over existing infrastructure and hand them to the runtime factory with one plugin:

```typescript
import { createPleachRuntime, setOrchestratorAdapterCtor } from "@pleach/core/runtime";

// 1. Wrap your existing LLM call as an OrchestratorAdapter (core drives it).
setOrchestratorAdapterCtor(MyExistingProviderAdapter);

// 2. Wrap your existing DB as a StorageAdapter + Checkpointer, and fold
//    your prompts / tools / safety rules into ONE plugin.
const runtime = createPleachRuntime({
  storage:      new MyPostgresStorageAdapter(pool),
  checkpointer: new MyPostgresCheckpointer(pool),
  plugins:      [myDomainPlugin],
  host: { strategies: { orchestratorConfig: { /* your provider config */ } } },
});
```

Pass storage and checkpointer as a pair. `createBrownfieldRuntime`, also exported from `@pleach/core/runtime`, refuses a split by throwing `SplitPersistenceError`.

If you're on the Vercel AI SDK or the Anthropic SDK, core ships the wrapper. `AiSdkProvider` wraps `streamText`, and `AnthropicSdkProvider` wraps `@anthropic-ai/sdk` directly. The per-stack pages cover [AI SDK](/docs/migrating-from-ai-sdk), [LangChain](/docs/migrating-from-langchain), [OpenAI SDK](/docs/with-openai-sdk), [Anthropic SDK](/docs/with-anthropic-sdk), and [Mastra](/docs/with-mastra).

### The row

Each row is keyed by `(sessionId, turnId, stageId, seqWithinTurn)`, and the ledger enforces that tuple as the idempotency key. The [row shape](/docs/auditable-call-row) groups fields:

| Group | Fields you'll query most |
|---|---|
| Identity | `recordId` (ULID), `sessionId`, `turnId`, `stageId`, `toolName`, `parentTurnId`, `subagentDepth` |
| Principal | `userId`, `actorKind`, `sessionAuthMethod`, plus `tenantId` |
| Call | `callClass`, `provider`, `model`, `transport` — what actually ran, not what was requested |
| Decision | `requestedModel`, `selectedReason`, `lockedFamily` |
| Outcome | `status`, `latencyMs`, `finishReason`, `httpStatus` |

Token counts live in `payload.tokenCost`. `tenantId` is opaque, so it carries whichever axis your finance team reports on. Subagent calls carry `parentTurnId` and `subagentDepth`, so grouping by the root turn rolls a delegation tree up to the user's turn. The ledger interface ships no update or delete primitive.

### The store

`PostgresProviderDecisionLedger` from `@pleach/core/audit` writes to a call ledger table in your Postgres. It takes any client with a parameterized `query(sql, params)` method, and each write is one `INSERT … ON CONFLICT … DO NOTHING`.

```typescript
import { PostgresProviderDecisionLedger } from "@pleach/core/audit";

const ledger = new PostgresProviderDecisionLedger({
  client: pool,
  hashChain: true, // opt-in; off by default
  onError: (err, call) => log.warn({ err, recordId: call.recordId }),
});
```

The default emitter is a no-op, so nothing lands until the host registers one. `recordCall` never rejects, so route `onError` to your alerting. With `hashChain` on, `verifyAuditableCallChain` checks that no row in a session was edited in place. The [audit ledger](/docs/audit-ledger) page covers the wiring.

Because core makes the call, it can decide before the wire. Family-lock pins the provider family per session, and a fallback walks in-family rungs only, recorded as `lockedFamily`.

## Key takeaways

- **Pick the layer by the question.** Spans answer latency, proxies answer spend per key, provider APIs answer the invoice, and your own table answers who and why.
- **Check sampling before you trust traces.** The SDK default keeps every root trace; a probability sampler keeps a fraction.
- **Provider usage APIs are aggregates.** They report buckets of `1m`, `1h`, or `1d`, grouped by the provider's own entities.
- **Enforcement sits where the call is made.** A proxy can apply budgets and `pre_call` guardrails; your own code can apply checks that need app state.
- **Make the write idempotent.** A unique key plus `ON CONFLICT DO NOTHING` keeps retries from duplicating rows.

## References

1. OpenTelemetry. [GenAI client inference semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/client-inference.md).
2. OpenTelemetry. [Semantic conventions for GenAI spans](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-spans.md).
3. OpenTelemetry. [Semantic conventions for GenAI agent spans](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md).
4. OpenTelemetry. [Tracing SDK specification](https://opentelemetry.io/docs/specs/otel/trace/sdk/).
5. LiteLLM. [Proxy logging](https://docs.litellm.ai/docs/proxy/logging).
6. LiteLLM. [StandardLoggingPayload specification](https://docs.litellm.ai/docs/proxy/logging_spec).
7. LiteLLM. [Spend tracking](https://docs.litellm.ai/docs/proxy/cost_tracking).
8. LiteLLM. [Budgets and rate limits](https://docs.litellm.ai/docs/proxy/users).
9. LiteLLM. [Guardrails quick start](https://docs.litellm.ai/docs/proxy/guardrails/quick_start).
10. OpenAI. [Completions usage API reference](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/completions).
11. Anthropic. [Usage and Cost API](https://platform.claude.com/docs/en/api/usage-cost-api).
12. PostgreSQL. [INSERT](https://www.postgresql.org/docs/current/sql-insert.html).

## Frequently asked

### How do I add audit logging to an existing AI agent without rewriting it?

Pick the layer that sees the calls you need to record. OpenTelemetry GenAI instrumentation emits one span per model call with provider, model, and token counts. An LLM proxy logs every request that passes through it. Provider usage APIs report aggregated buckets with no code change. A per-call table in your own database records the keys only your app knows, such as tenant, tool, and turn.

### What does an OpenTelemetry GenAI span record for an LLM call?

An inference span records the operation, the provider, the requested and response model, and token counts. In the client inference conventions, gen_ai.provider.name is Required and the gen_ai.usage.input_tokens and gen_ai.usage.output_tokens attributes are Recommended. The span is named after the operation and model. Prompt and completion content sit in Opt-In attributes. The GenAI conventions carry Development status.

### Do OpenTelemetry traces record every LLM call?

They do under the SDK default. The OpenTelemetry trace SDK specification sets the default sampler to ParentBased(root=AlwaysOn), so every root trace is sampled. If your team configures a probability sampler to cut volume, only that fraction of traces is kept. Check the sampler setting before you treat traces as a complete audit record.

### Can the OpenAI or Anthropic usage API give me a per-call audit log?

Both report usage in aggregated time buckets rather than per-request rows. OpenAI's completions usage endpoint supports 1m, 1h, and 1d buckets, grouped by fields such as project_id, user_id, api_key_id, and model. Anthropic's usage report groups by API key, workspace, model, and service tier, and its data typically appears within 5 minutes of request completion.

### Can an LLM proxy block a call before it reaches the provider?

Yes, for the checks it runs. LiteLLM's proxy enforces a max_budget per key, and its docs state that requests fail once a key crosses that budget. Guardrails configured in pre_call mode run before the LLM call, on the input. Checks that depend on your app's own state, such as which tool a step belongs to, need that state passed to the proxy.

### How does Pleach handle audit logging for an existing agent?

You wrap your provider client, database, and tools as adapters under @pleach/core, and core drives the turn over your code. With an audit emitter registered, every model call writes one AuditableCall row. PostgresProviderDecisionLedger writes those rows to a call ledger table in your own Postgres, keyed by sessionId, turnId, stageId, and seqWithinTurn.
