langdb_core 0.3.2

AI gateway Core for LangDB AI Gateway.
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
# LangDB Conditional Routing with Interceptors - Implementation Guide

## Overview

This module implements LangDB's conditional routing engine with interceptors and metadata support. The routing engine enables organizations to control how user requests are handled by AI models based on request conditions, user metadata, and real-time system metrics.

## Current Implementation Status

### ✅ Implemented Features

1. **Basic Conditional Routing**
   - Route conditions with `all`, `any`, and expression operators
   - Support for `eq`, `ne`, `in`, `gt`, `lt`, `gte`, `lte` operators
   - Target specifications with `$any` pools and sorting
   - Message mapping for request/response modification

2. **Interceptor System**
   - Pre-request and post-request interceptors
   - Guardrail integration
   - Rate limiting support

3. **Metrics Integration**
   - Real-time metrics collection
   - Provider and model-level metrics
   - Duration-based metrics (Total, Last15Minutes, LastHour)

## 🚧 TODO: Enhanced Conditional Routing Implementation

### 1. Extra Field Metadata Extraction

**Priority: High**
**Estimated Effort: 1-2 weeks**

#### TODO Items:
- [ ] **Extra Field Integration**
  - [ ] Extract metadata from `Extra.user` field (RequestUser)
  - [ ] Extract metadata from `Extra.variables` field (HashMap<String, serde_json::Value>)
  - [ ] Extract metadata from `Extra.guards` field for guardrail results
  - [ ] Create metadata access patterns for conditional routing

- [ ] **RequestUser Metadata Support**
  - [ ] Add `user.id` extraction for user identification
  - [ ] Add `user.name` extraction for user display
  - [ ] Add `user.email` extraction for user contact
  - [ ] Add `user.tiers` extraction for user tier-based routing

- [ ] **Variables Metadata Support**
  - [ ] Add dynamic variable extraction from `Extra.variables`
  - [ ] Support nested variable access patterns
  - [ ] Add variable validation and type checking
  - [ ] Create variable caching for performance

#### Example Implementation:
```rust
// TODO: Add to conditional/evaluator.rs
pub enum MetadataField {
    // User metadata from Extra.user
    UserId,
    UserName,
    UserEmail,
    UserTiers,
    
    // Dynamic variables from Extra.variables
    Variable(String), // Dynamic access to Extra.variables
    
    // Guardrail results from Extra.guards
    GuardrailResult(String), // Access guardrail results
}
```

### 2. Enhanced Interceptor System

#### TODO Items:
- [ ] **Advanced Guardrails**
  - [ ] Add custom guardrail framework with plugin system

- [ ] **Request/Response Transformation**
  - [ ] Message content modification and enrichment
  - [ ] Header injection and modification
  - [ ] Response redaction and sanitization
  - [ ] Request validation and normalization
  - [ ] Metadata injection and propagation

- [ ] **Interceptor Type Restrictions**
  - [ ] Pre-request interceptors: Allow all interceptor types (guardrails, rate limiters, transformers, etc.)
  - [ ] Post-request interceptors: Allow only guardrails for response validation, message mapper and content filtering

#### Example Implementation:
```rust
// TODO: Add to interceptor/mod.rs
pub enum InterceptorType {
    Guardrail { 
        guard_id: String,
        config: GuardrailConfig 
    },
    SemanticGuardrail { 
        topics: Vec<String>,
        threshold: f64,
        action: GuardrailAction 
    },
    ToxicityGuardrail { 
        threshold: f64,
        action: ToxicityAction,
        categories: Vec<String> 
    },
    ComplianceGuardrail {
        regulations: Vec<String>, // GDPR, HIPAA, etc.
        data_classification: String,
        action: ComplianceAction
    },
    MessageTransformer { 
        rules: Vec<TransformRule>,
        direction: TransformDirection // pre_request, post_response
    },
    MetadataEnricher {
        fields: Vec<String>,
        sources: Vec<MetadataSource>
    },
}

// TODO: Add validation for post-request interceptors
impl InterceptorType {
    pub fn is_allowed_in_post_request(&self) -> bool {
        matches!(self, 
            InterceptorType::Guardrail { .. } |
            InterceptorType::SemanticGuardrail { .. } |
            InterceptorType::ToxicityGuardrail { .. } |
            InterceptorType::ComplianceGuardrail { .. }
        )
    }
}
```

### 3. Rate Limiting System

#### TODO Items:
- [ ] **Rate Limiter Configuration**
  - [ ] Implement manual rate limiter configuration structure
  - [ ] Support different limit targets (InputTokens, OutputTokens, Requests, Cost)
  - [ ] Support different limit entities (UserName, UserId, ProjectId, OrganizationId)
  - [ ] Support different periods (Minute, Hour, Day, Month, Year)

- [ ] **Rate Limiter Engine**
  - [ ] Token bucket algorithm implementation
  - [ ] Sliding window rate limiting
  - [ ] Distributed rate limiting with Redis
  - [ ] Rate limiter state persistence

- [ ] **Rate Limiter Monitoring**
  - [ ] Rate limit usage tracking
  - [ ] Rate limit violation alerts
  - [ ] Rate limit analytics and reporting
  - [ ] Dynamic rate limit adjustment

#### Example Implementation:
```rust
// TODO: Add to interceptor/rate_limiter.rs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimiter {
    pub limit: u64,
    pub limit_target: LimitTarget,
    pub limit_entity: LimitEntity,
    pub period: RateLimitPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub burst_protection: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<RateLimitAction>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LimitTarget {
    InputTokens,
    OutputTokens,
    Requests,
    Cost,
    Custom(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LimitEntity {
    UserName,
    UserId,
    ProjectId,
    OrganizationId,
    Model,
    Provider,
    Custom(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RateLimitPeriod {
    Minute,
    Hour,
    Day,
    Month,
    Year,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RateLimitAction {
    Block,
    Throttle,
    Redirect(String), // Redirect to different model
    Fallback(String), // Use fallback model
}

impl RateLimiter {
    pub fn new(limit: u64, limit_target: LimitTarget, limit_entity: LimitEntity, period: RateLimitPeriod) -> Self {
        Self {
            limit,
            limit_target,
            limit_entity,
            period,
            burst_protection: None,
            action: None,
        }
    }
}
```

#### Configuration Examples:
```json
{
  "name": "user_token_limit",
  "type": "rate_limiter",
  "limit": 100000,
  "limit_target": "input_tokens",
  "limit_entity": "user_name",
  "period": "day",
  "action": "block"
}
```

```json
{
  "name": "project_cost_limit",
  "type": "rate_limiter",
  "limit": 500,
  "limit_target": "cost",
  "limit_entity": "project_id",
  "period": "month",
  "action": "fallback",
  "fallback_model": "openai/gpt-3.5-turbo"
}
```

```json
{
  "name": "model_request_limit",
  "type": "rate_limiter",
  "limit": 1000,
  "limit_target": "requests",
  "limit_entity": "model",
  "period": "hour",
  "burst_protection": true,
  "action": "throttle"
}
```

### 4. Extra Field Context Management

#### TODO Items:
- [ ] **Extra Field Extraction Engine**
  - [ ] Extract user metadata from `Extra.user`
  - [ ] Extract dynamic variables from `Extra.variables`
  - [ ] Extract guardrail results from `Extra.guards`
  - [ ] Create metadata access patterns

- [ ] **Metadata Caching**
  - [ ] User metadata caching with TTL
  - [ ] Variable metadata caching
  - [ ] Guardrail result caching
  - [ ] Cache invalidation strategies

- [ ] **Metadata Validation**
  - [ ] Required metadata field validation
  - [ ] Metadata format validation
  - [ ] Metadata consistency checks
  - [ ] Metadata security validation

#### Example Implementation:
```rust
// TODO: Add to conditional/metadata.rs
pub struct MetadataManager {
    pub extractors: Vec<Box<dyn MetadataExtractor>>,
    pub cache: MetadataCache,
    pub validators: Vec<Box<dyn MetadataValidator>>,
}

pub trait MetadataExtractor {
    async fn extract(&self, request: &ChatCompletionRequest, extra: &Option<Extra>) -> Result<HashMap<String, serde_json::Value>, RouterError>;
}

pub struct MetadataCache {
    pub user_cache: Cache<String, RequestUser>,
    pub variables_cache: Cache<String, HashMap<String, serde_json::Value>>,
    pub guardrail_cache: Cache<String, GuardrailResult>,
}
```

### 5. Interceptor Context & State Management

#### TODO Items:
- [ ] **Interceptor Context Enhancement**
  - [ ] Rich context with Extra field metadata
  - [ ] Request/response state tracking
  - [ ] Interceptor chain state management
  - [ ] Context serialization for debugging

- [ ] **Interceptor State Persistence**
  - [ ] Rate limiter state persistence
  - [ ] Guardrail state tracking
  - [ ] Interceptor statistics collection
  - [ ] State recovery mechanisms

- [ ] **Interceptor Chain Management**
  - [ ] Conditional interceptor execution
  - [ ] Interceptor dependency management
  - [ ] Interceptor error handling and fallbacks
  - [ ] Interceptor performance monitoring

#### Example Implementation:
```rust
// TODO: Add to interceptor/mod.rs
pub struct InterceptorContext {
    pub request: ChatCompletionRequest,
    pub headers: HashMap<String, String>,
    pub extra: Option<Extra>,
    pub metadata: HashMap<String, serde_json::Value>,
    pub state: InterceptorState,
    pub chain_position: usize,
    pub results: HashMap<String, InterceptorResult>,
}

pub struct InterceptorState {
    pub rate_limiters: HashMap<String, RateLimiterState>,
    pub guardrails: HashMap<String, GuardrailState>,
    pub transformers: HashMap<String, TransformerState>,
    pub statistics: InterceptorStatistics,
}
```

## Testing Strategy

### Unit Tests
- [ ] Extra field metadata extraction tests
- [ ] Interceptor execution tests
- [ ] Conditional routing logic tests
- [ ] Context management tests
- [ ] Rate limiter tests

### Integration Tests
- [ ] End-to-end conditional routing tests
- [ ] Interceptor chain execution tests
- [ ] Metadata caching tests
- [ ] Performance impact tests
- [ ] Rate limiter integration tests

### Load Tests
- [ ] High-throughput conditional routing
- [ ] Concurrent interceptor execution
- [ ] Metadata extraction performance
- [ ] Memory usage under load
- [ ] Rate limiter performance under load

## Configuration Examples

### Basic Tier-Based Routing
```json
{
  "routes": [
    {
      "name": "premium_user_routing",
      "conditions": {
        "all": [
          { "extra.user.tiers": { "in": ["premium", "enterprise"] } },
          { "extra.variables.request_priority": { "eq": "high" } }
        ]
      },
      "targets": {
        "$any": ["openai/gpt-4", "anthropic/claude-3-opus"],
        "sort": { "latency": "MIN" }
      }
    },
    {
      "name": "standard_user_routing",
      "conditions": {
        "extra.user.tiers": { "in": ["standard", "free"] }
      },
      "targets": {
        "$any": ["openai/gpt-3.5-turbo", "anthropic/claude-3-haiku"]
      }
    }
  ]
}
```

### Rate Limiting with Conditional Routing
```json
{
  "pre_request": [
    {
      "name": "user_token_limit",
      "type": "rate_limiter",
      "limit": 100000,
      "limit_target": "input_tokens",
      "limit_entity": "user_name",
      "period": "day"
    }
  ],
  "routes": [
    {
      "name": "within_limit_routing",
      "conditions": {
        "extra.guards.user_token_limit.passed": { "eq": true }
      },
      "targets": {
        "$any": ["openai/gpt-4", "anthropic/claude-3-opus"]
      }
    },
    {
      "name": "limit_exceeded_routing",
      "conditions": {
        "extra.guards.user_token_limit.passed": { "eq": false }
      },
      "targets": {
        "$any": ["openai/gpt-3.5-turbo", "anthropic/claude-3-haiku"]
      }
    }
  ]
}
```

## Performance Considerations

### Optimization Targets
- [ ] Conditional routing decision latency < 5ms
- [ ] Extra field extraction latency < 2ms
- [ ] Interceptor execution latency < 10ms
- [ ] Rate limiter check latency < 1ms
- [ ] Memory usage < 50MB per router

### Monitoring
- [ ] Conditional routing performance metrics
- [ ] Spans storage for later extraction performance
- [ ] Interceptor execution metrics
- [ ] Cache hit rates and efficiency
- [ ] Rate limiter performance metrics

## References

- [Current Router Example]ai-gateway/core/src/routing/router_example.json
- [Conditional Router Implementation]ai-gateway/core/src/routing/strategy/conditional/
- [Interceptor Implementation]ai-gateway/core/src/routing/interceptor/
- [Metrics Implementation]ai-gateway/core/src/routing/strategy/metric.rs
- [Extra Struct Definition]ai-gateway/core/src/types/gateway.rs