pub struct Agent<M, H = (), C = M, Schema = HandoffDocument> { /* private fields */ }Expand description
An autonomous agent that runs a conversation with a language model, executing the tool calls it makes.
The agent manages conversation context, handles tool execution in a loop,
and applies context compression when needed. Unlike the raw LanguageModel
trait which only emits events, the agent handles the full tool execution
cycle.
§Type Parameters
M: The conversation modelH: Composed hooks for customizing behavior (defaults to())C: The optional compaction model, seeAgentBuilder::compaction_model(defaults toM; unused while none is set)Schema: theHandoffSchemaevery compaction asks the model for;HandoffDocumentunless the builder’shandoffsets another.
Compaction runs on the conversation model, so it reads the conversation’s prompt cache, unless a compaction model is set.
§Example
let agent = Agent::new(claude);
let response = agent.query("What is 2+2?").await?;Implementations§
Source§impl<M: LanguageModel> Agent<M>
impl<M: LanguageModel> Agent<M>
Sourcepub fn with_config(llm: M, config: AgentConfig) -> Self
pub fn with_config(llm: M, config: AgentConfig) -> Self
Creates a new agent with the specified configuration.
Sourcepub fn builder(llm: M) -> AgentBuilder<M>
pub fn builder(llm: M) -> AgentBuilder<M>
Returns a builder for more complex agent construction.
Source§impl<M, H, C, Schema> Agent<M, H, C, Schema>
impl<M, H, C, Schema> Agent<M, H, C, Schema>
Sourcepub async fn keep_cache_warm(&mut self) -> Result<Option<Usage>, AgentError>
pub async fn keep_cache_warm(&mut self) -> Result<Option<Usage>, AgentError>
Re-sends the last request to refresh the cache entry of an idle agent.
Re-sends the last request with no output (max_tokens: 0,
non-streaming, the same thinking and effort settings), so the
provider restarts the entry’s lifetime. The history is untouched, the
request’s usage is recorded in cache_stats and
the entry’s cache_warmth restarts. The caller
decides when to call it, shortly before the entry goes cold.
Returns the request’s usage so the caller can account for its cost
(all fields empty when the provider reported none), or None when
there is nothing to refresh: no request was sent yet, or the entry is
permanent or already cold.
§Errors
Returns the provider error when the keep-alive request fails.
Sourcepub fn cache_warmth(&self) -> CacheWarmth
pub fn cache_warmth(&self) -> CacheWarmth
A shared handle on whether the provider’s prompt-cache entry for this agent’s context is warm and how long until it goes cold. It keeps tracking this agent’s later requests and keep-alives.
Sourcepub const fn cache_lifetime(&self) -> CacheLifetime
pub const fn cache_lifetime(&self) -> CacheLifetime
How long the provider’s prompt-cache entry for this agent’s context stays warm without a hit.
Sourcepub async fn query(&mut self, prompt: &str) -> Result<String, AgentError>
pub async fn query(&mut self, prompt: &str) -> Result<String, AgentError>
Performs a one-shot query and returns the final response.
This is the simplest way to use the agent. The agent handles tool execution internally and returns the final text response.
§Errors
Returns an error if:
- The LLM returns an error
- A hook aborts the operation
- Tool execution fails
- The run paused (
AgentError::Paused) or was cancelled (AgentError::Cancelled) before it had a reply
Sourcepub fn run(
&mut self,
prompt: &str,
attachments: impl IntoIterator<Item = Attachment>,
) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
pub fn run( &mut self, prompt: &str, attachments: impl IntoIterator<Item = Attachment>, ) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
Starts a run on prompt; Run::drive runs it and hands each event
to the caller as it happens, text chunks as they arrive from the LLM.
§Example
use std::ops::ControlFlow;
let mut shown = String::new();
agent
.run("Implement the feature", std::iter::empty())
.drive(&mut shown, std::future::pending(), |shown, timed| async move {
if let AgentEvent::BlockDelta { kind: OutputKind::Text, text, .. } = timed.event {
shown.push_str(&text);
}
ControlFlow::<(), _>::Continue(shown)
})
.await?;Sourcepub fn resume(
&mut self,
) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
pub fn resume( &mut self, ) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
Continues the conversation without a new user message, so the model
acts on the messages the host added with
push_message. Driven like run.
Sourcepub fn register_tool<T: Tool + 'static>(
&mut self,
tool: T,
) -> Result<(), RegisterError>
pub fn register_tool<T: Tool + 'static>( &mut self, tool: T, ) -> Result<(), RegisterError>
Registers a tool for the agent to use.
§Errors
Returns RegisterError if the
name collides with a registered tool, or the tool has no description.
Sourcepub const fn context_mut(&mut self) -> &mut Context
pub const fn context_mut(&mut self) -> &mut Context
Returns a mutable reference to the unified context manager.
Use this to insert/update system blocks, push messages, etc.
Sourcepub fn push_message(&mut self, message: Message)
pub fn push_message(&mut self, message: Message)
Adds a message to the conversation history.
Sourcepub const fn cache_stats(&self) -> &CacheStats
pub const fn cache_stats(&self) -> &CacheStats
Returns the rolling KV-cache statistics for this agent session.
The stats are updated every time the underlying provider emits a
Usage event (which, for providers like Claude with prompt
caching, includes cache_read_tokens and cache_write_tokens).
Hosts can read the hit rate, reset the accumulator, or snapshot
it for per-turn diffs.
Sourcepub const fn cache_stats_mut(&mut self) -> &mut CacheStats
pub const fn cache_stats_mut(&mut self) -> &mut CacheStats
Returns a mutable reference to the KV-cache statistics accumulator.
Hosts typically only use this to CacheStats::reset between
distinct sessions, since the agent itself records new observations.
Sourcepub fn clear_history(&mut self)
pub fn clear_history(&mut self)
Clears the conversation history.
Sourcepub fn compact(
&mut self,
focus: Option<&str>,
) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
pub fn compact( &mut self, focus: Option<&str>, ) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
Compacts the conversation by generating a structured handoff and
starting fresh, focused on focus when one is given. Driven like
run.
The run emits AgentEvent::CompactionStarted and then
AgentEvent::CompactionEnded, whose
CompactionOutcome carries the CompactResult when the handoff
applied. A compaction forked earlier alongside a run is stale once this
one starts: it finishes as CompactionOutcome::Discarded first.
§Errors
drive returns the failure when handoff generation
fails, after the finish event reported it.
Sourcepub fn parameters(&self) -> &Parameters
pub fn parameters(&self) -> &Parameters
The parameters of the requests the agent sends on its model.
Sourcepub fn set_parameters(&mut self, parameters: Parameters)
pub fn set_parameters(&mut self, parameters: Parameters)
Changes the parameters of the requests sent on the model, from the next request on.
A reasoning effort change keeps the prompt cache warm when the model
takes per-message effort updates
(Ability::PerMessageEffort):
the next request carries the update inside the conversation, before
the next user message when one starts the turn, and the request-level
effort stays as the first request sent it. Clearing the effort there
is an update to the model’s documented default
(Profile::default_reasoning_effort);
with none recorded, the next turn fails with AgentError::Config
rather than leave the earlier level in force. Any other model, and any
other parameter, takes the new value at the request level, which
restarts the cache.
Sourcepub fn set_model(&mut self, model: M)
pub fn set_model(&mut self, model: M)
Replaces the conversation model.
The next request goes to model; history, context and tools stay. A
new model reads none of the old one’s prompt cache, so the change
applies at once. A compaction already running finishes on the model it
started on.
Sourcepub fn idle_compaction_due_in(&self) -> Option<Duration>
pub fn idle_compaction_due_in(&self) -> Option<Duration>
How long from now the idle compaction is due: Some(Duration::ZERO)
when it is due now, None when none is pending.
The window is compacted once, shortly before the conversation’s cache
lifetime ends (ContextPolicy::idle_compact_before_expiry ahead of
it), counted from the entry’s last use, so the compaction reads the
still-warm cache. None is pending when:
- a compaction model is set, which cannot read that cache;
- the lifetime is
CacheLifetime::Permanent; - nothing has been sent yet, or the conversation is empty;
- the context holds fewer tokens than the policy’s
compaction_floor; - it already ran since the last request;
- the cache has expired already, when compacting would only pay to write the whole context again.
The agent has no timer of its own: the host sleeps this long while the
session is idle, then calls compact_when_idle.
Sourcepub fn compact_when_idle(
&mut self,
) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
pub fn compact_when_idle( &mut self, ) -> Run<impl Future<Output = Result<(), AgentError>> + '_>
Compacts the idle session once its cache is about to expire.
Runs one compaction through the normal fork and apply path when
idle_compaction_due_in says it is due
now, and returns None otherwise, so a host may call it whenever its
idle timer fires. One idle gap compacts once: the next request re-arms
it. Nothing is kept across the handoff, so no thinking produced under
the old prefix is replayed after it.
Driven like compact, and emits its compaction
events only when the compaction is due; otherwise the run emits
nothing.
§Errors
drive returns the compaction failure; the window is
left as it was.
Sourcepub async fn export_checkpoint(&mut self) -> Result<AgentCheckpoint, AgentError>
pub async fn export_checkpoint(&mut self) -> Result<AgentCheckpoint, AgentError>
Export a checkpoint bundle for restart-safe persistence.
§Errors
Returns an error when checkpoint construction or checkpoint hooks fail.
Sourcepub fn restore_checkpoint(
&mut self,
checkpoint: AgentCheckpoint,
) -> Result<(), AgentError>
pub fn restore_checkpoint( &mut self, checkpoint: AgentCheckpoint, ) -> Result<(), AgentError>
Restore a previously exported checkpoint bundle.
§Errors
Returns an error when the checkpoint cannot be restored into this agent.
Sourcepub async fn snapshot_context_window(
&mut self,
) -> Result<ContextWindowSnapshot, AgentError>
pub async fn snapshot_context_window( &mut self, ) -> Result<ContextWindowSnapshot, AgentError>
Returns a structured snapshot of the current context window.
This is a pure measurement: no source baseline is advanced and no alert is consumed, so a host may poll it as often as it likes.
§Errors
Returns an error when the model profiles cannot be fetched during initialization.
Sourcepub const fn identity(&self) -> &AgentIdentity
pub const fn identity(&self) -> &AgentIdentity
The identity this agent was built with.
Sourcepub const fn profile(&self) -> Option<&ModelProfile>
pub const fn profile(&self) -> Option<&ModelProfile>
Returns the model profile if available.
Sourcepub async fn preview_request_messages(
&mut self,
prompt: &str,
attachments: impl IntoIterator<Item = Attachment>,
) -> Result<Vec<Message>, AgentError>
pub async fn preview_request_messages( &mut self, prompt: &str, attachments: impl IntoIterator<Item = Attachment>, ) -> Result<Vec<Message>, AgentError>
Returns the exact request message sequence that would be sent for the next turn.
Intended for observability and debug UIs: the prompt is added to a forked context and the sources are rendered without committing, so a preview cannot consume a change the real request should surface.
§Errors
Returns an error when the model profiles cannot be fetched during initialization.
Sourcepub async fn preview_request_messages_with(
&mut self,
prompt: &str,
extra_messages: impl IntoIterator<Item = Message>,
attachments: impl IntoIterator<Item = Attachment>,
) -> Result<Vec<Message>, AgentError>
pub async fn preview_request_messages_with( &mut self, prompt: &str, extra_messages: impl IntoIterator<Item = Message>, attachments: impl IntoIterator<Item = Attachment>, ) -> Result<Vec<Message>, AgentError>
Returns the exact request message sequence that would be sent for the
next turn, with extra_messages appended at the conversation tail
before the prompt.
This is the non-mutating counterpart of pushing those messages onto the live context and then running the turn — the shape a host gets for per-turn hidden context injected ahead of the user’s message. The extras are not persisted: the context and the sources’ committed state are left exactly as a normal first assembly would, because sources are only told about a request once it is actually sent.
The tail and the stable blocks are the ones the request would carry:
the sources are asked through [ContextSource::peek] and the
before_request hook is asked as it would be, so nothing a source
holds for delivery is consumed. A live source’s change is not
previewed, since staging it writes to the context.
§Errors
Returns an error when the model profiles cannot be fetched during initialization.
Trait Implementations§
Source§impl<M, H, C, Schema> ChildAgent for Agent<M, H, C, Schema>
impl<M, H, C, Schema> ChildAgent for Agent<M, H, C, Schema>
Source§async fn run(
&mut self,
prompt: &str,
events: &ChildEvents,
cancel: CancelSignal,
) -> RunOutcome
async fn run( &mut self, prompt: &str, events: &ChildEvents, cancel: CancelSignal, ) -> RunOutcome
prompt until it ends, and says how it ended.