adk-core
Core traits and types for ADK-Rust agents, tools, sessions, and events.
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
Overview
adk-core provides the foundational abstractions for ADK-Rust. Every other ADK crate builds on the traits and types it defines:
Agent— the abstraction every agent implementsTool/Toolset— capabilities an agent can callLlm— the interface every model provider implementsSchemaAdapter— provider-aware JSON Schema normalization for tool declarations- Context hierarchy —
ReadonlyContext→CallbackContext→ToolContext/InvocationContext Content/Part— message contentEvent/EventActions— the event stream an agent producesSession/State— conversation contextAdkError— the structured error envelope- Governance —
ToolPolicy,authorize_tool_call,GovernanceControl, approvals, run budgets, and the spend ledger - Computer actuation —
ComputerActuator,ComputerAction,Screenshot: the provider-neutral trait computer use tools act through, andTool::batch_groupfor calls that run in order and stop at the first failure - Durable runtime contracts —
LeaseStore,DurableRunStore,ScheduleStore,GovernanceStateStore,ActionLedger,ApprovalStore,SpendLedger,AuditLogStore
The crate contains no model provider client.
Installation
[]
= "3.0.0"
Or use the umbrella crate:
[]
= "3.0.0"
Feature Flags
No feature is enabled by default.
| Feature | Enables |
|---|---|
rustls |
ensure_crypto_provider() installs the aws-lc-rs rustls provider process-wide |
conformance |
The conformance module: the *_conformance_tests! suites for durable store backends |
cron |
Cron schedules in IANA time zones for ScheduleStore and schedule::plan_fires |
webhooks |
The webhook module: Standard Webhooks signing, verification, and replay protection |
egress-dns |
egress::SystemResolver: the operating system resolver for egress checks |
egress-client |
egress::GuardedClient and egress::EgressResolver: HTTP clients that enforce an EgressPolicy (implies egress-dns) |
webhook-delivery |
The webhook_delivery module: signed outbound webhook delivery (implies webhooks, egress-client) |
auth-bridge |
request_context::RequestContextExtractor, the trait an HTTP server authenticates requests through |
ort |
The onnx module: the process's one ONNX Runtime environment, which ort allows once per process and adk-audio, adk-rag and adk-vision share |
Core Traits
Agent
| Method | Default | Purpose |
|---|---|---|
name() |
required | Unique name within the agent tree |
description() |
required | Returns &str; shown to models that route between agents |
sub_agents() |
required | Child agents; return &[] for a leaf agent |
run(ctx) |
required | Returns Result<EventStream> |
allows_transfer_to_parent() / allows_transfer_to_peers() |
true |
Transfer restrictions the runner enforces for every transfer |
screen_user_input(content) |
screens with each sub-agent | Input guardrails the runner applies before it saves a user message; a wrapper whose inner agent is not a sub-agent delegates to it |
close() |
closes each sub-agent | Releases what the agent holds; Runner::close calls it |
EventStream is Pin<Box<dyn Stream<Item = Result<Event>> + Send>>.
Tool
use Arc;
use ;
use async_trait;
use ;
;
| Method | Default | Purpose |
|---|---|---|
parameters_schema() / response_schema() |
None |
JSON Schemas sent to the model |
is_long_running() |
false |
The call returns before its work completes |
is_read_only() |
false |
The call has no side effects |
is_concurrency_safe() |
false |
The call can run beside other calls |
is_agent_delegation() |
false |
The tool delegates to another agent |
effect() |
ReadOnly when is_read_only(), else NonIdempotent |
Governs retries, the action ledger, and DeclarativePolicy effect rules |
timeout_override() |
None (the agent's tool timeout) |
Some(None) removes the timeout; Some(Some(d)) sets one |
origin() |
STATIC_TOOL_ORIGIN ("static") |
Where the tool came from; MCP tools report mcp:{toolset name} |
annotations() |
None |
Behaviour annotations the tool's publisher declared |
egress(args) |
ToolEgress::Undeclared |
Network destinations the call reaches; a run with an egress policy refuses an undeclared call |
required_scopes() |
&[] |
Scopes the caller must hold |
Only ReadOnly and Idempotent tools are retried, and only after a retryable error or a timeout. With an ActionLedger on RunConfig::action_ledger (InMemoryActionLedger here, SqliteActionLedger and the other backends in adk-session), a NonIdempotent call executes at most once per ToolContext::idempotency_key(); a replay of a call that never recorded an outcome is answered with outcome_unknown_response() instead of executing again.
An answer an agent writes in place of a tool's result — a refusal, a hold, a failure, a withheld result, an unknown outcome, a ledger replay — carries a ToolResultStatus (refused, not_run, held, failed, outcome_unknown, withheld, succeeded) in the function response's annotations, read with Part::tool_result_status(), beside the code and category of the error behind it. The payload the model reads is unchanged.
ToolExecutionStrategy::Auto keeps the LLM-returned order and overlaps a call with its adjacent neighbours only when the selected tool returns true from both is_read_only() and is_concurrency_safe(). Every other call runs alone, in its place: it starts after the calls listed before it finish, and the calls listed after it wait for it. The guarantee is ordering only — a write that is held for confirmation, refused, skipped or failed has changed nothing when the next call runs.
ensure_unique_tool_names fails with agent.duplicate_tool_name (DUPLICATE_TOOL_NAME_CODE) when two tools share a name; LlmAgentBuilder::build and the other agent builders run the same check.
Toolset
use Arc;
use ;
use async_trait;
process_llm_request adds toolset-specific guidance to each model request, and close releases connections or subprocesses; both default to doing nothing.
Llm
| Method | Default | Purpose |
|---|---|---|
name() |
required | Model identifier |
generate_content(request, stream) |
required | Returns Result<LlmResponseStream> |
schema_adapter() |
GenericSchemaAdapter |
Provider-specific schema normalization |
max_cost_micro_usd(request) |
None |
Upper bound on the request's cost; a spend cap refuses a model that returns None |
context_window() |
None |
The model's context window in tokens; auto-compaction sets its threshold from it, or uses 100,000 tokens without one |
native_web_search() |
None |
The provider-executed web search the model's transport serves |
native_compaction() |
None |
The conversation compaction the model's provider performs itself; auto-compaction asks it for the summary (NativeCompactionRequest) and keeps its signed result (is_native_compaction) |
data_locality() |
DataLocality::Remote |
Where a call's request data goes: InProcess, Loopback (a server on this machine) or Remote; guardrails read it to tell which calls leave the machine |
Wrappers around another Llm forward max_cost_micro_usd, context_window, native_web_search, native_compaction, and data_locality; a wrapper over several models reports DataLocality::least_local of them.
SchemaAdapter
normalize_schema (required), normalize_tool_name, empty_schema, and parameters_field adapt tool declarations to a provider's schema dialect. Each Llm returns its adapter from schema_adapter(); GenericSchemaAdapter is the default.
Key Types
Content and Part
use Content;
Part variants: Text, Thinking, InlineData, FileData, FunctionCall, FunctionResponse, ServerToolCall, ServerToolResponse, and EmbeddedResource. Content::with_inline_data() and Part::inline_data() panic above 10 MB (MAX_INLINE_DATA_SIZE).
Multimodal Function Responses
A tool returns images, audio, or file references alongside JSON:
use ;
use ;
// A tool result with `inline_data` or `file_data` arrays is split into parts
// by `FunctionResponseData::from_tool_result`.
Event
use Event;
Complete Response Snapshots
Terminal events marked with llm_response.provider_metadata.content_complete contain the complete response for their event ID, including earlier streamed text. Preserve the original event for persistence and replacement-aware UIs. Append-only output can use one EventTextDeltas adapter per live stream:
use ;
use StreamExt;
async
The adapter preserves tool parts, thinking signatures, actions, and usage. A non-prefix correction is returned in full because append-only output cannot retract text already rendered.
Tool Events
Events expose typed views of tool activity, so UIs render tool calls and results without matching Part internals:
use Event;
call_id correlates a call with its result and its progress chunks. A tool pushes intermediate output with ToolContext::emit_progress("stdout", chunk); the framework forwards each chunk as a partial event on the same EventStream. The default emit_progress does nothing.
EventActions
| Field | Purpose |
|---|---|
state_delta |
State updates |
artifact_delta |
Artifact versions saved by the event |
skip_summarization |
End the turn on a tool result without another model call |
transfer_to_agent |
Agent transfer |
escalate |
Escalate to the parent |
tool_confirmation / tool_confirmation_decision |
A call held for confirmation, and its decision |
compaction |
An EventCompaction summary that replaces earlier events |
route |
Target node names for dynamic routing in graph workflows |
input_screened |
The runner screened this user message with input guardrails |
workflow_positions |
Where each workflow agent stopped on a held call |
steering |
A user message that reached the run through Runner::steer |
grounding_sources |
Sources a tool call retrieved, which citation checks match against |
EventActions derives Default; struct literals end with ..Default::default().
Tool Context Engineering
| Type | Purpose |
|---|---|
ResolvedContext |
A system instruction together with the Arc<dyn Tool> instances it describes |
ToolRegistry |
Maps tool names from configuration or skills to tool instances |
ValidationMode |
Strict (default) rejects a request that names a missing tool; Permissive binds the tools that exist and logs a warning |
Context Hierarchy
ReadonlyContext
├── invocation_id(), agent_name(), user_id(), app_name(), session_id(), branch()
├── user_content()
└── acting_context()
CallbackContext (extends ReadonlyContext)
├── artifacts()
└── shared_state()
ToolContext (extends CallbackContext)
├── function_call_id(), idempotency_key()
├── actions() / set_actions()
├── search_memory()
└── emit_progress()
InvocationContext (extends CallbackContext)
├── agent(), memory(), session()
├── run_config()
└── end_invocation() / ended()
Context wrappers forward acting_context(); otherwise they report the derived identity.
Error Handling
AdkError carries a component, a category, a stable code, a message, a retry hint, and details:
use ;
let err = new
.with_provider
.with_upstream_status;
assert!;
assert_eq!;
let _problem = err.to_problem_json;
let _log_line = err.diagnostics.to_string; // everything but the message
| Category | HTTP | Retryable by default |
|---|---|---|
InvalidInput |
400 | no |
Unauthorized |
401 | no |
Forbidden |
403 | no |
NotFound |
404 | no |
Timeout |
408 | yes |
Conflict |
409 | no |
RateLimited |
429 | yes |
ResourceExhausted |
429 | no |
Cancelled |
499 | no |
Internal |
500 | no |
Unsupported |
501 | no |
Unavailable |
503 | yes |
ResourceExhausted covers a used-up run budget and a provider account out of quota, credit, or spend limit; neither is retried within the run. ErrorCategory is not #[non_exhaustive], so exhaustive matches list every category. upstream_excerpt and json_error_summary keep upstream text and JSON values out of messages and logs.
Governed Tool Execution
LlmAgent and CodeActAgent run each tool call through authorize_tool_call after plugin and callback rewrites and immediately before Tool::execute:
| Step | Type | Effect |
|---|---|---|
| Kill switch | GovernanceControl |
A frozen run ends with a governance.frozen error |
| Resume binding | GovernedCall::resuming |
A resumed held call runs only for the agent that held it, on a tool with the ToolOrigin it was held for |
| Policy | ToolPolicy, DeclarativePolicy, StrictestPolicy |
Allow, deny, or require approval; DeclarativePolicy denies unlisted tools; evaluate_call also receives the tool's ToolOrigin and the call ID (PolicyCall); StrictestPolicy applies several policies and keeps the strictest decision |
| Screen | ToolCallScreen |
The agent's guardrails; a rewrite is checked against the policy again |
| Confirmation | ToolApproval, ApprovalStore, ToolConfirmationHandler::decide_approval |
A live handler may return edited arguments, checked against the policy again, or a denial message. Decisions bind to the call's fingerprint — acting agent, tool origin and declaration digest, tool name, arguments, and the digests of any evidence the call is held with — so they survive a re-issued call ID and never authorize another agent's call, another server's tool, or a call whose image changed |
| Evidence | Tool::approval_evidence, Evidence, ImageEvidence, ArtifactLocator |
A held call carries the exact image it would send, by digest and artifact; ToolConfirmationRequest, ApprovalRequest and ApprovalRoute hold it, and audit records name its digests |
| Model reviewer | ToolReviewer, ModelApprover, ReviewScope, ReviewVerdict |
Opt-in approver before a person (RunConfig::tool_reviewer): approves, denies or escalates a call the policy holds, never a denied, confirmation-policy, requested or already-held one; an isolated model request with the call and the user's recent messages as untrusted data, a confidence floor, an audited verdict filed in the inbox as model:<id> (ApprovalService::record_review), metered against the run budget |
| Approval service | ApprovalService, StoreApprovalService, ApprovalPolicy |
An inbox over the approval store: quorum, slots filled by distinct approvers, an approver directory, delegation, escalation, expiry, and edit / reject / respond actions with compare-and-swap decisions. route_unrouted files held calls under a host's router, such as a kernel's inbox, and add_notifier adds an ApprovalNotifier to a service already built; wrappers forward both |
use ;
use json;
let policy = builder
.allow_read_only
.rule
.build;
let request = new;
assert!;
Build a fingerprint from the request a held call surfaced, or with ToolConfirmationRequest::for_tool(tool, args).with_acting_context(..); tool_call_fingerprint(name, args) alone, or a request without an acting agent, matches no call, and RunConfigBuilder::tool_approval refuses such a fingerprint (ToolConfirmationRequest::fingerprint_agent). ToolApproval::approve() and ToolApproval::deny() take with_edited_args, with_message, and an expiry.
Provider-executed built-in tools (Gemini Google Search, OpenAI hosted web search, Anthropic web search, and the others) never reach authorize_tool_call. BuiltinToolGovernor applies the kill switch, the tool-call budget, and the policy to them before each model request: a denied tool, or one that needs an approval that does not exist yet, is withheld from the request. The uses a provider reports are counted in UsageMetadata::builtin_tool_uses, against the run's tool-call budget, and in UsageMetadata::cost.
Agent Identity
Every run has an acting agent. AgentId, AgentPrincipal, and ActingContext (module principal) identify it; ActingConfig (module acting, on RunConfig::acting) maps agent names to principals and pins the subject to the session's user. Without configuration an agent acts as urn:adk:agent:{app}/{agent}. IdentitySource, StaticIdentitySource, and CredentialBroker (module credential) resolve principals and mint audience-bound ScopedTokens. PolicyRule::for_agent, for_tenant, and for_class restrict a policy rule to an acting agent.
Network Egress
egress::EgressPolicy is a host, port and CIDR allowlist with a pure decide(), intersected by narrow() so lower layers only tighten an operator's ceiling; cloud metadata endpoints are always refused and non-public addresses need an explicit CIDR rule or with_private_networks(). egress::classify is the one address classifier the workspace shares. egress::ContextUrls collects the URLs a conversation's user messages and tool results hold, so a fetch tool can refuse a URL the model composed to carry data out. egress::GuardedClient (feature egress-client) checks every request URL, every resolved address and every redirect hop, ignores proxy settings, and fails to build rather than fall back to an unguarded client; its get and post return a reqwest 0.13 RequestBuilder. See Network Egress Policy.
Run Budgets and Spend
RunBudget limits model calls, total tokens, cost (micro-USD), wall time, tool calls, and usage per unit (max_units); RunConfig::budget carries it and RunConfig::budget_tracker carries the shared BudgetTracker. A violation converts to an AdkError with category ResourceExhausted and a budget.* code.
use ;
let tracker = new;
assert!;
assert!;
SpendLedger holds one budget for model calls and payments: reserve holds an amount against every SpendLimits cap that covers a SpendKey (org, agent, vendor; day, month, or lifetime in UTC), commit records the actual amount, and release drops the hold. Unsettled holds expire after a TTL. InMemorySpendLedger is the process-local implementation; adk-session provides SQLite, PostgreSQL, Redis, MongoDB, Neo4j, and Firestore ledgers. Set RunConfig::spend_ledger to cap a run; a refused reservation fails with spend.limit_exceeded. with_clock takes a Clock; ManualClock lets a test cross a day or month boundary.
use ;
let ledger = new;
ModelCallScope applies the run budget and the spend ledger to model calls made outside an agent's own loop — compaction summaries, LLM routing, MCP sampling. generate_metered and MeteredLlm meter against the scope made current with ModelCallScope::within. LlmResponse carries model and provider so usage and cost are attributable.
Calls billed in units rather than tokens — images, audio, characters — go through ModelCallScope::meter or meter_usage: the spend hold covers UsageCall::max_cost_micro_usd before the call is sent, and MeteredUsage commits the cost in micro-USD and counts its UsageVector (UsageUnit::Images, AudioMillis, Characters, …) in BudgetTracker::units. A unit call with no known price is refused under a cost cap. A call that declares its units (UsageCall::with_units) is held against RunBudget::max_units before it is sent and refused with budget.units, naming the unit and the cap, when it would pass one. Agents make the run's scope current around every tool call (ModelCallScope::within_tool), so media calls in tools count against the run. UnitRate prices a unit in integer micro-USD, with an optional per-request minimum (with_minimum_per_request); UsageUnit::Frames counts video frames.
Typed Decisions
decide::<T>(model, input) has a model pick one value of a Choice type, such as an enum of
routes, and returns a Decision with the option's name, the model's rationale and its
confidence. The request carries a JSON response schema whose choice enumerates the options,
declares no tool and forces no tool_choice; a reply that names no option fails with
decision.invalid_choice. Decider adds an instruction, an explicit ModelCallScope and
decide_among for options known only at run time; without an explicit scope the call is
metered against the current one. adk-agent's DecisionAgent and adk-graph's
DecisionNode route on it, and adk-rust-macros derives Choice for an enum.
use Arc;
use ;
async
Audit Records
AuditRecorder (module audit_log) receives a record for every governed tool decision, approval decision, kill-switch change, and outcome_unknown answer; InMemoryAuditRecorder keeps them in memory and FileAuditRecorder appends them to a JSON Lines file that survives a restart. Each record names the acting agent and the subject it acts for and carries an argument digest, never the arguments. Under AuditFailureMode::Block (the default) an action whose record cannot be written does not happen. AuditLogStore and InMemoryAuditLogStore hold append-only logs with a compare-and-swap on the log size; adk-auth's signed_audit::AuditLog signs them. AuditLogStore::redact drops chosen record bodies and keeps their hashes; subject::PseudonymousRecorder names visitors (or every subject) by registry pseudonym, and subject::AuditLogSubjectData redacts the records that name a subject being erased.
Subject Rights
Module subject holds what a deployment needs to know whom it holds data about and to act on that person's data across stores. SubjectKind::Visitor names a person known only by a random VisitorId; a visitor's run is never authenticated and a visitor cannot decide an approval. ConsentStore keeps ConsentRecords per subject and ConsentPurpose; SubjectRegistry keeps each subject's pseudonym, links, and erasure state. SubjectRights exports, erases, and links a subject over every registered SubjectDataStore adapter and reports each store's outcome — erased, scheduled, unsupported, unreachable, or failed — so no store is skipped silently. InMemorySubjectRegistry and InMemoryConsentStore are the reference implementations, and subject_registry_conformance_tests!, consent_store_conformance_tests!, and subject_data_store_conformance_tests! (feature conformance) prove other backends. See Subject Rights.
Background Sub-Agents
adk_core::subagent is the contract for sub-agents a parent starts and does not wait for:
SubagentHost (start, get, list, send, cancel, scoped to the parent's session by
SubagentScope), SubagentStatus (queued, running, waitingForHuman, parked,
completed, failed, cancelled), SubagentLaunch (what a sub-agent's runs carry), the
notice a parent receives (subagent_notice), and ToolCeiling, the policy that keeps a
sub-agent to its parent's tools. BudgetTracker::carve takes a sub-agent's budget slice out
of what the parent's run has left; RunBudget serializes, RunBudget::narrowed combines two
budgets into the stricter, and RunLimits is what an agent run's input narrows its runner by. adk-server (DurableSubagents) and adk-kernel
(Kernel::subagents) host them; see
Background sub-agents.
Durable Runtime Contracts
Backend-neutral traits for running agents durably across replicas, each with an in-memory implementation that takes a Clock through with_clock:
| Trait | In-memory | Holds |
|---|---|---|
LeaseStore |
InMemoryLeaseStore |
Leases with fencing epochs |
DurableRunStore |
InMemoryRunStore |
The run queue: claims, heartbeats, waits, retries, cancellation |
ScheduleStore |
InMemoryScheduleStore |
Cron, one-shot, and interval schedules with a revision compare-and-swap |
GovernanceStateStore |
InMemoryGovernanceStateStore |
Freeze state per organisation, tenant, and agent |
ActionLedger |
InMemoryActionLedger |
Begun and completed non-idempotent tool calls |
ApprovalStore |
InMemoryApprovalStore |
Pending approvals, decisions, and delegations |
SpendLedger |
InMemorySpendLedger |
Spend reservations and committed spend |
AuditLogStore |
InMemoryAuditLogStore |
Append-only audit logs and checkpoints |
A retryable RunOutcome::Failed with attempts left requeues the run, claimable once its backoff has passed; RetryBackoff computes a jittered, doubling wait that honours an error's Retry-After. NewRun::with_service_subject marks a scheduled, webhook, or queue run as acting for a service. schedule::plan_fires computes fire times; cron specs need the cron feature. GovernanceControl::mirrored mirrors a shared GovernanceStateStore, so a freeze on one replica reaches every replica.
use Duration;
use ;
use json;
async
Store Conformance Suites
The conformance feature provides one suite per durable store trait. A backend implements a harness that opens it and calls the matching *_conformance_tests! macro, which generates one #[tokio::test] per contract case: accounting, period rollover, fencing, single-winner concurrency across two handles, and restart survival. Every in-memory and adk-session backend runs the same suites.
[]
= { = "3.0.0", = ["conformance"] }
Wake-ups and Webhooks
| Module | Feature | Provides |
|---|---|---|
webhook |
webhooks |
Standard Webhooks WebhookSigner / WebhookVerifier (timestamp tolerance, several secrets for rotation), WebhookReplayGuard |
webhook_delivery |
webhook-delivery |
WebhookDelivery: signed outbound POSTs with exponential backoff and jitter, a DeadLetterSink, and an egress::EgressPolicy enforced at resolve time |
queue_source |
— | QueueSource (pull, ack, nack), InMemoryQueueSource, and QueueIngress, which enqueues each message as a durable run keyed by its message id and acks only after the enqueue succeeds |
queue_source_conformance_tests! (feature conformance) checks any QueueSource. See Wake-ups and Webhooks.
State Management
State keys use prefixes for scope:
| Prefix | Scope |
|---|---|
user: |
The user, across sessions |
app: |
The application, across users |
temp: |
The current invocation; session services do not persist it |
use ;
use json;
validate_state_key() rejects keys that are empty, longer than MAX_STATE_KEY_LEN (256 bytes), or that contain /, \, .., or a null byte.
use validate_state_key;
assert!;
assert!;
Instruction Templates
inject_session_state fills {var} (required), {var?} (optional), prefixed {user:var} / {app:var} / {temp:var}, and {artifact.name} placeholders. ${x}, \{x}, and {{x}} stay literal, so instructions can quote shell, JavaScript, and template code.
Callbacks
| Alias | Receives | Returns |
|---|---|---|
BeforeAgentCallback / AfterAgentCallback |
Arc<dyn CallbackContext> |
Result<Option<Content>> |
BeforeModelCallback |
context, LlmRequest |
Result<BeforeModelResult> (Continue(request) or Skip(response)) |
AfterModelCallback |
context, LlmResponse |
Result<Option<LlmResponse>> |
HistoryProcessor |
context, the agent's history (Vec<Content>) |
Result<Vec<Content>>, the history the rest of the turn continues from |
BeforeToolCallback / AfterToolCallback |
Arc<dyn CallbackContext> |
Result<Option<Content>> |
AfterToolCallbackFull |
context, tool, arguments, response | Result<Option<Value>> |
OnToolErrorCallback |
context, tool, arguments, error message | Result<Option<Value>> |
InstructionProvider / GlobalInstructionProvider |
Arc<dyn ReadonlyContext> |
Result<String> |
Each alias boxes an async closure: Box<dyn Fn(..) -> Pin<Box<dyn Future<Output = ..> + Send>> + Send + Sync>. InvocationHooks carries run-wide hooks (the runner's plugins) that agents run ahead of their own callbacks.
Context Compaction
EventsCompactionConfig configures compaction: compaction_interval (compaction runs when the session's user-message count is a multiple of it), overlap_size (the most recent invocations left out of the summary), and a summarizer implementing BaseEventsSummarizer. Compaction never covers a call still held for confirmation (held_call_compaction_limit).
IntraCompactionConfig sets auto-compaction, which is on by default: before each model call an agent passes its history to RunConfig::history_compactor (a HistoryCompactor, which the runner installs), and the compactor summarizes it once the request passes the threshold.
| Field | Default | Meaning |
|---|---|---|
enabled |
true |
IntraCompactionConfig::disabled() turns auto-compaction off |
token_threshold |
None |
A fixed threshold in estimated tokens (IntraCompactionConfig::at_tokens(n)); None derives it from the model's window |
context_window_fraction |
0.8 |
The share of Llm::context_window a request may reach (IntraCompactionConfig::at_window_fraction(f)); a model that reports no window compacts at 100,000 estimated tokens (intra_compaction::DEFAULT_TOKEN_THRESHOLD) |
overlap_event_count |
10 |
The most recent history entries kept as they are, within half the threshold (with_overlap_event_count) |
chars_per_token |
4 |
Characters per token for the estimate |
use ;
let config = RunConfig ;
RunConfig::intra_compaction overrides the runner's setting for one run. is_context_limit_error tells a model's rejection of a too-long request from other errors, and LlmEventSummarizer writes summaries for both.
Streaming Modes
StreamingMode is None (complete responses), SSE (the default), or Bidi (realtime).
ToolExecutionStrategy
| Strategy | Dispatch |
|---|---|
Sequential (default) |
One call at a time, in order |
Parallel |
Every call concurrently; does not inspect tool metadata |
Auto |
In order; adjacent read-only, concurrency-safe calls overlap |
Set per agent with LlmAgentBuilder::tool_execution_strategy().
Changes in 3.0
| Change | Migration |
|---|---|
ToolConfirmationRequest::fingerprint() names the acting agent and the tool's ToolOrigin |
Take fingerprints from the held call's request or ToolConfirmationRequest::for_tool |
ErrorCategory gains Conflict (409) and ResourceExhausted (429); a provider account out of quota or credit is ResourceExhausted, not RateLimited |
Add match arms |
RetryBudget gains max_delay; only ReadOnly and Idempotent tools are retried |
RetryBudget::new(..).with_max_delay(..); declare ToolEffect::Idempotent where a retry is safe |
RunConfig gains acting, action_ledger, approval_service, approval_store, audit, budget, budget_tracker, consent_gate, deny_on_confirmation_timeout, durable_run_id, egress_policy, governance, history_compactor, intra_compaction, invocation_hooks, llm_spend_estimate, request_context, request_metadata, requested_call, spend_ledger, tool_approvals, tool_confirmation_timeout, tool_policy, tool_reviewer, and transfer_target_descriptions |
End struct literals with ..Default::default() |
IntraCompactionConfig gains enabled and context_window_fraction; token_threshold is Option<u64>; auto-compaction runs before every model call and is on by default |
IntraCompactionConfig::at_tokens(n) replaces a literal; IntraCompactionConfig::disabled() turns it off |
Tool gains effect(), timeout_override(), origin(), annotations(), and egress(); Llm gains context_window(); ReadonlyContext gains acting_context(); Agent gains close(), screen_user_input(), and transfer flags |
Wrappers forward them |
LlmResponse gains model and provider; UsageMetadata gains builtin_tool_uses |
End struct literals with ..Default::default() |
inject_session_state leaves ${x}, \{x}, and {{x}} literal |
— |
See the 2.x to 3.0 migration guide and the changelog for the full list.
Related Crates
- adk-rust — umbrella crate with every component
- adk-agent — agent implementations
- adk-model — model providers
- adk-tool — tool implementations
- adk-runner — the execution runtime
License
Apache-2.0
Part of ADK-Rust
This crate is part of the ADK-Rust framework for building AI agents in Rust.