openrouter_sdk/
client.rs

1use crate::{models::*, error::OpenRouterError};
2use reqwest::Client;
3use std::sync::Arc;
4
5#[derive(Debug, Clone)]
6pub struct OpenRouterClient {
7    inner: Arc<Client>,
8    api_key: String,
9    base_url: String,
10}
11
12impl OpenRouterClient {
13    pub fn new(api_key: impl Into<String>) -> Self {
14        Self {
15            inner: Arc::new(Client::new()),
16            api_key: api_key.into(),
17            base_url: "https://openrouter.ai/api/v1".to_string(),
18        }
19    }
20
21    pub async fn chat(
22        &self,
23        request: ChatRequest
24    ) -> Result<ChatResponse, OpenRouterError> {
25        self.request("/chat/completions", request).await
26    }
27
28    async fn request<T: serde::de::DeserializeOwned>(
29        &self,
30        endpoint: &str,
31        body: impl serde::Serialize,
32    ) -> Result<T, OpenRouterError> {
33        let response = self.inner
34            .post(format!("{}{}", self.base_url, endpoint))
35            .header("Authorization", format!("Bearer {}", self.api_key))
36            .header("Content-Type", "application/json")
37            .json(&body)
38            .send()
39            .await?;
40
41        if !response.status().is_success() {
42            let error_text = response.text().await.unwrap_or_default();
43            return Err(OpenRouterError::ApiError(error_text));
44        }
45
46        response.json().await.map_err(Into::into)
47    }
48}