Skip to main content

Agent

Struct Agent 

Source
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, ()>

Source

pub fn new(llm: LLM) -> Self

Creates a new agent with default configuration.

All model tiers (advanced/balanced/fast) use the same model.

Source

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

Source

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>
where Advanced: LanguageModel, Balanced: LanguageModel, Fast: LanguageModel, H: Hook,

Source

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
Source

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,
        _ => {}
    }
}
Source

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.

Source

pub const fn context(&self) -> &Context

Returns a reference to the unified context manager.

Source

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.

Source

pub fn push_message(&mut self, message: Message)

Adds a message to the conversation history.

Source

pub fn set_transient_system_messages( &mut self, messages: impl IntoIterator<Item = String>, )

Replaces transient per-turn system messages.

Source

pub fn clear_transient_system_messages(&mut self)

Clears transient per-turn system messages.

Source

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.

Source

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.

Source

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.

Source

pub fn clear_history(&mut self)

Clears the conversation history.

Source

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.

Source

pub fn history(&self) -> Vec<Message>

Returns the current conversation history.

Source

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.

Source

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.

Source

pub async fn snapshot_context_window(&mut self) -> ContextWindowSnapshot

Returns a structured snapshot of the currently assembled context window.

Source

pub const fn profile(&self) -> Option<&ModelProfile>

Returns the model profile if available.

Source

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§

Source§

impl<Advanced: Debug, Balanced: Debug, Fast: Debug, H: Debug> Debug for Agent<Advanced, Balanced, Fast, H>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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>
where Advanced: Freeze, Balanced: Freeze, Fast: Freeze, H: Freeze,

§

impl<Advanced, Balanced, Fast, H> Send for Agent<Advanced, Balanced, Fast, H>
where Advanced: Send, Balanced: Send, Fast: Send, H: Send,

§

impl<Advanced, Balanced, Fast, H> Sync for Agent<Advanced, Balanced, Fast, H>
where Advanced: Sync, Balanced: Sync, Fast: Sync, H: Sync,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more