magicapi-ai-gateway 1.0.0

[DEPRECATED] This package has been renamed to 'noveum-ai-gateway'. Please use the new package for all future development. A high-performance AI Gateway proxy for routing requests to various AI providers, offering seamless integration and management of multiple AI providers.
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
use super::Provider;
use crate::error::AppError;
use crate::telemetry::provider_metrics::{MetricsExtractor, ProviderMetrics};
use async_trait::async_trait;
use axum::http::HeaderMap;
use serde_json::{Value, json};
use tracing::{debug, error};
use std::cell::RefCell;
use axum::{
    body::{Body, to_bytes},
    http::{HeaderValue, Response},
};
use chrono;

thread_local! {
    static ANTHROPIC_INPUT_TOKENS: RefCell<Option<u32>> = RefCell::new(None);
}

pub struct AnthropicProvider {
    base_url: String,
}

impl AnthropicProvider {
    pub fn new() -> Self {
        Self {
            base_url: "https://api.anthropic.com".to_string(),
        }
    }
}

#[async_trait]
impl Provider for AnthropicProvider {
    fn base_url(&self) -> String {
        self.base_url.clone()
    }

    fn name(&self) -> &str {
        "anthropic"
    }

    fn transform_path(&self, path: &str) -> String {
        if path.contains("/chat/completions") {
            "/v1/messages".to_string()
        } else {
            path.to_string()
        }
    }

    fn process_headers(&self, original_headers: &HeaderMap) -> Result<HeaderMap, AppError> {
        debug!("Processing Anthropic request headers");
        let mut headers = HeaderMap::new();

        // Add content type
        headers.insert(
            http::header::CONTENT_TYPE,
            http::header::HeaderValue::from_static("application/json"),
        );

        // Add Anthropic version header
        headers.insert(
            http::header::HeaderName::from_static("anthropic-version"),
            http::header::HeaderValue::from_static("2023-06-01"),
        );

        // Process authentication
        if let Some(auth) = original_headers
            .get("authorization")
            .and_then(|h| h.to_str().ok())
        {
            debug!("Converting Bearer token to x-api-key format");
            let api_key = auth.trim_start_matches("Bearer ");
            headers.insert(
                http::header::HeaderName::from_static("x-api-key"),
                http::header::HeaderValue::from_str(api_key).map_err(|_| {
                    error!("Failed to process Anthropic authorization header");
                    AppError::InvalidHeader
                })?,
            );
        } else {
            error!("No authorization header found for Anthropic request");
            return Err(AppError::MissingApiKey);
        }

        Ok(headers)
    }

    async fn process_response(&self, response: Response<Body>) -> Result<Response<Body>, AppError> {
        // Clone response parts and body
        let (mut parts, body) = response.into_parts();
        
        // Check if it's a streaming response
        let is_streaming = parts.headers.get(http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map_or(false, |ct| ct.contains("text/event-stream"));
        
        // For streaming responses, we need to add the request ID header if it's available in other headers
        if is_streaming {
            // Anthropic sometimes includes a request-id header directly, let's check for it
            let request_id = parts.headers.get("request-id")
                .and_then(|v| v.to_str().ok())
                .map(|id| id.to_string());
            
            // If we found a request_id, add it as an x-request-id header
            if let Some(id) = request_id {
                debug!("Adding Anthropic request ID to streaming response headers: {}", id);
                if let Ok(header_value) = HeaderValue::from_str(&id) {
                    parts.headers.insert("x-request-id", header_value);
                }
            } else {
                // For Anthropic, we might need to extract from the first streaming chunk
                // For now, we'll rely on the telemetry middleware to extract the request ID 
                // from the streaming chunks and include it in the metrics
                debug!("No request-id header found for Anthropic streaming response");
            }
            
            // Currently, we'll return the original streaming response without transformation
            // as transforming streams is complex and should be implemented more carefully
            
            // TODO: Implement proper streaming transformation for Anthropic to OpenAI format
            // This would require inspecting each chunk, transforming it to OpenAI format,
            // and reconstructing the stream. For now, we'll focus on regular responses.
            debug!("Returning streaming response without transformation");
            return Ok(Response::from_parts(parts, body));
        }
        
        // For regular responses, extract request_id from body and transform to OpenAI format
        let bytes = to_bytes(body, usize::MAX).await?;
        
        // Check if we have a request-id header in the response
        let request_id = parts.headers.get("request-id")
            .and_then(|v| v.to_str().ok())
            .map(|id| id.to_string());
        
        // If we found a request_id in the headers, add it as an x-request-id header
        if let Some(id) = request_id.clone() {
            debug!("Adding Anthropic request ID from headers to response: {}", id);
            if let Ok(header_value) = HeaderValue::from_str(&id) {
                parts.headers.insert("x-request-id", header_value);
            }
        }
        
        // Always try to parse the response as JSON
        if let Ok(json) = serde_json::from_slice::<Value>(&bytes) {
            debug!("Successfully parsed response body as JSON: {:?}", json);
            
            // If we couldn't find a request_id in the headers, try to extract it from the body as a fallback
            let body_request_id = if request_id.is_none() {
                if let Some(id) = json.get("id").and_then(|v| v.as_str()) {
                    Some(id.to_string())
                } else if let Some(message) = json.get("message") {
                    message.get("id").and_then(|v| v.as_str()).map(|id| id.to_string())
                } else {
                    None
                }
            } else {
                None
            };
            
            // If we found a request_id in the body (and not in headers), add it as an x-request-id header
            if let Some(id) = body_request_id {
                debug!("Adding Anthropic request ID from body to response headers: {}", id);
                if let Ok(header_value) = HeaderValue::from_str(&id) {
                    parts.headers.insert("x-request-id", header_value);
                }
            }
            
            // Extract the ID from the JSON response for later use
            let json_id = json.get("id").and_then(|v| v.as_str()).map(String::from);
            
            // Transform Anthropic API response to OpenAI format
            let transformed_response = transform_anthropic_to_openai_format(json);
            debug!("Transformed Anthropic response to OpenAI format");
            
            // Ensure x-request-id header is set in the response
            if !parts.headers.contains_key("x-request-id") {
                if let Some(id) = json_id {
                    debug!("Setting x-request-id header from Anthropic response ID: {}", id);
                    if let Ok(header_value) = HeaderValue::from_str(&id) {
                        parts.headers.insert("x-request-id", header_value);
                    }
                }
            }
            
            // Return the modified response
            return Ok(Response::from_parts(parts, Body::from(serde_json::to_vec(&transformed_response)?)));
        } else {
            debug!("Failed to parse response body as JSON, returning original response");
        }
        
        // If we couldn't parse the JSON, return the original response
        Ok(Response::from_parts(parts, Body::from(bytes)))
    }
}

// Anthropic-specific metrics extractor
pub struct AnthropicMetricsExtractor;

impl MetricsExtractor for AnthropicMetricsExtractor {
    fn extract_metrics(&self, response_body: &Value) -> ProviderMetrics {
        debug!("Extracting Anthropic metrics from response: {}", response_body);
        let mut metrics = ProviderMetrics::default();
        
        // Extract usage data
        if let Some(usage) = response_body.get("usage") {
            metrics.input_tokens = usage.get("input_tokens").and_then(|v| v.as_u64()).map(|v| v as u32);
            metrics.output_tokens = usage.get("output_tokens").and_then(|v| v.as_u64()).map(|v| v as u32);
            
            // Calculate total tokens if both input and output tokens are available
            if let (Some(input), Some(output)) = (metrics.input_tokens, metrics.output_tokens) {
                metrics.total_tokens = Some(input + output);
            }
            // If only one is available, use that as the total
            else if metrics.input_tokens.is_some() {
                metrics.total_tokens = metrics.input_tokens;
            } 
            else if metrics.output_tokens.is_some() {
                metrics.total_tokens = metrics.output_tokens;
            }
        }

        // Extract model information
        if let Some(model) = response_body.get("model").and_then(|v| v.as_str()) {
            metrics.model = model.to_string();
            
            // Calculate cost if we have token information
            if let Some(total_tokens) = metrics.total_tokens {
                metrics.cost = Some(calculate_anthropic_cost(&metrics.model, total_tokens));
            }
        }

        // Extract message ID to use as request ID
        if let Some(id) = response_body.get("id").and_then(|v| v.as_str()) {
            debug!("Found Anthropic message ID: {}", id);
            metrics.request_id = Some(id.to_string());
        } else if let Some(message) = response_body.get("message") {
            if let Some(id) = message.get("id").and_then(|v| v.as_str()) {
                debug!("Found Anthropic message ID in message object: {}", id);
                metrics.request_id = Some(id.to_string());
            }
        }

        debug!("Final extracted Anthropic metrics: {:?}", metrics);
        metrics
    }
    
    fn try_extract_provider_specific_streaming_metrics(&self, chunk: &str) -> Option<ProviderMetrics> {
        debug!("Attempting to extract metrics from Anthropic streaming chunk: {}", chunk);
        
        // Try to parse the chunk as JSON
        if let Ok(json) = serde_json::from_str::<Value>(chunk) {
            // Get event type
            let event_type = json.get("type").and_then(|t| t.as_str())?;
            
            // Create metrics object
            let mut metrics = ProviderMetrics::default();
            metrics.model = "claude".to_string();
            
            // Extract model if available
            if let Some(model) = json.get("message").and_then(|m| m.get("model")).and_then(|v| v.as_str()) {
                metrics.model = model.to_string();
            }
            
            // Process message_start event - this contains input tokens
            if event_type == "message_start" {
                if let Some(message) = json.get("message") {
                    if let Some(usage) = message.get("usage") {
                        if let Some(input_tokens) = usage.get("input_tokens").and_then(|v| v.as_u64()).map(|v| v as u32) {
                            // Store input tokens for later
                            ANTHROPIC_INPUT_TOKENS.with(|tokens| {
                                *tokens.borrow_mut() = Some(input_tokens);
                                debug!("Stored input tokens from message_start: {}", input_tokens);
                            });
                            
                            // Set input tokens in metrics
                            metrics.input_tokens = Some(input_tokens);
                            metrics.total_tokens = Some(input_tokens);
                            
                            // Extract request ID if available
                            if let Some(id) = message.get("id").and_then(|v| v.as_str()) {
                                metrics.request_id = Some(id.to_string());
                            }
                            
                            return Some(metrics);
                        }
                    }
                }
            }
            
            // Process message_delta event - this usually contains output tokens at the end 
            else if event_type == "message_delta" {
                if let Some(usage) = json.get("usage") {
                    if let Some(output_tokens) = usage.get("output_tokens").and_then(|v| v.as_u64()).map(|v| v as u32) {
                        // Get the stored input tokens
                        let input_tokens = ANTHROPIC_INPUT_TOKENS.with(|tokens| *tokens.borrow());
                        
                        // Set output tokens
                        metrics.output_tokens = Some(output_tokens);
                        
                        // Set input tokens from stored value
                        metrics.input_tokens = input_tokens;
                        
                        // Calculate total tokens
                        if let Some(input) = input_tokens {
                            metrics.total_tokens = Some(input + output_tokens);
                            metrics.cost = Some(calculate_anthropic_cost(&metrics.model, input + output_tokens));
                            debug!("Combined stored input tokens ({}) with output tokens ({}) in message_delta", 
                                   input, output_tokens);
                        } else {
                            metrics.total_tokens = Some(output_tokens);
                            metrics.cost = Some(calculate_anthropic_cost(&metrics.model, output_tokens));
                            debug!("No stored input tokens, using only output tokens ({}) in message_delta", output_tokens);
                        }
                        
                        return Some(metrics);
                    }
                }
            }
        }
        
        None
    }
}

// Helper function for Anthropic-specific cost calculation
fn calculate_anthropic_cost(model: &str, total_tokens: u32) -> f64 {
    let tokens = total_tokens as f64;
    
    match model {
        // Claude 3.5 models
        m if m.contains("claude-3.5-sonnet") => tokens * 0.000003, // $3.00 per million tokens
        
        // Claude 3 models
        m if m.contains("claude-3-opus") => tokens * 0.000015, // $15.00 per million tokens
        m if m.contains("claude-3-sonnet") => tokens * 0.000003, // $3.00 per million tokens
        m if m.contains("claude-3-haiku") => tokens * 0.000000125, // $0.25 per million input, $1.25 per million output, using average
        
        // Claude 2 models
        m if m.contains("claude-2") => tokens * 0.000008, // $8.00 per million tokens
        
        // Claude Instant models
        m if m.contains("claude-instant") => tokens * 0.000001, // $1.00 per million tokens
        
        // Generic fallbacks by model family
        m if m.contains("claude-3") => tokens * 0.000003, // Use Sonnet pricing as default for Claude 3
        m if m.contains("claude") => tokens * 0.000002, // Use a conservative estimate for unknown Claude models
        
        // Default case
        _ => {
            debug!("Unknown Anthropic model for cost calculation: {}", model);
            tokens * 0.000002 // Conservative default
        },
    }
}

// Convert Anthropic API response format to OpenAI format
fn transform_anthropic_to_openai_format(anthropic_response: Value) -> Value {
    // Extract content from Anthropic's array-based content structure
    let content = if let Some(content_array) = anthropic_response.get("content").and_then(|c| c.as_array()) {
        // Extract text content from content array (typically contains objects with "type" and "text")
        let mut text = String::new();
        for item in content_array {
            if let Some(item_text) = item.get("text").and_then(|t| t.as_str()) {
                text.push_str(item_text);
            }
        }
        text
    } else {
        // Fallback if content structure is different
        anthropic_response.get("content").and_then(|c| c.as_str()).unwrap_or("").to_string()
    };
    
    // Map Anthropic usage fields to OpenAI format
    let usage = {
        let mut usage_map = json!({
            "prompt_tokens": 0,
            "completion_tokens": 0,
            "total_tokens": 0
        });
        
        if let Some(anthropic_usage) = anthropic_response.get("usage") {
            // Map input_tokens to prompt_tokens
            if let Some(input_tokens) = anthropic_usage.get("input_tokens").and_then(|t| t.as_u64()) {
                usage_map["prompt_tokens"] = json!(input_tokens);
            }
            
            // Map output_tokens to completion_tokens
            if let Some(output_tokens) = anthropic_usage.get("output_tokens").and_then(|t| t.as_u64()) {
                usage_map["completion_tokens"] = json!(output_tokens);
            }
            
            // Calculate total tokens
            let prompt_tokens = usage_map["prompt_tokens"].as_u64().unwrap_or(0);
            let completion_tokens = usage_map["completion_tokens"].as_u64().unwrap_or(0);
            usage_map["total_tokens"] = json!(prompt_tokens + completion_tokens);
        }
        
        usage_map
    };
    
    // Map stop_reason to finish_reason (Anthropic uses "end_turn", "max_tokens", etc.)
    let finish_reason = match anthropic_response.get("stop_reason").and_then(|r| r.as_str()) {
        Some("end_turn") => "stop",
        Some("max_tokens") => "length",
        Some("stop_sequence") => "stop",
        Some(reason) => reason,
        None => "stop" // Default
    };
    
    // Create OpenAI-compatible format
    let mut transformed = json!({
        "id": anthropic_response.get("id").unwrap_or(&Value::Null),
        "object": "chat.completion",
        "created": chrono::Utc::now().timestamp(),
        "model": anthropic_response.get("model").unwrap_or(&Value::Null),
        "type": anthropic_response.get("type").unwrap_or(&json!("message")),
        "role": anthropic_response.get("role").unwrap_or(&json!("assistant")),
        "choices": [{
            "index": 0,
            "message": {
                "role": anthropic_response.get("role").unwrap_or(&json!("assistant")),
                "content": content
            },
            "finish_reason": finish_reason
        }],
        "usage": usage,
        "system_fingerprint": format!("anthropic-{}", anthropic_response.get("model").and_then(|m| m.as_str()).unwrap_or("claude"))
    });
    
    // Handle the seed value - convert to string if present to avoid Elasticsearch long integer overflow
    if let Some(seed) = anthropic_response.get("seed") {
        if let Some(choices) = transformed.get_mut("choices").and_then(|c| c.as_array_mut()) {
            for choice in choices {
                if seed.is_number() {
                    // Convert the numeric seed to a string to avoid Elasticsearch integer range issues
                    choice["seed"] = json!(seed.to_string());
                } else {
                    // If it's already a string or other type, just preserve it
                    choice["seed"] = seed.clone();
                }
            }
        }
    }
    
    transformed
}