Skip to main content

AgentBuilder

Struct AgentBuilder 

Source
pub struct AgentBuilder<M, ToolState = NoToolConfig>
where M: CompletionModel,
{ /* private fields */ }
Expand description

A builder for creating an agent

The builder uses a typestate pattern to enforce that tool configuration is done in a mutually exclusive way: either provide a pre-existing ToolServerHandle, or add tools via the builder API, but not both.

§Example

use rig_agent::AgentBuilder;
use rig_core::{client::{CompletionClient, ProviderClient}, providers::openai};

let openai = openai::Client::from_env()?;

let model = openai.completion_model(openai::GPT_5_2);

// Configure the agent
let agent = AgentBuilder::new(model)
    .preamble("System prompt")
    .context("Context document 1")
    .context("Context document 2")
    .temperature(0.8)
    .build();

Implementations§

Source§

impl<M, ToolState> AgentBuilder<M, ToolState>
where M: CompletionModel,

Source

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

Set the name of the agent

Source

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

Set the description of the agent

Source

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

Set the system prompt

Source

pub fn without_preamble(self) -> Self

Remove the system prompt

Source

pub fn append_preamble(self, doc: &str) -> Self

Append to the preamble of the agent

Source

pub fn context(self, doc: &str) -> Self

Add a static context document to the agent

Source

pub fn dynamic_context<I>(self, samples: usize, index: I) -> Self
where I: VectorStoreIndexDyn + 'static,

Add dynamic context retrieved from a vector store on every model call.

This is a convenience wrapper around an internal completion-call hook. The hook searches with the current prompt’s first text part, falling back to the latest textual history message, and appends the retrieved documents to the request after static context. Retrieval and injected documents follow registration order relative to application hooks, so register a stop policy before this helper when it should prevent retrieval. A retrieval failure stops the run before provider I/O.

Source

pub fn tool_choice(self, tool_choice: ToolChoice) -> Self

Set the tool choice for the agent

Source

pub fn default_max_turns(self, default_max_turns: usize) -> Self

Set the default total model-call budget, including the initial call and every retry or continuation. Zero permits no model calls.

Source

pub fn temperature(self, temperature: f64) -> Self

Set the temperature of the model

Source

pub fn max_tokens(self, max_tokens: u64) -> Self

Set the maximum number of tokens for the completion

Source

pub fn additional_params(self, params: Value) -> Self

Set additional parameters to be passed to the model

Source

pub fn record_content_telemetry(self, enabled: bool) -> Self

Opt in or out of recording sensitive request, response, and tool content on GenAI telemetry spans for requests made by this agent.

Defaults to false. Enabling this can expose prompts, retrieved context, tool results, model responses, and other sensitive or high-cardinality data through OpenTelemetry span attributes, which can increase observability backend storage and query costs. Only enable it when content telemetry is acceptable for this agent. Structural metadata and token usage remain available when this is disabled.

Source

pub fn output_schema<T>(self) -> Self
where T: JsonSchema,

Set the output schema for structured output. When set, providers that support native structured outputs will constrain the model’s response to match this schema.

Source

pub fn output_schema_raw(self, schema: Schema) -> Self

Set the output schema for structured output. In comparison to AgentBuilder::schema() which requires type annotation, you can put in any schema you’d like here.

Source

pub fn output_mode(self, mode: OutputMode) -> Self

Set how output_schema is enforced — OutputMode::Tool (output as a tool call, the default when the agent has tools), OutputMode::Native (provider structured output), or OutputMode::Prompted (see #1928). Has no effect unless output_schema/output_schema_raw is also set.

Source

pub fn memory<B>(self, memory: B) -> Self
where B: ConversationMemory + 'static,

Attach a ConversationMemory backend.

When set, the agent will automatically load prior conversation history before each prompt and append the new turn after a successful response. A conversation_id must be supplied either via AgentBuilder::conversation or per-request via crate::agent::prompt_request::PromptRequest::conversation. If neither is set, memory is silently bypassed.

Source

pub fn conversation(self, id: impl Into<String>) -> Self

Set a default conversation id used when none is provided per-request.

Most agents are reused across users or threads; prefer setting the id per-request via crate::agent::prompt_request::PromptRequest::conversation.

Source

pub fn add_hook<H>(self, hook: H) -> Self
where H: AgentHook + 'static,

Attach a default hook to the agent. Each call appends to the agent’s hook stack; hooks run for every prompt request (unless more are added per request) in registration order. How their results compose is event-dependent: CompletionCall request patches accumulate and merge, ToolCall/ToolResult rewrites chain, while model-turn steering and observe-only/recovery events use first-non-Continue-wins. See the hook module docs.

Source§

impl<M> AgentBuilder<M, NoToolConfig>
where M: CompletionModel,

Source

pub fn new(model: M) -> Self

Create a new agent builder with the given model

Source§

impl<M> AgentBuilder<M, NoToolConfig>
where M: CompletionModel,

Source

pub fn tool_server_handle( self, handle: ToolServerHandle, ) -> AgentBuilder<M, WithToolServerHandle>

Set a pre-existing ToolServerHandle for the agent.

After calling this method, tool-adding methods (.tool(), .dynamic_tool(), etc.) will not be available. Use this when you want to share a ToolServer between multiple agents or have pre-configured tools.

Source

pub fn tool<T>(self, tool: T) -> AgentBuilder<M, WithBuilderTools>
where T: Tool + 'static,

Add a static tool to the agent.

This transitions the builder to the WithBuilderTools state, where additional tools can be added but tool_server_handle() is no longer available.

Source

pub fn dynamic_tool( self, tool: DynamicTool, ) -> AgentBuilder<M, WithBuilderTools>

Add one runtime-defined tool to the agent.

Source

pub fn portable_dynamic_tool( self, tool: PortableDynamicTool, ) -> AgentBuilder<M, WithBuilderTools>

Add one context-free dynamic tool through the classic registry adapter.

Source

pub fn dynamic_tools( self, tools: Vec<DynamicTool>, ) -> AgentBuilder<M, WithBuilderTools>

Add runtime-defined tools to the agent.

This is useful when tool definitions and callbacks are constructed at runtime. Transitions the builder to the WithBuilderTools state.

Source

pub fn rmcp_tool( self, tool: Tool, client: ServerSink, ) -> AgentBuilder<M, WithBuilderTools>

Available on crate feature rmcp only.

Add an MCP tool (from rmcp) to the agent, bounded by DEFAULT_MCP_TOOL_TIMEOUT (see issue #1914). Use rmcp_tool_with_timeout to change or disable it.

Transitions the builder to the WithBuilderTools state.

Source

pub fn rmcp_tool_with_timeout( self, tool: Tool, client: ServerSink, timeout: impl Into<Option<Duration>>, ) -> AgentBuilder<M, WithBuilderTools>

Available on crate feature rmcp only.

Add an MCP tool (from rmcp) with a per-call timeout (see issue #1914).

Pass a Duration to bound the call, or None to disable the timeout (unbounded). On timeout the call resolves to a tool error the agent can recover from instead of blocking forever. Transitions the builder to the WithBuilderTools state.

Source

pub fn rmcp_tools( self, tools: Vec<Tool>, client: ServerSink, ) -> AgentBuilder<M, WithBuilderTools>

Available on crate feature rmcp only.

Add an array of MCP tools (from rmcp) to the agent, each bounded by DEFAULT_MCP_TOOL_TIMEOUT (see issue #1914). Use rmcp_tools_with_timeout to change or disable it.

Transitions the builder to the WithBuilderTools state.

Source

pub fn rmcp_tools_with_timeout( self, tools: Vec<Tool>, client: ServerSink, timeout: impl Into<Option<Duration>>, ) -> AgentBuilder<M, WithBuilderTools>

Available on crate feature rmcp only.

Add an array of MCP tools (from rmcp) with a per-call timeout (see issue #1914).

Pass a Duration to bound calls, or None to disable the timeout (unbounded). On timeout a call resolves to a tool error the agent can recover from instead of blocking forever. Transitions the builder to the WithBuilderTools state.

Source

pub fn retrieved_tools( self, sample: usize, index: impl VectorStoreIndexDyn + Send + Sync + 'static, toolset: ToolSet, ) -> AgentBuilder<M, WithBuilderTools>

Configure tools retrieved from a vector index for each prompt.

Transitions the builder to the WithBuilderTools state.

Source

pub fn build(self) -> Agent<M>

Build the agent with no tools configured.

An empty ToolServer will be created for the agent.

Source§

impl<M> AgentBuilder<M, WithToolServerHandle>
where M: CompletionModel,

Source

pub fn build(self) -> Agent<M>

Build the agent using the pre-configured ToolServerHandle.

Source§

impl<M> AgentBuilder<M, WithBuilderTools>
where M: CompletionModel,

Source

pub fn tool<T>(self, tool: T) -> Self
where T: Tool + 'static,

Add another static tool to the agent.

Source

pub fn dynamic_tool(self, tool: DynamicTool) -> Self

Add one runtime-defined tool to the agent.

Source

pub fn portable_dynamic_tool(self, tool: PortableDynamicTool) -> Self

Add one context-free dynamic tool through the classic registry adapter.

Source

pub fn dynamic_tools(self, tools: Vec<DynamicTool>) -> Self

Add runtime-defined tools to the agent.

Source

pub fn rmcp_tools(self, tools: Vec<Tool>, client: ServerSink) -> Self

Available on crate feature rmcp only.

Add an array of MCP tools (from rmcp) to the agent, each bounded by DEFAULT_MCP_TOOL_TIMEOUT (see issue #1914). Use rmcp_tools_with_timeout to change or disable it.

Source

pub fn rmcp_tools_with_timeout( self, tools: Vec<Tool>, client: ServerSink, timeout: impl Into<Option<Duration>>, ) -> Self

Available on crate feature rmcp only.

Add an array of MCP tools (from rmcp) with a per-call timeout (see issue #1914).

Pass a Duration to bound calls, or None to disable the timeout (unbounded). On timeout a call resolves to a tool error the agent can recover from instead of blocking forever.

Source

pub fn retrieved_tools( self, sample: usize, index: impl VectorStoreIndexDyn + Send + Sync + 'static, toolset: ToolSet, ) -> Self

Configure tools retrieved from a vector index for each prompt.

Source

pub fn build(self) -> Agent<M>

Build the agent with the configured tools.

A new ToolServer will be created containing all tools added via .tool(), .dynamic_tool(), .dynamic_tools(), and .retrieved_tools().

Auto Trait Implementations§

§

impl<M, ToolState = NoToolConfig> !RefUnwindSafe for AgentBuilder<M, ToolState>

§

impl<M, ToolState = NoToolConfig> !UnwindSafe for AgentBuilder<M, ToolState>

§

impl<M, ToolState> Freeze for AgentBuilder<M, ToolState>
where M: Freeze, ToolState: Freeze,

§

impl<M, ToolState> Send for AgentBuilder<M, ToolState>
where ToolState: Send,

§

impl<M, ToolState> Sync for AgentBuilder<M, ToolState>
where ToolState: Sync,

§

impl<M, ToolState> Unpin for AgentBuilder<M, ToolState>
where M: Unpin, ToolState: Unpin,

§

impl<M, ToolState> UnsafeUnpin for AgentBuilder<M, ToolState>
where M: UnsafeUnpin, ToolState: 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<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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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: Sized + 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> 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 = 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

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