rumenx-chess 0.2.0

A high-performance chess engine and REST API server written in Rust
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
use std::future::Future;
use std::pin::Pin;

use serde::{Deserialize, Serialize};

use crate::config::ProviderConfig;

use super::types::ChatError;

// ---------------------------------------------------------------------------
// Provider trait
// ---------------------------------------------------------------------------

/// Trait for LLM providers.  Each provider takes a system prompt + user
/// message and returns the assistant's reply text.
pub trait LlmProvider: Send + Sync {
    /// Send a prompt to the LLM and return the response text.
    fn ask<'a>(
        &'a self,
        system_prompt: &'a str,
        user_message: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<String, ChatError>> + Send + 'a>>;

    /// Provider name for logging / response metadata.
    fn name(&self) -> &str;
}

// ---------------------------------------------------------------------------
// OpenAI-compatible provider (OpenAI, xAI, DeepSeek)
// ---------------------------------------------------------------------------

/// Works with any OpenAI-compatible chat-completions API.
#[derive(Debug)]
pub struct OpenAiCompatible {
    pub provider_name: String,
    pub api_key: String,
    pub model: String,
    pub endpoint: String,
    client: reqwest::Client,
}

#[derive(Serialize)]
struct OpenAiRequest {
    model: String,
    messages: Vec<OpenAiMessage>,
    max_tokens: u32,
    temperature: f32,
}

#[derive(Serialize, Deserialize, Clone)]
struct OpenAiMessage {
    role: String,
    content: String,
}

#[derive(Deserialize)]
struct OpenAiResponse {
    choices: Vec<OpenAiChoice>,
}

#[derive(Deserialize)]
struct OpenAiChoice {
    message: OpenAiMessage,
}

impl OpenAiCompatible {
    pub fn new(provider_name: &str, config: &ProviderConfig) -> Result<Self, ChatError> {
        if config.api_key.is_empty() {
            return Err(ChatError::MissingApiKey(provider_name.to_string()));
        }
        Ok(Self {
            provider_name: provider_name.to_string(),
            api_key: config.api_key.clone(),
            model: config.model.clone(),
            endpoint: config.endpoint.clone(),
            client: reqwest::Client::new(),
        })
    }
}

impl LlmProvider for OpenAiCompatible {
    fn ask<'a>(
        &'a self,
        system_prompt: &'a str,
        user_message: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<String, ChatError>> + Send + 'a>> {
        Box::pin(async move {
            let body = OpenAiRequest {
                model: self.model.clone(),
                messages: vec![
                    OpenAiMessage {
                        role: "system".to_string(),
                        content: system_prompt.to_string(),
                    },
                    OpenAiMessage {
                        role: "user".to_string(),
                        content: user_message.to_string(),
                    },
                ],
                max_tokens: 300,
                temperature: 0.7,
            };

            let resp = self
                .client
                .post(&self.endpoint)
                .header("Authorization", format!("Bearer {}", self.api_key))
                .header("Content-Type", "application/json")
                .json(&body)
                .send()
                .await
                .map_err(|e| ChatError::RequestFailed(e.to_string()))?;

            if !resp.status().is_success() {
                let status = resp.status();
                let text = resp.text().await.unwrap_or_default();
                return Err(ChatError::ProviderError(format!(
                    "{} returned {}: {}",
                    self.provider_name, status, text
                )));
            }

            let parsed: OpenAiResponse = resp
                .json()
                .await
                .map_err(|e| ChatError::ParseError(e.to_string()))?;

            parsed
                .choices
                .first()
                .map(|c| c.message.content.clone())
                .ok_or_else(|| ChatError::ParseError("empty choices array".to_string()))
        })
    }

    fn name(&self) -> &str {
        &self.provider_name
    }
}

// ---------------------------------------------------------------------------
// Anthropic provider
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub struct AnthropicProvider {
    pub api_key: String,
    pub model: String,
    pub endpoint: String,
    client: reqwest::Client,
}

#[derive(Serialize)]
struct AnthropicRequest {
    model: String,
    system: String,
    messages: Vec<AnthropicMessage>,
    max_tokens: u32,
}

#[derive(Serialize)]
struct AnthropicMessage {
    role: String,
    content: String,
}

#[derive(Deserialize)]
struct AnthropicResponse {
    content: Vec<AnthropicContent>,
}

#[derive(Deserialize)]
struct AnthropicContent {
    text: String,
}

impl AnthropicProvider {
    pub fn new(config: &ProviderConfig) -> Result<Self, ChatError> {
        if config.api_key.is_empty() {
            return Err(ChatError::MissingApiKey("anthropic".to_string()));
        }
        Ok(Self {
            api_key: config.api_key.clone(),
            model: config.model.clone(),
            endpoint: config.endpoint.clone(),
            client: reqwest::Client::new(),
        })
    }
}

impl LlmProvider for AnthropicProvider {
    fn ask<'a>(
        &'a self,
        system_prompt: &'a str,
        user_message: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<String, ChatError>> + Send + 'a>> {
        Box::pin(async move {
            let body = AnthropicRequest {
                model: self.model.clone(),
                system: system_prompt.to_string(),
                messages: vec![AnthropicMessage {
                    role: "user".to_string(),
                    content: user_message.to_string(),
                }],
                max_tokens: 300,
            };

            let resp = self
                .client
                .post(&self.endpoint)
                .header("x-api-key", &self.api_key)
                .header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .json(&body)
                .send()
                .await
                .map_err(|e| ChatError::RequestFailed(e.to_string()))?;

            if !resp.status().is_success() {
                let status = resp.status();
                let text = resp.text().await.unwrap_or_default();
                return Err(ChatError::ProviderError(format!(
                    "anthropic returned {}: {}",
                    status, text
                )));
            }

            let parsed: AnthropicResponse = resp
                .json()
                .await
                .map_err(|e| ChatError::ParseError(e.to_string()))?;

            parsed
                .content
                .first()
                .map(|c| c.text.clone())
                .ok_or_else(|| ChatError::ParseError("empty content array".to_string()))
        })
    }

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

// ---------------------------------------------------------------------------
// Gemini provider
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub struct GeminiProvider {
    pub api_key: String,
    pub model: String,
    pub endpoint: String,
    client: reqwest::Client,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct GeminiRequest {
    system_instruction: GeminiSystemInstruction,
    contents: Vec<GeminiContent>,
    generation_config: GeminiGenerationConfig,
}

#[derive(Serialize)]
struct GeminiSystemInstruction {
    parts: Vec<GeminiPart>,
}

#[derive(Serialize)]
struct GeminiContent {
    parts: Vec<GeminiPart>,
}

#[derive(Serialize, Deserialize)]
struct GeminiPart {
    text: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct GeminiGenerationConfig {
    max_output_tokens: u32,
    temperature: f32,
}

#[derive(Deserialize)]
struct GeminiResponse {
    candidates: Vec<GeminiCandidate>,
}

#[derive(Deserialize)]
struct GeminiCandidate {
    content: GeminiCandidateContent,
}

#[derive(Deserialize)]
struct GeminiCandidateContent {
    parts: Vec<GeminiPart>,
}

impl GeminiProvider {
    pub fn new(config: &ProviderConfig) -> Result<Self, ChatError> {
        if config.api_key.is_empty() {
            return Err(ChatError::MissingApiKey("gemini".to_string()));
        }
        Ok(Self {
            api_key: config.api_key.clone(),
            model: config.model.clone(),
            endpoint: config.endpoint.clone(),
            client: reqwest::Client::new(),
        })
    }
}

impl LlmProvider for GeminiProvider {
    fn ask<'a>(
        &'a self,
        system_prompt: &'a str,
        user_message: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<String, ChatError>> + Send + 'a>> {
        Box::pin(async move {
            let url = format!("{}/{}:generateContent", self.endpoint, self.model);

            let body = GeminiRequest {
                system_instruction: GeminiSystemInstruction {
                    parts: vec![GeminiPart {
                        text: system_prompt.to_string(),
                    }],
                },
                contents: vec![GeminiContent {
                    parts: vec![GeminiPart {
                        text: user_message.to_string(),
                    }],
                }],
                generation_config: GeminiGenerationConfig {
                    max_output_tokens: 300,
                    temperature: 0.7,
                },
            };

            let resp = self
                .client
                .post(&url)
                .header("Content-Type", "application/json")
                .header("x-goog-api-key", &self.api_key)
                .json(&body)
                .send()
                .await
                .map_err(|e| ChatError::RequestFailed(e.to_string()))?;

            if !resp.status().is_success() {
                let status = resp.status();
                let text = resp.text().await.unwrap_or_default();
                return Err(ChatError::ProviderError(format!(
                    "gemini returned {}: {}",
                    status, text
                )));
            }

            let parsed: GeminiResponse = resp
                .json()
                .await
                .map_err(|e| ChatError::ParseError(e.to_string()))?;

            parsed
                .candidates
                .first()
                .and_then(|c| c.content.parts.first())
                .map(|p| p.text.clone())
                .ok_or_else(|| ChatError::ParseError("empty candidates".to_string()))
        })
    }

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

// ---------------------------------------------------------------------------
// Factory
// ---------------------------------------------------------------------------

/// Create an LLM provider from a provider name and config.
pub fn create_provider(
    name: &str,
    config: &ProviderConfig,
) -> Result<Box<dyn LlmProvider>, ChatError> {
    match name {
        "openai" | "xai" | "deepseek" => Ok(Box::new(OpenAiCompatible::new(name, config)?)),
        "anthropic" => Ok(Box::new(AnthropicProvider::new(config)?)),
        "gemini" => Ok(Box::new(GeminiProvider::new(config)?)),
        other => Err(ChatError::UnsupportedProvider(other.to_string())),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn openai_compatible_rejects_empty_key() {
        let cfg = ProviderConfig {
            api_key: String::new(),
            model: "gpt-4o-mini".to_string(),
            endpoint: "https://api.openai.com".to_string(),
        };
        let result = OpenAiCompatible::new("openai", &cfg);
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ChatError::MissingApiKey(_)));
    }

    #[test]
    fn anthropic_rejects_empty_key() {
        let cfg = ProviderConfig {
            api_key: String::new(),
            model: "claude-3-haiku".to_string(),
            endpoint: "https://api.anthropic.com".to_string(),
        };
        assert!(AnthropicProvider::new(&cfg).is_err());
    }

    #[test]
    fn gemini_rejects_empty_key() {
        let cfg = ProviderConfig {
            api_key: String::new(),
            model: "gemini-1.5-flash".to_string(),
            endpoint: "https://generativelanguage.googleapis.com".to_string(),
        };
        assert!(GeminiProvider::new(&cfg).is_err());
    }

    #[test]
    fn openai_compatible_accepts_valid_key() {
        let cfg = ProviderConfig {
            api_key: "sk-test-key".to_string(),
            model: "gpt-4o-mini".to_string(),
            endpoint: "https://api.openai.com/v1/chat/completions".to_string(),
        };
        let provider = OpenAiCompatible::new("openai", &cfg).unwrap();
        assert_eq!(provider.name(), "openai");
        assert_eq!(provider.model, "gpt-4o-mini");
    }

    #[test]
    fn factory_creates_openai() {
        let cfg = ProviderConfig {
            api_key: "sk-test".to_string(),
            model: "gpt-4o-mini".to_string(),
            endpoint: "https://api.openai.com/v1/chat/completions".to_string(),
        };
        let p = create_provider("openai", &cfg).unwrap();
        assert_eq!(p.name(), "openai");
    }

    #[test]
    fn factory_creates_xai() {
        let cfg = ProviderConfig {
            api_key: "xai-test".to_string(),
            model: "grok-1.5".to_string(),
            endpoint: "https://api.x.ai/v1/chat/completions".to_string(),
        };
        let p = create_provider("xai", &cfg).unwrap();
        assert_eq!(p.name(), "xai");
    }

    #[test]
    fn factory_creates_deepseek() {
        let cfg = ProviderConfig {
            api_key: "ds-test".to_string(),
            model: "deepseek-chat".to_string(),
            endpoint: "https://api.deepseek.com/v1/chat/completions".to_string(),
        };
        let p = create_provider("deepseek", &cfg).unwrap();
        assert_eq!(p.name(), "deepseek");
    }

    #[test]
    fn factory_creates_anthropic() {
        let cfg = ProviderConfig {
            api_key: "sk-ant-test".to_string(),
            model: "claude-3-haiku-20240307".to_string(),
            endpoint: "https://api.anthropic.com/v1/messages".to_string(),
        };
        let p = create_provider("anthropic", &cfg).unwrap();
        assert_eq!(p.name(), "anthropic");
    }

    #[test]
    fn factory_creates_gemini() {
        let cfg = ProviderConfig {
            api_key: "gem-test".to_string(),
            model: "gemini-1.5-flash".to_string(),
            endpoint: "https://generativelanguage.googleapis.com/v1beta/models".to_string(),
        };
        let p = create_provider("gemini", &cfg).unwrap();
        assert_eq!(p.name(), "gemini");
    }

    #[test]
    fn factory_rejects_unknown() {
        let cfg = ProviderConfig {
            api_key: "key".to_string(),
            model: "model".to_string(),
            endpoint: "https://example.com".to_string(),
        };
        assert!(create_provider("unknown", &cfg).is_err());
    }
}