Skip to main content

AgentBuilder

Struct AgentBuilder 

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

Builder for Agent.

Implementations§

Source§

impl AgentBuilder

Source

pub fn model<M>(self, model: M) -> Self
where M: ChatModel + 'static,

Sets the model adapter used by the agent.

Examples found in repository?
examples/local_loop.rs (line 90)
88fn build_agent(responses: Vec<Result<ModelCompletion, ProviderError>>) -> Agent {
89    Agent::builder()
90        .model(ScriptedModel::new(responses))
91        .tool(add_tool())
92        .tool(done_tool())
93        .build()
94        .expect("agent builds")
95}
More examples
Hide additional examples
examples/di_override.rs (line 97)
43async fn main() -> Result<(), Box<dyn Error>> {
44    let read_dep_tool = ToolSpec::new("read_dep", "read injected value")
45        .with_schema(json!({
46            "type": "object",
47            "properties": {},
48            "required": [],
49            "additionalProperties": false
50        }))?
51        .with_handler(|_args, deps| {
52            let value = deps.get::<u32>().map(|v| *v).unwrap_or_default();
53            async move { Ok(ToolOutcome::Text(value.to_string())) }
54        });
55
56    let done_tool = ToolSpec::new("done", "finish")
57        .with_schema(json!({
58            "type": "object",
59            "properties": {
60                "message": {"type": "string"}
61            },
62            "required": ["message"],
63            "additionalProperties": false
64        }))?
65        .with_handler(|args, _deps| async move {
66            let message = args
67                .get("message")
68                .and_then(|v| v.as_str())
69                .unwrap_or("done");
70            Ok(ToolOutcome::Done(message.to_string()))
71        });
72
73    let model = ScriptedModel::new(vec![
74        Ok(ModelCompletion {
75            text: None,
76            thinking: None,
77            tool_calls: vec![ModelToolCall {
78                id: "call_1".to_string(),
79                name: "read_dep".to_string(),
80                arguments: json!({}),
81            }],
82            usage: None,
83        }),
84        Ok(ModelCompletion {
85            text: None,
86            thinking: None,
87            tool_calls: vec![ModelToolCall {
88                id: "call_2".to_string(),
89                name: "done".to_string(),
90                arguments: json!({"message": "dependency override applied"}),
91            }],
92            usage: None,
93        }),
94    ]);
95
96    let mut agent = Agent::builder()
97        .model(model)
98        .tool(read_dep_tool)
99        .tool(done_tool)
100        .dependency(1_u32)
101        .dependency_override(9_u32)
102        .build()?;
103
104    let response = agent.query("use dependency").await?;
105    println!("final: {response}");
106
107    Ok(())
108}
Source

pub fn tool(self, tool: ToolSpec) -> Self

Adds one tool to the registry.

Examples found in repository?
examples/local_loop.rs (line 91)
88fn build_agent(responses: Vec<Result<ModelCompletion, ProviderError>>) -> Agent {
89    Agent::builder()
90        .model(ScriptedModel::new(responses))
91        .tool(add_tool())
92        .tool(done_tool())
93        .build()
94        .expect("agent builds")
95}
More examples
Hide additional examples
examples/di_override.rs (line 98)
43async fn main() -> Result<(), Box<dyn Error>> {
44    let read_dep_tool = ToolSpec::new("read_dep", "read injected value")
45        .with_schema(json!({
46            "type": "object",
47            "properties": {},
48            "required": [],
49            "additionalProperties": false
50        }))?
51        .with_handler(|_args, deps| {
52            let value = deps.get::<u32>().map(|v| *v).unwrap_or_default();
53            async move { Ok(ToolOutcome::Text(value.to_string())) }
54        });
55
56    let done_tool = ToolSpec::new("done", "finish")
57        .with_schema(json!({
58            "type": "object",
59            "properties": {
60                "message": {"type": "string"}
61            },
62            "required": ["message"],
63            "additionalProperties": false
64        }))?
65        .with_handler(|args, _deps| async move {
66            let message = args
67                .get("message")
68                .and_then(|v| v.as_str())
69                .unwrap_or("done");
70            Ok(ToolOutcome::Done(message.to_string()))
71        });
72
73    let model = ScriptedModel::new(vec![
74        Ok(ModelCompletion {
75            text: None,
76            thinking: None,
77            tool_calls: vec![ModelToolCall {
78                id: "call_1".to_string(),
79                name: "read_dep".to_string(),
80                arguments: json!({}),
81            }],
82            usage: None,
83        }),
84        Ok(ModelCompletion {
85            text: None,
86            thinking: None,
87            tool_calls: vec![ModelToolCall {
88                id: "call_2".to_string(),
89                name: "done".to_string(),
90                arguments: json!({"message": "dependency override applied"}),
91            }],
92            usage: None,
93        }),
94    ]);
95
96    let mut agent = Agent::builder()
97        .model(model)
98        .tool(read_dep_tool)
99        .tool(done_tool)
100        .dependency(1_u32)
101        .dependency_override(9_u32)
102        .build()?;
103
104    let response = agent.query("use dependency").await?;
105    println!("final: {response}");
106
107    Ok(())
108}
Source

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

Adds multiple tools to the registry.

Source

pub fn config(self, config: AgentConfig) -> Self

Replaces the full agent config.

Source

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

Sets the system prompt.

Source

pub fn require_done_tool(self, require_done_tool: bool) -> Self

Enables or disables explicit done completion mode.

Source

pub fn max_iterations(self, max_iterations: u32) -> Self

Sets max iterations for each query.

Source

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

Sets tool-choice policy for model invocations.

Source

pub fn llm_retry_config( self, max_retries: u32, base_delay_ms: u64, max_delay_ms: u64, ) -> Self

Configures request retry behavior (exponential backoff).

Source

pub fn hidden_user_message_prompt(self, prompt: impl Into<String>) -> Self

Sets a hidden user prompt injected once if model returns no tool calls.

Source

pub fn dependency<T>(self, value: T) -> Self
where T: Send + Sync + 'static,

Inserts a typed runtime dependency.

Examples found in repository?
examples/di_override.rs (line 100)
43async fn main() -> Result<(), Box<dyn Error>> {
44    let read_dep_tool = ToolSpec::new("read_dep", "read injected value")
45        .with_schema(json!({
46            "type": "object",
47            "properties": {},
48            "required": [],
49            "additionalProperties": false
50        }))?
51        .with_handler(|_args, deps| {
52            let value = deps.get::<u32>().map(|v| *v).unwrap_or_default();
53            async move { Ok(ToolOutcome::Text(value.to_string())) }
54        });
55
56    let done_tool = ToolSpec::new("done", "finish")
57        .with_schema(json!({
58            "type": "object",
59            "properties": {
60                "message": {"type": "string"}
61            },
62            "required": ["message"],
63            "additionalProperties": false
64        }))?
65        .with_handler(|args, _deps| async move {
66            let message = args
67                .get("message")
68                .and_then(|v| v.as_str())
69                .unwrap_or("done");
70            Ok(ToolOutcome::Done(message.to_string()))
71        });
72
73    let model = ScriptedModel::new(vec![
74        Ok(ModelCompletion {
75            text: None,
76            thinking: None,
77            tool_calls: vec![ModelToolCall {
78                id: "call_1".to_string(),
79                name: "read_dep".to_string(),
80                arguments: json!({}),
81            }],
82            usage: None,
83        }),
84        Ok(ModelCompletion {
85            text: None,
86            thinking: None,
87            tool_calls: vec![ModelToolCall {
88                id: "call_2".to_string(),
89                name: "done".to_string(),
90                arguments: json!({"message": "dependency override applied"}),
91            }],
92            usage: None,
93        }),
94    ]);
95
96    let mut agent = Agent::builder()
97        .model(model)
98        .tool(read_dep_tool)
99        .tool(done_tool)
100        .dependency(1_u32)
101        .dependency_override(9_u32)
102        .build()?;
103
104    let response = agent.query("use dependency").await?;
105    println!("final: {response}");
106
107    Ok(())
108}
Source

pub fn dependency_named<T>(self, key: impl Into<String>, value: T) -> Self
where T: Send + Sync + 'static,

Inserts a named runtime dependency.

Source

pub fn dependency_override<T>(self, value: T) -> Self
where T: Send + Sync + 'static,

Inserts a typed dependency override.

Examples found in repository?
examples/di_override.rs (line 101)
43async fn main() -> Result<(), Box<dyn Error>> {
44    let read_dep_tool = ToolSpec::new("read_dep", "read injected value")
45        .with_schema(json!({
46            "type": "object",
47            "properties": {},
48            "required": [],
49            "additionalProperties": false
50        }))?
51        .with_handler(|_args, deps| {
52            let value = deps.get::<u32>().map(|v| *v).unwrap_or_default();
53            async move { Ok(ToolOutcome::Text(value.to_string())) }
54        });
55
56    let done_tool = ToolSpec::new("done", "finish")
57        .with_schema(json!({
58            "type": "object",
59            "properties": {
60                "message": {"type": "string"}
61            },
62            "required": ["message"],
63            "additionalProperties": false
64        }))?
65        .with_handler(|args, _deps| async move {
66            let message = args
67                .get("message")
68                .and_then(|v| v.as_str())
69                .unwrap_or("done");
70            Ok(ToolOutcome::Done(message.to_string()))
71        });
72
73    let model = ScriptedModel::new(vec![
74        Ok(ModelCompletion {
75            text: None,
76            thinking: None,
77            tool_calls: vec![ModelToolCall {
78                id: "call_1".to_string(),
79                name: "read_dep".to_string(),
80                arguments: json!({}),
81            }],
82            usage: None,
83        }),
84        Ok(ModelCompletion {
85            text: None,
86            thinking: None,
87            tool_calls: vec![ModelToolCall {
88                id: "call_2".to_string(),
89                name: "done".to_string(),
90                arguments: json!({"message": "dependency override applied"}),
91            }],
92            usage: None,
93        }),
94    ]);
95
96    let mut agent = Agent::builder()
97        .model(model)
98        .tool(read_dep_tool)
99        .tool(done_tool)
100        .dependency(1_u32)
101        .dependency_override(9_u32)
102        .build()?;
103
104    let response = agent.query("use dependency").await?;
105    println!("final: {response}");
106
107    Ok(())
108}
Source

pub fn dependency_override_named<T>( self, key: impl Into<String>, value: T, ) -> Self
where T: Send + Sync + 'static,

Inserts a named dependency override.

Source

pub fn build(self) -> Result<Agent, AgentError>

Builds an Agent and validates required config.

Examples found in repository?
examples/local_loop.rs (line 93)
88fn build_agent(responses: Vec<Result<ModelCompletion, ProviderError>>) -> Agent {
89    Agent::builder()
90        .model(ScriptedModel::new(responses))
91        .tool(add_tool())
92        .tool(done_tool())
93        .build()
94        .expect("agent builds")
95}
More examples
Hide additional examples
examples/di_override.rs (line 102)
43async fn main() -> Result<(), Box<dyn Error>> {
44    let read_dep_tool = ToolSpec::new("read_dep", "read injected value")
45        .with_schema(json!({
46            "type": "object",
47            "properties": {},
48            "required": [],
49            "additionalProperties": false
50        }))?
51        .with_handler(|_args, deps| {
52            let value = deps.get::<u32>().map(|v| *v).unwrap_or_default();
53            async move { Ok(ToolOutcome::Text(value.to_string())) }
54        });
55
56    let done_tool = ToolSpec::new("done", "finish")
57        .with_schema(json!({
58            "type": "object",
59            "properties": {
60                "message": {"type": "string"}
61            },
62            "required": ["message"],
63            "additionalProperties": false
64        }))?
65        .with_handler(|args, _deps| async move {
66            let message = args
67                .get("message")
68                .and_then(|v| v.as_str())
69                .unwrap_or("done");
70            Ok(ToolOutcome::Done(message.to_string()))
71        });
72
73    let model = ScriptedModel::new(vec![
74        Ok(ModelCompletion {
75            text: None,
76            thinking: None,
77            tool_calls: vec![ModelToolCall {
78                id: "call_1".to_string(),
79                name: "read_dep".to_string(),
80                arguments: json!({}),
81            }],
82            usage: None,
83        }),
84        Ok(ModelCompletion {
85            text: None,
86            thinking: None,
87            tool_calls: vec![ModelToolCall {
88                id: "call_2".to_string(),
89                name: "done".to_string(),
90                arguments: json!({"message": "dependency override applied"}),
91            }],
92            usage: None,
93        }),
94    ]);
95
96    let mut agent = Agent::builder()
97        .model(model)
98        .tool(read_dep_tool)
99        .tool(done_tool)
100        .dependency(1_u32)
101        .dependency_override(9_u32)
102        .build()?;
103
104    let response = agent.query("use dependency").await?;
105    println!("final: {response}");
106
107    Ok(())
108}

Trait Implementations§

Source§

impl Default for AgentBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

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