llmg-providers 0.1.2

Provider implementations for LLMG - LLM 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
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
//! OpenRouter API client for LLMG
//!
//! OpenRouter provides a unified interface for accessing many LLM providers.
//! It uses an OpenAI-compatible API format.
//!
//! Environment variables:
//! - OPENROUTER_API_KEY: Required API key
//! - OPENROUTER_API_BASE: Optional custom base URL (default: https://openrouter.ai/api/v1)
//! - OPENROUTER_APP_NAME: Optional app name for rankings
//! - OPENROUTER_HTTP_REFERER: Optional HTTP referer

use llmg_core::{
    provider::{ApiKeyCredentials, Credentials, LlmError, Provider},
    types::{ChatCompletionRequest, ChatCompletionResponse, EmbeddingRequest, EmbeddingResponse},
};
use std::sync::Arc;
// use serde::Serialize; // removed unused import

/// OpenRouter API client
///
/// OpenRouter is a unified interface for LLMs that provides:
/// - Access to 100+ models from various providers
/// - OpenAI-compatible API
/// - Automatic fallback and routing
#[derive(Debug, Clone)]
pub struct OpenRouterClient {
    http_client: reqwest::Client,
    base_url: String,
    credentials: Arc<dyn Credentials>,
    app_name: Option<String>,
    http_referer: Option<String>,
}

/// OpenRouter-specific request extensions
#[derive(Debug, Clone, Default)]
pub struct OpenRouterExtras {
    /// Provider selection preferences (e.g., ["Anthropic", "OpenAI"])
    pub provider: Option<serde_json::Value>,
    /// Transformations to apply
    pub transforms: Option<Vec<String>>,
    /// Route configuration
    pub route: Option<String>,
    /// Models to include/exclude
    pub models: Option<Vec<String>>,
}

/// OpenRouter chat request with extensions
#[derive(Debug, serde::Serialize)]
struct OpenRouterChatRequest {
    #[serde(flatten)]
    base: ChatCompletionRequest,
    #[serde(skip_serializing_if = "Option::is_none")]
    provider: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    transforms: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    route: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    models: Option<Vec<String>>,
}

impl OpenRouterClient {
    /// Create a new OpenRouter client from environment
    ///
    /// Required: OPENROUTER_API_KEY
    /// Optional: OPENROUTER_API_BASE, OPENROUTER_APP_NAME, OPENROUTER_HTTP_REFERER
    pub fn from_env() -> Result<Self, LlmError> {
        let api_key = std::env::var("OPENROUTER_API_KEY").map_err(|_| LlmError::AuthError)?;

        let base_url = std::env::var("OPENROUTER_API_BASE")
            .unwrap_or_else(|_| "https://openrouter.ai/api/v1".to_string());

        let app_name = std::env::var("OPENROUTER_APP_NAME").ok();
        let http_referer = std::env::var("OPENROUTER_HTTP_REFERER").ok();

        Ok(Self::with_config(api_key, base_url, app_name, http_referer))
    }

    /// Create a new OpenRouter client with explicit API key
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::with_config(
            api_key,
            "https://openrouter.ai/api/v1".to_string(),
            None,
            None,
        )
    }

    /// Create with custom configuration
    pub fn with_config(
        api_key: impl Into<String>,
        base_url: impl Into<String>,
        app_name: Option<String>,
        http_referer: Option<String>,
    ) -> Self {
        let api_key = api_key.into();

        Self {
            http_client: reqwest::Client::new(),
            base_url: base_url.into(),
            credentials: Arc::new(ApiKeyCredentials::bearer(api_key)),
            app_name,
            http_referer,
        }
    }

    /// Create with custom base URL
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Set app name for OpenRouter rankings
    pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
        self.app_name = Some(name.into());
        self
    }

    /// Set HTTP referer for OpenRouter rankings
    pub fn with_http_referer(mut self, referer: impl Into<String>) -> Self {
        self.http_referer = Some(referer.into());
        self
    }

    /// Build request with OpenRouter-specific headers
    fn build_request(
        &self,
        request: ChatCompletionRequest,
        extras: Option<OpenRouterExtras>,
    ) -> Result<reqwest::Request, LlmError> {
        let url = format!("{}/chat/completions", self.base_url);

        // Convert to OpenRouter format with extensions
        let openrouter_req = if let Some(extras) = extras {
            OpenRouterChatRequest {
                base: request,
                provider: extras.provider,
                transforms: extras.transforms,
                route: extras.route,
                models: extras.models,
            }
        } else {
            OpenRouterChatRequest {
                base: request,
                provider: None,
                transforms: None,
                route: None,
                models: None,
            }
        };

        let mut req_builder = self.http_client.post(&url).json(&openrouter_req);

        // Add OpenRouter-specific headers
        if let Some(ref app_name) = self.app_name {
            req_builder = req_builder.header("X-Title", app_name);
        }

        if let Some(ref referer) = self.http_referer {
            req_builder = req_builder.header("HTTP-Referer", referer);
        }

        let mut req = req_builder
            .build()
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        self.credentials.apply(&mut req)?;

        Ok(req)
    }

    async fn make_request(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, LlmError> {
        let req = self.build_request(request, None)?;

        let response = self
            .http_client
            .execute(req)
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text().await.unwrap_or_default();
            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        response
            .json::<ChatCompletionResponse>()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))
    }

    /// Make a chat completion with OpenRouter-specific extras
    pub async fn chat_completion_with_extras(
        &self,
        request: ChatCompletionRequest,
        extras: OpenRouterExtras,
    ) -> Result<ChatCompletionResponse, LlmError> {
        let req = self.build_request(request, Some(extras))?;

        let response = self
            .http_client
            .execute(req)
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text().await.unwrap_or_default();
            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        response
            .json::<ChatCompletionResponse>()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))
    }
}

#[async_trait::async_trait]
impl Provider for OpenRouterClient {
    async fn chat_completion(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, LlmError> {
        self.make_request(request).await
    }

    async fn embeddings(&self, request: EmbeddingRequest) -> Result<EmbeddingResponse, LlmError> {
        let url = format!("{}/embeddings", self.base_url);

        let mut req = self
            .http_client
            .post(&url)
            .json(&request)
            .build()
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        self.credentials.apply(&mut req)?;

        let response = self
            .http_client
            .execute(req)
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text().await.unwrap_or_default();
            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        response
            .json::<EmbeddingResponse>()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))
    }
    fn provider_name(&self) -> &'static str {
        "openrouter"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use llmg_core::types::Message;

    #[test]
    fn test_openrouter_client_creation() {
        let client = OpenRouterClient::new("test-key");
        assert_eq!(client.provider_name(), "openrouter");
    }

    #[test]
    fn test_from_env_missing_key() {
        // Temporarily remove env var
        let original = std::env::var("OPENROUTER_API_KEY").ok();
        std::env::remove_var("OPENROUTER_API_KEY");

        let result = OpenRouterClient::from_env();
        assert!(result.is_err());

        // Restore
        if let Some(key) = original {
            std::env::set_var("OPENROUTER_API_KEY", key);
        }
    }

    #[test]
    fn test_custom_config() {
        let client = OpenRouterClient::with_config(
            "test-key",
            "https://custom.openrouter.ai/api/v1",
            Some("MyApp".to_string()),
            Some("https://myapp.com".to_string()),
        );

        assert_eq!(client.base_url, "https://custom.openrouter.ai/api/v1");
        assert_eq!(client.app_name, Some("MyApp".to_string()));
        assert_eq!(client.http_referer, Some("https://myapp.com".to_string()));
    }

    #[test]
    fn test_extras_builder() {
        let extras = OpenRouterExtras {
            provider: Some(serde_json::json!({"order": ["Anthropic", "OpenAI"]})),
            transforms: Some(vec!["middle-out".to_string()]),
            route: Some("fallback".to_string()),
            models: Some(vec!["anthropic/claude-3-opus".to_string()]),
        };

        let request = ChatCompletionRequest {
            model: "anthropic/claude-3-opus".to_string(),
            messages: vec![Message::User {
                content: "Hello".to_string(),
                name: None,
            }],
            temperature: None,
            max_tokens: None,
            stream: None,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            stop: None,
            user: None,
            tools: None,
            tool_choice: None,
        };

        let client = OpenRouterClient::new("test-key").with_app_name("test-app");
        let built_req = client.build_request(request, Some(extras)).unwrap();

        // Verify headers
        assert!(built_req.headers().contains_key("x-title"));
        let body = String::from_utf8_lossy(built_req.body().unwrap().as_bytes().unwrap());
        assert!(body.contains("provider"));
    }
}

/// Integration tests with rig-core (requires OPENROUTER_API_KEY)
/// These tests verify that LLMG providers work correctly with Rig's formatting.
#[cfg(all(test, feature = "integration"))]
mod rig_integration_tests {
    use crate::OpenRouterClient;
    use llmg_core::provider::Provider;
    use llmg_core::rig::RigAdapter;
    use llmg_core::types::{ChatCompletionRequest, Message};

    /// Test Aurora Alpha model with Rig adapter - single turn
    #[tokio::test]
    #[ignore]
    async fn test_rig_adapter_aurora_alpha_single_turn() {
        let api_key = std::env::var("OPENROUTER_API_KEY")
            .expect("OPENROUTER_API_KEY must be set for integration tests");

        let client = OpenRouterClient::new(api_key);
        let adapter = RigAdapter::new(client, "openrouter/aurora-alpha");

        let completion = adapter
            .completion()
            .system("You are a helpful assistant. Answer in brief.")
            .user("What is 2+2?")
            .send()
            .await;

        if let Err(e) = &completion {
            eprintln!("Error: {:?}", e);
        }
        assert!(completion.is_ok());
        let result = completion.unwrap();
        assert!(!result.content.is_empty(), "Response should not be empty");
        println!("Aurora Alpha response: {}", result.content);
    }

    /// Test Aurora Alpha model with Rig adapter - multi-turn
    #[tokio::test]
    #[ignore]
    async fn test_rig_adapter_aurora_alpha_multi_turn() {
        let api_key = std::env::var("OPENROUTER_API_KEY")
            .expect("OPENROUTER_API_KEY must be set for integration tests");

        let client = OpenRouterClient::new(api_key);

        let adapter1 = RigAdapter::new(client.clone(), "openrouter/aurora-alpha");
        let completion1 = adapter1
            .completion()
            .system("You are a helpful math tutor.")
            .user("What is 5+3?")
            .send()
            .await
            .expect("First request should succeed");

        assert!(!completion1.content.is_empty());
        println!("Turn 1 - Question: 5+3");
        println!("Turn 1 - Answer: {}", completion1.content);

        let adapter2 = RigAdapter::new(client.clone(), "openrouter/aurora-alpha");
        let completion2 = adapter2
            .completion()
            .system("You are a helpful math tutor.")
            .user("What is 5+3?")
            .user(&format!("{}", completion1.content))
            .user("Now multiply that by 2")
            .send()
            .await
            .expect("Second request should succeed");

        assert!(!completion2.content.is_empty());
        println!("Turn 2 - Question: Now multiply that by 2");
        println!("Turn 2 - Answer: {}", completion2.content);
    }

    /// Test gpt-oss-120b:free model with Rig adapter - single turn
    #[tokio::test]
    #[ignore]
    async fn test_rig_adapter_gpt_oss_120b_single_turn() {
        let api_key = std::env::var("OPENROUTER_API_KEY")
            .expect("OPENROUTER_API_KEY must be set for integration tests");

        let client = OpenRouterClient::new(api_key);
        let adapter = RigAdapter::new(client, "openai/gpt-oss-120b:free");

        let completion = adapter
            .completion()
            .system("You are a helpful assistant. Answer in brief.")
            .user("What is the capital of France?")
            .send()
            .await;

        assert!(completion.is_ok());
        let result = completion.unwrap();
        assert!(!result.content.is_empty(), "Response should not be empty");
        println!("GPT-OSS-120B response: {}", result.content);
    }

    /// Test gpt-oss-120b:free model with Rig adapter - multi-turn
    #[tokio::test]
    #[ignore]
    async fn test_rig_adapter_gpt_oss_120b_multi_turn() {
        let api_key = std::env::var("OPENROUTER_API_KEY")
            .expect("OPENROUTER_API_KEY must be set for integration tests");

        let client = OpenRouterClient::new(api_key);

        let adapter1 = RigAdapter::new(client.clone(), "openai/gpt-oss-120b:free");
        let completion1 = adapter1
            .completion()
            .system("You are a helpful geography teacher.")
            .user("What is the capital of Japan?")
            .send()
            .await
            .expect("First request should succeed");

        assert!(!completion1.content.is_empty());
        println!("Turn 1 - Question: What is the capital of Japan?");
        println!("Turn 1 - Answer: {}", completion1.content);

        let adapter2 = RigAdapter::new(client, "openai/gpt-oss-120b:free");
        let completion2 = adapter2
            .completion()
            .system("You are a helpful geography teacher.")
            .user("What is the capital of Japan?")
            .user(&format!("{}", completion1.content))
            .user("What is its population?")
            .send()
            .await
            .expect("Second request should succeed");

        assert!(!completion2.content.is_empty());
        println!("Turn 2 - Question: What is its population?");
        println!("Turn 2 - Answer: {}", completion2.content);
    }

    /// Test both models in sequence to verify Rig functions work with formatting
    #[tokio::test]
    #[ignore]
    async fn test_rig_adapter_model_comparison() {
        let api_key = std::env::var("OPENROUTER_API_KEY")
            .expect("OPENROUTER_API_KEY must be set for integration tests");

        let client1 = OpenRouterClient::new(api_key.clone());
        let adapter1 = RigAdapter::new(client1, "openrouter/aurora-alpha");
        let result1 = adapter1
            .completion()
            .system("Answer with just the word 'Hello'.")
            .user("Say hi")
            .send()
            .await
            .expect("Aurora Alpha should work");

        let client2 = OpenRouterClient::new(api_key);
        let adapter2 = RigAdapter::new(client2, "openai/gpt-oss-120b:free");
        let result2 = adapter2
            .completion()
            .system("Answer with just the word 'Hello'.")
            .user("Say hi")
            .send()
            .await
            .expect("GPT-OSS-120B should work");

        println!("Aurora Alpha: {}", result1.content);
        println!("GPT-OSS-120B: {}", result2.content);

        assert!(!result1.content.is_empty());
        assert!(!result2.content.is_empty());
    }
}