Skip to main content

rig_core/providers/xai/
client.rs

1use crate::{
2    client::{
3        self, BearerAuth, Capabilities, Capable, DebugExt, Nothing, Provider, ProviderBuilder,
4        ProviderClient,
5    },
6    http_client,
7};
8
9#[derive(Debug, Default, Clone, Copy)]
10pub struct XAiExt;
11#[derive(Debug, Default, Clone, Copy)]
12pub struct XAiExtBuilder;
13
14type XAiApiKey = BearerAuth;
15
16pub type Client<H = reqwest::Client> = client::Client<XAiExt, H>;
17pub type ClientBuilder<H = crate::markers::Missing> =
18    client::ClientBuilder<XAiExtBuilder, XAiApiKey, H>;
19
20const XAI_BASE_URL: &str = "https://api.x.ai";
21
22impl Provider for XAiExt {
23    type Builder = XAiExtBuilder;
24
25    const VERIFY_PATH: &'static str = "/v1/api-key";
26}
27
28impl<H> Capabilities<H> for XAiExt {
29    type Completion = Capable<super::completion::CompletionModel<H>>;
30
31    type Embeddings = Nothing;
32    type Transcription = Nothing;
33    type ModelListing = Nothing;
34    #[cfg(feature = "image")]
35    type ImageGeneration = Capable<super::image_generation::ImageGenerationModel<H>>;
36    #[cfg(feature = "audio")]
37    type AudioGeneration = Capable<super::audio_generation::AudioGenerationModel<H>>;
38}
39
40impl DebugExt for XAiExt {}
41
42impl ProviderBuilder for XAiExtBuilder {
43    type Extension<H>
44        = XAiExt
45    where
46        H: http_client::HttpClientExt;
47    type ApiKey = XAiApiKey;
48
49    const BASE_URL: &'static str = XAI_BASE_URL;
50
51    fn build<H>(
52        _builder: &client::ClientBuilder<Self, Self::ApiKey, H>,
53    ) -> http_client::Result<Self::Extension<H>>
54    where
55        H: http_client::HttpClientExt,
56    {
57        Ok(XAiExt)
58    }
59}
60
61impl ProviderClient for Client {
62    type Input = String;
63    type Error = crate::client::ProviderClientError;
64
65    /// Create a new xAI client from the `XAI_API_KEY` environment variable.
66    fn from_env() -> Result<Self, Self::Error> {
67        let api_key = crate::client::required_env_var("XAI_API_KEY")?;
68        Self::new(&api_key).map_err(Into::into)
69    }
70
71    fn from_val(input: Self::Input) -> Result<Self, Self::Error> {
72        Self::new(&input).map_err(Into::into)
73    }
74}
75#[cfg(test)]
76mod tests {
77    #[test]
78    fn test_client_initialization() {
79        let _client_from_builder = crate::providers::xai::Client::builder()
80            .api_key("dummy-key")
81            .build()
82            .expect("Client::builder() failed");
83    }
84}