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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Auto-execution mode integration tests
//!
//! Tests for automatic tool execution loop functionality.
//! These tests verify that when auto_execute_tools=true, the client
//! automatically executes tools and continues until a text-only response.
//!
//! NOTE: These tests make real API calls to Ollama at localhost:11434
//! Run with: cargo test --test auto_execution_test -- --test-threads=1 --nocapture

use open_agent::{AgentOptions, Client, ContentBlock, Error, tool};
use serde_json::json;
use tokio::time::{Duration, timeout};

const TEST_TIMEOUT: Duration = Duration::from_secs(30);
const OLLAMA_URL: &str = "http://localhost:11434/v1";
const MODEL: &str = "qwen3:8b";

/// Helper: Collect all response blocks with timeout
async fn collect_response(client: &mut Client) -> Result<(Vec<String>, usize), String> {
    let result = timeout(TEST_TIMEOUT, async {
        let mut text_blocks = Vec::new();
        let mut tool_blocks_received = 0;

        loop {
            match client.receive().await {
                Ok(Some(ContentBlock::Text(text))) => {
                    text_blocks.push(text.text);
                }
                Ok(Some(ContentBlock::ToolUse(_))) => {
                    tool_blocks_received += 1;
                }
                Ok(Some(ContentBlock::ToolResult(_))) => {
                    // Ignore tool results in auto mode
                }
                Ok(Some(ContentBlock::Image(_))) => {
                    // Images not relevant for this test
                }
                Ok(None) => break,
                Err(e) => {
                    return Err(format!("Error receiving block: {}", e));
                }
            }
        }

        Ok((text_blocks, tool_blocks_received))
    })
    .await;

    match result {
        Ok(Ok(data)) => Ok(data),
        Ok(Err(e)) => Err(e),
        Err(_) => Err("Test timed out after 30 seconds".to_string()),
    }
}

/// Test: Basic auto-execution with simple query (no tools needed)
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_simple_query() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant. Respond concisely.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client
        .send("What is 2+2? Answer with just the number.")
        .await
        .unwrap();

    let (text_blocks, tool_blocks) = collect_response(&mut client)
        .await
        .expect("Failed to collect response");

    assert!(!text_blocks.is_empty(), "Should receive text response");
    assert_eq!(
        tool_blocks, 0,
        "Should not receive tool blocks without tools"
    );
}

/// Test: Auto-execution with calculator tools
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_with_tools() {
    let add_tool = tool(
        "add",
        "Add two numbers a and b. Use this for addition only.",
    )
    .param("a", "number")
    .param("b", "number")
    .build(|args| async move {
        let a = args["a"].as_f64().unwrap_or(0.0);
        let b = args["b"].as_f64().unwrap_or(0.0);
        Ok(json!({"result": a + b}))
    });

    let options = AgentOptions::builder()
        .system_prompt(
            "You are a calculator. ALWAYS use the add tool for addition. Never calculate manually.",
        )
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .tools(vec![add_tool])
        .auto_execute_tools(true)
        .max_tool_iterations(5)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client
        .send("Use the add tool to calculate 25 + 17")
        .await
        .unwrap();

    let (text_blocks, tool_blocks) = collect_response(&mut client)
        .await
        .expect("Failed to collect response");

    // In auto mode, we should receive either text response or tool blocks
    // Some models return final text, others just execute the tool
    assert!(
        !text_blocks.is_empty() || tool_blocks > 0,
        "Should receive either text response or tool execution (got {} text blocks, {} tool blocks)",
        text_blocks.len(),
        tool_blocks
    );
}

/// Test: Auto-execution respects max_tool_iterations limit
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_max_iterations() {
    let increment_tool = tool("increment", "Add 1 to the value")
        .param("value", "number")
        .build(|args| async move {
            let value = args["value"].as_f64().unwrap_or(0.0);
            Ok(json!({"result": value + 1.0}))
        });

    let options = AgentOptions::builder()
        .system_prompt("You are a counter. Use the increment tool.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .tools(vec![increment_tool])
        .auto_execute_tools(true)
        .max_tool_iterations(2) // Limit to 2 iterations
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Increment 0 five times").await.unwrap();

    let result = collect_response(&mut client).await;

    // Should complete even if max iterations hit
    assert!(result.is_ok(), "Should complete despite iteration limit");
}

/// Test: Auto-execution handles tool errors gracefully
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_tool_error() {
    let failing_tool = tool("divide", "Divide two numbers")
        .param("a", "number")
        .param("b", "number")
        .build(|args| async move {
            let a = args["a"].as_f64().unwrap_or(0.0);
            let b = args["b"].as_f64().unwrap_or(0.0);

            if b == 0.0 {
                return Err(Error::tool("Cannot divide by zero"));
            }

            Ok(json!({"result": a / b}))
        });

    let options = AgentOptions::builder()
        .system_prompt("You are a calculator. Use the divide tool.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .tools(vec![failing_tool])
        .auto_execute_tools(true)
        .max_tool_iterations(3)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Calculate 10 divided by 2").await.unwrap();

    let result = collect_response(&mut client).await;

    // Should handle gracefully
    assert!(
        result.is_ok(),
        "Should complete even with potential tool errors"
    );
}

/// Test: Multiple tools available
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_multiple_tools() {
    let add_tool = tool("add", "Add two numbers")
        .param("a", "number")
        .param("b", "number")
        .build(|args| async move {
            let a = args["a"].as_f64().unwrap_or(0.0);
            let b = args["b"].as_f64().unwrap_or(0.0);
            Ok(json!({"result": a + b}))
        });

    let multiply_tool = tool("multiply", "Multiply two numbers")
        .param("a", "number")
        .param("b", "number")
        .build(|args| async move {
            let a = args["a"].as_f64().unwrap_or(0.0);
            let b = args["b"].as_f64().unwrap_or(0.0);
            Ok(json!({"result": a * b}))
        });

    let options = AgentOptions::builder()
        .system_prompt("You are a calculator with multiple operations.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .tools(vec![add_tool, multiply_tool])
        .auto_execute_tools(true)
        .max_tool_iterations(5)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client
        .send("What tools do you have available?")
        .await
        .unwrap();

    let result = collect_response(&mut client).await;
    assert!(result.is_ok(), "Should complete successfully");
}

/// Test: Auto-execution without tools behaves like normal mode
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_no_tools() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true) // Enabled but no tools provided
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Hello, respond briefly").await.unwrap();

    let (text_blocks, tool_blocks) = collect_response(&mut client)
        .await
        .expect("Failed to collect response");

    assert!(!text_blocks.is_empty(), "Should receive text response");
    assert_eq!(tool_blocks, 0, "Should not receive tool blocks");
}

/// Test: Manual mode (auto_execute_tools=false) returns ToolUse blocks
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_manual_mode_returns_tool_blocks() {
    let add_tool = tool("add", "Add two numbers")
        .param("a", "number")
        .param("b", "number")
        .build(|args| async move {
            let a = args["a"].as_f64().unwrap_or(0.0);
            let b = args["b"].as_f64().unwrap_or(0.0);
            Ok(json!({"result": a + b}))
        });

    let options = AgentOptions::builder()
        .system_prompt("You are a calculator. Use tools when asked.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .tools(vec![add_tool])
        .auto_execute_tools(false) // Manual mode
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("What is 5 plus 3?").await.unwrap();

    let result = timeout(TEST_TIMEOUT, async {
        let mut received_blocks = 0;

        loop {
            match client.receive().await {
                Ok(Some(_)) => {
                    received_blocks += 1;
                    // In manual mode, just verify we receive some blocks
                    if received_blocks > 0 {
                        break;
                    }
                }
                Ok(None) => break,
                Err(e) => {
                    return Err(format!("Error: {}", e));
                }
            }
        }

        Ok(received_blocks)
    })
    .await;

    assert!(result.is_ok(), "Should receive blocks in manual mode");
}

/// Test: Streaming response with auto-execution
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_streaming() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Count to 3").await.unwrap();

    let result = timeout(TEST_TIMEOUT, async {
        let mut block_count = 0;

        loop {
            match client.receive().await {
                Ok(Some(_)) => {
                    block_count += 1;
                }
                Ok(None) => break,
                Err(_) => break,
            }
        }

        block_count
    })
    .await;

    assert!(result.is_ok(), "Should stream response");
    assert!(result.unwrap() > 0, "Should receive at least one block");
}

/// Test: History tracking in auto-execution mode
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_history() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");

    let initial_history_len = client.history().len();

    client.send("Hello").await.unwrap();

    timeout(TEST_TIMEOUT, async {
        while client.receive().await.unwrap_or(None).is_some() {}
    })
    .await
    .ok();

    let final_history_len = client.history().len();

    assert!(
        final_history_len > initial_history_len,
        "History should grow after interaction"
    );
}

/// Test: Temperature affects randomness
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_temperature() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .temperature(0.1) // Low temperature for consistent responses
        .auto_execute_tools(true)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Say hello").await.unwrap();

    let result = collect_response(&mut client).await;
    assert!(result.is_ok(), "Should complete with custom temperature");
}

/// Test: Max tokens limit
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_max_tokens() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Tell me a story").await.unwrap();

    let (text_blocks, _) = collect_response(&mut client)
        .await
        .expect("Should complete despite low token limit");

    let total_text = text_blocks.join("");
    // Response should be short due to token limit
    assert!(!total_text.is_empty(), "Should receive some response");
}

/// Test: Timeout configuration
#[ignore] // Requires running Ollama server at localhost:11434
#[tokio::test]
async fn test_auto_execution_custom_timeout() {
    let options = AgentOptions::builder()
        .system_prompt("You are a helpful assistant.")
        .model(MODEL)
        .base_url(OLLAMA_URL)
        .auto_execute_tools(true)
        .temperature(0.1)
        .build()
        .unwrap();

    let mut client = Client::new(options).expect("Failed to create client");
    client.send("Hello").await.unwrap();

    // Should complete within our test timeout
    let result = collect_response(&mut client).await;
    assert!(result.is_ok(), "Should complete with custom timeout");
}