pub struct Agent { /* private fields */ }Expand description
Builder for a single agent invocation.
Create with Agent::new, chain configuration methods, then call
run with an AgentProvider to execute.
§Examples
use ironflow_core::prelude::*;
let provider = ClaudeCodeProvider::new();
let result = Agent::new()
.system_prompt("You are a Rust expert.")
.prompt("Review this code for safety issues.")
.model(Model::OPUS)
.allowed_tools(&["Read", "Grep"])
.max_turns(5)
.max_budget_usd(0.50)
.working_dir("/tmp/project")
.permission_mode(PermissionMode::Auto)
.run(&provider)
.await?;
println!("Cost: ${:.4}", result.cost_usd().unwrap_or(0.0));Implementations§
Source§impl Agent
impl Agent
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new agent builder with default settings.
Defaults: Model::SONNET, no system prompt, no tool restrictions,
no budget/turn limits, PermissionMode::Default.
Sourcepub fn system_prompt(self, prompt: &str) -> Self
pub fn system_prompt(self, prompt: &str) -> Self
Set the system prompt that defines the agent’s persona or constraints.
Sourcepub fn prompt(self, prompt: &str) -> Self
pub fn prompt(self, prompt: &str) -> Self
Set the user prompt - the main instruction sent to the agent.
Sourcepub fn model(self, model: impl Into<String>) -> Self
pub fn model(self, model: impl Into<String>) -> Self
Set the model to use for this invocation.
Accepts any string-like value. Use Model constants for well-known
Claude models, or pass an arbitrary string for custom providers.
Defaults to Model::SONNET if not called.
Sourcepub fn allowed_tools(self, tools: &[&str]) -> Self
pub fn allowed_tools(self, tools: &[&str]) -> Self
Restrict which tools the agent may invoke.
Pass an empty slice (or do not call this method) to allow the provider default set of tools.
Sourcepub fn max_budget_usd(self, budget: f64) -> Self
pub fn max_budget_usd(self, budget: f64) -> Self
Set the maximum spend in USD for this invocation.
§Panics
Panics if budget is negative, NaN, or infinity.
Sourcepub fn working_dir(self, dir: &str) -> Self
pub fn working_dir(self, dir: &str) -> Self
Set the working directory for the agent process.
Sourcepub fn mcp_config(self, config: &str) -> Self
pub fn mcp_config(self, config: &str) -> Self
Set the path to an MCP (Model Context Protocol) server configuration file.
Sourcepub fn permission_mode(self, mode: PermissionMode) -> Self
pub fn permission_mode(self, mode: PermissionMode) -> Self
Set the permission mode controlling tool-use approval behavior.
See PermissionMode for details on each variant.
Sourcepub fn output<T: JsonSchema>(self) -> Self
pub fn output<T: JsonSchema>(self) -> Self
Request structured (typed) output from the agent.
The type T must implement JsonSchema. The generated schema is sent
to the provider so the model returns JSON conforming to T, which can
then be deserialized with AgentResult::json.
§Examples
use ironflow_core::prelude::*;
#[derive(Deserialize, JsonSchema)]
struct Review {
score: u8,
summary: String,
}
let provider = ClaudeCodeProvider::new();
let result = Agent::new()
.prompt("Review the codebase")
.output::<Review>()
.run(&provider)
.await?;
let review: Review = result.json().expect("schema-validated output");
println!("Score: {}/10 - {}", review.score, review.summary);Sourcepub fn output_schema_raw(self, schema: &str) -> Self
pub fn output_schema_raw(self, schema: &str) -> Self
Set structured output from a pre-serialized JSON Schema string.
Use this when the schema comes from configuration or another source
rather than a Rust type. For type-safe schema generation, prefer
output.
Important: structured output requires max_turns >= 2. The Claude CLI
uses the first turn for reasoning and a second turn to produce the
schema-conforming JSON.
§Examples
use ironflow_core::prelude::*;
let schema = r#"{"type":"object","properties":{"labels":{"type":"array","items":{"type":"string"}}}}"#;
let agent = Agent::new()
.prompt("Classify this email")
.output_schema_raw(schema);Sourcepub fn retry(self, max_retries: u32) -> Self
pub fn retry(self, max_retries: u32) -> Self
Retry the agent invocation up to max_retries times on transient failures.
Uses default exponential backoff settings (200ms initial, 2x multiplier,
30s cap). For custom backoff parameters, use retry_policy.
Only transient errors are retried: process failures and timeouts. Deterministic errors (prompt too large, schema validation) are never retried.
§Panics
Panics if max_retries is 0.
§Examples
use ironflow_core::prelude::*;
let provider = ClaudeCodeProvider::new();
let result = Agent::new()
.prompt("Summarize the codebase")
.retry(2)
.run(&provider)
.await?;Sourcepub fn retry_policy(self, policy: RetryPolicy) -> Self
pub fn retry_policy(self, policy: RetryPolicy) -> Self
Set a custom RetryPolicy for this agent invocation.
Allows full control over backoff duration, multiplier, and max delay.
See RetryPolicy for details.
§Examples
use std::time::Duration;
use ironflow_core::prelude::*;
use ironflow_core::retry::RetryPolicy;
let provider = ClaudeCodeProvider::new();
let result = Agent::new()
.prompt("Analyze the code")
.retry_policy(
RetryPolicy::new(3)
.backoff(Duration::from_secs(1))
.max_backoff(Duration::from_secs(60))
)
.run(&provider)
.await?;Sourcepub fn dry_run(self, enabled: bool) -> Self
pub fn dry_run(self, enabled: bool) -> Self
Enable or disable dry-run mode for this specific operation.
When dry-run is active, the agent call is logged but not executed.
A synthetic AgentResult is returned with a placeholder text,
zero cost, and zero tokens.
If not set, falls back to the global dry-run setting
(see set_dry_run).
Sourcepub fn resume(self, session_id: &str) -> Self
pub fn resume(self, session_id: &str) -> Self
Resume a previous agent conversation by session ID.
Pass the session ID from a previous AgentResult::session_id() to
continue the multi-turn conversation.
§Examples
use ironflow_core::prelude::*;
let provider = ClaudeCodeProvider::new();
let first = Agent::new()
.prompt("Analyze the src/ directory")
.max_budget_usd(0.10)
.run(&provider)
.await?;
let session = first.session_id().expect("provider returned session ID");
let followup = Agent::new()
.prompt("Now suggest improvements")
.resume(session)
.max_budget_usd(0.10)
.run(&provider)
.await?;§Panics
Panics if session_id is empty or contains characters other than
alphanumerics, hyphens, and underscores.
Sourcepub async fn run(
self,
provider: &dyn AgentProvider,
) -> Result<AgentResult, OperationError>
pub async fn run( self, provider: &dyn AgentProvider, ) -> Result<AgentResult, OperationError>
Execute the agent invocation using the given AgentProvider.
If a retry_policy is configured, transient
failures (process crashes, timeouts) are retried with exponential
backoff. Deterministic errors (prompt too large, schema validation)
are returned immediately without retry.
§Errors
Returns OperationError::Agent if the provider reports a failure
(process crash, timeout, or schema validation error).
§Panics
Panics if prompt was never called or the prompt is
empty (whitespace-only counts as empty).