open_agent/types/agent_options.rs
1/// Configuration options for an AI agent instance.
2///
3/// `AgentOptions` controls all aspects of agent behavior including model selection,
4/// conversation management, tool usage, and lifecycle hooks. This struct should be
5/// constructed using [`AgentOptions::builder()`] rather than direct instantiation
6/// to ensure required fields are validated.
7///
8/// # Architecture
9///
10/// The options are organized into several functional areas:
11///
12/// - **Model Configuration**: `model`, `base_url`, `api_key`, `temperature`, `max_tokens`
13/// - **Conversation Control**: `system_prompt`, `max_turns`, `timeout`
14/// - **Tool Management**: `tools`, `auto_execute_tools`, `max_tool_iterations`
15/// - **Lifecycle Hooks**: `hooks` for monitoring and interception
16///
17/// # Thread Safety
18///
19/// Tools are wrapped in `Arc<Tool>` to allow efficient cloning and sharing across
20/// threads, as agents may need to be cloned for parallel processing.
21///
22/// # Examples
23///
24/// ```no_run
25/// use open_agent::AgentOptions;
26///
27/// let options = AgentOptions::builder()
28/// .model("qwen2.5-32b-instruct")
29/// .base_url("http://localhost:1234/v1")
30/// .system_prompt("You are a helpful coding assistant")
31/// .max_turns(5)
32/// .temperature(0.7)
33/// .build()
34/// .expect("Valid configuration");
35/// ```
36#[derive(Clone)]
37pub struct AgentOptions {
38 /// System prompt that defines the agent's behavior and personality.
39 ///
40 /// This is sent as the first message in the conversation to establish
41 /// context and instructions. Can be empty if no system-level guidance
42 /// is needed.
43 system_prompt: String,
44
45 /// Model identifier for the LLM to use (e.g., "qwen2.5-32b-instruct", "gpt-4").
46 ///
47 /// This must match a model available at the configured `base_url`.
48 /// Different models have varying capabilities for tool use, context
49 /// length, and response quality.
50 model: String,
51
52 /// OpenAI-compatible API endpoint URL (e.g., "http://localhost:1234/v1").
53 ///
54 /// The SDK communicates using the OpenAI chat completions API format,
55 /// which is widely supported by local inference servers (LM Studio,
56 /// llama.cpp, vLLM) and cloud providers.
57 base_url: String,
58
59 /// API authentication key for the provider.
60 ///
61 /// Many local servers don't require authentication, so the default
62 /// "not-needed" is often sufficient. For cloud providers like OpenAI,
63 /// set this to your actual API key.
64 api_key: String,
65
66 /// Maximum number of conversation turns (user message + assistant response = 1 turn).
67 ///
68 /// This limits how long a conversation can continue. In auto-execution mode
69 /// with tools, this prevents infinite loops. Set to 1 for single-shot
70 /// interactions or higher for multi-turn conversations.
71 max_turns: u32,
72
73 /// Maximum tokens the model should generate in a single response.
74 ///
75 /// `None` uses the provider's default. Lower values constrain response
76 /// length, which can be useful for cost control or ensuring concise answers.
77 /// Note this is separate from the model's context window size.
78 max_tokens: Option<u32>,
79
80 /// Sampling temperature for response generation (typically 0.0 to 2.0).
81 ///
82 /// - 0.0: Deterministic, always picks most likely tokens
83 /// - 0.7: Balanced creativity and consistency
84 /// - 1.0+: More random and creative responses
85 ///
86 /// `None` omits the field from the wire request entirely, leaving the server to apply
87 /// its own default. That is the default, and it is load-bearing rather than tidy: a
88 /// growing number of models reject the parameter outright — Anthropic's range stops at
89 /// 1.0, and several reasoning models 400 on any value at all — so a client-invented
90 /// temperature turns a working request into a hard error the caller never asked for.
91 /// This mirrors `max_tokens`, which stopped being defaulted in 0.7.0 for the same
92 /// reason.
93 temperature: Option<f32>,
94
95 /// HTTP request timeout in seconds.
96 ///
97 /// Maximum time to wait for the API to respond. Applies per API call,
98 /// not to the entire conversation. Increase for slower models or when
99 /// expecting long responses.
100 timeout: u64,
101
102 /// Tools available for the agent to use during conversations.
103 ///
104 /// Tools are wrapped in `Arc` for efficient cloning. When the agent
105 /// receives a tool use request, it looks up the tool by name in this
106 /// vector. Empty by default.
107 tools: Vec<Arc<Tool>>,
108
109 /// Whether to automatically execute tools and continue the conversation.
110 ///
111 /// - `true`: SDK automatically executes tool calls and sends results back
112 /// to the model, continuing until no more tools are requested
113 /// - `false`: Tool calls are returned to the caller, who must manually
114 /// execute them and provide results
115 ///
116 /// Auto-execution is convenient but gives less control. Manual execution
117 /// allows for approval workflows and selective tool access.
118 auto_execute_tools: bool,
119
120 /// Maximum iterations of tool execution in automatic mode.
121 ///
122 /// Prevents infinite loops where the agent continuously requests tools.
123 /// Each tool execution attempt counts as one iteration. Only relevant
124 /// when `auto_execute_tools` is true.
125 max_tool_iterations: u32,
126
127 /// Whether the model's reasoning channel is surfaced to the caller.
128 ///
129 /// Reasoning models stream chain-of-thought separately from content
130 /// (`reasoning_content` on DeepSeek, `reasoning` on OpenRouter). It is never
131 /// merged into assistant text regardless of this setting; the flag only decides
132 /// whether it is buffered and emitted as `StreamEvent::Reasoning` or discarded
133 /// as it arrives. `false` by default, because a caller that does not want it
134 /// should not pay to buffer it.
135 include_reasoning: bool,
136
137 /// The wire protocol this endpoint speaks.
138 ///
139 /// Selects the request path, the auth header, the body shape and the streaming
140 /// vocabulary. Defaults to [`ApiProtocol::OpenAiChat`], which is what every endpoint the
141 /// SDK supported before 0.9.0 speaks, so an existing configuration keeps its behaviour.
142 protocol: ApiProtocol,
143
144 /// Lifecycle hooks for observing and intercepting agent operations.
145 ///
146 /// Hooks allow you to inject custom logic at various points:
147 /// - Before/after API requests
148 /// - Tool execution interception
149 /// - Response streaming callbacks
150 ///
151 /// Useful for logging, metrics, debugging, and implementing custom
152 /// authorization logic.
153 hooks: Hooks,
154}
155
156/// Custom Debug implementation to prevent sensitive data leakage.
157///
158/// We override the default Debug implementation because:
159/// 1. The `api_key` field may contain sensitive credentials that shouldn't
160/// appear in logs or error messages
161/// 2. The `tools` vector contains Arc-wrapped closures that don't debug nicely,
162/// so we show a count instead
163///
164/// This ensures that debug output is safe for logging while remaining useful
165/// for troubleshooting.
166impl std::fmt::Debug for AgentOptions {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("AgentOptions")
169 .field("system_prompt", &self.system_prompt)
170 .field("model", &self.model)
171 .field("base_url", &self.base_url)
172 // Mask API key to prevent credential leakage in logs
173 .field("api_key", &"***")
174 .field("max_turns", &self.max_turns)
175 .field("max_tokens", &self.max_tokens)
176 .field("temperature", &self.temperature)
177 .field("timeout", &self.timeout)
178 // Show tool count instead of trying to debug Arc<Tool> contents
179 .field("tools", &format!("{} tools", self.tools.len()))
180 .field("auto_execute_tools", &self.auto_execute_tools)
181 .field("max_tool_iterations", &self.max_tool_iterations)
182 .field("include_reasoning", &self.include_reasoning)
183 .field("protocol", &self.protocol)
184 .field("hooks", &self.hooks)
185 .finish()
186 }
187}
188
189/// Default values optimized for common single-turn use cases.
190///
191/// These defaults are chosen to:
192/// - Require explicit configuration of critical fields (model, base_url)
193/// - Provide safe, sensible defaults for optional fields
194/// - Work with local inference servers that don't need authentication
195impl Default for AgentOptions {
196 fn default() -> Self {
197 Self {
198 // Empty string forces users to explicitly set context
199 system_prompt: String::new(),
200 // Empty string forces users to explicitly choose a model
201 model: String::new(),
202 // Empty string forces users to explicitly configure the endpoint
203 base_url: String::new(),
204 // Most local servers (LM Studio, llama.cpp) don't require auth
205 api_key: "not-needed".to_string(),
206 // Default to single-shot interaction; users opt into conversations
207 max_turns: 1,
208 // No client-imposed cap; the server decides how long a response may be.
209 // Callers who want a ceiling set one explicitly via `max_tokens()`.
210 max_tokens: None,
211 // Unset: the field is omitted and the server decides. A client-invented value
212 // is rejected outright by several current models.
213 temperature: None,
214 // 60 seconds handles most requests without timing out prematurely
215 timeout: 60,
216 // No tools by default; users explicitly add capabilities
217 tools: Vec::new(),
218 // Manual tool execution by default for safety and control
219 auto_execute_tools: false,
220 // 5 iterations prevent infinite loops while allowing multi-step workflows
221 max_tool_iterations: 5,
222 // Empty hooks for no-op behavior
223 hooks: Hooks::new(),
224 // Reasoning is dropped unless a caller explicitly asks for it
225 include_reasoning: false,
226 // The only protocol the SDK spoke before 0.9.0
227 protocol: ApiProtocol::OpenAiChat,
228 }
229 }
230}
231
232impl AgentOptions {
233 /// Creates a new builder for constructing [`AgentOptions`].
234 ///
235 /// The builder pattern is used because:
236 /// 1. Some fields are required (model, base_url) and need validation
237 /// 2. Many fields have sensible defaults that can be overridden
238 /// 3. The API is more discoverable and readable than struct initialization
239 ///
240 /// # Example
241 ///
242 /// ```no_run
243 /// use open_agent::AgentOptions;
244 ///
245 /// let options = AgentOptions::builder()
246 /// .model("qwen2.5-32b-instruct")
247 /// .base_url("http://localhost:1234/v1")
248 /// .build()
249 /// .expect("Valid configuration");
250 /// ```
251 pub fn builder() -> AgentOptionsBuilder {
252 AgentOptionsBuilder::default()
253 }
254
255 /// Returns the system prompt.
256 pub fn system_prompt(&self) -> &str {
257 &self.system_prompt
258 }
259
260 /// Returns the model identifier.
261 pub fn model(&self) -> &str {
262 &self.model
263 }
264
265 /// Returns the base URL.
266 pub fn base_url(&self) -> &str {
267 &self.base_url
268 }
269
270 /// Returns the API key.
271 pub fn api_key(&self) -> &str {
272 &self.api_key
273 }
274
275 /// Returns the maximum number of conversation turns.
276 pub fn max_turns(&self) -> u32 {
277 self.max_turns
278 }
279
280 /// Returns the maximum tokens setting.
281 pub fn max_tokens(&self) -> Option<u32> {
282 self.max_tokens
283 }
284
285 /// Returns the sampling temperature, or `None` when the server should choose.
286 pub fn temperature(&self) -> Option<f32> {
287 self.temperature
288 }
289
290 /// Returns the wire protocol this endpoint speaks.
291 pub fn protocol(&self) -> ApiProtocol {
292 self.protocol
293 }
294
295 /// Returns the HTTP timeout in seconds.
296 pub fn timeout(&self) -> u64 {
297 self.timeout
298 }
299
300 /// Returns a reference to the tools vector.
301 pub fn tools(&self) -> &[Arc<Tool>] {
302 &self.tools
303 }
304
305 /// Returns whether automatic tool execution is enabled.
306 pub fn auto_execute_tools(&self) -> bool {
307 self.auto_execute_tools
308 }
309
310 /// Returns the maximum tool execution iterations.
311 pub fn max_tool_iterations(&self) -> u32 {
312 self.max_tool_iterations
313 }
314
315 /// Returns a reference to the hooks configuration.
316 pub fn hooks(&self) -> &Hooks {
317 &self.hooks
318 }
319
320 /// Returns whether the reasoning channel is surfaced to the caller.
321 pub fn include_reasoning(&self) -> bool {
322 self.include_reasoning
323 }
324}