pub struct Agent<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> { /* private fields */ }Expand description
An autonomous agent that processes tasks using tiered language models.
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
Advanced: The primary LLM for main reasoning (most capable)Balanced: LLM for moderate tasks like subagents (defaults to Advanced)Fast: LLM for quick tasks like compaction (defaults to Balanced)H: Composed hooks for customizing behavior (defaults to())
§Model Tier Selection
Each agent uses one tier for its main reasoning loop (set via tier()):
- Main agent: typically
ModelTier::Advanced - Explore subagent:
ModelTier::Balanced(cheaper but capable) - Quick tasks:
ModelTier::Fast
The Fast tier is always used for compaction, regardless of main tier.
§Example
// Simple usage (all tiers use same model)
let agent = Agent::new(claude);
let response = agent.query("What is 2+2?").await?;
// With tiered models
let agent = Agent::builder(opus)
.balanced_model(sonnet)
.fast_model(haiku)
.build();
// Subagent using balanced tier
let explore_agent = Agent::builder(opus)
.balanced_model(sonnet)
.fast_model(haiku)
.tier(ModelTier::Balanced) // Use sonnet for reasoning
.build();Implementations§
Source§impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()>
impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()>
Sourcepub fn new(llm: LLM) -> Self
pub fn new(llm: LLM) -> Self
Creates a new agent with default configuration.
All model tiers (advanced/balanced/fast) use the same model.
Sourcepub fn with_config(llm: LLM, config: AgentConfig) -> Self
pub fn with_config(llm: LLM, config: AgentConfig) -> Self
Creates a new agent with the specified configuration.
All model tiers (advanced/balanced/fast) use the same model.
Source§impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()>
impl<LLM: LanguageModel + Clone> Agent<LLM, LLM, LLM, ()>
Sourcepub fn builder(llm: LLM) -> AgentBuilder<LLM, LLM, LLM, ()>
pub fn builder(llm: LLM) -> AgentBuilder<LLM, LLM, LLM, ()>
Returns a builder for more complex agent construction.
Source§impl<Advanced, Balanced, Fast, H> Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced, Fast, H> Agent<Advanced, Balanced, Fast, H>
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
Sourcepub fn run(
&mut self,
prompt: &str,
attachments: impl IntoIterator<Item = Attachment>,
) -> impl Stream<Item = Result<AgentEvent, AgentError>> + '_
pub fn run( &mut self, prompt: &str, attachments: impl IntoIterator<Item = Attachment>, ) -> impl Stream<Item = Result<AgentEvent, AgentError>> + '_
Runs the agent with streaming events.
Returns a stream of AgentEvents that can be consumed to observe
the agent’s progress in real-time. Text chunks are yielded as they
arrive from the LLM for true streaming display.
§Example
use futures::StreamExt;
let mut stream = agent.run("Implement the feature", std::iter::empty());
while let Some(event) = stream.next().await {
match event? {
AgentEvent::Text(t) => print!("{}", t),
AgentEvent::Complete { .. } => break,
_ => {}
}
}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 async fn kill_running_terminal_jobs(&self) -> usize
pub async fn kill_running_terminal_jobs(&self) -> usize
Stops every terminal task that is still running for this agent.
Returns the number of tasks that received a stop request.
Sourcepub fn clear_history(&mut self)
pub fn clear_history(&mut self)
Clears the conversation history.
Sourcepub async fn compact(
&mut self,
focus: Option<&str>,
) -> Result<Option<CompactResult>, AgentError>
pub async fn compact( &mut self, focus: Option<&str>, ) -> Result<Option<CompactResult>, AgentError>
Compacts the conversation by generating a structured handoff and starting fresh.
§Errors
Returns an error if handoff generation fails.
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) -> ContextWindowSnapshot
pub async fn snapshot_context_window(&mut self) -> ContextWindowSnapshot
Returns a structured snapshot of the current context window.
This is a pure measurement: it does not repopulate reminders or otherwise mutate the context.
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>,
) -> Vec<Message>
pub async fn preview_request_messages( &mut self, prompt: &str, attachments: impl IntoIterator<Item = Attachment>, ) -> Vec<Message>
Returns the exact request message sequence that would be sent for the next turn.
This is intended for observability/debug UIs and does not mutate agent memory. Temporarily adds the prompt to a forked context, builds the messages, then discards.
Trait Implementations§
Auto Trait Implementations§
impl<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> !RefUnwindSafe for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> !Unpin for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> !UnsafeUnpin for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced = Advanced, Fast = Balanced, H = ()> !UnwindSafe for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced, Fast, H> Freeze for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced, Fast, H> Send for Agent<Advanced, Balanced, Fast, H>
impl<Advanced, Balanced, Fast, H> Sync for Agent<Advanced, Balanced, Fast, H>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more