Skip to main content

Agent

Struct Agent 

Source
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

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>

Source

pub fn new(llm: M) -> Self

Creates a new agent with default configuration.

Source

pub fn with_config(llm: M, config: AgentConfig) -> Self

Creates a new agent with the specified configuration.

Source

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>
where Schema: HandoffSchema, M: LanguageModel + 'static, C: LanguageModel + 'static, H: Hooks,

Source

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.

Source

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.

Source

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.

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:

Source

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?;
Source

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.

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 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 fn clear_history(&mut self)

Clears the conversation history.

Source

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.

Source

pub fn parameters(&self) -> &Parameters

The parameters of the requests the agent sends on its model.

Source

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.

Source

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.

Source

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.

Source

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.

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

Source

pub const fn identity(&self) -> &AgentIdentity

The identity this agent was built with.

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

Source

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>
where Schema: HandoffSchema, M: LanguageModel + 'static, C: LanguageModel + 'static, H: Hooks,

Source§

async fn run( &mut self, prompt: &str, events: &ChildEvents, cancel: CancelSignal, ) -> RunOutcome

Runs the child on prompt until it ends, and says how it ended.
Source§

impl<M: Debug, H: Debug, C: Debug, Schema: Debug> Debug for Agent<M, H, C, Schema>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<M, H = (), C = M, Schema = HandoffDocument> !RefUnwindSafe for Agent<M, H, C, Schema>

§

impl<M, H = (), C = M, Schema = HandoffDocument> !UnwindSafe for Agent<M, H, C, Schema>

§

impl<M, H, C, Schema> Forget for Agent<M, H, C, Schema>

§

impl<M, H, C, Schema> Freeze for Agent<M, H, C, Schema>
where Arc<M>: Freeze, Option<WithParameters<Arc<C>>>: Freeze, H: Freeze, PhantomData<fn() -> Schema>: Freeze,

§

impl<M, H, C, Schema> Move for Agent<M, H, C, Schema>

§

impl<M, H, C, Schema> Send for Agent<M, H, C, Schema>
where Arc<M>: Send, Option<WithParameters<Arc<C>>>: Send, H: Send, PhantomData<fn() -> Schema>: Send,

§

impl<M, H, C, Schema> Sync for Agent<M, H, C, Schema>
where Arc<M>: Sync, Option<WithParameters<Arc<C>>>: Sync, H: Sync, PhantomData<fn() -> Schema>: Sync,

§

impl<M, H, C, Schema> Unpin for Agent<M, H, C, Schema>
where Arc<M>: Unpin, Option<WithParameters<Arc<C>>>: Unpin, H: Unpin, PhantomData<fn() -> Schema>: Unpin,

§

impl<M, H, C, Schema> UnsafeUnpin for Agent<M, H, C, Schema>
where Arc<M>: UnsafeUnpin, Option<WithParameters<Arc<C>>>: UnsafeUnpin, H: UnsafeUnpin, PhantomData<fn() -> Schema>: UnsafeUnpin,

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