Skip to Content
These docs describe donkey-kit v0.3.0. Release notes
Cost attribution

Live

Cost attribution

A small, fixed set of tags (team, project, env, enduser.id) set once and recorded on every model call’s span:

donkey = Donkey.from_env(team="support", project="triage-v2", env="prod") async with donkey.run(id=ticket.id, enduser_id=agent_user.id): await triage_agent.run(ticket)

The tags resolve in this order: Donkey.from_env(team=…) kwargs, then DONKEY_COST_* env vars, then a [donkey.cost] table in the config files (see Configuration). Per-run overrides layer on top: donkey.run(team=…, project=…, env=…, enduser_id=…) wins per field for its block, and the rest fall back to the configured tags. The key set is fixed: an unknown dimension is a configuration error, never a silently dropped tag. Values are validated (fixed keys, bounded length), so nobody stuffs a JSON blob into a span attribute or header. For dimensions beyond these four, declare them once (see Custom dimensions).

Where the tags go

CarrierNamesWhenGoes to
Span attributesdonkey.cost.team, donkey.cost.project, donkey.cost.env, donkey.cost.enduser.id, and donkey.cost.<name> for each custom dimensionAlways, for each tag that is set, on every donkey.llm.chat span. Needs telemetry on (the default) and OpenTelemetry installed. The SDK’s shared client opens the span, so CrewAI, which has only header injection, records none.Your OpenTelemetry pipeline: the OTLP exporter when OTEL_EXPORTER_OTLP_ENDPOINT is set, or any TracerProvider your process installed
Request headersX-Anypoint-Cost-Team, X-Anypoint-Cost-Project, X-Anypoint-Cost-Env, X-Anypoint-Cost-Enduser-Id (renamable with cost_*_header), and X-Anypoint-Cost-<Name> for each custom dimension (cost_center is sent as X-Anypoint-Cost-Cost-Center, not renamable)Only with send_cost_headers / DONKEY_SEND_COST_HEADERS=true. Off by default.Model requests to the LLM proxy only. See the note below.

Each header carries the tag’s value unchanged (for example X-Anypoint-Cost-Enduser-Id: user-42). A tag that isn’t set is sent under neither carrier.

The Anypoint LLM Gateway doesn’t read cost tags from request headers: it meters cost from token usage per API instance and consuming client application. So the span attributes are the carrier that matters. Turn the headers on only when something of your own reads them.

With send_cost_headers on, the headers go only on model requests to the LLM proxy. The connected-app token request and other Anypoint control-plane requests never carry them, so the end-user ID doesn’t reach those hosts. Adapters with transport injection also send per-run donkey.run(...) values; adapters that get only a default_headers snapshot send the configured tags.

The end-user ID reaches your trace backend regardless of send_cost_headers. If enduser_id is set, every model-call span carries donkey.cost.enduser.id, and any exporter you’ve configured receives it. To keep it out of traces, don’t set enduser_id (DONKEY_COST_ENDUSER_ID, "enduser.id" in [donkey.cost], or donkey.run(enduser_id=…)), drop the attribute in your collector, or turn spans off with DONKEY_TELEMETRY=false.

Per-request attribution

One process often serves several tenants or teams: a shared agent platform, a multi-tenant SaaS agent, or one job that spans two cost centres. Keep one Donkey (one client, pool, auth cache and budget) and say per request which group a call belongs to:

async def handle(tenant: str, prompt: str): with donkey.attribution(business_group=tenant): return await model.ainvoke(prompt)

donkey.attribution(business_group=…, team=…, project=…, env=…, enduser_id=…) attributes every governed call in its block, on both the async and the blocking client. The business group replaces the configured business_group for the block. The precedence is this scope, then the Donkey config, then DONKEY_BUSINESS_GROUP, then the config file. The cost tags merge per field over any already bound by an enclosing block.

It doesn’t start a run, so the correlation ID stays the same and one run can span two cost centres:

async with donkey.run(id=job.id): with donkey.attribution(business_group="risk-eu"): await score(job) with donkey.attribution(business_group="risk-us"): await score(job)

donkey.run(business_group=…) and @donkey.governed(business_group=…) take the same argument when the group belongs to the whole run. Like the run ID, the binding is contextvar-based: it reaches framework-spawned tasks, concurrent tasks never see each other’s group, and nested blocks restore the outer value on exit. The value is validated like a cost tag, and an invalid one raises ConfigError where you set it.

Adapters that get only a default_headers snapshot don’t follow the scope. They captured the configured business group when they were built, so they keep sending it. Adapters with transport injection send the scoped value. The header name, X-Anypoint-Business-Group, is still an unverified placeholder; see Configuration.

Custom dimensions

Some organisations allocate spend by more than team, project and environment: a cost center, a legal entity, a jurisdiction. Declare those names once, when you build the client, and set their values per request in the same donkey.attribution(...) scope as the business group:

donkey = Donkey.from_env(cost_dimensions=["cost_center", "legal_entity", "jurisdiction"]) with donkey.attribution(business_group="risk-eu", cost_center="CC-4471", jurisdiction="EU"): await score(job)

donkey.run(...), donkey.run_from_headers(...) and @donkey.governed(...) accept the same keywords. Each value is recorded as a donkey.cost.<name> span attribute, on model-call spans and on outbound A2A call spans alike, merges per dimension over an enclosing block like the fixed tags, and goes out as a request header only with send_cost_headers.

The declared set is checked when the config is built:

RuleLimit
Name1-32 lowercase letters, digits and underscores, starting with a letter. Not team, project, env, enduser or enduser_id.
CountAt most 10 declared dimensions.
ValueA non-empty string of at most 256 characters, with no control characters, like the fixed tags.

A name you didn’t declare raises ConfigError where you passed it, and names it, so a typo never becomes a silently missing tag:

ConfigError: Unknown cost dimension(s) in donkey.attribution(): 'cost_centre' (did you mean 'cost_center'?). Declared: cost_center, legal_entity, jurisdiction. Declare each custom dimension once, when building the client: Donkey.from_env(cost_dimensions=[...]).

Declare them in the environment or a config file instead of code with DONKEY_COST_DIMENSIONS=cost_center,legal_entity or cost_dimensions = ["cost_center", "legal_entity"] under [donkey] (see Configuration).

Keep custom dimensions low-cardinality. Every distinct value is a new series in any backend that groups spans or metrics by it. A dimension such as a request ID or a case number, with a new value on every call, makes those backends slow and expensive. So a client accepts at most 1000 distinct values per custom dimension; the next new value raises ConfigError, while values it has already seen keep working. When a dimension really is high-cardinality, opt it out by also listing it in high_cardinality_cost_dimensions:

donkey = Donkey.from_env( cost_dimensions=["cost_center", "case_id"], high_cardinality_cost_dimensions=["case_id"], )

The question this answers

Finance asks what the support agent cost last month versus the HR bot. Without tags, both agents share one client_id and there is no way to split the bill. With tags it is a group-by.

For compliance — “prove the HR bot’s answer to user X on date Y went through the content-safety policy” — the correlation ID on the log line joins to the gateway record, and the span carries donkey.cost.enduser.id and donkey.policy.type. An EU AI Act Article 12 log request becomes one query, not an investigation.

Next steps

  • Correlation IDs: the per-run id that joins a call’s tags to its log lines and gateway record.
  • Configuration: where the tags and the attribution headers are set.
  • Budget & pacing: the token and request windows the gateway enforces per consumer.
  • OpenTelemetry spans: the span attributes these tags are recorded on.
Last updated on