agents-core 0.0.27

Core traits, data models, and prompt primitives for building deep agents.
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
# Rust Deep Agents SDK

[![Crates.io](https://img.shields.io/crates/v/agents-runtime.svg)](https://crates.io/crates/agents-runtime)
[![Documentation](https://docs.rs/agents-runtime/badge.svg)](https://docs.rs/agents-runtime)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)

A high-performance Rust framework for building AI agents with custom tools, sub-agents, and persistent state management. Built for production use with enterprise-grade features like token tracking, cost monitoring, and human-in-the-loop workflows.

## 🆕 What's New in v0.0.24

- **Streaming Events**: Real-time token-by-token event broadcasting for streaming responses
- **StreamingToken Events**: New `AgentEvent::StreamingToken` variant for live updates
- **Opt-in Streaming**: Broadcasters can enable streaming via `supports_streaming()` method
- **Backward Compatible**: Existing broadcasters work unchanged (streaming disabled by default)
- **Enhanced Streaming**: `handle_message_stream()` now emits events for SSE/WebSocket integrations
- **Example**: New `streaming-events-demo` showing real-time token broadcasting

## Quick Start

### Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
agents-sdk = "0.0.24"
tokio = { version = "1.0", features = ["full"] }
anyhow = "1.0"
```

### Basic Agent

```rust
use agents_sdk::{ConfigurableAgentBuilder, OpenAiConfig, OpenAiChatModel, get_default_model};
use agents_macros::tool;
use agents_core::state::AgentStateSnapshot;
use std::sync::Arc;

// Define a tool using the #[tool] macro
#[tool("Adds two numbers together")]
fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create OpenAI configuration
    let config = OpenAiConfig::new(
        std::env::var("OPENAI_API_KEY")?,
        "gpt-4o-mini"
    );

    // Create the model
    let model = Arc::new(OpenAiChatModel::new(config)?);

    // Build an agent with tools
    let agent = ConfigurableAgentBuilder::new("You are a helpful math assistant.")
        .with_model(model)
        .with_tool(AddTool::as_tool())
        .build()?;

    // Use the agent
    let response = agent.handle_message(
        "What is 5 + 3?",
        Arc::new(AgentStateSnapshot::default())
    ).await?;
    
    println!("{}", response.content.as_text().unwrap_or("No response"));

    Ok(())
}
```

## Core Features

### 🤖 Agent Builder API

The `ConfigurableAgentBuilder` provides a fluent interface for constructing agents:

```rust
use agents_sdk::{ConfigurableAgentBuilder, OpenAiConfig, OpenAiChatModel, AnthropicConfig, AnthropicMessagesModel, GeminiConfig, GeminiChatModel};
use std::sync::Arc;

// OpenAI
let config = OpenAiConfig::new(api_key, "gpt-4o-mini")?;
let model = Arc::new(OpenAiChatModel::new(config)?);
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .build()?;

// Anthropic
let config = AnthropicConfig::new(api_key, "claude-3-5-sonnet-20241022")?;
let model = Arc::new(AnthropicMessagesModel::new(config)?);
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .build()?;

// Gemini
let config = GeminiConfig::new(api_key, "gemini-2.0-flash-exp")?;
let model = Arc::new(GeminiChatModel::new(config)?);
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .build()?;
```

### 🛠️ Tool System

Define tools using the `#[tool]` macro:

```rust
use agents_macros::tool;

// Simple synchronous tool
#[tool("Multiplies two numbers")]
fn multiply(a: f64, b: f64) -> f64 {
    a * b
}

// Async tool
#[tool("Fetches user data from API")]
async fn get_user(user_id: String) -> String {
    // Make API call...
    format!("User {}", user_id)
}

// Tool with optional parameters
#[tool("Searches with optional filters")]
fn search(query: String, max_results: Option<u32>) -> Vec<String> {
    let limit = max_results.unwrap_or(10);
    // Perform search...
    vec![]
}

// Use the tools
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_tools(vec![
        MultiplyTool::as_tool(),
        GetUserTool::as_tool(),
        SearchTool::as_tool(),
    ])
    .build()?;
```

### 💾 State Persistence

Choose from multiple persistence backends:

```rust
use agents_sdk::{ConfigurableAgentBuilder, InMemoryCheckpointer, RedisCheckpointer};

// In-memory (development)
let checkpointer = Arc::new(InMemoryCheckpointer::new());

// Redis (production)
let checkpointer = Arc::new(
    RedisCheckpointer::new("redis://127.0.0.1:6379").await?
);

let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_checkpointer(checkpointer)
    .build()?;

// Save and load state across sessions
let thread_id = "user-123";
agent.save_state(&thread_id).await?;
agent.load_state(&thread_id).await?;
```

### 📊 Token Tracking & Cost Monitoring

Monitor LLM usage and costs with built-in token tracking:

```rust
use agents_sdk::{ConfigurableAgentBuilder, TokenTrackingConfig, TokenCosts};

// Enable token tracking with default settings
let model = Arc::new(OpenAiChatModel::new(config)?);
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_token_tracking(true)  // Enable with defaults
    .build()?;

// Or configure with custom settings
let token_config = TokenTrackingConfig {
    enabled: true,
    emit_events: true,
    log_usage: true,
    custom_costs: Some(TokenCosts::openai_gpt4o_mini()),
};

let model = Arc::new(OpenAiChatModel::new(config)?);
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_token_tracking_config(token_config)
    .build()?;
```

**Features:**
- Real-time token usage tracking
- Cost estimation with predefined pricing models
- Performance metrics (duration, throughput)
- Event broadcasting integration
- Flexible configuration options

### 🔒 Human-in-the-Loop (HITL)

Require human approval for critical operations:

```rust
use agents_sdk::{ConfigurableAgentBuilder, HitlPolicy};
use std::collections::HashMap;

// Configure HITL policies
let mut policies = HashMap::new();
policies.insert(
    "delete_file".to_string(),
    HitlPolicy {
        allow_auto: false,
        note: Some("File deletion requires security review".to_string()),
    }
);

let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_tool_interrupts(policies)
    .with_checkpointer(checkpointer)  // Required for HITL
    .build()?;

// Handle interrupts
match agent.handle_message("Delete the old_data.txt file", state).await {
    Ok(response) => {
        // Check if execution was paused
        if let Some(text) = response.content.as_text() {
            if text.contains("paused") || text.contains("approval") {
                // HITL was triggered!
                if let Some(interrupt) = agent.current_interrupt().await? {
                    println!("Tool: {}", interrupt.tool_name);
                    println!("Args: {}", interrupt.tool_args);
                }
            }
        }
    }
    Err(e) => println!("Error: {}", e),
}

// Resume with approval
agent.resume_with_approval(HitlAction::Accept).await?;
```

### 📡 Event System

Real-time progress tracking and multi-channel notifications:

```rust
use agents_sdk::{ConfigurableAgentBuilder, EventBroadcaster};
use agents_core::events::AgentEvent;
use async_trait::async_trait;

struct ConsoleLogger;

#[async_trait]
impl EventBroadcaster for ConsoleLogger {
    fn id(&self) -> &str { "console" }
    
    async fn broadcast(&self, event: &AgentEvent) -> anyhow::Result<()> {
        match event {
            AgentEvent::AgentStarted(e) => println!("🚀 Agent started: {}", e.agent_name),
            AgentEvent::ToolStarted(e) => println!("🔧 Tool started: {}", e.tool_name),
            AgentEvent::ToolCompleted(e) => println!("✅ Tool completed: {}", e.tool_name),
            AgentEvent::TokenUsage(e) => println!("📊 Token usage: ${:.4}", e.usage.estimated_cost),
            _ => {}
        }
        Ok(())
    }
}

let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_event_broadcaster(Arc::new(ConsoleLogger))
    .build()?;
```

### 🔐 Security & PII Protection

Built-in security features prevent PII leakage:

```rust
// PII sanitization is enabled by default
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .build()?;

// Events automatically have:
// - Message previews truncated to 100 characters
// - Sensitive fields (passwords, tokens, etc.) redacted
// - PII patterns (emails, phones, credit cards) removed

// Disable only if you need raw data and have other security measures
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_pii_sanitization(false)  // Not recommended for production
    .build()?;
```

## Advanced Features

### Sub-Agents

Delegate tasks to specialized sub-agents:

```rust
use agents_sdk::{ConfigurableAgentBuilder, SubAgentConfig};

let subagent = SubAgentConfig {
    name: "data-processor".to_string(),
    description: "Processes complex data with custom logic".to_string(),
    instructions: "You are a data processing specialist.".to_string(),
    tools: vec![/* specialized tools */],
};

let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_subagent(subagent)
    .with_auto_general_purpose(true)  // Enable automatic delegation
    .build()?;
```

### Built-in Tools

The SDK includes useful built-in tools:

```rust
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_builtin_tools(vec![
        "write_todos".to_string(),
        "ls".to_string(),
        "read_file".to_string(),
        "write_file".to_string(),
    ])
    .build()?;
```

### Prompt Caching

Optimize performance with prompt caching:

```rust
let agent = ConfigurableAgentBuilder::new("You are a helpful assistant")
    .with_model(model)
    .with_prompt_caching(true)
    .build()?;
```

## Examples

The SDK includes comprehensive examples:

- [`simple-agent`]examples/simple-agent - Basic agent with OpenAI
- [`token-tracking-demo`]examples/token-tracking-demo - Token usage monitoring
- [`hitl-financial-advisor`]examples/hitl-financial-advisor - Human-in-the-loop workflows
- [`event-system-demo`]examples/event-system-demo - Event broadcasting
- [`checkpointer-demo`]examples/checkpointer-demo - State persistence
- [`subagent-demo`]examples/subagent-demo - Sub-agent delegation

Run examples:

```bash
# Clone the repository
git clone https://github.com/yafatek/rust-deep-agents-sdk.git
cd rust-deep-agents-sdk

# Run a specific example
cargo run --example simple-agent
cargo run --example token-tracking-demo
```

## Architecture

### Workspace Layout

- `crates/agents-core` - Core traits, message structures, and state models
- `crates/agents-runtime` - Runtime engine, builders, and middleware
- `crates/agents-toolkit` - Built-in tools and utilities
- `crates/agents-aws` - AWS integrations (DynamoDB, Secrets Manager)
- `crates/agents-persistence` - Persistence backends (Redis, PostgreSQL)
- `crates/agents-sdk` - Unified SDK with feature flags
- `examples/` - Working examples and demos
- `docs/` - Documentation and guides

### Middleware Stack

The SDK includes a powerful middleware system:

- **Planning Middleware**: Todo list management
- **Filesystem Middleware**: Mock filesystem operations
- **SubAgent Middleware**: Task delegation
- **HITL Middleware**: Human approval workflows
- **Token Tracking Middleware**: Usage and cost monitoring
- **Summarization Middleware**: Context window management
- **PII Sanitization**: Automatic data protection

### Provider Support

- **OpenAI**: GPT models (gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo)
- **Anthropic**: Claude models (claude-3-5-sonnet-20241022, claude-3-haiku-20240307)
- **Gemini**: Google's Gemini models (gemini-2.0-flash-exp, gemini-1.5-pro)

## Development

### Building from Source

```bash
git clone https://github.com/yafatek/rust-deep-agents-sdk.git
cd rust-deep-agents-sdk

# Format, lint, and test
cargo fmt
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all

# Build release
cargo build --release
```

### Feature Flags

The SDK supports feature flags for modular functionality:

```toml
[dependencies]
agents-sdk = { version = "0.0.23", features = ["aws", "redis"] }

# Available features:
# - "aws" - AWS integrations (DynamoDB, Secrets Manager)
# - "redis" - Redis persistence backend
# - "postgres" - PostgreSQL persistence backend
# - "dynamodb" - DynamoDB persistence backend
# - "full" - All features enabled
```

### Environment Variables

Required environment variables:

```bash
# OpenAI
export OPENAI_API_KEY="your-openai-api-key"

# Anthropic
export ANTHROPIC_API_KEY="your-anthropic-api-key"

# Gemini
export GOOGLE_API_KEY="your-google-api-key"

# Optional: Tavily for web search
export TAVILY_API_KEY="your-tavily-api-key"
```

## Performance

The Rust SDK is designed for high performance:

- **Memory Efficient**: Zero-copy message handling where possible
- **Async First**: Built on Tokio for concurrent operations
- **Type Safe**: Compile-time guarantees for agent configurations
- **Fast Compilation**: Optimized build times with feature flags
- **Low Latency**: Minimal overhead for tool calls and state management

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Run `cargo fmt` and `cargo clippy`
6. Submit a pull request

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

## Support

- 📖 [Documentation]https://docs.rs/agents-runtime
- 🐛 [Issue Tracker]https://github.com/yafatek/rust-deep-agents-sdk/issues
- 💬 [Discussions]https://github.com/yafatek/rust-deep-agents-sdk/discussions

## Roadmap

- [ ] Custom sub-agent execution graphs
- [ ] Dict-based model configuration
- [ ] Advanced state features (encryption, migrations)
- [ ] Enhanced tool system (composition, validation)
- [ ] Performance optimizations
- [ ] Additional LLM providers

---

**Built with ❤️ in Rust for the AI community**