open-agent-sdk 0.6.4

Production-ready Rust SDK for building AI agents with local OpenAI-compatible servers (LMStudio, Ollama, llama.cpp, vLLM). Features streaming, tools, hooks, retry logic, and comprehensive examples.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Advanced Patterns - Retry Logic and Concurrent Requests
//!
//! This example demonstrates advanced patterns for production use:
//! 1. Retry with exponential backoff for handling transient failures
//! 2. Concurrent request handling for parallel queries
//! 3. Error handling strategies
//!
//! Usage:
//!     cargo run --example advanced_patterns

use futures::stream::{FuturesUnordered, StreamExt};
use open_agent::retry::{RetryConfig, retry_with_backoff, retry_with_backoff_conditional};
use open_agent::{AgentOptions, Client, ContentBlock};
use std::time::Duration;
use tokio::time::Instant;

// ============================================================================
// Example 1: Retry with Exponential Backoff
// ============================================================================
async fn retry_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "=".repeat(60));
    println!("Example 1: Retry with Exponential Backoff");
    println!("{}", "=".repeat(60));
    println!();

    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model("qwen3:8b")
        .base_url("http://localhost:11434/v1")
        .temperature(0.7)
        .timeout(5) // Short timeout to demonstrate retries
        .build()?;

    // Configure retry behavior
    let retry_config = RetryConfig::new()
        .with_max_attempts(3)
        .with_initial_delay(Duration::from_secs(1))
        .with_backoff_multiplier(2.0)
        .with_jitter_factor(0.1);

    println!("🔄 Attempting query with retry (up to 3 attempts)...\n");

    let start = Instant::now();
    let result = retry_with_backoff(retry_config, || async {
        let mut client = Client::new(options.clone())?;
        client.send("What is 2+2?").await?;

        let mut response = String::new();
        while let Some(block) = client.receive().await? {
            if let ContentBlock::Text(text) = block {
                response.push_str(&text.text);
            }
        }

        Ok::<_, open_agent::Error>(response)
    })
    .await;

    match result {
        Ok(response) => {
            println!("✅ Success after {:?}", start.elapsed());
            println!("Response: {}\n", response.trim());
        }
        Err(e) => {
            println!("❌ Failed after all retries: {}\n", e);
        }
    }

    Ok(())
}

// ============================================================================
// Example 2: Conditional Retry (Only Retry Transient Errors)
// ============================================================================
async fn conditional_retry_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "=".repeat(60));
    println!("Example 2: Conditional Retry (Transient Errors Only)");
    println!("{}", "=".repeat(60));
    println!();

    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model("qwen3:8b")
        .base_url("http://localhost:11434/v1")
        .temperature(0.7)
        .build()?;

    let retry_config = RetryConfig::new().with_max_attempts(3);

    println!("🔄 Using conditional retry (only retries network/server errors)...\n");

    let start = Instant::now();
    let result = retry_with_backoff_conditional(retry_config, || async {
        let mut client = Client::new(options.clone())?;
        client
            .send("Explain quantum computing in one sentence")
            .await?;

        let mut response = String::new();
        while let Some(block) = client.receive().await? {
            if let ContentBlock::Text(text) = block {
                response.push_str(&text.text);
            }
        }

        Ok::<_, open_agent::Error>(response)
    })
    .await;

    match result {
        Ok(response) => {
            println!("✅ Success after {:?}", start.elapsed());
            println!("Response: {}\n", response.trim());
        }
        Err(e) => {
            println!("❌ Failed: {}\n", e);
        }
    }

    Ok(())
}

// ============================================================================
// Example 3: Concurrent Requests
// ============================================================================
async fn concurrent_requests_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "=".repeat(60));
    println!("Example 3: Concurrent Requests");
    println!("{}", "=".repeat(60));
    println!();

    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model("qwen3:8b")
        .base_url("http://localhost:11434/v1")
        .temperature(0.7)
        .build()?;

    let questions = [
        "What is 5+5?",
        "What is the capital of France?",
        "Name a primary color",
    ];

    println!("🚀 Running {} queries in parallel...\n", questions.len());

    let start = Instant::now();

    // Create concurrent futures using FuturesUnordered (doesn't require Sync)
    let mut futures = FuturesUnordered::new();
    for (i, question) in questions.iter().enumerate() {
        let options_clone = options.clone();
        let question_owned = question.to_string();

        let future = async move {
            let mut client = Client::new(options_clone)?;
            client.send(&question_owned).await?;

            let mut response = String::new();
            while let Some(block) = client.receive().await? {
                if let ContentBlock::Text(text) = block {
                    response.push_str(&text.text);
                }
            }

            Ok::<(usize, String, String), open_agent::Error>((i, question_owned, response))
        };

        futures.push(future);
    }

    // Collect all results
    let mut results = Vec::new();
    while let Some(result) = futures.next().await {
        results.push(result);
    }

    let elapsed = start.elapsed();

    println!("✅ All queries completed in {:?}\n", elapsed);

    // Print results
    for result in results {
        match result {
            Ok((i, question, response)) => {
                println!("Query {}: {}", i + 1, question);
                println!("Response: {}", response.trim());
                println!();
            }
            Err(e) => {
                println!("❌ Query failed: {}\n", e);
            }
        }
    }

    Ok(())
}

// ============================================================================
// Example 4: Concurrent with Retry
// ============================================================================
async fn concurrent_with_retry_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "=".repeat(60));
    println!("Example 4: Concurrent Requests with Retry");
    println!("{}", "=".repeat(60));
    println!();

    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model("qwen3:8b")
        .base_url("http://localhost:11434/v1")
        .temperature(0.7)
        .build()?;

    let questions = ["What is 10+10?", "What is the capital of Japan?"];

    let retry_config = RetryConfig::new()
        .with_max_attempts(2)
        .with_initial_delay(Duration::from_millis(500));

    println!(
        "🚀 Running {} queries in parallel with retry...\n",
        questions.len()
    );

    let start = Instant::now();

    // Create concurrent futures with retry using FuturesUnordered
    let mut futures = FuturesUnordered::new();
    for (i, question) in questions.iter().enumerate() {
        let options_clone = options.clone();
        let question_owned = question.to_string();
        let retry_config_clone = retry_config.clone();

        let future = async move {
            // Wrap the operation in retry logic
            let result = retry_with_backoff(retry_config_clone, || async {
                let mut client = Client::new(options_clone.clone())?;
                client.send(&question_owned).await?;

                let mut response = String::new();
                while let Some(block) = client.receive().await? {
                    if let ContentBlock::Text(text) = block {
                        response.push_str(&text.text);
                    }
                }

                Ok::<String, open_agent::Error>(response)
            })
            .await;

            result.map(|response| (i, question_owned, response))
        };

        futures.push(future);
    }

    // Collect all results
    let mut results = Vec::new();
    while let Some(result) = futures.next().await {
        results.push(result);
    }

    let elapsed = start.elapsed();

    println!("✅ All queries completed in {:?}\n", elapsed);

    // Print results
    for result in results {
        match result {
            Ok((i, question, response)) => {
                println!("Query {}: {}", i + 1, question);
                println!("Response: {}", response.trim());
                println!();
            }
            Err(e) => {
                println!("❌ Query failed after retries: {}\n", e);
            }
        }
    }

    Ok(())
}

// ============================================================================
// Example 5: Rate Limiting with Semaphore
// ============================================================================
async fn rate_limiting_example() -> Result<(), Box<dyn std::error::Error>> {
    println!("{}", "=".repeat(60));
    println!("Example 5: Rate Limiting with Semaphore");
    println!("{}", "=".repeat(60));
    println!();

    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model("qwen3:8b")
        .base_url("http://localhost:11434/v1")
        .temperature(0.7)
        .build()?;

    let questions = [
        "What is 1+1?",
        "What is 2+2?",
        "What is 3+3?",
        "What is 4+4?",
        "What is 5+5?",
    ];

    // Limit to 2 concurrent requests at a time
    let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(2));

    println!(
        "🚦 Running {} queries with max 2 concurrent...\n",
        questions.len()
    );

    let start = Instant::now();

    // Create futures with rate limiting using FuturesUnordered
    let mut futures = FuturesUnordered::new();
    for (i, question) in questions.iter().enumerate() {
        let options_clone = options.clone();
        let question_owned = question.to_string();
        let semaphore_clone = semaphore.clone();

        let future = async move {
            // Acquire permit before executing
            let _permit = semaphore_clone.acquire().await.unwrap();
            println!("  [Starting Query {}]", i + 1);

            let mut client = Client::new(options_clone)?;
            client.send(&question_owned).await?;

            let mut response = String::new();
            while let Some(block) = client.receive().await? {
                if let ContentBlock::Text(text) = block {
                    response.push_str(&text.text);
                }
            }

            println!("  [Completed Query {}]", i + 1);

            Ok::<(usize, String, String), open_agent::Error>((i, question_owned, response))
            // Permit is automatically released when _permit drops
        };

        futures.push(future);
    }

    // Collect all results
    let mut results = Vec::new();
    while let Some(result) = futures.next().await {
        results.push(result);
    }

    let elapsed = start.elapsed();

    println!("\n✅ All queries completed in {:?}\n", elapsed);

    // Print results
    for result in results {
        match result {
            Ok((i, question, response)) => {
                println!("Query {}: {} => {}", i + 1, question, response.trim());
            }
            Err(e) => {
                println!("❌ Query failed: {}\n", e);
            }
        }
    }

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n{}", "=".repeat(60));
    println!("ADVANCED PATTERNS DEMO");
    println!("{}", "=".repeat(60));
    println!();

    println!("This demo requires Ollama running at http://localhost:11434");
    println!("with a model loaded (e.g., qwen3:8b)\n");

    // Run examples
    if let Err(e) = retry_example().await {
        eprintln!("Retry example error: {}", e);
    }
    tokio::time::sleep(Duration::from_secs(1)).await;

    if let Err(e) = conditional_retry_example().await {
        eprintln!("Conditional retry example error: {}", e);
    }
    tokio::time::sleep(Duration::from_secs(1)).await;

    if let Err(e) = concurrent_requests_example().await {
        eprintln!("Concurrent requests example error: {}", e);
    }
    tokio::time::sleep(Duration::from_secs(1)).await;

    if let Err(e) = concurrent_with_retry_example().await {
        eprintln!("Concurrent with retry example error: {}", e);
    }
    tokio::time::sleep(Duration::from_secs(1)).await;

    if let Err(e) = rate_limiting_example().await {
        eprintln!("Rate limiting example error: {}", e);
    }

    println!("\n{}", "=".repeat(60));
    println!("All examples completed!");
    println!("{}", "=".repeat(60));

    Ok(())
}