deepseek_api/async_impl/
client.rs

1use crate::completions::ChatCompletions;
2use crate::response::{BalanceResp, ModelResp};
3use anyhow::Result;
4use reqwest::header::{HeaderMap, HeaderValue};
5use reqwest::{Client as ReqwestClient, ClientBuilder};
6
7#[derive(Clone)]
8/// A client for interacting with the DeepSeek API.
9///
10/// # Example
11///
12/// ```no_run
13/// #[tokio::main]
14/// async fn main() {
15///     use deepseek_api::Client;
16///
17///     let api_key = "your_api_key";
18///     let client = Client::new(api_key);
19///
20///     // Get available models
21///     let models = client.models().await.unwrap();
22///
23///     // Get user balance
24///     let balance = client.balance().await.unwrap();
25///
26///     // Create a chat completion
27///     let chat = client.chat();
28/// }
29/// ```
30///
31/// # Fields
32///
33/// * `client` - The underlying HTTP client.
34/// * `host` - The base URL for the DeepSeek API.
35pub struct Client {
36    client: ReqwestClient,
37    host: &'static str,
38}
39
40impl Client {
41    /// Creates a new `Client` instance with the provided API key.
42    ///
43    /// This method initializes the client with the necessary headers, including
44    /// the authorization header with the provided API key.
45    ///
46    /// # Arguments
47    ///
48    /// * `api_key` - A string slice that holds the API key for authorization.
49    ///
50    /// # Returns
51    ///
52    /// A new instance of the `Client` struct.
53    ///
54    /// # Panics
55    ///
56    /// This function will panic if the `HeaderValue` cannot be created from the
57    /// provided API key or if the `Client` cannot be built.
58    ///
59    /// # Example
60    ///
61    /// ```no_run
62    /// use deepseek_api::Client;
63    ///
64    /// let client = Client::new("your_api_key");
65    /// ```
66    pub fn new(api_key: &str) -> Self {
67        let mut headers = HeaderMap::new();
68        let bearer = format!("Bearer {}", api_key);
69        headers.insert(
70            "Authorization",
71            HeaderValue::from_str(&bearer).expect("bearer"),
72        );
73
74        let client = ClientBuilder::new()
75            .default_headers(headers)
76            .build()
77            .expect("Client::new()");
78
79        Client {
80            client,
81            host: "https://api.deepseek.com",
82        }
83    }
84
85    pub fn chat(&self) -> ChatCompletions {
86        ChatCompletions {
87            client: self.client.clone(),
88            host: self.host,
89        }
90    }
91
92    /// Retrieves the list of available models from the DeepSeek API.
93    ///
94    /// This method sends a GET request to the `/models` endpoint of the DeepSeek API
95    /// and returns a `Result` containing a `ModelResp` on success.
96    ///
97    /// # Errors
98    ///
99    /// This function will return an error if the request fails or if the response
100    /// cannot be deserialized into a `ModelResp`.
101    ///
102    /// # Example
103    ///
104    /// ```no_run
105    /// #[tokio::main]
106    /// async fn main() {
107    ///     use deepseek_api::Client;
108    ///
109    ///     let client = Client::new("your_api_key");
110    ///     let models = client.models().await.unwrap();
111    ///     println!("{:?}", models);
112    /// }
113    /// ```
114    ///
115    /// For more information, see the [DeepSeek API documentation](https://api-docs.deepseek.com/zh-cn/api/list-models).
116    pub async fn models(&self) -> Result<ModelResp> {
117        Ok(self
118            .client
119            .get(self.host.to_owned() + "/models")
120            .send()
121            .await?
122            .json()
123            .await?)
124    }
125
126    /// Retrieves the balance information of the user from the DeepSeek API.
127    ///
128    /// This method sends a GET request to the `/user/balance` endpoint of the DeepSeek API
129    /// and returns a `Result` containing a `BalanceResp` on success.
130    ///
131    /// # Errors
132    ///
133    /// This function will return an error if the request fails or if the response
134    /// cannot be deserialized into a `BalanceResp`.
135    ///
136    /// # Example
137    ///
138    /// ```no_run
139    /// #[tokio::main]
140    /// async fn main() {
141    ///     use deepseek_api::Client;
142    ///
143    ///     let client = Client::new("your_api_key");
144    ///     let balance = client.balance().await.unwrap();
145    ///     println!("{:?}", balance);
146    /// }
147    /// ```
148    ///
149    /// For more information, see the [DeepSeek API documentation](https://api-docs.deepseek.com/zh-cn/api/get-user-balance).
150    pub async fn balance(&self) -> Result<BalanceResp> {
151        Ok(self
152            .client
153            .get(self.host.to_owned() + "/user/balance")
154            .send()
155            .await?
156            .json()
157            .await?)
158    }
159}