helios-engine 0.2.5

A powerful and flexible Rust framework for building LLM-powered agents with tool support Both locally and online
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# Helios Usage Guide

This guide covers all the ways to use Helios - both as a CLI tool and as a library crate.

## Table of Contents

1. [Installation]#installation
2. [CLI Usage]#cli-usage
3. [Library Usage]#library-usage
4. [Configuration]#configuration
5. [Examples]#examples

## Installation

### Install as CLI Tool

Once published to crates.io, install globally:

```bash
cargo install helios-engine
```

Then use anywhere:

```bash
helios-engine --help
```

### Use as Library

Add to your project's `Cargo.toml`:

```toml
[dependencies]
helios-engine = "0.1.0"
tokio = { version = "1.35", features = ["full"] }
```

### Build from Source

```bash
git clone https://github.com/yourusername/helios.git
cd helios

# Build and install CLI
cargo install --path .

# Or just build
cargo build --release
./target/release/helios
```

## CLI Usage

### Initialize Configuration

Create a new config file:

```bash
helios-engine init
```

This creates `config.toml` with default settings. Edit it to add your API key.

Create config in a custom location:

```bash
helios-engine init --output ~/.helios/config.toml
```

### Interactive Chat

Start an interactive chat session (default command):

```bash
helios-engine
# or explicitly
helios-engine chat
```

With custom config file:

```bash
helios-engine --config /path/to/config.toml chat
```

With custom system prompt:

```bash
helios-engine chat --system-prompt "You are a Python expert"
```

With custom max iterations:

```bash
helios-engine chat --max-iterations 10
```

### One-Off Questions

Ask a single question without interactive mode:

```bash
helios-engine ask "What is the capital of France?"
```

With custom config:

```bash
helios-engine --config my-config.toml ask "Calculate 123 * 456"
```

### Verbose Mode

Enable debug logging:

```bash
helios-engine --verbose chat
```

### CLI Examples

```bash
# Initialize config
helios-engine init

# Start chat with default settings
helios-engine

# Chat with custom prompt
helios-engine chat -s "You are a Rust expert"

# Single question
helios-engine ask "What is 2+2?"

# Verbose logging
helios -v chat

# Custom config location
helios -c ~/.config/helios.toml chat
```

### CLI Help

```bash
# General help
helios-engine --help

# Help for specific command
helios-engine chat --help
helios-engine init --help
helios-engine ask --help
```

## Library Usage

### Use Case 1: Direct LLM Calls (Simplest)

For simple, direct calls to LLM models:

```rust
use helios_engine::{LLMClient, ChatMessage, LLMConfig};

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    // Configure LLM
    let config = LLMConfig {
        model_name: "gpt-3.5-turbo".to_string(),
        base_url: "https://api.openai.com/v1".to_string(),
        api_key: std::env::var("OPENAI_API_KEY").unwrap(),
        temperature: 0.7,
        max_tokens: 2048,
    };

    // Create client
    let client = LLMClient::new(config);

    // Make a call
    let messages = vec![
        ChatMessage::system("You are a helpful assistant."),
        ChatMessage::user("What is Rust?"),
    ];

    let response = client.chat(messages, None).await?;
    println!("{}", response.content);

    Ok(())
}
```

### Use Case 2: Conversation with Context

Manage multi-turn conversations:

```rust
use helios_engine::{LLMClient, ChatSession, LLMConfig};

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    let config = LLMConfig {
        model_name: "gpt-3.5-turbo".to_string(),
        base_url: "https://api.openai.com/v1".to_string(),
        api_key: std::env::var("OPENAI_API_KEY").unwrap(),
        temperature: 0.7,
        max_tokens: 2048,
    };

    let client = LLMClient::new(config);
    
    // Create session with system prompt
    let mut session = ChatSession::new()
        .with_system_prompt("You are a helpful assistant.");

    // First message
    session.add_user_message("What is Rust?");
    let response = client.chat(session.get_messages(), None).await?;
    session.add_assistant_message(&response.content);
    println!("Assistant: {}", response.content);

    // Follow-up (with context)
    session.add_user_message("What are its main features?");
    let response = client.chat(session.get_messages(), None).await?;
    session.add_assistant_message(&response.content);
    println!("Assistant: {}", response.content);

    Ok(())
}
```

### Use Case 3: Agent with Tools

For advanced use cases with tools:

```rust
use helios_engine::{Agent, Config, CalculatorTool};

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    // Load config from file
    let config = Config::from_file("config.toml")?;

    // Create agent with tools
    let mut agent = Agent::builder("MyAgent")
        .config(config)
        .system_prompt("You are a helpful assistant with tools.")
        .tool(Box::new(CalculatorTool))
        .max_iterations(5)
        .build()?;

    // Chat
    let response = agent.chat("What is 123 * 456?").await?;
    println!("{}", response);

    Ok(())
}
```

### Use Case 4: Custom Tool Implementation

Create your own tools:

```rust
use helios_engine::{Tool, ToolParameter, ToolResult, Agent, Config};
use async_trait::async_trait;
use serde_json::json;

struct WeatherTool;

#[async_trait]
impl Tool for WeatherTool {
    fn name(&self) -> String {
        "get_weather".to_string()
    }

    fn description(&self) -> String {
        "Get weather for a location".to_string()
    }

    fn parameters(&self) -> Vec<ToolParameter> {
        vec![
            ToolParameter {
                name: "location".to_string(),
                param_type: "string".to_string(),
                description: "City name".to_string(),
                required: true,
            }
        ]
    }

    async fn execute(&self, args: serde_json::Value) -> ToolResult {
        let location = args["location"].as_str()
            .ok_or("Missing location")?;
        
        // Simulate weather API call
        let weather = format!("Sunny, 72°F in {}", location);
        Ok(json!({"weather": weather}).to_string())
    }
}

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    let config = Config::from_file("config.toml")?;

    let mut agent = Agent::builder("WeatherAgent")
        .config(config)
        .system_prompt("You help with weather info.")
        .tool(Box::new(WeatherTool))
        .build()?;

    let response = agent.chat("What's the weather in Paris?").await?;
    println!("{}", response);

    Ok(())
}
```

### Use Case 5: Multiple Agents

Create and manage multiple agents:

```rust
use helios_engine::{Agent, Config};

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    let config = Config::from_file("config.toml")?;

    let mut math_agent = Agent::builder("MathExpert")
        .config(config.clone())
        .system_prompt("You are a math expert.")
        .build()?;

    let mut writer_agent = Agent::builder("Writer")
        .config(config)
        .system_prompt("You are a creative writer.")
        .build()?;

    let math_response = math_agent.chat("What is 15 * 23?").await?;
    println!("Math Expert: {}", math_response);

    let writer_response = writer_agent.chat("Write a haiku about code").await?;
    println!("Writer: {}", writer_response);

    Ok(())
}
```

## Configuration

### Configuration File Format

Create a `config.toml` file:

```toml
[llm]
model_name = "gpt-3.5-turbo"
base_url = "https://api.openai.com/v1"
api_key = "sk-your-api-key-here"
temperature = 0.7
max_tokens = 2048
```

### Configuration in Code

Create config programmatically:

```rust
use helios_engine::config::LLMConfig;

let config = LLMConfig {
    model_name: "gpt-3.5-turbo".to_string(),
    base_url: "https://api.openai.com/v1".to_string(),
    api_key: std::env::var("OPENAI_API_KEY").unwrap(),
    temperature: 0.7,
    max_tokens: 2048,
};
```

### Provider-Specific Configurations

**OpenAI:**
```toml
[llm]
model_name = "gpt-4"
base_url = "https://api.openai.com/v1"
api_key = "sk-..."
```

**Azure OpenAI:**
```toml
[llm]
model_name = "gpt-35-turbo"
base_url = "https://your-resource.openai.azure.com/openai/deployments/your-deployment"
api_key = "your-azure-key"
```

**Local LM Studio:**
```toml
[llm]
model_name = "local-model"
base_url = "http://localhost:1234/v1"
api_key = "not-needed"
```

**Ollama:**
```toml
[llm]
model_name = "llama2"
base_url = "http://localhost:11434/v1"
api_key = "not-needed"
```

### Environment Variables

Use environment variables for sensitive data:

```rust
use helios_engine::config::LLMConfig;

let config = LLMConfig {
    model_name: "gpt-3.5-turbo".to_string(),
    base_url: std::env::var("LLM_BASE_URL")
        .unwrap_or_else(|_| "https://api.openai.com/v1".to_string()),
    api_key: std::env::var("OPENAI_API_KEY")
        .expect("OPENAI_API_KEY must be set"),
    temperature: 0.7,
    max_tokens: 2048,
};
```

## Examples

### CLI Examples

#### Quick Setup
```bash
# Initialize and configure
helios-engine init
# Edit config.toml with your API key
nano config.toml
# Start chatting
helios-engine
```

#### One-Off Tasks
```bash
# Quick question
helios-engine ask "Explain async/await in Rust"

# With calculation
helios-engine ask "What is 15% of 230?"
```

#### Custom Sessions
```bash
# Code review session
helios-engine chat -s "You are a code reviewer. Be thorough and constructive."

# Math tutor session
helios-engine chat -s "You are a patient math tutor for beginners."
```

### Library Examples

#### Simple CLI App
```rust
use helios_engine::{LLMClient, ChatMessage, LLMConfig};
use std::env;

#[tokio::main]
async fn main() -> helios_engine::Result<()> {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: {} <question>", args[0]);
        return Ok(());
    }

    let question = args[1..].join(" ");

    let config = LLMConfig {
        model_name: "gpt-3.5-turbo".to_string(),
        base_url: "https://api.openai.com/v1".to_string(),
        api_key: env::var("OPENAI_API_KEY")?,
        temperature: 0.7,
        max_tokens: 2048,
    };

    let client = LLMClient::new(config);
    let messages = vec![ChatMessage::user(&question)];
    let response = client.chat(messages, None).await?;
    
    println!("{}", response.content);
    Ok(())
}
```

#### Web Service Integration
```rust
use helios_engine::{LLMClient, ChatMessage, LLMConfig};
use std::sync::Arc;

// In your web service
struct AppState {
    llm_client: Arc<LLMClient>,
}

async fn handle_request(
    state: Arc<AppState>,
    user_message: String,
) -> Result<String, Box<dyn std::error::Error>> {
    let messages = vec![
        ChatMessage::system("You are a helpful API assistant."),
        ChatMessage::user(user_message),
    ];

    let response = state.llm_client.chat(messages, None).await?;
    Ok(response.content)
}

#[tokio::main]
async fn main() {
    let config = LLMConfig {
        model_name: "gpt-3.5-turbo".to_string(),
        base_url: "https://api.openai.com/v1".to_string(),
        api_key: std::env::var("OPENAI_API_KEY").unwrap(),
        temperature: 0.7,
        max_tokens: 2048,
    };

    let state = Arc::new(AppState {
        llm_client: Arc::new(LLMClient::new(config)),
    });

    // Use in your web framework...
}
```

## Best Practices

### Security
- Never commit API keys to version control
- Use environment variables for sensitive data
- Rotate API keys regularly

### Performance
- Reuse `LLMClient` instances (they're cheap to clone)
- Use appropriate `max_tokens` to control costs
- Consider caching responses for common queries

### Error Handling
```rust
match client.chat(messages, None).await {
    Ok(response) => println!("{}", response.content),
    Err(helios_engine::HeliosError::LLMError(e)) => {
        eprintln!("LLM error: {}", e);
    }
    Err(e) => eprintln!("Other error: {}", e),
}
```

### Temperature Settings
- **0.0-0.3**: Deterministic, factual responses
- **0.7**: Balanced creativity and coherence (default)
- **0.9-1.0**: Very creative, less predictable

## Troubleshooting

### CLI Issues

**"Configuration file not found"**
```bash
helios-engine init
# Edit config.toml
helios-engine chat
```

**"API key not configured"**
- Edit config.toml and add your API key
- Or use environment variable: `export OPENAI_API_KEY="sk-..."`

### Library Issues

**"Cannot find module helios"**
- Add to Cargo.toml: `helios-engine = "0.1.0"`
- Run: `cargo build`

**Connection errors**
- Check internet connectivity
- Verify base_url is correct
- Ensure API key is valid

## Additional Resources

- [Full Documentation]README.md
- [API Reference]docs/API.md
- [Using as Crate Guide]docs/USING_AS_CRATE.md
- [Examples Directory]examples/
- [Publishing Guide]PUBLISHING.md