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 + 'static,
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(skip_serializing_if = "Option::is_none")]
212    temperature: Option<f64>,
213    #[serde(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    async fn completion(
324        &self,
325        completion_request: CompletionRequest,
326    ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
327        let span = if tracing::Span::current().is_disabled() {
328            info_span!(
329                target: "rig::completions",
330                "chat",
331                gen_ai.operation.name = "chat",
332                gen_ai.provider.name = "mira",
333                gen_ai.request.model = self.model,
334                gen_ai.system_instructions = tracing::field::Empty,
335                gen_ai.response.id = tracing::field::Empty,
336                gen_ai.response.model = tracing::field::Empty,
337                gen_ai.usage.output_tokens = tracing::field::Empty,
338                gen_ai.usage.input_tokens = tracing::field::Empty,
339            )
340        } else {
341            tracing::Span::current()
342        };
343
344        span.record("gen_ai.system_instructions", &completion_request.preamble);
345
346        if !completion_request.tools.is_empty() {
347            tracing::warn!(target: "rig::completions",
348                "Tool calls are not supported by Mira AI. {len} tools will be ignored.",
349                len = completion_request.tools.len()
350            );
351        }
352
353        if completion_request.tool_choice.is_some() {
354            tracing::warn!("WARNING: `tool_choice` not supported on Mira AI");
355        }
356
357        if completion_request.additional_params.is_some() {
358            tracing::warn!("WARNING: Additional parameters not supported on Mira AI");
359        }
360
361        let request = MiraCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
362
363        if tracing::enabled!(tracing::Level::TRACE) {
364            tracing::trace!(target: "rig::completions",
365                "Mira completion request: {}",
366                serde_json::to_string_pretty(&request)?
367            );
368        }
369
370        let body = serde_json::to_vec(&request)?;
371
372        let req = self
373            .client
374            .post("/v1/chat/completions")?
375            .body(body)
376            .map_err(http_client::Error::from)?;
377
378        let async_block = async move {
379            let response = self
380                .client
381                .send::<_, bytes::Bytes>(req)
382                .await
383                .map_err(|e| CompletionError::ProviderError(e.to_string()))?;
384
385            let status = response.status();
386            let response_body = response.into_body().into_future().await?.to_vec();
387
388            if !status.is_success() {
389                let status = status.as_u16();
390                let error_text = String::from_utf8_lossy(&response_body).to_string();
391                return Err(CompletionError::ProviderError(format!(
392                    "API error: {status} - {error_text}"
393                )));
394            }
395
396            let response: CompletionResponse = serde_json::from_slice(&response_body)?;
397
398            if tracing::enabled!(tracing::Level::TRACE) {
399                tracing::trace!(target: "rig::completions",
400                    "Mira completion response: {}",
401                    serde_json::to_string_pretty(&response)?
402                );
403            }
404
405            if let CompletionResponse::Structured {
406                id, model, usage, ..
407            } = &response
408            {
409                let span = tracing::Span::current();
410                span.record("gen_ai.response.model_name", model);
411                span.record("gen_ai.response.id", id);
412                if let Some(usage) = usage {
413                    span.record("gen_ai.usage.input_tokens", usage.prompt_tokens);
414                    span.record(
415                        "gen_ai.usage.output_tokens",
416                        usage.total_tokens - usage.prompt_tokens,
417                    );
418                }
419            }
420
421            response.try_into()
422        };
423
424        async_block.instrument(span).await
425    }
426
427    async fn stream(
428        &self,
429        completion_request: CompletionRequest,
430    ) -> Result<StreamingCompletionResponse<Self::StreamingResponse>, CompletionError> {
431        let span = if tracing::Span::current().is_disabled() {
432            info_span!(
433                target: "rig::completions",
434                "chat_streaming",
435                gen_ai.operation.name = "chat_streaming",
436                gen_ai.provider.name = "mira",
437                gen_ai.request.model = self.model,
438                gen_ai.system_instructions = tracing::field::Empty,
439                gen_ai.response.id = tracing::field::Empty,
440                gen_ai.response.model = tracing::field::Empty,
441                gen_ai.usage.output_tokens = tracing::field::Empty,
442                gen_ai.usage.input_tokens = tracing::field::Empty,
443            )
444        } else {
445            tracing::Span::current()
446        };
447
448        span.record("gen_ai.system_instructions", &completion_request.preamble);
449
450        if !completion_request.tools.is_empty() {
451            tracing::warn!(target: "rig::completions",
452                "Tool calls are not supported by Mira AI. {len} tools will be ignored.",
453                len = completion_request.tools.len()
454            );
455        }
456
457        if completion_request.tool_choice.is_some() {
458            tracing::warn!("WARNING: `tool_choice` not supported on Mira AI");
459        }
460
461        if completion_request.additional_params.is_some() {
462            tracing::warn!("WARNING: Additional parameters not supported on Mira AI");
463        }
464        let mut request =
465            MiraCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
466        request.stream = true;
467
468        if tracing::enabled!(tracing::Level::TRACE) {
469            tracing::trace!(target: "rig::completions",
470                "Mira completion request: {}",
471                serde_json::to_string_pretty(&request)?
472            );
473        }
474
475        let body = serde_json::to_vec(&request)?;
476
477        let req = self
478            .client
479            .post("/v1/chat/completions")?
480            .body(body)
481            .map_err(http_client::Error::from)?;
482
483        send_compatible_streaming_request(self.client.clone(), req)
484            .instrument(span)
485            .await
486    }
487}
488
489impl From<ApiErrorResponse> for CompletionError {
490    fn from(err: ApiErrorResponse) -> Self {
491        CompletionError::ProviderError(err.message)
492    }
493}
494
495impl TryFrom<CompletionResponse> for completion::CompletionResponse<CompletionResponse> {
496    type Error = CompletionError;
497
498    fn try_from(response: CompletionResponse) -> Result<Self, Self::Error> {
499        let (content, usage) = match &response {
500            CompletionResponse::Structured { choices, usage, .. } => {
501                let choice = choices.first().ok_or_else(|| {
502                    CompletionError::ResponseError("Response contained no choices".to_owned())
503                })?;
504
505                let usage = usage
506                    .as_ref()
507                    .map(|usage| completion::Usage {
508                        input_tokens: usage.prompt_tokens as u64,
509                        output_tokens: (usage.total_tokens - usage.prompt_tokens) as u64,
510                        total_tokens: usage.total_tokens as u64,
511                    })
512                    .unwrap_or_default();
513
514                // Convert RawMessage to message::Message
515                let message = message::Message::try_from(choice.message.clone())?;
516
517                let content = match message {
518                    Message::Assistant { content, .. } => {
519                        if content.is_empty() {
520                            return Err(CompletionError::ResponseError(
521                                "Response contained empty content".to_owned(),
522                            ));
523                        }
524
525                        // Log warning for unsupported content types
526                        for c in content.iter() {
527                            if !matches!(c, AssistantContent::Text(_)) {
528                                tracing::warn!(target: "rig",
529                                    "Unsupported content type encountered: {:?}. The Mira provider currently only supports text content", c
530                                );
531                            }
532                        }
533
534                        content.iter().map(|c| {
535                            match c {
536                                AssistantContent::Text(text) => Ok(completion::AssistantContent::text(&text.text)),
537                                other => Err(CompletionError::ResponseError(
538                                    format!("Unsupported content type: {other:?}. The Mira provider currently only supports text content")
539                                ))
540                            }
541                        }).collect::<Result<Vec<_>, _>>()?
542                    }
543                    Message::User { .. } => {
544                        tracing::warn!(target: "rig", "Received user message in response where assistant message was expected");
545                        return Err(CompletionError::ResponseError(
546                            "Received user message in response where assistant message was expected".to_owned()
547                        ));
548                    }
549                };
550
551                (content, usage)
552            }
553            CompletionResponse::Simple(text) => (
554                vec![completion::AssistantContent::text(text)],
555                completion::Usage::new(),
556            ),
557        };
558
559        let choice = OneOrMany::many(content).map_err(|_| {
560            CompletionError::ResponseError(
561                "Response contained no message or tool call (empty)".to_owned(),
562            )
563        })?;
564
565        Ok(completion::CompletionResponse {
566            choice,
567            usage,
568            raw_response: response,
569        })
570    }
571}
572
573#[derive(Clone, Debug, Deserialize, Serialize)]
574pub struct Usage {
575    pub prompt_tokens: usize,
576    pub total_tokens: usize,
577}
578
579impl std::fmt::Display for Usage {
580    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
581        write!(
582            f,
583            "Prompt tokens: {} Total tokens: {}",
584            self.prompt_tokens, self.total_tokens
585        )
586    }
587}
588
589impl From<Message> for serde_json::Value {
590    fn from(msg: Message) -> Self {
591        match msg {
592            Message::User { content } => {
593                let text = content
594                    .iter()
595                    .map(|c| match c {
596                        UserContent::Text(text) => &text.text,
597                        _ => "",
598                    })
599                    .collect::<Vec<_>>()
600                    .join("\n");
601                serde_json::json!({
602                    "role": "user",
603                    "content": text
604                })
605            }
606            Message::Assistant { content, .. } => {
607                let text = content
608                    .iter()
609                    .map(|c| match c {
610                        AssistantContent::Text(text) => &text.text,
611                        _ => "",
612                    })
613                    .collect::<Vec<_>>()
614                    .join("\n");
615                serde_json::json!({
616                    "role": "assistant",
617                    "content": text
618                })
619            }
620        }
621    }
622}
623
624impl TryFrom<serde_json::Value> for Message {
625    type Error = CompletionError;
626
627    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
628        let role = value["role"].as_str().ok_or_else(|| {
629            CompletionError::ResponseError("Message missing role field".to_owned())
630        })?;
631
632        // Handle both string and array content formats
633        let content = match value.get("content") {
634            Some(content) => match content {
635                serde_json::Value::String(s) => s.clone(),
636                serde_json::Value::Array(arr) => arr
637                    .iter()
638                    .filter_map(|c| {
639                        c.get("text")
640                            .and_then(|t| t.as_str())
641                            .map(|text| text.to_string())
642                    })
643                    .collect::<Vec<_>>()
644                    .join("\n"),
645                _ => {
646                    return Err(CompletionError::ResponseError(
647                        "Message content must be string or array".to_owned(),
648                    ));
649                }
650            },
651            None => {
652                return Err(CompletionError::ResponseError(
653                    "Message missing content field".to_owned(),
654                ));
655            }
656        };
657
658        match role {
659            "user" => Ok(Message::User {
660                content: OneOrMany::one(UserContent::Text(message::Text { text: content })),
661            }),
662            "assistant" => Ok(Message::Assistant {
663                id: None,
664                content: OneOrMany::one(AssistantContent::Text(message::Text { text: content })),
665            }),
666            _ => Err(CompletionError::ResponseError(format!(
667                "Unsupported message role: {role}"
668            ))),
669        }
670    }
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use crate::message::UserContent;
677    use serde_json::json;
678
679    #[test]
680    fn test_deserialize_message() {
681        // Test string content format
682        let assistant_message_json = json!({
683            "role": "assistant",
684            "content": "Hello there, how may I assist you today?"
685        });
686
687        let user_message_json = json!({
688            "role": "user",
689            "content": "What can you help me with?"
690        });
691
692        // Test array content format
693        let assistant_message_array_json = json!({
694            "role": "assistant",
695            "content": [{
696                "type": "text",
697                "text": "Hello there, how may I assist you today?"
698            }]
699        });
700
701        let assistant_message = Message::try_from(assistant_message_json).unwrap();
702        let user_message = Message::try_from(user_message_json).unwrap();
703        let assistant_message_array = Message::try_from(assistant_message_array_json).unwrap();
704
705        // Test string content format
706        match assistant_message {
707            Message::Assistant { content, .. } => {
708                assert_eq!(
709                    content.first(),
710                    AssistantContent::Text(message::Text {
711                        text: "Hello there, how may I assist you today?".to_string()
712                    })
713                );
714            }
715            _ => panic!("Expected assistant message"),
716        }
717
718        match user_message {
719            Message::User { content } => {
720                assert_eq!(
721                    content.first(),
722                    UserContent::Text(message::Text {
723                        text: "What can you help me with?".to_string()
724                    })
725                );
726            }
727            _ => panic!("Expected user message"),
728        }
729
730        // Test array content format
731        match assistant_message_array {
732            Message::Assistant { content, .. } => {
733                assert_eq!(
734                    content.first(),
735                    AssistantContent::Text(message::Text {
736                        text: "Hello there, how may I assist you today?".to_string()
737                    })
738                );
739            }
740            _ => panic!("Expected assistant message"),
741        }
742    }
743
744    #[test]
745    fn test_message_conversion() {
746        // Test converting from our Message type to Mira's format and back
747        let original_message = message::Message::User {
748            content: OneOrMany::one(message::UserContent::text("Hello")),
749        };
750
751        // Convert to Mira format
752        let mira_value: serde_json::Value = original_message.clone().into();
753
754        // Convert back to our Message type
755        let converted_message: Message = mira_value.try_into().unwrap();
756
757        assert_eq!(original_message, converted_message);
758    }
759
760    #[test]
761    fn test_completion_response_conversion() {
762        let mira_response = CompletionResponse::Structured {
763            id: "resp_123".to_string(),
764            object: "chat.completion".to_string(),
765            created: 1234567890,
766            model: "deepseek-r1".to_string(),
767            choices: vec![ChatChoice {
768                message: RawMessage {
769                    role: "assistant".to_string(),
770                    content: "Test response".to_string(),
771                },
772                finish_reason: Some("stop".to_string()),
773                index: Some(0),
774            }],
775            usage: Some(Usage {
776                prompt_tokens: 10,
777                total_tokens: 20,
778            }),
779        };
780
781        let completion_response: completion::CompletionResponse<CompletionResponse> =
782            mira_response.try_into().unwrap();
783
784        assert_eq!(
785            completion_response.choice.first(),
786            completion::AssistantContent::text("Test response")
787        );
788    }
789}