rig/providers/
mira.rs

1//! Mira API client and Rig integration
2//!
3//! # Example
4//! ```
5//! use rig::providers::mira;
6//!
7//! let client = mira::Client::new("YOUR_API_KEY");
8//!
9//! ```
10use crate::client::{
11    self, BearerAuth, Capabilities, Capable, DebugExt, Nothing, Provider, ProviderBuilder,
12    ProviderClient,
13};
14use crate::http_client::{self, HttpClientExt};
15use crate::message::{Document, DocumentSourceKind};
16use crate::providers::openai;
17use crate::providers::openai::send_compatible_streaming_request;
18use crate::streaming::StreamingCompletionResponse;
19use crate::{
20    OneOrMany,
21    completion::{self, CompletionError, CompletionRequest},
22    message::{self, AssistantContent, Message, UserContent},
23};
24use serde::{Deserialize, Serialize};
25use std::string::FromUtf8Error;
26use thiserror::Error;
27use tracing::{self, Instrument, info_span};
28
29#[derive(Debug, Default, Clone, Copy)]
30pub struct MiraExt;
31#[derive(Debug, Default, Clone, Copy)]
32pub struct MiraBuilder;
33
34type MiraApiKey = BearerAuth;
35
36impl Provider for MiraExt {
37    type Builder = MiraBuilder;
38
39    const VERIFY_PATH: &'static str = "/user-credits";
40
41    fn build<H>(
42        _: &crate::client::ClientBuilder<
43            Self::Builder,
44            <Self::Builder as crate::client::ProviderBuilder>::ApiKey,
45            H,
46        >,
47    ) -> http_client::Result<Self> {
48        Ok(Self)
49    }
50}
51
52impl<H> Capabilities<H> for MiraExt {
53    type Completion = Capable<CompletionModel<H>>;
54    type Embeddings = Nothing;
55    type Transcription = Nothing;
56
57    #[cfg(feature = "image")]
58    type ImageGeneration = Nothing;
59
60    #[cfg(feature = "audio")]
61    type AudioGeneration = Nothing;
62}
63
64impl DebugExt for MiraExt {}
65
66impl ProviderBuilder for MiraBuilder {
67    type Output = MiraExt;
68    type ApiKey = MiraApiKey;
69
70    const BASE_URL: &'static str = MIRA_API_BASE_URL;
71}
72
73pub type Client<H = reqwest::Client> = client::Client<MiraExt, H>;
74pub type ClientBuilder<H = reqwest::Client> = client::ClientBuilder<MiraBuilder, MiraApiKey, H>;
75
76#[derive(Debug, Error)]
77pub enum MiraError {
78    #[error("Invalid API key")]
79    InvalidApiKey,
80    #[error("API error: {0}")]
81    ApiError(u16),
82    #[error("Request error: {0}")]
83    RequestError(#[from] http_client::Error),
84    #[error("UTF-8 error: {0}")]
85    Utf8Error(#[from] FromUtf8Error),
86    #[error("JSON error: {0}")]
87    JsonError(#[from] serde_json::Error),
88}
89
90#[derive(Debug, Deserialize)]
91struct ApiErrorResponse {
92    message: String,
93}
94
95#[derive(Debug, Deserialize, Clone, Serialize)]
96pub struct RawMessage {
97    pub role: String,
98    pub content: String,
99}
100
101const MIRA_API_BASE_URL: &str = "https://api.mira.network";
102
103impl TryFrom<RawMessage> for message::Message {
104    type Error = CompletionError;
105
106    fn try_from(raw: RawMessage) -> Result<Self, Self::Error> {
107        match raw.role.as_str() {
108            "user" => Ok(message::Message::User {
109                content: OneOrMany::one(UserContent::Text(message::Text { text: raw.content })),
110            }),
111            "assistant" => Ok(message::Message::Assistant {
112                id: None,
113                content: OneOrMany::one(AssistantContent::Text(message::Text {
114                    text: raw.content,
115                })),
116            }),
117            _ => Err(CompletionError::ResponseError(format!(
118                "Unsupported message role: {}",
119                raw.role
120            ))),
121        }
122    }
123}
124
125#[derive(Debug, Deserialize, Serialize)]
126#[serde(untagged)]
127pub enum CompletionResponse {
128    Structured {
129        id: String,
130        object: String,
131        created: u64,
132        model: String,
133        choices: Vec<ChatChoice>,
134        #[serde(skip_serializing_if = "Option::is_none")]
135        usage: Option<Usage>,
136    },
137    Simple(String),
138}
139
140#[derive(Debug, Deserialize, Serialize)]
141pub struct ChatChoice {
142    pub message: RawMessage,
143    #[serde(default)]
144    pub finish_reason: Option<String>,
145    #[serde(default)]
146    pub index: Option<usize>,
147}
148
149#[derive(Debug, Deserialize, Serialize)]
150struct ModelsResponse {
151    data: Vec<ModelInfo>,
152}
153
154#[derive(Debug, Deserialize, Serialize)]
155struct ModelInfo {
156    id: String,
157}
158
159impl<T> Client<T>
160where
161    T: HttpClientExt,
162{
163    /// List available models
164    pub async fn list_models(&self) -> Result<Vec<String>, MiraError> {
165        let req = self.get("/v1/models").and_then(|req| {
166            req.body(http_client::NoBody)
167                .map_err(http_client::Error::Protocol)
168        })?;
169
170        let response = self.send(req).await?;
171
172        let status = response.status();
173
174        if !status.is_success() {
175            // Log the error text but don't store it in an unused variable
176            let error_text = http_client::text(response).await.unwrap_or_default();
177            tracing::error!("Error response: {}", error_text);
178            return Err(MiraError::ApiError(status.as_u16()));
179        }
180
181        let response_text = http_client::text(response).await?;
182
183        let models: ModelsResponse = serde_json::from_str(&response_text).map_err(|e| {
184            tracing::error!("Failed to parse response: {}", e);
185            MiraError::JsonError(e)
186        })?;
187
188        Ok(models.data.into_iter().map(|model| model.id).collect())
189    }
190}
191
192impl ProviderClient for Client {
193    type Input = String;
194
195    /// Create a new Mira client from the `MIRA_API_KEY` environment variable.
196    /// Panics if the environment variable is not set.
197    fn from_env() -> Self {
198        let api_key = std::env::var("MIRA_API_KEY").expect("MIRA_API_KEY not set");
199        Self::new(&api_key).unwrap()
200    }
201
202    fn from_val(input: Self::Input) -> Self {
203        Self::new(&input).unwrap()
204    }
205}
206
207#[derive(Debug, Serialize, Deserialize)]
208pub(super) struct MiraCompletionRequest {
209    model: String,
210    pub messages: Vec<RawMessage>,
211    #[serde(flatten, skip_serializing_if = "Option::is_none")]
212    temperature: Option<f64>,
213    #[serde(flatten, skip_serializing_if = "Option::is_none")]
214    max_tokens: Option<u64>,
215    pub stream: bool,
216}
217
218impl TryFrom<(&str, CompletionRequest)> for MiraCompletionRequest {
219    type Error = CompletionError;
220
221    fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
222        let mut messages = Vec::new();
223
224        if let Some(content) = &req.preamble {
225            messages.push(RawMessage {
226                role: "user".to_string(),
227                content: content.to_string(),
228            });
229        }
230
231        if let Some(Message::User { content }) = req.normalized_documents() {
232            let text = content
233                .into_iter()
234                .filter_map(|doc| match doc {
235                    UserContent::Document(Document {
236                        data: DocumentSourceKind::Base64(data) | DocumentSourceKind::String(data),
237                        ..
238                    }) => Some(data),
239                    UserContent::Text(text) => Some(text.text),
240
241                    // This should always be `Document`
242                    _ => None,
243                })
244                .collect::<Vec<_>>()
245                .join("\n");
246
247            messages.push(RawMessage {
248                role: "user".to_string(),
249                content: text,
250            });
251        }
252
253        for msg in req.chat_history {
254            let (role, content) = match msg {
255                Message::User { content } => {
256                    let text = content
257                        .iter()
258                        .map(|c| match c {
259                            UserContent::Text(text) => &text.text,
260                            _ => "",
261                        })
262                        .collect::<Vec<_>>()
263                        .join("\n");
264                    ("user", text)
265                }
266                Message::Assistant { content, .. } => {
267                    let text = content
268                        .iter()
269                        .map(|c| match c {
270                            AssistantContent::Text(text) => &text.text,
271                            _ => "",
272                        })
273                        .collect::<Vec<_>>()
274                        .join("\n");
275                    ("assistant", text)
276                }
277            };
278            messages.push(RawMessage {
279                role: role.to_string(),
280                content,
281            });
282        }
283
284        Ok(Self {
285            model: model.to_string(),
286            messages,
287            temperature: req.temperature,
288            max_tokens: req.max_tokens,
289            stream: false,
290        })
291    }
292}
293
294#[derive(Clone)]
295pub struct CompletionModel<T = reqwest::Client> {
296    client: Client<T>,
297    /// Name of the model
298    pub model: String,
299}
300
301impl<T> CompletionModel<T> {
302    pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
303        Self {
304            client,
305            model: model.into(),
306        }
307    }
308}
309
310impl<T> completion::CompletionModel for CompletionModel<T>
311where
312    T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
313{
314    type Response = CompletionResponse;
315    type StreamingResponse = openai::StreamingCompletionResponse;
316
317    type Client = Client<T>;
318
319    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
320        Self::new(client.clone(), model)
321    }
322
323    #[cfg_attr(feature = "worker", worker::send)]
324    async fn completion(
325        &self,
326        completion_request: CompletionRequest,
327    ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
328        if !completion_request.tools.is_empty() {
329            tracing::warn!(target: "rig::completions",
330                "Tool calls are not supported by Mira AI. {len} tools will be ignored.",
331                len = completion_request.tools.len()
332            );
333        }
334
335        if completion_request.tool_choice.is_some() {
336            tracing::warn!("WARNING: `tool_choice` not supported on Mira AI");
337        }
338
339        if completion_request.additional_params.is_some() {
340            tracing::warn!("WARNING: Additional parameters not supported on Mira AI");
341        }
342
343        let preamble = completion_request.preamble.clone();
344        let request = MiraCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
345
346        let span = if tracing::Span::current().is_disabled() {
347            info_span!(
348                target: "rig::completions",
349                "chat",
350                gen_ai.operation.name = "chat",
351                gen_ai.provider.name = "mira",
352                gen_ai.request.model = self.model,
353                gen_ai.system_instructions = preamble,
354                gen_ai.response.id = tracing::field::Empty,
355                gen_ai.response.model = tracing::field::Empty,
356                gen_ai.usage.output_tokens = tracing::field::Empty,
357                gen_ai.usage.input_tokens = tracing::field::Empty,
358                gen_ai.input.messages = serde_json::to_string(&request.messages)?,
359                gen_ai.output.messages = tracing::field::Empty,
360            )
361        } else {
362            tracing::Span::current()
363        };
364
365        let body = serde_json::to_vec(&request)?;
366
367        let req = self
368            .client
369            .post("/v1/chat/completions")?
370            .body(body)
371            .map_err(http_client::Error::from)?;
372
373        let async_block = async move {
374            let response = self
375                .client
376                .send::<_, bytes::Bytes>(req)
377                .await
378                .map_err(|e| CompletionError::ProviderError(e.to_string()))?;
379
380            let status = response.status();
381            let response_body = response.into_body().into_future().await?.to_vec();
382
383            if !status.is_success() {
384                let status = status.as_u16();
385                let error_text = String::from_utf8_lossy(&response_body).to_string();
386                return Err(CompletionError::ProviderError(format!(
387                    "API error: {status} - {error_text}"
388                )));
389            }
390
391            let response: CompletionResponse = serde_json::from_slice(&response_body)?;
392
393            if let CompletionResponse::Structured {
394                id,
395                model,
396                choices,
397                usage,
398                ..
399            } = &response
400            {
401                let span = tracing::Span::current();
402                span.record("gen_ai.response.model_name", model);
403                span.record("gen_ai.response.id", id);
404                span.record(
405                    "gen_ai.output.messages",
406                    serde_json::to_string(choices).unwrap(),
407                );
408                if let Some(usage) = usage {
409                    span.record("gen_ai.usage.input_tokens", usage.prompt_tokens);
410                    span.record(
411                        "gen_ai.usage.output_tokens",
412                        usage.total_tokens - usage.prompt_tokens,
413                    );
414                }
415            }
416
417            response.try_into()
418        };
419
420        async_block.instrument(span).await
421    }
422
423    #[cfg_attr(feature = "worker", worker::send)]
424    async fn stream(
425        &self,
426        completion_request: CompletionRequest,
427    ) -> Result<StreamingCompletionResponse<Self::StreamingResponse>, CompletionError> {
428        if !completion_request.tools.is_empty() {
429            tracing::warn!(target: "rig::completions",
430                "Tool calls are not supported by Mira AI. {len} tools will be ignored.",
431                len = completion_request.tools.len()
432            );
433        }
434
435        if completion_request.tool_choice.is_some() {
436            tracing::warn!("WARNING: `tool_choice` not supported on Mira AI");
437        }
438
439        if completion_request.additional_params.is_some() {
440            tracing::warn!("WARNING: Additional parameters not supported on Mira AI");
441        }
442        let preamble = completion_request.preamble.clone();
443        let mut request =
444            MiraCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
445        request.stream = true;
446
447        let span = if tracing::Span::current().is_disabled() {
448            info_span!(
449                target: "rig::completions",
450                "chat_streaming",
451                gen_ai.operation.name = "chat_streaming",
452                gen_ai.provider.name = "mira",
453                gen_ai.request.model = self.model,
454                gen_ai.system_instructions = preamble,
455                gen_ai.response.id = tracing::field::Empty,
456                gen_ai.response.model = tracing::field::Empty,
457                gen_ai.usage.output_tokens = tracing::field::Empty,
458                gen_ai.usage.input_tokens = tracing::field::Empty,
459                gen_ai.input.messages = serde_json::to_string(&request.messages)?,
460                gen_ai.output.messages = tracing::field::Empty,
461            )
462        } else {
463            tracing::Span::current()
464        };
465        let body = serde_json::to_vec(&request)?;
466
467        let req = self
468            .client
469            .post("/v1/chat/completions")?
470            .body(body)
471            .map_err(http_client::Error::from)?;
472
473        send_compatible_streaming_request(self.client.http_client().clone(), req)
474            .instrument(span)
475            .await
476    }
477}
478
479impl From<ApiErrorResponse> for CompletionError {
480    fn from(err: ApiErrorResponse) -> Self {
481        CompletionError::ProviderError(err.message)
482    }
483}
484
485impl TryFrom<CompletionResponse> for completion::CompletionResponse<CompletionResponse> {
486    type Error = CompletionError;
487
488    fn try_from(response: CompletionResponse) -> Result<Self, Self::Error> {
489        let (content, usage) = match &response {
490            CompletionResponse::Structured { choices, usage, .. } => {
491                let choice = choices.first().ok_or_else(|| {
492                    CompletionError::ResponseError("Response contained no choices".to_owned())
493                })?;
494
495                let usage = usage
496                    .as_ref()
497                    .map(|usage| completion::Usage {
498                        input_tokens: usage.prompt_tokens as u64,
499                        output_tokens: (usage.total_tokens - usage.prompt_tokens) as u64,
500                        total_tokens: usage.total_tokens as u64,
501                    })
502                    .unwrap_or_default();
503
504                // Convert RawMessage to message::Message
505                let message = message::Message::try_from(choice.message.clone())?;
506
507                let content = match message {
508                    Message::Assistant { content, .. } => {
509                        if content.is_empty() {
510                            return Err(CompletionError::ResponseError(
511                                "Response contained empty content".to_owned(),
512                            ));
513                        }
514
515                        // Log warning for unsupported content types
516                        for c in content.iter() {
517                            if !matches!(c, AssistantContent::Text(_)) {
518                                tracing::warn!(target: "rig",
519                                    "Unsupported content type encountered: {:?}. The Mira provider currently only supports text content", c
520                                );
521                            }
522                        }
523
524                        content.iter().map(|c| {
525                            match c {
526                                AssistantContent::Text(text) => Ok(completion::AssistantContent::text(&text.text)),
527                                other => Err(CompletionError::ResponseError(
528                                    format!("Unsupported content type: {other:?}. The Mira provider currently only supports text content")
529                                ))
530                            }
531                        }).collect::<Result<Vec<_>, _>>()?
532                    }
533                    Message::User { .. } => {
534                        tracing::warn!(target: "rig", "Received user message in response where assistant message was expected");
535                        return Err(CompletionError::ResponseError(
536                            "Received user message in response where assistant message was expected".to_owned()
537                        ));
538                    }
539                };
540
541                (content, usage)
542            }
543            CompletionResponse::Simple(text) => (
544                vec![completion::AssistantContent::text(text)],
545                completion::Usage::new(),
546            ),
547        };
548
549        let choice = OneOrMany::many(content).map_err(|_| {
550            CompletionError::ResponseError(
551                "Response contained no message or tool call (empty)".to_owned(),
552            )
553        })?;
554
555        Ok(completion::CompletionResponse {
556            choice,
557            usage,
558            raw_response: response,
559        })
560    }
561}
562
563#[derive(Clone, Debug, Deserialize, Serialize)]
564pub struct Usage {
565    pub prompt_tokens: usize,
566    pub total_tokens: usize,
567}
568
569impl std::fmt::Display for Usage {
570    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
571        write!(
572            f,
573            "Prompt tokens: {} Total tokens: {}",
574            self.prompt_tokens, self.total_tokens
575        )
576    }
577}
578
579impl From<Message> for serde_json::Value {
580    fn from(msg: Message) -> Self {
581        match msg {
582            Message::User { content } => {
583                let text = content
584                    .iter()
585                    .map(|c| match c {
586                        UserContent::Text(text) => &text.text,
587                        _ => "",
588                    })
589                    .collect::<Vec<_>>()
590                    .join("\n");
591                serde_json::json!({
592                    "role": "user",
593                    "content": text
594                })
595            }
596            Message::Assistant { content, .. } => {
597                let text = content
598                    .iter()
599                    .map(|c| match c {
600                        AssistantContent::Text(text) => &text.text,
601                        _ => "",
602                    })
603                    .collect::<Vec<_>>()
604                    .join("\n");
605                serde_json::json!({
606                    "role": "assistant",
607                    "content": text
608                })
609            }
610        }
611    }
612}
613
614impl TryFrom<serde_json::Value> for Message {
615    type Error = CompletionError;
616
617    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
618        let role = value["role"].as_str().ok_or_else(|| {
619            CompletionError::ResponseError("Message missing role field".to_owned())
620        })?;
621
622        // Handle both string and array content formats
623        let content = match value.get("content") {
624            Some(content) => match content {
625                serde_json::Value::String(s) => s.clone(),
626                serde_json::Value::Array(arr) => arr
627                    .iter()
628                    .filter_map(|c| {
629                        c.get("text")
630                            .and_then(|t| t.as_str())
631                            .map(|text| text.to_string())
632                    })
633                    .collect::<Vec<_>>()
634                    .join("\n"),
635                _ => {
636                    return Err(CompletionError::ResponseError(
637                        "Message content must be string or array".to_owned(),
638                    ));
639                }
640            },
641            None => {
642                return Err(CompletionError::ResponseError(
643                    "Message missing content field".to_owned(),
644                ));
645            }
646        };
647
648        match role {
649            "user" => Ok(Message::User {
650                content: OneOrMany::one(UserContent::Text(message::Text { text: content })),
651            }),
652            "assistant" => Ok(Message::Assistant {
653                id: None,
654                content: OneOrMany::one(AssistantContent::Text(message::Text { text: content })),
655            }),
656            _ => Err(CompletionError::ResponseError(format!(
657                "Unsupported message role: {role}"
658            ))),
659        }
660    }
661}
662
663#[cfg(test)]
664mod tests {
665    use super::*;
666    use crate::message::UserContent;
667    use serde_json::json;
668
669    #[test]
670    fn test_deserialize_message() {
671        // Test string content format
672        let assistant_message_json = json!({
673            "role": "assistant",
674            "content": "Hello there, how may I assist you today?"
675        });
676
677        let user_message_json = json!({
678            "role": "user",
679            "content": "What can you help me with?"
680        });
681
682        // Test array content format
683        let assistant_message_array_json = json!({
684            "role": "assistant",
685            "content": [{
686                "type": "text",
687                "text": "Hello there, how may I assist you today?"
688            }]
689        });
690
691        let assistant_message = Message::try_from(assistant_message_json).unwrap();
692        let user_message = Message::try_from(user_message_json).unwrap();
693        let assistant_message_array = Message::try_from(assistant_message_array_json).unwrap();
694
695        // Test string content format
696        match assistant_message {
697            Message::Assistant { content, .. } => {
698                assert_eq!(
699                    content.first(),
700                    AssistantContent::Text(message::Text {
701                        text: "Hello there, how may I assist you today?".to_string()
702                    })
703                );
704            }
705            _ => panic!("Expected assistant message"),
706        }
707
708        match user_message {
709            Message::User { content } => {
710                assert_eq!(
711                    content.first(),
712                    UserContent::Text(message::Text {
713                        text: "What can you help me with?".to_string()
714                    })
715                );
716            }
717            _ => panic!("Expected user message"),
718        }
719
720        // Test array content format
721        match assistant_message_array {
722            Message::Assistant { content, .. } => {
723                assert_eq!(
724                    content.first(),
725                    AssistantContent::Text(message::Text {
726                        text: "Hello there, how may I assist you today?".to_string()
727                    })
728                );
729            }
730            _ => panic!("Expected assistant message"),
731        }
732    }
733
734    #[test]
735    fn test_message_conversion() {
736        // Test converting from our Message type to Mira's format and back
737        let original_message = message::Message::User {
738            content: OneOrMany::one(message::UserContent::text("Hello")),
739        };
740
741        // Convert to Mira format
742        let mira_value: serde_json::Value = original_message.clone().into();
743
744        // Convert back to our Message type
745        let converted_message: Message = mira_value.try_into().unwrap();
746
747        assert_eq!(original_message, converted_message);
748    }
749
750    #[test]
751    fn test_completion_response_conversion() {
752        let mira_response = CompletionResponse::Structured {
753            id: "resp_123".to_string(),
754            object: "chat.completion".to_string(),
755            created: 1234567890,
756            model: "deepseek-r1".to_string(),
757            choices: vec![ChatChoice {
758                message: RawMessage {
759                    role: "assistant".to_string(),
760                    content: "Test response".to_string(),
761                },
762                finish_reason: Some("stop".to_string()),
763                index: Some(0),
764            }],
765            usage: Some(Usage {
766                prompt_tokens: 10,
767                total_tokens: 20,
768            }),
769        };
770
771        let completion_response: completion::CompletionResponse<CompletionResponse> =
772            mira_response.try_into().unwrap();
773
774        assert_eq!(
775            completion_response.choice.first(),
776            completion::AssistantContent::text("Test response")
777        );
778    }
779}