Skip to Content
These docs describe donkey-kit v0.3.0. Release notes
ReferencePython API

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, ) -> None

Donkey.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], ) -> Donkey

Build from the environment and the config files, with any DonkeyConfig field set in code on top.

Guide: /reference/configuration#precedence

donkey.config

donkey.config: DonkeyConfig

The resolved configuration this Donkey was built with (read-only).

Guide: /reference/configuration

donkey.llm

donkey.llm: LLMClient

The governed model-call surface: native OpenAI-compatible clients and per-framework connection kwargs pointed at the proxy.

Guide: /quickstart

donkey.budget

donkey.budget: Budget

The 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: LastCall

The 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 | None

A 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 | OpenAI

The 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 | DonkeyClientView

The 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: ExchangeRegistry

The Exchange registry client used for tool discovery and resolution.

Guide: /registry/discovery/mcp

donkey.a2a

donkey.a2a: A2AFacade

Governed outbound A2A sends and context-managed streams.

Guide: /a2a/call

donkey.tools

donkey.tools: ToolsFacade

Governed 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, ) -> RunScope

Group one logical agent run under a shared correlation id.

donkey.evaluate()

donkey.evaluate(*, on: Literal['run_end'], with_: RunScorer) -> None

Score 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, ) -> RunScope

Join 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) -> RunScope

Deprecated 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, ) -> AttributionScope

Attribute 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, ) -> CacheScope

Steer the gateway’s semantic cache for every governed model call in the block.

donkey.as_user()

donkey.as_user(*, token: str) -> UserScope

Run 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', ) -> None

Serve a @donkey.agent handler over A2A on host:port, blocking until the server stops.

Guide: /registry/serve

donkey.approvals

donkey.approvals: Approvals

This 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]) -> OnRefusal

Declare once what to do when a call is refused with refusal.

Guide: /refusal-handlers

donkey.classify

donkey.classify: Classifier

The 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) -> bool

Export 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() -> None

Close 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() -> None

Close 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], ) -> DonkeyConfig

Resolve every field along the configured precedence.

Guide: /reference/configuration#precedence

DonkeyConfig.from_env()

DonkeyConfig.from_env() -> DonkeyConfig

Build 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: str

The Anypoint control-plane base URL — explicit override or region.

config.source_of()

config.source_of(name: str) -> ConfigSource

Where 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]) -> DonkeyConfig

Return a copy with the given fields replaced.

config.validated()

config.validated(*, need: Capability = 'control_plane') -> DonkeyConfig

Return 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, ...] = (), ) -> None

Raise 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() -> None

Close the blocking client built by this standalone factory, if any.

donkey.llm.aclose()

async donkey.llm.aclose() -> None

Close this factory’s owned blocking client in an async scope.

donkey.llm.client()

donkey.llm.client(*, sync: bool = False, **kw: Any) -> AsyncOpenAI | OpenAI

An 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) -> ModelHandle

A 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) -> None

Note 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) -> None

Update 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, ) -> None

Sleep 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: bool

True iff a governed response actually populated this record.

donkey.last_call.substituted

donkey.last_call.substituted: bool

True 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: bool

True 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: bool

False 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, ) -> LastCall

Build 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.

AttributeInstallFactories
donkey.langgraphpip install "donkey-kit[langgraph]"chat_model()
donkey.adkpip install "donkey-kit[adk]"model(), gemini()
donkey.strandspip install "donkey-kit[strands]"model()
donkey.agent_frameworkpip install "donkey-kit[agent_framework]"chat_client()
donkey.openai_agentspip install "donkey-kit[openai-agents]"model()
donkey.anthropicpip install "donkey-kit[anthropic]"client()
donkey.crewaipip install "donkey-kit[crewai]"llm()
donkey.llamaindexpip install "donkey-kit[llamaindex]"llm()

Exceptions

Every typed refusal and SDK error. See Typed refusals for when each is raised.

ExceptionBaseMeaning
AgentKilledPolicyViolationThe gateway’s Agent Kill Switch blocked this agent — it is quarantined in Governance > Security, or listed in the policy’s Killed Agent IDs.
ApprovalErrorDonkeyErrorAn approval was refused, so the call it gated did not happen.
ApprovalNotFoundDonkeyErrorNo 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.
ApprovalRejectedApprovalErrorA human rejected an approval-gated call that a framework paused natively, so the tool was not run. approval is the call.
ApprovalRequiredDonkeyErrorA @donkey.tool(approval="required") tool was called, and was not run.
ApprovalTimedOutDonkeyErrorA pending approval passed its timeout before anyone resolved it, so the call was not made. approval is the expired call.
AuthErrorDonkeyErrorRejected credentials on the Anypoint control plane or LLM-proxy data plane.
BudgetReserveReachedDonkeyErrorRaised by Budget.pace before it lets a request through that would cross the caller’s reserve.
ConfigErrorDonkeyErrorConfiguration 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.
ContentSafetyBlockedPolicyViolationA 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.
DonkeyErrorExceptionBase for all SDK errors. Carries correlation/call/request IDs and the raw response so callers can inspect what actually happened.
GatewayApprovalDeniedPolicyViolationThe user denied the out-of-band (CIBA) approval the gateway requested.
GatewayApprovalPendingDonkeyErrorThe gateway is waiting for the user to approve this call out of band (CIBA).
GatewayAuthRequiredDonkeyErrorAn A2A task needs authorization, not CIBA polling or a local approval.
GatewayUnavailableDonkeyErrorThe gateway could not be reached at all — a transport-level failure (DNS, refused connection, TLS error, timeout) with NO HTTP response behind it.
ModelNotRoutableDonkeyErrorThe 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.
ModelSubstitutedDonkeyErrorThe 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.
PIIDetectedPolicyViolationPII policy refusal; MCP adds safe phase / findings metadata.
PolicyViolationDonkeyErrorBase for gateway-enforced refusals. NEVER retried.
PromptInjectionBlockedPolicyViolationThe prompt-injection-protection policy flagged the request as an injection attempt.
RequestRateLimitExceededPolicyViolationA request-rate-limit policy refused the request: the window’s request count is spent.
TokenBudgetExceededPolicyViolationA token-rate-limit policy refused the request: the budget window is spent.
ToolLockDriftDonkeyErrorThe gateway’s tools no longer match donkey.lock.
ToolNotInProfilePolicyViolationThe gateway refused an MCP tool call: the tool is outside this consumer’s access profile.
UngovernedMcpServerDonkeyErrorA ToolSet binding was refused because a server in it is not governed.
UpstreamModelErrorDonkeyErrorProvider-side failure (5xx). Retryable.
UpstreamRequestErrorDonkeyErrorThe 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.
WalletExhaustedTokenBudgetExceededA 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

NameKindMeaning
A2AFacadeclassdonkey.a2a: send official SDK requests through a governed gateway.
A2AResultclassWhat a handler returns when a plain string is not enough.
A2ATaskclassOne A2A task handed to a donkey.serve() handler.
AgentSpecclassAn introspectable record of a @donkey.agent-marked entry point.
ApprovalclassOne call of an approval-gated tool, waiting for a human. A framework adapter’s approval helpers carry the framework’s own object on native.
Approvalsclassdonkey.approvals: one client’s pending tool approvals.
AttributionScopeclassA dual sync/async context manager that attributes the governed calls in its block to a business group and cost tags, without starting a run.
BudgetclassThe 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.
CacheControlsclassThe per-request semantic-cache steering controls.
CacheScopeclassA dual sync/async context manager that applies CacheControls to the governed calls made in its block.
Classifierclassclassify: call it to map an error response to a typed DonkeyError; register a custom policy’s refusal shape on it.
ConfigOverridesclassThe 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.
CostTagsclassThe fixed four-dimension cost-attribution set, plus the values of any custom dimensions.
DonkeyclassThe SDK entry point: one governed handle on Agent Fabric.
DonkeyAsyncClientViewclassA non-owning httpx.AsyncClient over a shared DonkeyAsyncClient.
DonkeyClientViewclassThe blocking twin of DonkeyAsyncClientView, over a shared DonkeyClient. Get one from DonkeyClient.view.
DonkeyConfigclassEverything the SDK needs to reach Agent Fabric, resolved once and immutable.
ExchangeRegistryclassThe Exchange client behind donkey.registry: search, resolve and explain assets.
GatewayAuthChallengeclassOAuth metadata from the captured A2A v0.3 authorization-code challenge.
GovernanceCriteriaclassDefinition of ‘governed’. Every field is a separate, independently checkable condition. Defaults are deliberately moderate; orgs override.
LLMClientclassThe framework-free proxy client factory.
LastCallclassWhat the gateway said about the most recent governed model call.
LastCallStatusclassWhy 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.
McpAuthclassWhere a binding’s gateway credential headers come from.
OnRefusalclassReturned by donkey.on(refusal): pick exactly one reaction.
Regiontype aliasOne of us, eu, ca, jp.
RequestWindowclassThe gateway’s request-count window, donkey.budget.requests.
RunLedgerclassA snapshot of one run’s ledger: every governed model call, every refusal, and the token totals, as of when it was read.
RunRefusalclassOne refusal in a run’s ledger: what refused the call and how to find it, with none of the response content.
RunScopeclassA dual sync/async context manager that sets the run correlation id for the governed calls made in its block.
ToolSetclassA governed set of MCP tools, from donkey.tools.discover().
ToolSpecclassAn introspectable record of a @donkey.tool-marked callable.
ToolsFacadeclassdonkey.tools — discovery + lock.
TypedRefusalsclassRe-raise a refusal from the block as its typed DonkeyError.
UpstreamQuotaclassThe upstream provider’s quota windows, donkey.budget.upstream, kept apart from the gateway’s so neither source overwrites the other.
UpstreamWindowclassOne window of the upstream provider’s own quota, as the gateway passes it through: donkey.budget.upstream.requests or .tokens.
UserScopeclassThe dual sync/async context manager donkey.as_user(...) returns.
classifycallable objectclassify: call it to map an error response to a typed DonkeyError; register a custom policy’s refusal shape on it.
jsonrpc_refusalfunctionRecover a JSON-RPC policy refusal from mappings or exception.error ducks.
registered_agentsfunctionEvery entry point marked with @donkey.agent in this process, in decoration order.
registered_toolsfunctionEvery callable marked with @donkey.tool in this process, in decoration order. The introspection entry point for the scanner / card generator.
typed_refusalsfunctionRe-raise a governance refusal from the block as its typed DonkeyError.
Last updated on