open-agent-sdk 0.9.1

Production-ready Rust SDK for building AI agents over two wire protocols: OpenAI chat completions (LMStudio, Ollama, llama.cpp, vLLM, OpenRouter) and Anthropic messages. 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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
impl Client {
    /// Receives the next content block from the current stream.
    ///
    /// This is the primary method for consuming responses from the model. It works
    /// differently depending on the operating mode:
    ///
    /// ## Manual Mode (default)
    ///
    /// Streams blocks directly from the API response as they arrive. You receive:
    /// - `TextBlock`: Incremental text from the model
    /// - `ToolUseBlock`: Requests to execute tools
    /// - Other block types as they're emitted
    ///
    /// When you receive a `ToolUseBlock`, you must:
    /// 1. Execute the tool yourself
    /// 2. Call `add_tool_result()` with the result
    /// 3. Call `send("")` to continue the conversation
    ///
    /// ## Automatic Mode (`auto_execute_tools = true`)
    ///
    /// Transparently executes tools and only returns final text blocks. The first
    /// call to `receive()` triggers the auto-execution loop which:
    /// 1. Collects all blocks from the stream
    /// 2. Executes any tool calls automatically
    /// 3. Continues the conversation until reaching a text-only response
    /// 4. Buffers the final text blocks
    /// 5. Returns them one at a time on subsequent `receive()` calls
    ///
    /// # Returns
    ///
    /// - `Ok(Some(block))`: Successfully received a content block
    /// - `Ok(None)`: Stream ended normally or was interrupted
    /// - `Err(e)`: An error occurred during streaming or tool execution
    ///
    /// # Behavior Details
    ///
    /// ## Interruption
    ///
    /// Checks the interrupt flag on every call. If interrupted, immediately returns
    /// `Ok(None)` and clears the stream. The client can be reused after interruption.
    ///
    /// ## Stream Lifecycle
    ///
    /// 1. After `send()`, stream is active
    /// 2. Each `receive()` call yields one block
    /// 3. When stream ends, returns `Ok(None)`
    /// 4. Subsequent calls continue returning `Ok(None)` until next `send()`
    ///
    /// ## Auto-Execution Buffer
    ///
    /// In auto mode, blocks are buffered in memory. The buffer persists until
    /// fully consumed (index reaches length), at which point it's cleared.
    ///
    /// # State Changes
    ///
    /// - Advances stream position
    /// - In auto mode: May trigger entire execution loop and modify history
    /// - In manual mode: Only reads from stream, no history changes
    /// - Increments `auto_exec_index` when returning buffered blocks
    ///
    /// # Examples
    ///
    /// ## Manual Mode - Basic
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions, ContentBlock};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut client = Client::new(AgentOptions::default())?;
    /// client.send("Hello!").await?;
    ///
    /// while let Some(block) = client.receive().await? {
    ///     match block {
    ///         ContentBlock::Text(text) => print!("{}", text.text),
    ///         ContentBlock::ToolUse(_) | ContentBlock::ToolResult(_) | ContentBlock::Image(_) => {}
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Manual Mode - With Tools
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions, ContentBlock};
    /// # use serde_json::json;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut client = Client::new(AgentOptions::default())?;
    /// client.send("Use the calculator").await?;
    ///
    /// while let Some(block) = client.receive().await? {
    ///     match block {
    ///         ContentBlock::Text(text) => {
    ///             println!("{}", text.text);
    ///         }
    ///         ContentBlock::ToolUse(tool_use) => {
    ///             println!("Executing: {}", tool_use.name());
    ///
    ///             // Execute tool manually
    ///             let result = json!({"result": 42});
    ///
    ///             // Add result and continue
    ///             client.add_tool_result(tool_use.id(), result)?;
    ///             client.send("").await?;
    ///         }
    ///         ContentBlock::ToolResult(_) | ContentBlock::Image(_) => {}
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Auto Mode
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions, ContentBlock, Tool};
    /// # use serde_json::json;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::builder()
    ///     .auto_execute_tools(true)
    ///     .build()?)?;
    ///
    /// client.send("Calculate 2+2").await?;
    ///
    /// // Tools execute automatically - you only get final text
    /// while let Some(block) = client.receive().await? {
    ///     if let ContentBlock::Text(text) = block {
    ///         println!("{}", text.text);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## With Error Handling
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut client = Client::new(AgentOptions::default())?;
    /// client.send("Hello").await?;
    ///
    /// loop {
    ///     match client.receive().await {
    ///         Ok(Some(block)) => {
    ///             // Process block
    ///         }
    ///         Ok(None) => {
    ///             // Stream ended
    ///             break;
    ///         }
    ///         Err(e) => {
    ///             eprintln!("Error: {}", e);
    ///             break;
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    pub async fn receive(&mut self) -> Result<Option<ContentBlock>> {
        // ========================================================================
        // AUTO-EXECUTION MODE
        // ========================================================================
        if self.options.auto_execute_tools() {
            // Check if we have buffered blocks to return
            // In auto mode, all final text blocks are buffered and returned one at a time
            if self.auto_exec_index < self.auto_exec_buffer.len() {
                // Return next buffered block
                let block = self.auto_exec_buffer[self.auto_exec_index].clone();
                self.auto_exec_index += 1;
                return Ok(Some(block));
            }

            // No buffered blocks - need to run auto-execution loop
            // This only happens on the first receive() call after send()
            if self.auto_exec_buffer.is_empty() {
                match self.auto_execute_loop().await {
                    Ok(blocks) => {
                        // Buffer all final text blocks
                        self.auto_exec_buffer = blocks;
                        self.auto_exec_index = 0;

                        // If no blocks, return None (empty response)
                        if self.auto_exec_buffer.is_empty() {
                            return Ok(None);
                        }

                        // Return first buffered block
                        let block = self.auto_exec_buffer[0].clone();
                        self.auto_exec_index = 1;
                        return Ok(Some(block));
                    }
                    Err(e) => return Err(e),
                }
            }

            // Buffer exhausted - return None
            Ok(None)
        } else {
            // ====================================================================
            // MANUAL MODE
            // ====================================================================
            // Stream blocks to caller while accumulating them so we can add
            // the complete assistant message to history when the stream ends.
            match self.receive_one().await {
                Err(e) => {
                    // Stream error — discard partial output so a retry
                    // doesn't flush truncated blocks into history.
                    self.manual_receive_buffer.clear();
                    Err(e)
                }
                Ok(Some(block)) => {
                    self.manual_receive_buffer.push(block.clone());
                    Ok(Some(block))
                }
                Ok(None) => {
                    if self.interrupted.load(Ordering::SeqCst) && self.current_stream.is_some() {
                        // Interrupted a live stream — discard partial output.
                        // current_stream is still Some because receive_one()
                        // only clears it on natural EOF, not on interrupt.
                        self.current_stream = None;
                        self.manual_receive_buffer.clear();
                    } else if !self.manual_receive_buffer.is_empty() {
                        // Either natural EOF or interrupt after stream already
                        // finished — commit the (complete) assistant message.
                        let blocks = std::mem::take(&mut self.manual_receive_buffer);
                        self.history.push(Message::assistant(blocks));
                    }
                    Ok(None)
                }
            }
        }
    }

    /// Interrupts the current operation by setting the interrupt flag.
    ///
    /// This method provides a thread-safe way to cancel any in-progress streaming
    /// operation. The interrupt flag is checked by `receive()` before each block,
    /// allowing responsive cancellation.
    ///
    /// # Behavior
    ///
    /// - Sets the atomic interrupt flag to `true`
    /// - Next `receive()` call will return `Ok(None)` and clear the stream
    /// - Flag is automatically reset to `false` on next `send()` call
    /// - Safe to call from any thread (uses atomic operations)
    /// - Idempotent: calling multiple times has same effect as calling once
    /// - No-op if no operation is in progress
    ///
    /// # Thread Safety
    ///
    /// This method uses `Arc<AtomicBool>` internally, which can be safely shared
    /// across threads. You can clone the interrupt handle and use it from different
    /// threads or async tasks:
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::default())?;
    /// let interrupt_handle = client.interrupt_handle();
    ///
    /// // Use from another thread
    /// tokio::spawn(async move {
    ///     tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    ///     interrupt_handle.store(true, std::sync::atomic::Ordering::SeqCst);
    /// });
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # State Changes
    ///
    /// - Sets `interrupted` flag to `true`
    /// - Does NOT modify stream, history, or other state directly
    /// - Effect takes place on next `receive()` call
    ///
    /// # Use Cases
    ///
    /// - User cancellation (e.g., stop button in UI)
    /// - Timeout enforcement
    /// - Resource cleanup
    /// - Emergency shutdown
    ///
    /// # Examples
    ///
    /// ## Basic Interruption
    ///
    /// ```rust,no_run
    /// use open_agent::{Client, AgentOptions};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::default())?;
    ///
    /// client.send("Tell me a long story").await?;
    ///
    /// // Interrupt after receiving some blocks
    /// let mut count = 0;
    /// while let Some(block) = client.receive().await? {
    ///     count += 1;
    ///     if count >= 5 {
    ///         client.interrupt();
    ///     }
    /// }
    ///
    /// // Client is ready for new queries
    /// client.send("What's 2+2?").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## With Timeout
    ///
    /// ```rust,no_run
    /// use open_agent::{Client, AgentOptions};
    /// use std::time::Duration;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::default())?;
    ///
    /// client.send("Long request").await?;
    ///
    /// // Spawn timeout task
    /// let interrupt_handle = client.interrupt_handle();
    /// tokio::spawn(async move {
    ///     tokio::time::sleep(Duration::from_secs(10)).await;
    ///     interrupt_handle.store(true, std::sync::atomic::Ordering::SeqCst);
    /// });
    ///
    /// while let Some(_block) = client.receive().await? {
    ///     // Process until timeout
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn interrupt(&self) {
        // Set interrupt flag using SeqCst for immediate visibility across all threads
        self.interrupted.store(true, Ordering::SeqCst);
    }

    /// Returns a clone of the interrupt handle for thread-safe cancellation.
    ///
    /// This method provides access to the shared `Arc<AtomicBool>` interrupt flag,
    /// allowing it to be used from other threads or async tasks to signal cancellation.
    ///
    /// # Returns
    ///
    /// A cloned `Arc<AtomicBool>` that can be used to interrupt operations from any thread.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::default())?;
    /// let interrupt_handle = client.interrupt_handle();
    ///
    /// // Use from another thread
    /// tokio::spawn(async move {
    ///     tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    ///     interrupt_handle.store(true, std::sync::atomic::Ordering::SeqCst);
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub fn interrupt_handle(&self) -> Arc<AtomicBool> {
        self.interrupted.clone()
    }

    /// Returns a reference to the conversation history.
    ///
    /// The history contains all messages exchanged in the conversation, including:
    /// - User messages
    /// - Assistant messages (with text and tool use blocks)
    /// - Tool result messages
    ///
    /// # Returns
    ///
    /// A slice of `Message` objects in chronological order.
    ///
    /// # Use Cases
    ///
    /// - Inspecting conversation context
    /// - Debugging tool execution flow
    /// - Saving conversation state
    /// - Implementing custom history management
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use open_agent::{Client, AgentOptions};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new(AgentOptions::default())?;
    ///
    /// // Initially empty
    /// assert_eq!(client.history().len(), 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn history(&self) -> &[Message] {
        &self.history
    }

    /// Returns a mutable reference to the conversation history.
    ///
    /// This allows you to modify the history directly for advanced use cases like:
    /// - Removing old messages to manage context length
    /// - Editing messages for retry scenarios
    /// - Injecting synthetic messages for testing
    ///
    /// # Warning
    ///
    /// Modifying history directly can lead to inconsistent conversation state if not
    /// done carefully. The SDK expects history to follow the proper message flow
    /// (user → assistant → tool results → assistant, etc.).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use open_agent::{Client, AgentOptions};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = Client::new(AgentOptions::default())?;
    ///
    /// // Remove oldest messages to stay within context limit
    /// if client.history().len() > 50 {
    ///     client.history_mut().drain(0..10);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn history_mut(&mut self) -> &mut Vec<Message> {
        &mut self.history
    }

    /// Returns a reference to the agent configuration options.
    ///
    /// Provides read-only access to the `AgentOptions` used to configure this client.
    ///
    /// # Use Cases
    ///
    /// - Inspecting current configuration
    /// - Debugging issues
    /// - Conditional logic based on settings
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use open_agent::{Client, AgentOptions};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new(AgentOptions::builder()
    ///     .model("gpt-4")
    ///     .base_url("http://localhost:1234/v1")
    ///     .build()?)?;
    ///
    /// println!("Using model: {}", client.options().model());
    /// # Ok(())
    /// # }
    /// ```
    pub fn options(&self) -> &AgentOptions {
        &self.options
    }

    /// Returns why the most recent stream stopped generating.
    ///
    /// `None` until a stream completes; the value is cleared when the next request starts, so
    /// read it *after* the `receive()` loop drains, not during it.
    ///
    /// This is what distinguishes a response cut off at the token cap
    /// ([`FinishReason::Length`]) from one the model chose to end ([`FinishReason::Stop`]) and
    /// from a server that never said ([`FinishReason::Unspecified`]) — three cases that look
    /// identical from the content alone, and that call for different handling when the caller
    /// is parsing structured output.
    ///
    /// In auto-execution mode this reports the last generation of the tool loop, which is the
    /// one that produced the text the caller receives — except when the loop itself stopped
    /// at `max_tool_iterations`, which reports [`FinishReason::MaxToolIterations`] because
    /// the SDK, not the model, ended the operation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use open_agent::{Client, AgentOptions, FinishReason};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut client = Client::new(AgentOptions::default())?;
    /// let mut answer = String::new();
    /// client.send("Reply with JSON.").await?;
    /// while let Some(block) = client.receive().await? {
    ///     if let open_agent::ContentBlock::Text(text) = block {
    ///         answer.push_str(&text.text);
    ///     }
    /// }
    ///
    /// if client.finish_reason().is_some_and(FinishReason::is_truncated) {
    ///     // The JSON is missing because generation ran out of budget, not because the
    ///     // model refused. Retry with a larger cap instead of giving up.
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn finish_reason(&self) -> Option<&FinishReason> {
        self.last_finish_reason.as_ref()
    }

    /// Returns the reasoning text captured from the most recent stream.
    ///
    /// Always `None` unless
    /// [`AgentOptions::include_reasoning`](crate::AgentOptions::include_reasoning) is enabled.
    /// Reasoning is kept out of [`Client::history`], so enabling capture never changes what is
    /// replayed to the model on the next turn.
    ///
    /// Cleared when the caller starts a new turn. Unlike [`Client::finish_reason`], it
    /// *accumulates* across an auto-execution tool loop rather than being overwritten each
    /// round: the deliberation that chose the tools is the part worth keeping, so discarding
    /// all but the final round would throw away most of what was asked for.
    pub fn reasoning(&self) -> Option<&str> {
        (!self.last_reasoning.is_empty()).then_some(self.last_reasoning.as_str())
    }

}