cllient 0.2.1

A comprehensive Rust client for LLM APIs with unified interface and model management
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
# Architecture Guide

Deep dive into cllient's flexible architecture and core components.

## Overview

cllient implements a unique **configuration-driven architecture** that fundamentally separates:

1. **Services** (HTTP providers) - How to communicate with APIs
2. **Models** (LLM capabilities) - What models can do
3. **Associations** (runtime bindings) - Which models use which services

This separation enables maximum flexibility without code changes.

---

## Core Principles

### Service-Model Separation

Traditional LLM clients hardcode model-to-provider relationships:

```
❌ Traditional: gpt-4 → OpenAI only
❌ Traditional: claude → Anthropic only  
❌ Traditional: Code changes needed for new providers
```

cllient separates these concerns:

```
✅ cllient: gpt-4 → {openai, azure, openrouter}
✅ cllient: claude → {anthropic, openrouter, bedrock}
✅ cllient: Configuration-driven associations
```

### Benefits

- **Runtime Flexibility**: Switch providers without rebuilding
- **Provider Agnostic**: Same model via different APIs
- **HTTP Transparency**: See exactly what requests are sent
- **Zero Code Changes**: Add providers via YAML config

---

## System Components

> **Main Library**: [`src/lib.rs`]../src/lib.rs

### 1. Configuration System

> **Source**: [`src/config.rs`]../src/config.rs | **Embedded**: [`src/embedded_config.rs`]../src/embedded_config.rs

```
Configuration Hierarchy:
┌─────────────────────────┐
│ Embedded Configurations │ ← 330+ models compiled in
├─────────────────────────┤
│ External YAML Files     │ ← Custom overrides  
├─────────────────────────┤
│ Environment Variables   │ ← API keys, runtime config
└─────────────────────────┘
```

**Key Components**:
- **[ConfigProvider Trait]../src/config.rs** - Abstraction for config sources
- **[EmbeddedConfigLoader]../src/embedded_config.rs** - Built-in configurations via `rust-embed`
- **[FileBasedConfigLoader]../src/config.rs** - External YAML configurations

### 2. Runtime Layer

> **Source**: [`src/runtime.rs`]../src/runtime.rs#L12

The `ModelRegistry` provides the high-level API:

```rust
ModelRegistry
├── config_provider: Arc<dyn ConfigProvider>
├── from_id(model_id) → RequestBuilder
├── use_cheapest(pattern) → RequestBuilder  
├── use_fastest(pattern) → RequestBuilder
└── list_models() → Vec<String>
```

**Key Features**:
- **Model Selection**: Pattern matching, cost optimization
- **Request Building**: Fluent API for request construction
- **Configuration Management**: Loading and validation

### 3. HTTP Client Layer

> **Source**: [`src/client.rs`]../src/client.rs

Low-level HTTP communication with LLM providers:

```rust
HttpClient
├── service_config: ServiceConfig
├── complete(request) → CompletionResponse
├── complete_stream(request) → StreamResponse
└── build_request(template, data) → HttpRequest
```

### 4. Template Engine

> **Source**: [`src/template.rs`]../src/template.rs

Handlebars-based request templating with environment substitution:

```yaml
http:
  request: |
    POST /v1/chat/completions HTTP/1.1
    Authorization: Bearer ${OPENAI_API_KEY}

    {
      "model": "{{model_id}}",
      "messages": {{json messages}},
      "stream": {{stream}}
    }
```

**Features**:
- **Variable Substitution**: `${ENV_VAR}` and `{{template_var}}`
- **JSON Helpers**: `{{json data}}` for proper serialization
- **HTTP Transparency**: See exact requests being sent
- **Static Regex Patterns**: Uses `OnceLock` for compile-once regex patterns, avoiding repeated compilation overhead

### 5. Streaming Infrastructure

> **Source**: [`src/streaming/`]../src/streaming/

Real-time response processing via Server-Sent Events (SSE):

```
Streaming Pipeline:
Raw SSE → Generic Config-Driven Parser → Content Extractor → StreamChunk
```

**Components**:
- **[SSE Core]../src/streaming/sse/core/** - Generic SSE processing
- **[Generic SSE Handlers]../src/streaming/sse/** - Config-driven provider/extractor system (consolidated from provider-specific implementations)
- **[JSON Utils]../src/streaming/json_utils.rs** - JSON path extraction

> **Note**: SSE extractors and providers have been consolidated into a generic, config-driven system. Provider-specific files (e.g., `claude.rs`, `openai.rs`) were removed in favor of unified implementations that use configuration to handle different provider formats.

### 6. Streaming JSON Output System

> **Source**: [`src/streaming_json.rs`]../src/streaming_json.rs

A specialized state machine for outputting JSON structures incrementally to stdout:

```
State Machine Flow:
┌────────────┐   field_string()   ┌──────────────┐
│ Initialize │ ──────────────────→ │ Write Fields │
│  Output {  │                     │   (static)   │
└────────────┘                     └──────────────┘
                             field_streaming_string()
                                   ┌──────────────┐
                                   │ Stream Field │
                                   │  (dynamic)   │
                                   └──────────────┘
                                     close()
                                   ┌──────────────┐
                                   │  Finalize    │
                                   │  Output }    │
                                   └──────────────┘
```

**Key Features**:
- **Incremental Output**: JSON structure streams as it's built
- **Real-time Visibility**: See response field populate character-by-character
- **Valid JSON**: Output is always parseable, even mid-stream
- **Automatic Escaping**: Handles JSON special characters (quotes, newlines, etc.)
- **Instrumented**: Full tracing support for debugging

**Usage Example**:

```rust
let mut json = StreamingJsonObject::new()?;
json.field_string("model", "gpt-4o-mini")?;

let mut response = json.field_streaming_string("response")?;
// Tokens stream in from LLM...
response.write_chunk("Hello")?;
response.write_chunk(" world")?;
response.close()?;

json.field_bool("success", true)?;
json.close()?;

// Output (streaming incrementally):
// {
//   "model": "gpt-4o-mini",
//   "response": "Hello world",
//   "success": true
// }
```

**Tracing Integration**:

With `--verbose` flag, the streaming JSON module logs all operations:

```bash
DEBUG cllient::streaming_json: Initializing streaming JSON object
DEBUG field_string{key="model"}: Writing string field key=model value_len=11
DEBUG field_streaming_string{key="response"}: Starting streaming string field
TRACE write_chunk: Writing chunk chunk_len=5 chunk_preview="Hello"
```

---

## Data Flow Architecture

### Request Flow

```
1. CLI/API → ModelRegistry.from_id("gpt-4o-mini")
2. ModelRegistry → Load model config from embedded/external
3. ModelRegistry → Find associated service config  
4. RequestBuilder → Build CompletionRequest
5. HttpClient → Apply Handlebars template
6. HttpClient → Substitute environment variables
7. HttpClient → Send HTTP request to provider
8. StreamProcessor → Parse SSE response (if streaming)
9. Response → Return CompletionResponse
```

### Configuration Resolution

```
1. EmbeddedConfigLoader → Load built-in configs
2. FileBasedConfigLoader → Override with external configs
3. Environment → Substitute ${API_KEY} variables
4. Validation → Ensure service/model consistency
5. Runtime → Cache resolved configurations
```

---

## Core Types

> **Source**: [`src/types.rs`](../src/types.rs)

### Request Types

```rust
pub struct CompletionRequest {
    pub model_id: String,        // "gpt-4o-mini"
    pub messages: Vec<Message>,  // Conversation history
    pub stream: bool,           // Enable streaming
    pub max_tokens: Option<u32>, // Output limit
    pub temperature: Option<f32>, // Randomness
}

pub struct Message {
    pub role: Role,              // User/Assistant/System
    pub content: Vec<ContentBlock>, // Text/Image/Document
}

pub enum ContentBlock {
    Text { text: String },
    Image { url: String, detail: Option<String> },
    Document { data: Vec<u8>, media_type: String },
}
```

### Configuration Types

```rust
pub struct ModelConfig {
    pub model: ModelInfo,         // ID, family, service
    pub capabilities: Capabilities, // Context, vision, etc.
    pub pricing: Pricing,         // Cost per token
}

pub struct ServiceConfig {
    pub service: ServiceInfo,     // Name, base URL
    pub http: HttpConfig,        // Request template
    pub streaming: StreamConfig, // SSE configuration
    pub response: ResponseConfig, // Response extraction
}
```

---

## Provider Integration

### Service Definition

> **Example**: [`config/service/openai.yaml`]../config/service/openai.yaml

Services define HTTP communication patterns:

```yaml
service:
  name: OpenAI
  base_url: https://api.openai.com

http:
  request: |
    POST /v1/chat/completions HTTP/1.1
    Host: api.openai.com
    Authorization: Bearer ${OPENAI_API_KEY}
    
    {
      "model": "{{model_id}}",
      "messages": {{json messages}},
      "stream": {{stream}}
    }

streaming:
  format: text/event-stream
  parser: openai_sse

response:
  extract:
    content: choices[0].message.content
    usage: usage
```

### Model Association

> **Example**: [`config/family/openai/gpt-4o-mini.yaml`]../config/family/openai/gpt-4o-mini.yaml

Models reference services by name:

```yaml
model:
  id: gpt-4o-mini
  family: gpt
  service: openai  # ← References service config

capabilities:
  context_window: 128000
  streaming: true
  vision: true

pricing:
  input_per_1k_tokens: 0.000150
  output_per_1k_tokens: 0.000600
```

---

## Streaming Architecture

> **Source**: [`src/streaming/`]../src/streaming/

### SSE Processing Pipeline

```
HTTP Response Stream
│
├─ SSE Parser (provider-specific)
│   ├─ OpenAI format: data: {"choices":[{"delta":{"content":"text"}}]}
│   ├─ Anthropic format: data: {"delta":{"text":"content"}}  
│   └─ Google format: data: {"candidates":[{"content":{"parts":[{"text":"content"}]}}]}
│
├─ Content Extractor
│   ├─ Extract text content from JSON
│   ├─ Handle completion markers
│   └─ Process usage statistics
│
└─ Stream Chunks
    ├─ StreamChunk::Content(text)
    ├─ StreamChunk::Done
    └─ StreamChunk::Error(error)
```

### Generic Config-Driven SSE Parsing

> **Implementation**: [`src/streaming/sse/`]../src/streaming/sse/

SSE parsing is now handled by a generic, configuration-driven system. Instead of separate parser files per provider, JSON path extraction is defined in service configurations:

**Service Config Example**:
```yaml
streaming:
  format: text/event-stream
  content_path: choices[0].delta.content  # OpenAI format
  # or: delta.text                         # Anthropic format
  # or: candidates[0].content.parts[0].text  # Google format
```

**Supported Provider Formats**:

| Provider | Content JSON Path |
|----------|------------------|
| OpenAI/DeepSeek | `choices[0].delta.content` |
| Anthropic | `delta.text` |
| Google | `candidates[0].content.parts[0].text` |

This approach eliminates duplicate provider-specific code while maintaining full compatibility with all supported LLM APIs.

---

## Configuration Architecture

### Embedded Configuration

> **Implementation**: [`src/embedded_config.rs`]../src/embedded_config.rs

Uses `rust-embed` to compile configurations into the binary:

```rust
#[derive(RustEmbed)]
#[folder = "config/"]
struct ConfigAssets;

impl EmbeddedConfigLoader {
    fn load_service_configs(&self) -> Vec<ServiceConfig> {
        for file in ConfigAssets::iter() {
            if file.starts_with("service/") && file.ends_with(".yaml") {
                // Load and parse YAML
            }
        }
    }
}
```

**Benefits**:
- **Zero Dependencies**: No external config files required
- **Fast Loading**: Configs loaded from memory
- **Version Consistency**: Configs versioned with code

### External Configuration Override

> **Implementation**: [`src/config.rs`]../src/config.rs

```rust
impl FileBasedConfigLoader {
    fn load_from_directory(&self, dir: &Path) -> Result<ConfigSet> {
        // Load service/*.yaml files
        // Load family/**/*.yaml files  
        // Override embedded configs
    }
}
```

---

## Error Handling

> **Source**: [`src/error.rs`]../src/error.rs

Comprehensive error types for different failure modes:

```rust
pub enum ClientError {
    ModelNotFound(String),        // Invalid model ID
    ServiceNotFound(String),      // Invalid service name
    Config(ConfigError),          // Configuration errors
    Http(HttpError),             // Network errors
    Template(TemplateError),     // Template rendering errors
    Streaming(StreamingError),   // SSE parsing errors
    Auth(AuthError),             // Authentication errors
}
```

---

## Extension Points

### Adding New Providers

1. **Create Service Config**: Define HTTP communication
2. **Add Models**: Reference the service
3. **Custom Parser**: If needed for streaming
4. **Test Integration**: Validate functionality

### Custom Content Types

Extend `ContentBlock` enum for new content types:

```rust
pub enum ContentBlock {
    Text { text: String },
    Image { url: String, detail: Option<String> },
    Document { data: Vec<u8>, media_type: String },
    Audio { data: Vec<u8>, format: AudioFormat },    // ← New
    Video { url: String, timestamps: Vec<f64> },     // ← New
}
```

### Custom Message Builders

> **Implementation**: [`src/streaming/`]../src/streaming/

Create provider-specific message formatting:

```rust
trait MessageBuilder {
    fn build_messages(&self, messages: &[Message]) -> serde_json::Value;
}
```

---

## Performance Characteristics

### Configuration Loading

- **Embedded**: ~1ms startup time
- **External**: ~10ms for 100 configs  
- **Caching**: Configs cached after first load

### HTTP Performance

- **Connection Reuse**: HTTP/2 connection pooling
- **Streaming**: Sub-100ms first token
- **Concurrency**: Async/await throughout

### Memory Usage

- **Embedded Configs**: ~500KB compiled size
- **Runtime**: ~10MB for loaded configs
- **Streaming**: ~1KB per active stream

---

## Security Architecture

### API Key Handling

- **Environment Variables**: Keys loaded from environment
- **Template Substitution**: `${VAR}` expanded at request time
- **No Storage**: Keys never persisted to disk
- **Scope Isolation**: Keys scoped to specific services

### HTTP Security

- **TLS Required**: All provider communication via HTTPS
- **Header Validation**: Proper authorization headers
- **Request Signing**: Provider-specific authentication
- **Error Sanitization**: No secrets in error messages

---

## Recent Refactoring

### Commit c0ef5a1 - Code Quality and Performance Improvements

A major refactoring effort focused on eliminating redundancy, improving performance, and enhancing code quality.

**Key Changes**:

- **SSE Consolidation**: Provider-specific extractor and parser files (`claude.rs`, `openai.rs` in `extractors/` and `providers/`) were deleted in favor of a generic, config-driven implementation
- **Static Regex Patterns**: `template.rs` now uses `OnceLock` for compile-once regex patterns instead of repeated `Regex::new()` calls
- **Macro-Based Trait Implementations**: Duplicate `ConfigProvider` trait implementations replaced with declarative macros
- **Performance Optimizations**: Index-based lookups in `runtime.rs`, Entry API usage in `registry_index.rs`, consuming `into_*` methods in `export.rs`

**Stats**: ~230 net lines removed, 4 duplicate files deleted, 20 files changed.

For detailed architecture decisions and future plans, see the [architecture documentation](architecture/).

---

**Next**: [Examples]examples/ | [6. Development]6_development.md