Skip to main content

reflex/semantic/providers/
mod.rs

1//! LLM provider implementations
2
3pub mod anthropic;
4#[cfg(test)]
5pub mod mock;
6pub mod openai;
7pub mod openai_compatible;
8pub mod openrouter;
9pub mod wire;
10
11use anyhow::{Context, Result};
12use async_trait::async_trait;
13use std::collections::HashMap;
14use std::time::Duration;
15
16/// What shape the model must answer in.
17#[derive(Debug, Clone, Copy)]
18pub enum OutputMode<'a> {
19    /// Free text.
20    Text,
21    /// Any JSON object (OpenAI `json_object`, Anthropic prompt-only).
22    JsonObject,
23    /// JSON that matches `schema` (OpenAI strict `json_schema`, Anthropic forced tool use).
24    JsonSchema {
25        name: &'a str,
26        schema: &'a serde_json::Value,
27    },
28}
29
30impl OutputMode<'_> {
31    /// Stable label for cache keys and logs.
32    pub fn label(&self) -> &'static str {
33        match self {
34            OutputMode::Text => "text",
35            OutputMode::JsonObject => "json_object",
36            OutputMode::JsonSchema { .. } => "json_schema",
37        }
38    }
39
40    pub fn is_json(&self) -> bool {
41        !matches!(self, OutputMode::Text)
42    }
43}
44
45/// A completion request with a separate system prompt and an explicit output contract.
46///
47/// Used by Pulse. `rfx ask` still uses [`LlmProvider::complete`].
48#[derive(Debug, Clone, Copy)]
49pub struct CompletionRequest<'a> {
50    pub system: &'a str,
51    pub user: &'a str,
52    pub output: OutputMode<'a>,
53    pub max_tokens: u32,
54    pub temperature: f32,
55    /// Task id for logs and test routing. Never sent to the provider.
56    pub tag: &'a str,
57}
58
59/// Token usage as the provider reports it.
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
61pub struct Usage {
62    pub input_tokens: u32,
63    pub output_tokens: u32,
64    /// Input tokens served from the provider's prompt cache, when reported.
65    #[serde(default)]
66    pub cached_input_tokens: u32,
67}
68
69/// Why the model stopped.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum StopReason {
72    End,
73    MaxTokens,
74    Other(String),
75}
76
77#[derive(Debug, Clone)]
78pub struct CompletionResponse {
79    pub text: String,
80    pub usage: Option<Usage>,
81    pub stop: StopReason,
82    pub model: String,
83}
84
85/// Classification of a provider failure. Fatal kinds will not succeed on retry.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum ProviderErrorKind {
88    Auth,
89    NotFound,
90    BadRequest,
91    RateLimited,
92    Server,
93    Timeout,
94    Network,
95    Malformed,
96}
97
98impl ProviderErrorKind {
99    /// Auth, NotFound and BadRequest fail the same way every time.
100    pub fn is_fatal(&self) -> bool {
101        matches!(self, Self::Auth | Self::NotFound | Self::BadRequest)
102    }
103
104    /// Transient failures worth a retry with backoff.
105    pub fn is_retryable(&self) -> bool {
106        matches!(
107            self,
108            Self::RateLimited | Self::Server | Self::Timeout | Self::Network
109        )
110    }
111}
112
113/// A classified provider error. Returned inside `anyhow::Error`; recover it with
114/// `err.downcast_ref::<ProviderError>()`.
115#[derive(Debug, Clone, thiserror::Error)]
116#[error("{provider} API error ({kind:?}{}): {body}", status.map(|s| format!(", HTTP {s}")).unwrap_or_default())]
117pub struct ProviderError {
118    pub provider: String,
119    pub kind: ProviderErrorKind,
120    pub status: Option<u16>,
121    pub retry_after: Option<Duration>,
122    pub body: String,
123}
124
125/// What a provider supports natively.
126#[derive(Debug, Clone, Copy, Default)]
127pub struct ProviderCaps {
128    pub system_role: bool,
129    pub json_object: bool,
130    pub json_schema: bool,
131    pub reports_usage: bool,
132}
133
134/// Trait for LLM providers that generate structured query responses
135#[async_trait]
136pub trait LlmProvider: Send + Sync {
137    /// Send a prompt and get response
138    ///
139    /// # Arguments
140    ///
141    /// * `prompt` - The prompt to send to the LLM
142    /// * `json_mode` - Whether to request JSON structured output (true) or plain text (false)
143    ///
144    /// When `json_mode` is true, the response should be valid JSON matching the QueryResponse schema.
145    /// When `json_mode` is false, the response can be plain text (used for answer generation).
146    async fn complete(&self, prompt: &str, json_mode: bool) -> Result<String>;
147
148    /// Get provider name (for logging and error messages)
149    fn name(&self) -> &str;
150
151    /// Get default model identifier
152    fn default_model(&self) -> &str;
153
154    /// The model this instance actually calls (configured, else default).
155    fn model(&self) -> &str {
156        self.default_model()
157    }
158
159    /// Native capabilities. The default claims none.
160    fn caps(&self) -> ProviderCaps {
161        ProviderCaps::default()
162    }
163
164    /// Send a structured request.
165    ///
166    /// The default joins system and user into one prompt and calls [`Self::complete`],
167    /// so providers without native support still work (no usage, no schema enforcement).
168    async fn complete_request(&self, req: &CompletionRequest<'_>) -> Result<CompletionResponse> {
169        let prompt = if req.system.is_empty() {
170            req.user.to_string()
171        } else {
172            format!("{}\n\n{}", req.system, req.user)
173        };
174        let text = self.complete(&prompt, req.output.is_json()).await?;
175        Ok(CompletionResponse {
176            text,
177            usage: None,
178            stop: StopReason::End,
179            model: self.model().to_string(),
180        })
181    }
182}
183
184/// Default model name for a provider, for display when no model is configured.
185pub fn default_model_for(provider_name: &str) -> &'static str {
186    match provider_name.to_lowercase().as_str() {
187        "openai" => "gpt-4o-mini",
188        "anthropic" => "claude-3-5-haiku-20241022",
189        "openrouter" => "anthropic/claude-sonnet-4",
190        "openai-compatible" | "openai_compatible" => "",
191        _ => "",
192    }
193}
194
195/// Create a provider instance from name, API key, and request timeout.
196pub fn create_provider(
197    provider_name: &str,
198    api_key: String,
199    model: Option<String>,
200    options: Option<HashMap<String, String>>,
201    timeout_secs: u64,
202) -> Result<Box<dyn LlmProvider>> {
203    match provider_name.to_lowercase().as_str() {
204        "openai" => Ok(Box::new(openai::OpenAiProvider::new(
205            api_key,
206            model,
207            timeout_secs,
208        )?)),
209        "anthropic" => Ok(Box::new(anthropic::AnthropicProvider::new(
210            api_key,
211            model,
212            timeout_secs,
213        )?)),
214        "openrouter" => {
215            let sort = options.as_ref().and_then(|o| o.get("sort").cloned());
216            Ok(Box::new(openrouter::OpenRouterProvider::new(
217                api_key,
218                model,
219                sort,
220                timeout_secs,
221            )?))
222        }
223        "openai-compatible" | "openai_compatible" => {
224            let base_url = options
225                .as_ref()
226                .and_then(|o| o.get("base_url").cloned())
227                .context(
228                    "openai-compatible provider requires 'base_url' in options \
229                     (set credentials.openai_compatible_base_url in ~/.reflex/config.toml \
230                     or the OPENAI_COMPATIBLE_BASE_URL env var)",
231                )?;
232            let model = model.unwrap_or_default();
233            let key = if api_key.is_empty() {
234                None
235            } else {
236                Some(api_key)
237            };
238            Ok(Box::new(openai_compatible::OpenAiCompatibleProvider::new(
239                key,
240                model,
241                base_url,
242                timeout_secs,
243            )?))
244        }
245        _ => anyhow::bail!(
246            "Unknown provider: {}. Supported: openai, anthropic, openrouter, openai-compatible",
247            provider_name
248        ),
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn test_create_provider_openai() {
258        let provider = create_provider("openai", "test-key".to_string(), None, None, 300);
259        assert!(provider.is_ok());
260        assert_eq!(provider.unwrap().name(), "openai");
261    }
262
263    #[test]
264    fn test_default_model_for_known_providers() {
265        assert_eq!(default_model_for("openai"), "gpt-4o-mini");
266        assert_eq!(default_model_for("OpenAI"), "gpt-4o-mini");
267        assert_eq!(default_model_for("anthropic"), "claude-3-5-haiku-20241022");
268        assert_eq!(default_model_for("openrouter"), "anthropic/claude-sonnet-4");
269        assert_eq!(default_model_for("openai-compatible"), "");
270        assert_eq!(default_model_for("openai_compatible"), "");
271        assert_eq!(default_model_for("unknown"), "");
272    }
273
274    #[test]
275    fn test_create_provider_case_insensitive() {
276        let provider = create_provider("OpenAI", "test-key".to_string(), None, None, 300);
277        assert!(provider.is_ok());
278    }
279
280    #[test]
281    fn test_create_provider_unknown() {
282        let provider = create_provider("unknown", "test-key".to_string(), None, None, 300);
283        assert!(provider.is_err());
284        if let Err(e) = provider {
285            assert!(e.to_string().contains("Unknown provider"));
286        }
287    }
288
289    #[test]
290    fn test_create_provider_openrouter() {
291        let provider = create_provider("openrouter", "test-key".to_string(), None, None, 300);
292        assert!(provider.is_ok());
293        assert_eq!(provider.unwrap().name(), "openrouter");
294    }
295
296    #[test]
297    fn test_create_provider_openrouter_with_sort() {
298        let mut opts = HashMap::new();
299        opts.insert("sort".to_string(), "speed".to_string());
300        let provider = create_provider(
301            "openrouter",
302            "test-key".to_string(),
303            Some("openai/gpt-4o-mini".to_string()),
304            Some(opts),
305            300,
306        );
307        assert!(provider.is_ok());
308    }
309
310    #[test]
311    fn test_create_provider_openai_compatible_with_base_url() {
312        let mut opts = HashMap::new();
313        opts.insert(
314            "base_url".to_string(),
315            "http://localhost:1234/v1".to_string(),
316        );
317        let provider = create_provider(
318            "openai-compatible",
319            "test-key".to_string(),
320            Some("qwen2.5-coder".to_string()),
321            Some(opts),
322            300,
323        );
324        assert!(provider.is_ok());
325        assert_eq!(provider.unwrap().name(), "openai-compatible");
326    }
327
328    #[test]
329    fn test_create_provider_openai_compatible_accepts_underscore_alias() {
330        let mut opts = HashMap::new();
331        opts.insert(
332            "base_url".to_string(),
333            "http://localhost:1234/v1".to_string(),
334        );
335        let provider = create_provider(
336            "openai_compatible",
337            "test-key".to_string(),
338            Some("qwen2.5-coder".to_string()),
339            Some(opts),
340            300,
341        );
342        assert!(provider.is_ok());
343    }
344
345    #[test]
346    fn test_create_provider_openai_compatible_allows_empty_api_key() {
347        let mut opts = HashMap::new();
348        opts.insert(
349            "base_url".to_string(),
350            "http://localhost:1234/v1".to_string(),
351        );
352        let provider = create_provider(
353            "openai-compatible",
354            String::new(),
355            Some("qwen2.5-coder".to_string()),
356            Some(opts),
357            300,
358        );
359        assert!(provider.is_ok());
360    }
361
362    #[test]
363    fn test_create_provider_openai_compatible_requires_base_url() {
364        let provider = create_provider(
365            "openai-compatible",
366            String::new(),
367            Some("qwen2.5-coder".to_string()),
368            None,
369            300,
370        );
371        assert!(provider.is_err());
372        if let Err(e) = provider {
373            assert!(e.to_string().contains("base_url"));
374        }
375    }
376
377    #[test]
378    fn test_create_provider_openai_compatible_requires_model() {
379        let mut opts = HashMap::new();
380        opts.insert(
381            "base_url".to_string(),
382            "http://localhost:1234/v1".to_string(),
383        );
384        let provider = create_provider("openai-compatible", String::new(), None, Some(opts), 300);
385        assert!(provider.is_err());
386    }
387}