Live
Python API reference
The public API of donkey-kit, generated from its
signatures and docstrings. Each entry shows the first paragraph of the
docstring; help() on the object prints the rest. Everything listed here is
importable from donkey_kit.
Stability
Except for the provisional APIs described below, the names in
donkey_kit.__all__ and the public methods and properties of Donkey
are stable. During 0.x a stable name
is removed or renamed only in a minor release, and only after an earlier
minor release shipped it as a working alias that emits a
DeprecationWarning. A patch release never breaks one.
A2AFacade and Donkey.a2a (donkey.a2a) are provisional (ADR 0022).
A2AFacade is an explicit exception to the stable-root-export rule,
even though it is importable from donkey_kit and listed in
donkey_kit.__all__. The facade’s send/stream signatures and the accessor
may change in a minor release with a migration note.
ToolLockDrift is also provisional (ADR 0020):
a root export by exception, not covered by the stable deprecation guarantee,
and may change in a minor release with a migration note.
donkey_kit.core and the other public submodules are provisional: they
are documented and may change in a minor release, with a migration note.
Some types you meet through a stable object live there, such as
RefusalContext (what a refusal handler receives),
RunUsage (RunLedger.usage) and PolicyRegistration (what
classify.registered() returns); import them from donkey_kit.core.
So is a method of a stable object whose docstring says Provisional
(help() shows it), such as donkey.tools.live_tools() and
donkey.tools.live_card().
donkey_kit.experimental holds types for surfaces that are still blocked
on verification, and they may change in any release.
Donkey
The SDK entry point: one governed handle on Agent Fabric.
Each framework adapter is an attribute too, listed under Framework adapters.
Donkey(
config: DonkeyConfig | None = None,
*,
auth: AuthProvider | None = None,
llm_auth: AuthProvider | None = None,
) -> NoneDonkey.from_env()
Donkey.from_env(
*,
team: str | None = None,
project: str | None = None,
env: str | None = None,
enduser_id: str | None = None,
path: str | os.PathLike[str] | None = None,
**overrides: Unpack[ConfigOverrides],
) -> DonkeyBuild from the environment and the config files, with any DonkeyConfig field set in code on top.
Guide: /reference/configuration#precedence
donkey.config
donkey.config: DonkeyConfigThe resolved configuration this Donkey was built with (read-only).
Guide: /reference/configuration
donkey.llm
donkey.llm: LLMClientThe governed model-call surface: native OpenAI-compatible clients and per-framework connection kwargs pointed at the proxy.
Guide: /quickstart
donkey.budget
donkey.budget: BudgetThe token-budget window for this Donkey, updated in-band from every response’s x-token-* headers. Unobserved (all fields None) until the first call returns; there is no budget-query endpoint, so it is only as fresh as budget.observed_at.
donkey.last_call
donkey.last_call: LastCallThe gateway’s own metadata about the most recent governed model call in this context — its request_id, api_instance_id and environment_id; what the gateway did with the request — served_provider / served_model / routing_type and the fallback flag, with substituted true when the served model differs from requested_model; and the per-call usage token counts (input_tokens / output_tokens / total_tokens and the cost-relevant cached_tokens / cache_write_tokens / reasoning_tokens). The success-path counterpart to the ids DonkeyError hands you on a refusal.
donkey.current_run
donkey.current_run: RunLedger | NoneA snapshot of the bound donkey.run() block’s ledger, or None outside a run.
Guide: /correlation#run-ledger
donkey.openai()
donkey.openai(*, sync: bool = False, **kw: Any) -> AsyncOpenAI | OpenAIThe headline two-line ergonomic: a native OpenAI client pointed at the governed proxy, with nothing new to learn.
donkey.http_client()
donkey.http_client(*, sync: bool = False) -> DonkeyAsyncClientView | DonkeyClientViewThe governed data-plane httpx client, for a framework or SDK that takes one (http_client=, async_http_client=, a pre-built AsyncOpenAI). Requests sent through it get the same headers, retries, span, budget and donkey.last_call as every adapter.
donkey.registry
donkey.registry: ExchangeRegistryThe Exchange registry client used for tool discovery and resolution.
Guide: /registry/discovery/mcp
donkey.a2a
donkey.a2a: A2AFacadeGoverned outbound A2A sends and context-managed streams.
Guide: /a2a/call
donkey.tools
donkey.tools: ToolsFacadeGoverned tool discovery and the donkey.lock lockfile.
Guide: /tool-access
donkey.run()
donkey.run(
id: str | None = None,
*,
team: str | None = None,
project: str | None = None,
env: str | None = None,
enduser_id: str | None = None,
business_group: str | None = None,
typed_refusals: bool = True,
ledger_max_entries: int = 1000,
**dimensions: str | None,
) -> RunScopeGroup one logical agent run under a shared correlation id.
donkey.evaluate()
donkey.evaluate(*, on: Literal['run_end'], with_: RunScorer) -> NoneScore every donkey.run() block at its end, on the run span.
donkey.run_from_headers()
donkey.run_from_headers(
headers: Mapping[str, str],
*,
team: str | None = None,
project: str | None = None,
env: str | None = None,
enduser_id: str | None = None,
business_group: str | None = None,
typed_refusals: bool = True,
ledger_max_entries: int = 1000,
**dimensions: str | None,
) -> RunScopeJoin the caller’s run: run, with the id read from an inbound request’s headers.
Guide: /correlation
donkey.correlation_headers()
donkey.correlation_headers() -> dict[str, str]The bound run’s correlation header, for an outbound hop the governed transport does not carry.
donkey.run_context()
donkey.run_context(run_id: str | None = None) -> RunScopeDeprecated alias for run: use donkey.run(id=…). Emits a DeprecationWarning.
donkey.attribution()
donkey.attribution(
*,
business_group: str | None = None,
team: str | None = None,
project: str | None = None,
env: str | None = None,
enduser_id: str | None = None,
**dimensions: str | None,
) -> AttributionScopeAttribute every governed call in the block to a business group and cost tags, per request, without starting a run.
Guide: /cost-attribution
donkey.cache()
donkey.cache(
*,
skip: bool | None = None,
no_store: bool | None = None,
ttl: int | None = None,
threshold: float | None = None,
principal_id: str | None = None,
) -> CacheScopeSteer the gateway’s semantic cache for every governed model call in the block.
donkey.as_user()
donkey.as_user(*, token: str) -> UserScopeRun the governed model calls in the block as the user behind token, not as this service.
donkey.governed()
donkey.governed(
func: Callable[P, R] | None = None,
*,
team: str | None = None,
project: str | None = None,
env: str | None = None,
enduser_id: str | None = None,
business_group: str | None = None,
typed_refusals: bool = True,
**dimensions: str | None,
) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]Wrap a callable so its body runs inside a donkey.run() scope.
donkey.tool()
donkey.tool(
func: Callable | None = None,
/,
*,
approval: ApprovalMode | None = None,
risk: str | None = None,
approval_timeout: Duration = '15m',
server: str | None = None,
) -> Callable | Callable[[Callable], Callable]Mark a callable as a governed tool, recording its name, signature and docstring in an introspectable registry, and optionally gate it behind a human approval.
Guide: /hitl
donkey.agent()
donkey.agent(*, name: str, skills: Sequence[str] = ()) -> Callable[[Callable], Callable]Mark a callable as an agent entry point, recording its name, skills and docstring in an introspectable registry.
Guide: /registry/serve
donkey.serve()
donkey.serve(
handler: Callable[..., Any],
*,
host: str = '127.0.0.1',
port: int = 8000,
url: str | None = None,
version: str = '0.0.0',
) -> NoneServe a @donkey.agent handler over A2A on host:port, blocking until the server stops.
Guide: /registry/serve
donkey.approvals
donkey.approvals: ApprovalsThis client’s pending tool approvals: resolve or reject the call a ApprovalRequired names. Each Donkey owns its own: it holds the gated calls run in this client’s run / as_user blocks, and those of the tools declared on it with tool or bound from its tools.discover() when they run outside any block.
Guide: /hitl
donkey.on()
donkey.on(refusal: type[PolicyViolation]) -> OnRefusalDeclare once what to do when a call is refused with refusal.
Guide: /refusal-handlers
donkey.classify
donkey.classify: ClassifierThe process-wide refusal classifier: the same object as donkey_kit.classify. Call it to type an error response, or register a custom gateway policy’s refusal shape on it.
Guide: /custom-policies
donkey.simulate()
donkey.simulate(
error: type[DonkeyError],
*,
times: int = 1,
) -> AbstractContextManager[None]Inject a real gateway refusal in-process, no server.
donkey.simulate_mcp()
donkey.simulate_mcp(
capture: str,
*,
servers: Mapping[str, Sequence[Mapping[str, Any]]],
times: int = 1,
call_tool: Callable[[str, Mapping[str, Any]], Mapping[str, Any]] | None = None,
) -> AbstractContextManager[None]Inject a captured gateway refusal into MCP tool calls, no gateway.
Guide: /simulator/mcp
donkey.simulate_a2a()
donkey.simulate_a2a(
capture: str,
*,
agents: Sequence[str],
version: str = '1.0',
times: int = 1,
reply: Callable[[str], str] | None = None,
) -> AbstractContextManager[None]Inject a captured gateway refusal into outbound A2A calls, no gateway.
Guide: /simulator/a2a
donkey.flush_telemetry()
donkey.flush_telemetry(timeout_s: float = 2.0) -> boolExport the spans DDK’s own TracerProvider still holds, waiting up to timeout_s, before a serverless runtime freezes the process or a script exits.
Guide: /telemetry
donkey.aclose()
async donkey.aclose() -> NoneClose every transport this Donkey owns: the data-plane and control-plane clients, the connected-app token-fetch client it built (a caller-supplied auth provider stays caller-owned), and the blocking client. Each one is closed even if an earlier close raises.
donkey.close()
donkey.close() -> NoneClose the blocking transport.
DonkeyConfig
Everything the SDK needs to reach Agent Fabric, resolved once and immutable.
Its fields are listed in Configuration.
DonkeyConfig.resolve()
DonkeyConfig.resolve(
*,
path: str | os.PathLike[str] | None = None,
**overrides: Unpack[ConfigOverrides],
) -> DonkeyConfigResolve every field along the configured precedence.
Guide: /reference/configuration#precedence
DonkeyConfig.from_env()
DonkeyConfig.from_env() -> DonkeyConfigBuild from env + the optional config files: resolve with no arguments (see the module docstring). Does not validate; call validated when you know which capability you need.
config.control_plane_url
config.control_plane_url: strThe Anypoint control-plane base URL — explicit override or region.
config.source_of()
config.source_of(name: str) -> ConfigSourceWhere field name was resolved from. explicit (set in code) when resolve did not resolve it or its value has changed since, e.g. through dataclasses.replace, with_overrides or direct construction; copies that keep the value keep the label, and so does DonkeyConfig(**dataclasses.asdict(cfg)) in the same process. A label recorded in another process can’t be checked against the value: an endpoint keeps it and a credential counts as set in code.
config.with_overrides()
config.with_overrides(**kw: Unpack[ConfigOverrides]) -> DonkeyConfigReturn a copy with the given fields replaced.
config.validated()
config.validated(*, need: Capability = 'control_plane') -> DonkeyConfigReturn self if valid for the requested capability, else raise a ConfigError listing EVERY missing field at once.
config.missing_fields()
config.missing_fields(*, need: Capability) -> list[str]Every required field for need that is unset, each with the env var that sets it. The list validated reports.
config.check_endpoints()
config.check_endpoints(
*,
need: Capability,
code_credential: str | None = None,
fields: tuple[str, ...] = (),
) -> NoneRaise ConfigError if need’s endpoint may not receive the credentials that would be sent to it.
LLMClient (donkey.llm)
The framework-free proxy client factory.
donkey.llm.close()
donkey.llm.close() -> NoneClose the blocking client built by this standalone factory, if any.
donkey.llm.aclose()
async donkey.llm.aclose() -> NoneClose this factory’s owned blocking client in an async scope.
donkey.llm.client()
donkey.llm.client(*, sync: bool = False, **kw: Any) -> AsyncOpenAI | OpenAIAn OpenAI client pointed at the LLM proxy, using our shared http client so headers + retries apply.
donkey.llm.list_models()
async donkey.llm.list_models(*, live: bool = False) -> list[ModelHandle]List logical models the proxy exposes.
donkey.llm.resolve()
donkey.llm.resolve(model_id: str, *, provider: str | None = None) -> ModelHandleA ModelHandle for a model id.
Budget (donkey.budget)
The token-budget window for one Donkey, updated in-band from each response’s budget headers (numeric x-token-* or the prose x-llm-proxy-ratelimit fallback). Its request-count sibling is requests.
donkey.budget.observe_refusal()
donkey.budget.observe_refusal(refusal: DonkeyError) -> NoneNote a typed refusal the gateway sent, as observe notes its headers. The transport calls it; only an AgentKilled changes anything.
donkey.budget.observe()
donkey.budget.observe(response: httpx.Response, *, now: datetime | None = None) -> NoneUpdate from a response’s budget headers.
donkey.budget.pace()
donkey.budget.pace(
*,
reserve: float = 0.0,
now: datetime | None = None,
) -> AbstractAsyncContextManager[None]Guard a request so it is refused before it crosses your reserve, not after a 429 comes back.
donkey.budget.wait_for_reset()
async donkey.budget.wait_for_reset(
*,
window: str | None = None,
now: datetime | None = None,
) -> NoneSleep until the tripped window’s reset_at, then return — the recovery half of pacing.
LastCall (donkey.last_call)
What the gateway said about the most recent governed model call.
Its fields are listed in last_call fields.
donkey.last_call.observed
donkey.last_call.observed: boolTrue iff a governed response actually populated this record.
donkey.last_call.substituted
donkey.last_call.substituted: boolTrue iff the gateway served a different model than the one requested — a silent model substitution the developer’s cost model, token assumptions and evaluation are otherwise blind to. Requires both the requested and served model to be known; a missing either side is not a substitution claim. A provider/ prefix naming served_provider is not a difference — see is_substitution.
donkey.last_call.cache_hit
donkey.last_call.cache_hit: boolTrue iff the gateway served this call from its semantic cache (cache_status == "hit") — a verbatim replay with no provider round-trip. The zero-spend read a cost rollup uses to exclude a hit’s replayed usage from fresh spend. False for every other status and for an unobserved / non-cached response.
donkey.last_call.available
donkey.last_call.available: boolFalse only when the current surface structurally cannot be observed (the framework owns the transport, or the adapter gets only default_headers); a plain cold read is still available — it just has not observed anything yet.
LastCall.from_response()
LastCall.from_response(
response: httpx.Response,
*,
requested_model: str | None = None,
now: datetime | None = None,
) -> LastCallBuild an OBSERVED record from a governed response’s headers.
Framework adapters
donkey.<attribute> imports the adapter on first use. If its framework is
not installed, the access raises ImportError with the pip install line.
See Frameworks for what each factory returns.
| Attribute | Install | Factories |
|---|---|---|
donkey.langgraph | pip install "donkey-kit[langgraph]" | chat_model() |
donkey.adk | pip install "donkey-kit[adk]" | model(), gemini() |
donkey.strands | pip install "donkey-kit[strands]" | model() |
donkey.agent_framework | pip install "donkey-kit[agent_framework]" | chat_client() |
donkey.openai_agents | pip install "donkey-kit[openai-agents]" | model() |
donkey.anthropic | pip install "donkey-kit[anthropic]" | client() |
donkey.crewai | pip install "donkey-kit[crewai]" | llm() |
donkey.llamaindex | pip install "donkey-kit[llamaindex]" | llm() |
Exceptions
Every typed refusal and SDK error. See Typed refusals for when each is raised.
| Exception | Base | Meaning |
|---|---|---|
AgentKilled | PolicyViolation | The gateway’s Agent Kill Switch blocked this agent — it is quarantined in Governance > Security, or listed in the policy’s Killed Agent IDs. |
ApprovalError | DonkeyError | An approval was refused, so the call it gated did not happen. |
ApprovalNotFound | DonkeyError | No approval with this id is pending in this client’s donkey.approvals: it was already resolved or rejected, it was recorded by another Donkey or process, or the process restarted. approval_id is the id. |
ApprovalRejected | ApprovalError | A human rejected an approval-gated call that a framework paused natively, so the tool was not run. approval is the call. |
ApprovalRequired | DonkeyError | A @donkey.tool(approval="required") tool was called, and was not run. |
ApprovalTimedOut | DonkeyError | A pending approval passed its timeout before anyone resolved it, so the call was not made. approval is the expired call. |
AuthError | DonkeyError | Rejected credentials on the Anypoint control plane or LLM-proxy data plane. |
BudgetReserveReached | DonkeyError | Raised by Budget.pace before it lets a request through that would cross the caller’s reserve. |
ConfigError | DonkeyError | Configuration is missing or invalid, or an endpoint may not receive the credentials that would be sent to it (see DonkeyConfig.check_endpoints). Raised locally before any request; reports ALL missing fields at once. The transport also raises it, with its own remediation, for a send on a closed client or from a closed event loop. |
ContentSafetyBlocked | PolicyViolation | A provider-backed content-moderation policy (Azure Content Safety, Amazon Bedrock Guardrails, Google Model Armor or CrowdStrike AIDR) blocked the request or response. The AIDR shape is read from the policy’s source, not captured live. |
DonkeyError | Exception | Base for all SDK errors. Carries correlation/call/request IDs and the raw response so callers can inspect what actually happened. |
GatewayApprovalDenied | PolicyViolation | The user denied the out-of-band (CIBA) approval the gateway requested. |
GatewayApprovalPending | DonkeyError | The gateway is waiting for the user to approve this call out of band (CIBA). |
GatewayAuthRequired | DonkeyError | An A2A task needs authorization, not CIBA polling or a local approval. |
GatewayUnavailable | DonkeyError | The gateway could not be reached at all — a transport-level failure (DNS, refused connection, TLS error, timeout) with NO HTTP response behind it. |
ModelNotRoutable | DonkeyError | The gateway could not pick a provider for the model, so it rejected the request before any upstream call: a bare model name on a multi-provider proxy (gpt-5-mini, ambiguous unless exactly one provider knows it; the flat-string error asks for provider/model), a missing model, or a provider with no route or fallback. A client configuration mistake, NOT a refusal (not a PolicyViolation) and NOT an upstream rejection (not an UpstreamRequestError). Terminal, never retried. model / provider: the model or unrouted provider the gateway echoed, else None. |
ModelSubstituted | DonkeyError | The gateway served a different model than the one requested — a routing fallback substituted the model, and on_model_substitution="raise" opted the caller into treating that as an error. |
PIIDetected | PolicyViolation | PII policy refusal; MCP adds safe phase / findings metadata. |
PolicyViolation | DonkeyError | Base for gateway-enforced refusals. NEVER retried. |
PromptInjectionBlocked | PolicyViolation | The prompt-injection-protection policy flagged the request as an injection attempt. |
RequestRateLimitExceeded | PolicyViolation | A request-rate-limit policy refused the request: the window’s request count is spent. |
TokenBudgetExceeded | PolicyViolation | A token-rate-limit policy refused the request: the budget window is spent. |
ToolLockDrift | DonkeyError | The gateway’s tools no longer match donkey.lock. |
ToolNotInProfile | PolicyViolation | The gateway refused an MCP tool call: the tool is outside this consumer’s access profile. |
UngovernedMcpServer | DonkeyError | A ToolSet binding was refused because a server in it is not governed. |
UpstreamModelError | DonkeyError | Provider-side failure (5xx). Retryable. |
UpstreamRequestError | DonkeyError | The upstream provider rejected the request (4xx), passed through the gateway verbatim (e.g. OpenAI model_not_found). This is a client-side mistake, NOT a gateway policy refusal and NOT a provider outage, so it is terminal (never retried) but distinct from PolicyViolation. |
WalletExhausted | TokenBudgetExceeded | A model wallet is spent: the gateway refused the call because the wallet that matched the caller has no budget left in its window. |
Other exports
| Name | Kind | Meaning |
|---|---|---|
A2AFacade | class | donkey.a2a: send official SDK requests through a governed gateway. |
A2AResult | class | What a handler returns when a plain string is not enough. |
A2ATask | class | One A2A task handed to a donkey.serve() handler. |
AgentSpec | class | An introspectable record of a @donkey.agent-marked entry point. |
Approval | class | One call of an approval-gated tool, waiting for a human. A framework adapter’s approval helpers carry the framework’s own object on native. |
Approvals | class | donkey.approvals: one client’s pending tool approvals. |
AttributionScope | class | A dual sync/async context manager that attributes the governed calls in its block to a business group and cost tags, without starting a run. |
Budget | class | The token-budget window for one Donkey, updated in-band from each response’s budget headers (numeric x-token-* or the prose x-llm-proxy-ratelimit fallback). Its request-count sibling is requests. |
CacheControls | class | The per-request semantic-cache steering controls. |
CacheScope | class | A dual sync/async context manager that applies CacheControls to the governed calls made in its block. |
Classifier | class | classify: call it to map an error response to a typed DonkeyError; register a custom policy’s refusal shape on it. |
ConfigOverrides | class | The public DonkeyConfig fields, each optional, as keyword arguments: what DonkeyConfig.resolve, DonkeyConfig.with_overrides and Donkey.from_env accept, so a misspelt field fails type checking. |
CostTags | class | The fixed four-dimension cost-attribution set, plus the values of any custom dimensions. |
Donkey | class | The SDK entry point: one governed handle on Agent Fabric. |
DonkeyAsyncClientView | class | A non-owning httpx.AsyncClient over a shared DonkeyAsyncClient. |
DonkeyClientView | class | The blocking twin of DonkeyAsyncClientView, over a shared DonkeyClient. Get one from DonkeyClient.view. |
DonkeyConfig | class | Everything the SDK needs to reach Agent Fabric, resolved once and immutable. |
ExchangeRegistry | class | The Exchange client behind donkey.registry: search, resolve and explain assets. |
GatewayAuthChallenge | class | OAuth metadata from the captured A2A v0.3 authorization-code challenge. |
GovernanceCriteria | class | Definition of ‘governed’. Every field is a separate, independently checkable condition. Defaults are deliberately moderate; orgs override. |
LLMClient | class | The framework-free proxy client factory. |
LastCall | class | What the gateway said about the most recent governed model call. |
LastCallStatus | class | Why LastCall fields are (or are not) populated — so a None is never ambiguous between “the gateway said nothing” and “the SDK never saw the response”. str-valued so it prints and logs cleanly. |
McpAuth | class | Where a binding’s gateway credential headers come from. |
OnRefusal | class | Returned by donkey.on(refusal): pick exactly one reaction. |
Region | type alias | One of us, eu, ca, jp. |
RequestWindow | class | The gateway’s request-count window, donkey.budget.requests. |
RunLedger | class | A snapshot of one run’s ledger: every governed model call, every refusal, and the token totals, as of when it was read. |
RunRefusal | class | One refusal in a run’s ledger: what refused the call and how to find it, with none of the response content. |
RunScope | class | A dual sync/async context manager that sets the run correlation id for the governed calls made in its block. |
ToolSet | class | A governed set of MCP tools, from donkey.tools.discover(). |
ToolSpec | class | An introspectable record of a @donkey.tool-marked callable. |
ToolsFacade | class | donkey.tools — discovery + lock. |
TypedRefusals | class | Re-raise a refusal from the block as its typed DonkeyError. |
UpstreamQuota | class | The upstream provider’s quota windows, donkey.budget.upstream, kept apart from the gateway’s so neither source overwrites the other. |
UpstreamWindow | class | One window of the upstream provider’s own quota, as the gateway passes it through: donkey.budget.upstream.requests or .tokens. |
UserScope | class | The dual sync/async context manager donkey.as_user(...) returns. |
classify | callable object | classify: call it to map an error response to a typed DonkeyError; register a custom policy’s refusal shape on it. |
jsonrpc_refusal | function | Recover a JSON-RPC policy refusal from mappings or exception.error ducks. |
registered_agents | function | Every entry point marked with @donkey.agent in this process, in decoration order. |
registered_tools | function | Every callable marked with @donkey.tool in this process, in decoration order. The introspection entry point for the scanner / card generator. |
typed_refusals | function | Re-raise a governance refusal from the block as its typed DonkeyError. |