AgentOptionsBuilder

Struct AgentOptionsBuilder 

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

Builder for constructing AgentOptions with validation.

This builder implements the typestate pattern using Option<T> to track which required fields have been set. The build() method validates that all required fields are present before creating the final AgentOptions.

§Required Fields

  • model: The LLM model identifier
  • base_url: The API endpoint URL

All other fields have sensible defaults.

§Usage Pattern

  1. Call AgentOptions::builder()
  2. Chain method calls to set configuration
  3. Call build() to validate and create the final options

Methods return self for chaining, following the fluent interface pattern.

§Examples

use open_agent::AgentOptions;
use open_agent::Tool;

let calculator = Tool::new(
    "calculate",
    "Perform arithmetic",
    serde_json::json!({
        "type": "object",
        "properties": {
            "expression": {"type": "string"}
        }
    }),
    |input| Box::pin(async move {
        Ok(serde_json::json!({"result": 42}))
    }),
);

let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .system_prompt("You are a helpful assistant")
    .max_turns(10)
    .temperature(0.8)
    .tool(calculator)
    .auto_execute_tools(true)
    .build()
    .expect("Valid configuration");

Implementations§

Source§

impl AgentOptionsBuilder

Builder methods for configuring agent options.

All methods follow the builder pattern: they consume self, update a field, and return self for method chaining. The generic impl Into<String> parameters allow passing &str, String, or any other type that converts to String.

Source

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

Sets the system prompt that defines agent behavior.

The system prompt is sent at the beginning of every conversation to establish context, personality, and instructions for the agent.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .system_prompt("You are a helpful coding assistant. Be concise.")
    .build()
    .unwrap();
Source

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

Sets the model identifier (required).

This must match a model available at your configured endpoint. Common examples: “qwen2.5-32b-instruct”, “gpt-4”, “claude-3-sonnet”.

§Example
let options = AgentOptions::builder()
    .model("gpt-4")
    .base_url("https://api.openai.com/v1")
    .build()
    .unwrap();
Source

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

Sets the API endpoint URL (required).

Must be an OpenAI-compatible endpoint. Common values:

  • Local: “http://localhost:1234/v1” (LM Studio default)
  • OpenAI: https://api.openai.com/v1
  • Custom: Your inference server URL
§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .build()
    .unwrap();
Source

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

Sets the API key for authentication.

Required for cloud providers like OpenAI. Most local servers don’t need this - the default “not-needed” works fine.

§Example
let options = AgentOptions::builder()
    .model("gpt-4")
    .base_url("https://api.openai.com/v1")
    .api_key("sk-...")
    .build()
    .unwrap();
Source

pub fn max_turns(self, turns: u32) -> Self

Sets the maximum number of conversation turns.

One turn = user message + assistant response. Higher values enable longer conversations but may increase costs and latency.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .max_turns(10)  // Allow multi-turn conversation
    .build()
    .unwrap();
Source

pub fn max_tokens(self, tokens: u32) -> Self

Sets the maximum tokens to generate per response.

Constrains response length. Lower values reduce costs but may truncate responses. Higher values allow longer, more complete answers.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .max_tokens(1000)  // Limit to shorter responses
    .build()
    .unwrap();
Source

pub fn temperature(self, temp: f32) -> Self

Sets the sampling temperature for response generation.

Controls randomness:

  • 0.0: Deterministic, always picks most likely tokens
  • 0.7: Balanced (default)
  • 1.0+: More creative/random
§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .temperature(0.0)  // Deterministic for coding tasks
    .build()
    .unwrap();
Source

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

Sets the HTTP request timeout in seconds.

How long to wait for the API to respond. Increase for slower models or when expecting long responses.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .timeout(120)  // 2 minutes for complex tasks
    .build()
    .unwrap();
Source

pub fn auto_execute_tools(self, auto: bool) -> Self

Enables or disables automatic tool execution.

When true, the SDK automatically executes tool calls and continues the conversation. When false, tool calls are returned for manual handling, allowing approval workflows.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .auto_execute_tools(true)  // Automatic execution
    .build()
    .unwrap();
Source

pub fn max_tool_iterations(self, iterations: u32) -> Self

Sets the maximum tool execution iterations in automatic mode.

Prevents infinite loops where the agent continuously calls tools. Only relevant when auto_execute_tools is true.

§Example
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .auto_execute_tools(true)
    .max_tool_iterations(10)  // Allow up to 10 tool calls
    .build()
    .unwrap();
Source

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

Adds a single tool to the agent’s available tools.

The tool is wrapped in Arc for efficient sharing. Can be called multiple times to add multiple tools.

§Example
let calculator = Tool::new(
    "calculate",
    "Evaluate a math expression",
    serde_json::json!({"type": "object"}),
    |input| Box::pin(async move { Ok(serde_json::json!({"result": 42})) }),
);

let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .tool(calculator)
    .build()
    .unwrap();
Source

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

Adds multiple tools at once to the agent’s available tools.

Convenience method for bulk tool addition. All tools are wrapped in Arc automatically.

§Example
let tools = vec![
    Tool::new("add", "Add numbers", serde_json::json!({}),
        |input| Box::pin(async move { Ok(serde_json::json!({})) })),
    Tool::new("multiply", "Multiply numbers", serde_json::json!({}),
        |input| Box::pin(async move { Ok(serde_json::json!({})) })),
];

let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .tools(tools)
    .build()
    .unwrap();
Source

pub fn hooks(self, hooks: Hooks) -> Self

Sets lifecycle hooks for monitoring and intercepting agent operations.

Hooks allow custom logic at various points: before/after API calls, tool execution, response streaming, etc. Useful for logging, metrics, debugging, and custom authorization.

§Example
let hooks = Hooks::new()
    .add_user_prompt_submit(|event| async move {
        println!("User prompt: {}", event.prompt);
        Some(HookDecision::continue_())
    });

let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .hooks(hooks)
    .build()
    .unwrap();
Source

pub fn build(self) -> Result<AgentOptions>

Validates configuration and builds the final AgentOptions.

This method performs validation to ensure required fields are set and applies default values for optional fields. Returns an error if validation fails.

§Required Fields
  • model: Must be set or build() returns an error
  • base_url: Must be set or build() returns an error
§Errors

Returns a configuration error if any required field is missing.

§Example
// Success - all required fields set
let options = AgentOptions::builder()
    .model("qwen2.5-32b-instruct")
    .base_url("http://localhost:1234/v1")
    .build()
    .expect("Valid configuration");

// Error - missing model
let result = AgentOptions::builder()
    .base_url("http://localhost:1234/v1")
    .build();
assert!(result.is_err());

Trait Implementations§

Source§

impl Debug for AgentOptionsBuilder

Custom Debug implementation for builder to show minimal useful information.

Similar to AgentOptions, we provide a simplified debug output that:

  • Omits sensitive fields like API keys (not shown at all in builder)
  • Shows tool count rather than tool details
  • Focuses on the most important configuration fields
Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for AgentOptionsBuilder

Source§

fn default() -> AgentOptionsBuilder

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