Skip to main content

api/
client.rs

1use crate::error::ApiError;
2use crate::sse::SseParser;
3use crate::types::*;
4use std::collections::VecDeque;
5use std::time::Duration;
6
7const DEFAULT_BASE_URL: &str = "https://api.ternlang.com";
8const REQUEST_ID_HEADER: &str = "x-request-id";
9const ALT_REQUEST_ID_HEADER: &str = "request-id";
10const DEFAULT_INITIAL_BACKOFF: Duration = Duration::from_millis(500);
11const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
14pub enum LlmProvider {
15    Ternlang,
16    Anthropic,
17    OpenAi,
18    HuggingFace,
19    Google,
20    Azure,
21    Aws,
22    Ollama,
23    Xai,
24}
25
26impl LlmProvider {
27    pub fn default_base_url(&self) -> &'static str {
28        match self {
29            Self::Ternlang => "https://api.ternlang.com",
30            Self::Anthropic => "https://api.anthropic.com",
31            Self::OpenAi => "https://api.openai.com",
32            Self::HuggingFace => "https://api-inference.huggingface.co",
33            Self::Google => "https://generativelanguage.googleapis.com",
34            Self::Azure => "https://api.azure.com",
35            Self::Aws => "https://bedrock-runtime.us-east-1.amazonaws.com",
36            Self::Ollama => "http://localhost:11434",
37            Self::Xai => "https://api.x.ai",
38        }
39    }
40
41    pub fn api_path(&self) -> &'static str {
42        match self {
43            Self::Ternlang => "/v1/messages",
44            Self::Anthropic => "/v1/messages",
45            Self::OpenAi => "/v1/chat/completions",
46            Self::HuggingFace => "/models",
47            Self::Google => "/v1beta",
48            Self::Ollama => "/v1/chat/completions",
49            Self::Xai => "/v1/chat/completions",
50            _ => "/v1/messages",
51        }
52    }
53}
54
55#[derive(Clone)]
56pub struct TernlangClient {
57    pub provider: LlmProvider,
58    pub base_url: String,
59    pub auth: AuthSource,
60    pub http: reqwest::Client,
61    pub max_retries: u32,
62    pub initial_backoff: Duration,
63    pub max_backoff: Duration,
64}
65
66impl TernlangClient {
67    pub fn from_auth(auth: AuthSource) -> Self {
68        Self {
69            provider: LlmProvider::Ternlang,
70            base_url: DEFAULT_BASE_URL.to_string(),
71            auth,
72            http: reqwest::Client::new(),
73            max_retries: 3,
74            initial_backoff: DEFAULT_INITIAL_BACKOFF,
75            max_backoff: DEFAULT_MAX_BACKOFF,
76        }
77    }
78
79    pub fn from_env() -> Result<Self, ApiError> {
80        Ok(Self::from_auth(AuthSource::from_env_or_saved()?).with_base_url(read_base_url()))
81    }
82
83    #[must_use]
84    pub fn with_auth_source(mut self, auth: AuthSource) -> Self {
85        self.auth = auth;
86        self
87    }
88
89    #[must_use]
90    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
91        self.base_url = base_url.into();
92        self
93    }
94
95    #[must_use]
96    pub fn with_provider(mut self, provider: LlmProvider) -> Self {
97        self.provider = provider;
98        if self.base_url == DEFAULT_BASE_URL {
99            self.base_url = provider.default_base_url().to_string();
100        }
101        self
102    }
103
104    #[must_use]
105    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
106        self.max_retries = max_retries;
107        self
108    }
109
110    #[must_use]
111    pub fn with_initial_backoff(mut self, initial_backoff: Duration) -> Self {
112        self.initial_backoff = initial_backoff;
113        self
114    }
115
116    async fn send_raw_request(
117        &self,
118        request: &MessageRequest,
119    ) -> Result<reqwest::Response, ApiError> {
120        let path = self.provider.api_path();
121        let mut request_url = format!("{}/{}", self.base_url.trim_end_matches('/'), path.trim_start_matches('/'));
122        
123        let body = match self.provider {
124            LlmProvider::Google => {
125                let model_id = if request.model.starts_with("models/") {
126                    request.model.clone()
127                } else {
128                    format!("models/{}", request.model)
129                };
130                request_url = format!("{}/{}:generateContent", self.base_url.trim_end_matches('/'), model_id);
131                translate_to_gemini(request)
132            }
133            LlmProvider::Anthropic => translate_to_anthropic(request),
134            LlmProvider::OpenAi | LlmProvider::Ollama | LlmProvider::Xai => translate_to_openai(request),
135            _ => serde_json::to_value(request).map_err(ApiError::from)?,
136        };
137
138        let mut request_builder = self
139            .http
140            .post(&request_url)
141            .header("content-type", "application/json");
142
143        if self.provider == LlmProvider::Anthropic {
144            request_builder = request_builder.header("anthropic-version", "2023-06-01");
145        }
146
147        let request_builder = self.auth.apply(self.provider, request_builder);
148
149        request_builder.json(&body).send().await.map_err(ApiError::from)
150    }
151
152    pub async fn send_message(
153        &self,
154        request: &MessageRequest,
155    ) -> Result<MessageResponse, ApiError> {
156        let request = MessageRequest {
157            stream: false,
158            ..request.clone()
159        };
160        let response = self.send_with_retry(&request).await?;
161        let request_id = request_id_from_headers(response.headers());
162        let response_json = response
163            .json::<serde_json::Value>()
164            .await
165            .map_err(ApiError::from)?;
166        
167        let mut final_response = match self.provider {
168            LlmProvider::Google => translate_from_gemini(response_json, &request.model),
169            LlmProvider::Anthropic => translate_from_anthropic(response_json, &request.model),
170            LlmProvider::OpenAi | LlmProvider::Ollama | LlmProvider::Xai => translate_from_openai(response_json, &request.model),
171            _ => serde_json::from_value::<MessageResponse>(response_json).map_err(ApiError::from)?,
172        };
173
174        if final_response.request_id.is_none() {
175            final_response.request_id = request_id;
176        }
177        Ok(final_response)
178    }
179
180    pub async fn stream_message(
181        &mut self,
182        request: &MessageRequest,
183    ) -> Result<MessageStream, ApiError> {
184        let response = self
185            .send_with_retry(&request.clone().with_streaming())
186            .await?;
187        Ok(MessageStream {
188            _request_id: request_id_from_headers(response.headers()),
189            response,
190            parser: SseParser::new(),
191            pending: VecDeque::new(),
192            done: false,
193        })
194    }
195
196    async fn send_with_retry(
197        &self,
198        request: &MessageRequest,
199    ) -> Result<reqwest::Response, ApiError> {
200        let mut attempts = 0;
201        #[allow(unused_assignments)]
202        let mut last_error: Option<ApiError> = None;
203
204        loop {
205            attempts += 1;
206            let result = match self.send_raw_request(request).await {
207                Ok(response) => expect_success(response).await,
208                Err(error) => Err(error),
209            };
210
211            match result {
212                Ok(response) => return Ok(response),
213                Err(error) if error.is_retryable() => {
214                    last_error = Some(error);
215                    if attempts > self.max_retries {
216                        break; // → RetriesExhausted
217                    }
218                }
219                Err(error) => return Err(error), // non-retryable: surface immediately
220            }
221
222            tokio::time::sleep(self.backoff_for_attempt(attempts)?).await;
223        }
224
225        Err(ApiError::RetriesExhausted {
226            attempts,
227            last_error: Box::new(last_error.unwrap_or(ApiError::Auth("max retries exceeded".to_string()))),
228        })
229    }
230
231    fn backoff_for_attempt(&self, attempt: u32) -> Result<Duration, ApiError> {
232        let multiplier = 2_u32.pow(attempt.saturating_sub(1));
233        Ok(self
234            .initial_backoff
235            .checked_mul(multiplier)
236            .map_or(self.max_backoff, |delay| delay.min(self.max_backoff)))
237    }
238
239    pub async fn list_remote_models(&self) -> Result<Vec<String>, ApiError> {
240        match self.provider {
241            LlmProvider::Google => {
242                let url = format!("{}/v1beta/models?key={}", self.base_url.trim_end_matches('/'), self.auth.api_key().unwrap_or(""));
243                let res = self.http.get(&url).send().await.map_err(ApiError::from)?;
244                let json: serde_json::Value = res.json().await.map_err(ApiError::from)?;
245                
246                let mut models = vec![];
247                if let Some(list) = json.get("models").and_then(|m| m.as_array()) {
248                    for m in list {
249                        if let Some(name) = m.get("name").and_then(|n| n.as_str()) {
250                            models.push(name.replace("models/", ""));
251                        }
252                    }
253                }
254                Ok(models)
255            }
256            LlmProvider::OpenAi | LlmProvider::Ollama | LlmProvider::Xai => {
257                let url = format!("{}/v1/models", self.base_url.trim_end_matches('/'));
258                let res = self.auth.apply(self.provider, self.http.get(&url)).send().await.map_err(ApiError::from)?;
259                let json: serde_json::Value = res.json().await.map_err(ApiError::from)?;
260                
261                let mut models = vec![];
262                if let Some(list) = json.get("data").and_then(|m| m.as_array()) {
263                    for m in list {
264                        if let Some(id) = m.get("id").and_then(|i| i.as_str()) {
265                            models.push(id.to_string());
266                        }
267                    }
268                }
269                Ok(models)
270            }
271            _ => Ok(vec![])
272        }
273    }
274
275    pub async fn exchange_oauth_code(
276        &self,
277        _config: OAuthConfig,
278        _request: &OAuthTokenExchangeRequest,
279    ) -> Result<RuntimeTokenSet, ApiError> {
280        Ok(RuntimeTokenSet {
281            access_token: "dummy_token".to_string(),
282            refresh_token: None,
283            expires_at: None,
284            scopes: vec![],
285        })
286    }
287}
288
289#[derive(Debug)]
290pub struct MessageStream {
291    _request_id: Option<String>,
292    response: reqwest::Response,
293    parser: SseParser,
294    pending: VecDeque<StreamEvent>,
295    done: bool,
296}
297
298impl MessageStream {
299    pub async fn next_event(&mut self) -> Result<Option<StreamEvent>, ApiError> {
300        loop {
301            if let Some(event) = self.pending.pop_front() {
302                return Ok(Some(event));
303            }
304            if self.done { return Ok(None); }
305            let Some(chunk) = self.response.chunk().await? else {
306                // TCP stream ended — treat as natural stream termination.
307                self.done = true;
308                return Ok(None);
309            };
310            self.pending.extend(self.parser.push(&chunk)?);
311        }
312    }
313}
314
315fn translate_to_anthropic(request: &MessageRequest) -> serde_json::Value {
316    use serde_json::json;
317    let messages: Vec<serde_json::Value> = request.messages.iter().map(|msg| {
318        let content: Vec<serde_json::Value> = msg.content.iter().map(|block| {
319            match block {
320                InputContentBlock::Text { text } => json!({ "type": "text", "text": text }),
321                InputContentBlock::ToolUse { id, name, input } => json!({
322                    "type": "tool_use", "id": id, "name": name, "input": input
323                }),
324                InputContentBlock::ToolResult { tool_use_id, content, is_error } => {
325                    let text = content.iter().filter_map(|c| {
326                        if let ToolResultContentBlock::Text { text } = c { Some(text.clone()) } else { None }
327                    }).collect::<Vec<String>>().join("\n");
328                    json!({
329                        "type": "tool_result", "tool_use_id": tool_use_id, "content": text, "is_error": is_error
330                    })
331                }
332            }
333        }).collect();
334        json!({ "role": msg.role, "content": content })
335    }).collect();
336
337    let mut body = json!({
338        "model": request.model,
339        "messages": messages,
340        "max_tokens": request.max_tokens.unwrap_or(4096),
341        "stream": request.stream
342    });
343    if let Some(system) = &request.system { body["system"] = json!(system); }
344    if let Some(tools) = &request.tools {
345        body["tools"] = json!(tools.iter().map(|t| {
346            json!({ "name": t.name, "description": t.description, "input_schema": t.input_schema })
347        }).collect::<Vec<_>>());
348    }
349    body
350}
351
352fn translate_to_openai(request: &MessageRequest) -> serde_json::Value {
353    use serde_json::json;
354    let mut messages = vec![];
355    if let Some(system) = &request.system { messages.push(json!({ "role": "system", "content": system })); }
356
357    for msg in &request.messages {
358        let mut content_text = String::new();
359        let mut tool_calls = vec![];
360
361        for block in &msg.content {
362            match block {
363                InputContentBlock::Text { text } => content_text.push_str(text),
364                InputContentBlock::ToolUse { id, name, input } => {
365                    tool_calls.push(json!({
366                        "id": id, "type": "function", "function": { "name": name, "arguments": input.to_string() }
367                    }));
368                }
369                InputContentBlock::ToolResult { tool_use_id, content, .. } => {
370                    let text = content.iter().filter_map(|c| {
371                        if let ToolResultContentBlock::Text { text } = c { Some(text.clone()) } else { None }
372                    }).collect::<Vec<String>>().join("\n");
373                    messages.push(json!({ "role": "tool", "tool_call_id": tool_use_id, "content": text }));
374                }
375            }
376        }
377
378        if !content_text.is_empty() || !tool_calls.is_empty() {
379            let mut m = json!({ "role": msg.role });
380            if !content_text.is_empty() { m["content"] = json!(content_text); }
381            if !tool_calls.is_empty() { m["tool_calls"] = json!(tool_calls); }
382            messages.push(m);
383        }
384    }
385
386    let mut body = json!({ "model": request.model, "messages": messages, "stream": request.stream });
387    if let Some(tools) = &request.tools {
388        body["tools"] = json!(tools.iter().map(|t| {
389            json!({ "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.input_schema } })
390        }).collect::<Vec<_>>());
391    }
392    body
393}
394
395fn translate_to_gemini(request: &MessageRequest) -> serde_json::Value {
396    use serde_json::json;
397    let contents: Vec<serde_json::Value> = request.messages.iter().map(|msg| {
398        let role = if msg.role == "assistant" { "model" } else { "user" };
399        let parts: Vec<serde_json::Value> = msg.content.iter().map(|block| {
400            match block {
401                InputContentBlock::Text { text } => json!({ "text": text }),
402                InputContentBlock::ToolUse { name, input, .. } => json!({ "functionCall": { "name": name, "args": input } }),
403                InputContentBlock::ToolResult { tool_use_id, content, .. } => {
404                    let text = content.iter().filter_map(|c| {
405                        if let ToolResultContentBlock::Text { text } = c { Some(text.clone()) } else { None }
406                    }).collect::<Vec<String>>().join("\n");
407                    json!({ "functionResponse": { "name": tool_use_id, "response": { "result": text } } })
408                }
409            }
410        }).collect();
411        json!({ "role": role, "parts": parts })
412    }).collect();
413
414    let mut body = json!({ "contents": contents });
415    if let Some(system) = &request.system { body["systemInstruction"] = json!({ "parts": [{ "text": system }] }); }
416    if let Some(tools) = &request.tools {
417        let declarations: Vec<serde_json::Value> = tools.iter().map(|t| {
418            json!({ "name": t.name, "description": t.description, "parameters": t.input_schema })
419        }).collect();
420        body["tools"] = json!([{ "functionDeclarations": declarations }]);
421    }
422    body
423}
424
425fn translate_from_anthropic(response: serde_json::Value, model: &str) -> MessageResponse {
426    let mut content = vec![];
427    if let Some(blocks) = response.get("content").and_then(|c| c.as_array()) {
428        for block in blocks {
429            match block.get("type").and_then(|t| t.as_str()) {
430                Some("text") => if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
431                    content.push(OutputContentBlock::Text { text: text.to_string() });
432                },
433                Some("tool_use") => if let (Some(id), Some(name), Some(input)) = (
434                    block.get("id").and_then(|i| i.as_str()),
435                    block.get("name").and_then(|n| n.as_str()),
436                    block.get("input")
437                ) {
438                    content.push(OutputContentBlock::ToolUse { id: id.to_string(), name: name.to_string(), input: input.clone() });
439                },
440                _ => {}
441            }
442        }
443    }
444    let mut usage = Usage { input_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 0 };
445    if let Some(u) = response.get("usage") {
446        usage.input_tokens = u.get("input_tokens").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
447        usage.output_tokens = u.get("output_tokens").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
448    }
449    MessageResponse {
450        id: response.get("id").and_then(|i| i.as_str()).unwrap_or("anthropic-response").to_string(),
451        kind: "message".to_string(), role: "assistant".to_string(), content, model: model.to_string(),
452        stop_reason: response.get("stop_reason").and_then(|s| s.as_str()).map(|s| s.to_string()),
453        stop_sequence: None, usage, request_id: None,
454    }
455}
456
457fn translate_from_openai(response: serde_json::Value, model: &str) -> MessageResponse {
458    let mut content = vec![];
459    if let Some(choices) = response.get("choices").and_then(|c| c.as_array()) {
460        if let Some(choice) = choices.first() {
461            if let Some(message) = choice.get("message") {
462                if let Some(text) = message.get("content").and_then(|c| c.as_str()) {
463                    content.push(OutputContentBlock::Text { text: text.to_string() });
464                }
465                if let Some(tool_calls) = message.get("tool_calls").and_then(|t| t.as_array()) {
466                    for call in tool_calls {
467                        if let (Some(id), Some(name), Some(args_str)) = (
468                            call.get("id").and_then(|i| i.as_str()),
469                            call.get("function").and_then(|f| f.get("name")).and_then(|n| n.as_str()),
470                            call.get("function").and_then(|f| f.get("arguments")).and_then(|a| a.as_str())
471                        ) {
472                            if let Ok(args) = serde_json::from_str(args_str) {
473                                content.push(OutputContentBlock::ToolUse { id: id.to_string(), name: name.to_string(), input: args });
474                            }
475                        }
476                    }
477                }
478            }
479        }
480    }
481    let mut usage = Usage { input_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 0 };
482    if let Some(u) = response.get("usage") {
483        usage.input_tokens = u.get("prompt_tokens").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
484        usage.output_tokens = u.get("completion_tokens").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
485    }
486    MessageResponse {
487        id: response.get("id").and_then(|i| i.as_str()).unwrap_or("openai-response").to_string(),
488        kind: "message".to_string(), role: "assistant".to_string(), content, model: model.to_string(),
489        stop_reason: Some("end_turn".to_string()), stop_sequence: None, usage, request_id: None,
490    }
491}
492
493fn translate_from_gemini(response: serde_json::Value, model: &str) -> MessageResponse {
494    let mut content = vec![];
495    if let Some(candidates) = response.get("candidates").and_then(|c| c.as_array()) {
496        if let Some(candidate) = candidates.first() {
497            if let Some(parts) = candidate.get("content").and_then(|c| c.get("parts")).and_then(|p| p.as_array()) {
498                for part in parts {
499                    if let Some(text) = part.get("text").and_then(|t| t.as_str()) {
500                        content.push(OutputContentBlock::Text { text: text.to_string() });
501                    }
502                    if let Some(call) = part.get("functionCall") {
503                        if let (Some(name), Some(args)) = (call.get("name").and_then(|n| n.as_str()), call.get("args")) {
504                            content.push(OutputContentBlock::ToolUse { id: name.to_string(), name: name.to_string(), input: args.clone() });
505                        }
506                    }
507                }
508            }
509        }
510    }
511    let mut usage = Usage { input_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 0 };
512    if let Some(u) = response.get("usageMetadata") {
513        usage.input_tokens = u.get("promptTokenCount").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
514        usage.output_tokens = u.get("candidatesTokenCount").and_then(|c| c.as_u64()).unwrap_or(0) as u32;
515    }
516    MessageResponse {
517        id: "gemini-response".to_string(), kind: "message".to_string(), role: "assistant".to_string(),
518        content, model: model.to_string(), stop_reason: Some("end_turn".to_string()),
519        stop_sequence: None, usage, request_id: None,
520    }
521}
522
523pub fn read_env_non_empty(key: &str) -> Result<Option<String>, ApiError> {
524    match std::env::var(key) {
525        Ok(value) if !value.is_empty() => Ok(Some(value)),
526        Ok(_) | Err(std::env::VarError::NotPresent) => Ok(None),
527        Err(error) => Err(ApiError::from(error)),
528    }
529}
530
531pub fn read_base_url() -> String {
532    std::env::var("TERNLANG_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.to_string())
533}
534
535fn request_id_from_headers(headers: &reqwest::header::HeaderMap) -> Option<String> {
536    headers
537        .get(REQUEST_ID_HEADER)
538        .or_else(|| headers.get(ALT_REQUEST_ID_HEADER))
539        .and_then(|value| value.to_str().ok())
540        .map(ToOwned::to_owned)
541}
542
543async fn expect_success(response: reqwest::Response) -> Result<reqwest::Response, ApiError> {
544    let status = response.status();
545    if status.is_success() {
546        return Ok(response);
547    }
548    // 429 (rate limit) and 5xx (server errors) are retryable; everything else
549    // (401, 403, 400, etc.) is a hard failure.
550    let retryable = status.as_u16() == 429 || status.is_server_error();
551    let body = response.text().await.unwrap_or_default();
552    // Try to extract structured error fields from the response body.
553    let (error_type, message) = if let Ok(json) = serde_json::from_str::<serde_json::Value>(&body) {
554        let t = json.pointer("/error/type").and_then(|v| v.as_str()).map(ToOwned::to_owned);
555        let m = json.pointer("/error/message").and_then(|v| v.as_str()).map(ToOwned::to_owned);
556        (t, m)
557    } else {
558        (None, None)
559    };
560    Err(ApiError::Api { status, error_type, message, body, retryable })
561}
562
563pub fn resolve_startup_auth_source() -> Result<AuthSource, ApiError> {
564    if let Some(api_key) = read_env_non_empty("TERNLANG_API_KEY")? {
565        return Ok(AuthSource::ApiKey(api_key));
566    }
567    Ok(AuthSource::None)
568}
569
570#[derive(serde::Deserialize)]
571pub struct OAuthConfig {}