Skip to main content

ChatAgent

Struct ChatAgent 

Source
pub struct ChatAgent { /* private fields */ }
Expand description

A simple chat agent that processes messages through an LLM provider with tool support.

This is the framework’s ready-to-use agent for text message -> response flows. It manages conversation history, streams responses from the provider, and automatically dispatches tool calls through a BuiltinToolExecutor.

§Example

use brainwires_agents::ChatAgent;
use brainwires_tools::{BuiltinToolExecutor, ToolRegistry};
use brainwires_core::{ChatOptions, ToolContext};
use std::sync::Arc;

let provider = /* create a provider */;
let registry = ToolRegistry::with_builtins();
let context = ToolContext::default();
let executor = Arc::new(BuiltinToolExecutor::new(registry, context));
let options = ChatOptions::default();

let mut agent = ChatAgent::new(provider, executor, options)
    .with_system_prompt("You are a helpful assistant.")
    .with_max_tool_rounds(5);

let response = agent.process_message("Hello!").await?;
println!("{}", response);

Implementations§

Source§

impl ChatAgent

Source

pub fn new( provider: Arc<dyn Provider>, executor: Arc<BuiltinToolExecutor>, options: ChatOptions, ) -> Self

Create a new ChatAgent.

Defaults max_tool_rounds to 10.

Source

pub fn with_max_tool_rounds(self, rounds: usize) -> Self

Set the maximum number of tool-call rounds before the agent stops.

Source

pub fn with_pre_execute_hook(self, hook: Arc<dyn ToolPreHook>) -> Self

Attach a pre-execution hook that can allow or reject tool calls before they run.

Source

pub fn with_system_prompt(self, prompt: &str) -> Self

Add a system prompt as the first message in the conversation.

If messages already exist, the system message is inserted at position 0.

Source

pub async fn process_message(&mut self, input: &str) -> Result<String>

Process a user message and return the final assistant text response.

This is the core completion loop:

  1. Adds the user message to history
  2. Streams the provider response, collecting text and tool calls
  3. If tool calls are present, executes them and loops
  4. Returns the final accumulated text once no more tool calls remain (or max_tool_rounds is reached)
Source

pub async fn process_message_streaming<F>( &mut self, input: &str, on_chunk: F, ) -> Result<String>
where F: Fn(&str) + Send + Sync,

Process a user message with streaming — calls on_chunk for each text fragment as it arrives from the provider.

Returns the full accumulated text once the completion loop finishes.

Source

pub fn messages(&self) -> &[Message]

Access the conversation history.

Source

pub fn restore_messages(&mut self, messages: Vec<Message>)

Replace the entire message history with the provided messages.

This is used by session persistence to restore a previously saved conversation when an agent session is recreated.

Source

pub fn clear_history(&mut self)

Clear all messages (including any system prompt).

Source

pub fn trim_history(&mut self, max_messages: usize)

Keep only the last max_messages messages, preserving the system prompt at position 0 if one exists.

Source

pub fn message_count(&self) -> usize

Return the number of messages in the conversation.

Source

pub fn cumulative_usage(&self) -> &Usage

Return the accumulated token usage for this agent session.

Counts prompt + completion tokens across all completions. Updated whenever the provider emits a StreamChunk::Usage event.

Source

pub fn reset_usage(&mut self)

Reset the cumulative token usage counter.

Source

pub async fn compact_history(&mut self) -> Result<()>

Compact conversation history by trimming older messages.

This is a simple, LLM-free compaction that keeps the system prompt (if any) and the most recent keep messages. For LLM-powered summarisation, use the DreamSummarizer from brainwires-autonomy.

Auto Trait Implementations§

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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> ErasedDestructor for T
where T: 'static,