rig/providers/huggingface/
completion.rs

1use super::client::Client;
2use crate::completion::GetTokenUsage;
3use crate::http_client::HttpClientExt;
4use crate::providers::openai::StreamingCompletionResponse;
5use crate::telemetry::SpanCombinator;
6use crate::{
7    OneOrMany,
8    completion::{self, CompletionError, CompletionRequest},
9    json_utils,
10    message::{self},
11    one_or_many::string_or_one_or_many,
12};
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use serde_json::Value;
15use std::{convert::Infallible, str::FromStr};
16use tracing::{Level, enabled, info_span};
17use tracing_futures::Instrument;
18
19#[derive(Debug, Deserialize)]
20#[serde(untagged)]
21pub enum ApiResponse<T> {
22    Ok(T),
23    Err(Value),
24}
25
26// ================================================================
27// Huggingface Completion API
28// ================================================================
29
30// Conversational LLMs
31/// `google/gemma-2-2b-it` completion model
32pub const GEMMA_2: &str = "google/gemma-2-2b-it";
33/// `meta-llama/Meta-Llama-3.1-8B-Instruct` completion model
34pub const META_LLAMA_3_1: &str = "meta-llama/Meta-Llama-3.1-8B-Instruct";
35/// `PowerInfer/SmallThinker-3B-Preview` completion model
36pub const SMALLTHINKER_PREVIEW: &str = "PowerInfer/SmallThinker-3B-Preview";
37/// `Qwen/Qwen2.5-7B-Instruct` completion model
38pub const QWEN2_5: &str = "Qwen/Qwen2.5-7B-Instruct";
39/// `Qwen/Qwen2.5-Coder-32B-Instruct` completion model
40pub const QWEN2_5_CODER: &str = "Qwen/Qwen2.5-Coder-32B-Instruct";
41
42// Conversational VLMs
43
44/// `Qwen/Qwen2-VL-7B-Instruct` visual-language completion model
45pub const QWEN2_VL: &str = "Qwen/Qwen2-VL-7B-Instruct";
46/// `Qwen/QVQ-72B-Preview` visual-language completion model
47pub const QWEN_QVQ_PREVIEW: &str = "Qwen/QVQ-72B-Preview";
48
49#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
50pub struct Function {
51    name: String,
52    #[serde(
53        serialize_with = "json_utils::stringified_json::serialize",
54        deserialize_with = "deserialize_arguments"
55    )]
56    pub arguments: serde_json::Value,
57}
58
59fn deserialize_arguments<'de, D>(deserializer: D) -> Result<Value, D::Error>
60where
61    D: Deserializer<'de>,
62{
63    let value = Value::deserialize(deserializer)?;
64
65    match value {
66        Value::String(s) => serde_json::from_str(&s).map_err(serde::de::Error::custom),
67        other => Ok(other),
68    }
69}
70
71impl From<Function> for message::ToolFunction {
72    fn from(value: Function) -> Self {
73        message::ToolFunction {
74            name: value.name,
75            arguments: value.arguments,
76        }
77    }
78}
79
80#[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)]
81#[serde(rename_all = "lowercase")]
82pub enum ToolType {
83    #[default]
84    Function,
85}
86
87#[derive(Debug, Deserialize, Serialize, Clone)]
88pub struct ToolDefinition {
89    pub r#type: String,
90    pub function: completion::ToolDefinition,
91}
92
93impl From<completion::ToolDefinition> for ToolDefinition {
94    fn from(tool: completion::ToolDefinition) -> Self {
95        Self {
96            r#type: "function".into(),
97            function: tool,
98        }
99    }
100}
101
102#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
103pub struct ToolCall {
104    pub id: String,
105    pub r#type: ToolType,
106    pub function: Function,
107}
108
109impl From<ToolCall> for message::ToolCall {
110    fn from(value: ToolCall) -> Self {
111        message::ToolCall {
112            id: value.id,
113            call_id: None,
114            function: value.function.into(),
115            signature: None,
116            additional_params: None,
117        }
118    }
119}
120
121impl From<message::ToolCall> for ToolCall {
122    fn from(value: message::ToolCall) -> Self {
123        ToolCall {
124            id: value.id,
125            r#type: ToolType::Function,
126            function: Function {
127                name: value.function.name,
128                arguments: value.function.arguments,
129            },
130        }
131    }
132}
133
134#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
135pub struct ImageUrl {
136    url: String,
137}
138
139#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
140#[serde(tag = "type", rename_all = "lowercase")]
141pub enum UserContent {
142    Text {
143        text: String,
144    },
145    #[serde(rename = "image_url")]
146    ImageUrl {
147        image_url: ImageUrl,
148    },
149}
150
151impl FromStr for UserContent {
152    type Err = Infallible;
153
154    fn from_str(s: &str) -> Result<Self, Self::Err> {
155        Ok(UserContent::Text {
156            text: s.to_string(),
157        })
158    }
159}
160
161#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
162#[serde(tag = "type", rename_all = "lowercase")]
163pub enum AssistantContent {
164    Text { text: String },
165}
166
167impl FromStr for AssistantContent {
168    type Err = Infallible;
169
170    fn from_str(s: &str) -> Result<Self, Self::Err> {
171        Ok(AssistantContent::Text {
172            text: s.to_string(),
173        })
174    }
175}
176
177#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
178#[serde(tag = "type", rename_all = "lowercase")]
179pub enum SystemContent {
180    Text { text: String },
181}
182
183impl FromStr for SystemContent {
184    type Err = Infallible;
185
186    fn from_str(s: &str) -> Result<Self, Self::Err> {
187        Ok(SystemContent::Text {
188            text: s.to_string(),
189        })
190    }
191}
192
193impl From<UserContent> for message::UserContent {
194    fn from(value: UserContent) -> Self {
195        match value {
196            UserContent::Text { text } => message::UserContent::text(text),
197            UserContent::ImageUrl { image_url } => {
198                message::UserContent::image_url(image_url.url, None, None)
199            }
200        }
201    }
202}
203
204impl TryFrom<message::UserContent> for UserContent {
205    type Error = message::MessageError;
206
207    fn try_from(content: message::UserContent) -> Result<Self, Self::Error> {
208        match content {
209            message::UserContent::Text(text) => Ok(UserContent::Text { text: text.text }),
210            message::UserContent::Document(message::Document {
211                data: message::DocumentSourceKind::Raw(raw),
212                ..
213            }) => {
214                let text = String::from_utf8_lossy(raw.as_slice()).into();
215                Ok(UserContent::Text { text })
216            }
217            message::UserContent::Document(message::Document {
218                data:
219                    message::DocumentSourceKind::Base64(text)
220                    | message::DocumentSourceKind::String(text),
221                ..
222            }) => Ok(UserContent::Text { text }),
223            message::UserContent::Image(message::Image { data, .. }) => match data {
224                message::DocumentSourceKind::Url(url) => Ok(UserContent::ImageUrl {
225                    image_url: ImageUrl { url },
226                }),
227                _ => Err(message::MessageError::ConversionError(
228                    "Huggingface only supports images as urls".into(),
229                )),
230            },
231            _ => Err(message::MessageError::ConversionError(
232                "Huggingface only supports text and images".into(),
233            )),
234        }
235    }
236}
237
238#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
239#[serde(tag = "role", rename_all = "lowercase")]
240pub enum Message {
241    System {
242        #[serde(deserialize_with = "string_or_one_or_many")]
243        content: OneOrMany<SystemContent>,
244    },
245    User {
246        #[serde(deserialize_with = "string_or_one_or_many")]
247        content: OneOrMany<UserContent>,
248    },
249    Assistant {
250        #[serde(default, deserialize_with = "json_utils::string_or_vec")]
251        content: Vec<AssistantContent>,
252        #[serde(default, deserialize_with = "json_utils::null_or_vec")]
253        tool_calls: Vec<ToolCall>,
254    },
255    #[serde(rename = "tool", alias = "Tool")]
256    ToolResult {
257        name: String,
258        #[serde(skip_serializing_if = "Option::is_none")]
259        arguments: Option<serde_json::Value>,
260        #[serde(
261            deserialize_with = "string_or_one_or_many",
262            serialize_with = "serialize_tool_content"
263        )]
264        content: OneOrMany<String>,
265    },
266}
267
268fn serialize_tool_content<S>(content: &OneOrMany<String>, serializer: S) -> Result<S::Ok, S::Error>
269where
270    S: Serializer,
271{
272    // OpenAI-compatible APIs expect tool content as a string, not an array
273    let joined = content
274        .iter()
275        .map(String::as_str)
276        .collect::<Vec<_>>()
277        .join("\n");
278    serializer.serialize_str(&joined)
279}
280
281impl Message {
282    pub fn system(content: &str) -> Self {
283        Message::System {
284            content: OneOrMany::one(SystemContent::Text {
285                text: content.to_string(),
286            }),
287        }
288    }
289}
290
291impl TryFrom<message::Message> for Vec<Message> {
292    type Error = message::MessageError;
293
294    fn try_from(message: message::Message) -> Result<Vec<Message>, Self::Error> {
295        match message {
296            message::Message::User { content } => {
297                let (tool_results, other_content): (Vec<_>, Vec<_>) = content
298                    .into_iter()
299                    .partition(|content| matches!(content, message::UserContent::ToolResult(_)));
300
301                if !tool_results.is_empty() {
302                    tool_results
303                        .into_iter()
304                        .map(|content| match content {
305                            message::UserContent::ToolResult(message::ToolResult {
306                                id,
307                                content,
308                                ..
309                            }) => Ok::<_, message::MessageError>(Message::ToolResult {
310                                name: id,
311                                arguments: None,
312                                content: content.try_map(|content| match content {
313                                    message::ToolResultContent::Text(message::Text { text }) => {
314                                        Ok(text)
315                                    }
316                                    _ => Err(message::MessageError::ConversionError(
317                                        "Tool result content does not support non-text".into(),
318                                    )),
319                                })?,
320                            }),
321                            _ => unreachable!(),
322                        })
323                        .collect::<Result<Vec<_>, _>>()
324                } else {
325                    let other_content = OneOrMany::many(other_content).expect(
326                        "There must be other content here if there were no tool result content",
327                    );
328
329                    Ok(vec![Message::User {
330                        content: other_content.try_map(|content| match content {
331                            message::UserContent::Text(text) => {
332                                Ok(UserContent::Text { text: text.text })
333                            }
334                            message::UserContent::Image(image) => {
335                                let url = image.try_into_url()?;
336
337                                Ok(UserContent::ImageUrl {
338                                    image_url: ImageUrl { url },
339                                })
340                            }
341                            message::UserContent::Document(message::Document {
342                                data: message::DocumentSourceKind::Raw(raw), ..
343                            }) => {
344                                let text = String::from_utf8_lossy(raw.as_slice()).into();
345                                Ok(UserContent::Text { text })
346                            }
347                            message::UserContent::Document(message::Document {
348                                data: message::DocumentSourceKind::Base64(text) | message::DocumentSourceKind::String(text), ..
349                            }) => {
350                                Ok(UserContent::Text { text })
351                            }
352                            _ => Err(message::MessageError::ConversionError(
353                                "Huggingface inputs only support text and image URLs (both base64-encoded images and regular URLs)".into(),
354                            )),
355                        })?,
356                    }])
357                }
358            }
359            message::Message::Assistant { content, .. } => {
360                let (text_content, tool_calls) = content.into_iter().fold(
361                    (Vec::new(), Vec::new()),
362                    |(mut texts, mut tools), content| {
363                        match content {
364                            message::AssistantContent::Text(text) => texts.push(text),
365                            message::AssistantContent::ToolCall(tool_call) => tools.push(tool_call),
366                            message::AssistantContent::Reasoning(_) => {
367                                panic!("Reasoning is not supported on HuggingFace via Rig");
368                            }
369                            message::AssistantContent::Image(_) => {
370                                panic!("Image content is not supported on HuggingFace via Rig");
371                            }
372                        }
373                        (texts, tools)
374                    },
375                );
376
377                // `OneOrMany` ensures at least one `AssistantContent::Text` or `ToolCall` exists,
378                //  so either `content` or `tool_calls` will have some content.
379                Ok(vec![Message::Assistant {
380                    content: text_content
381                        .into_iter()
382                        .map(|content| AssistantContent::Text { text: content.text })
383                        .collect::<Vec<_>>(),
384                    tool_calls: tool_calls
385                        .into_iter()
386                        .map(|tool_call| tool_call.into())
387                        .collect::<Vec<_>>(),
388                }])
389            }
390        }
391    }
392}
393
394impl TryFrom<Message> for message::Message {
395    type Error = message::MessageError;
396
397    fn try_from(message: Message) -> Result<Self, Self::Error> {
398        Ok(match message {
399            Message::User { content, .. } => message::Message::User {
400                content: content.map(|content| content.into()),
401            },
402            Message::Assistant {
403                content,
404                tool_calls,
405                ..
406            } => {
407                let mut content = content
408                    .into_iter()
409                    .map(|content| match content {
410                        AssistantContent::Text { text } => message::AssistantContent::text(text),
411                    })
412                    .collect::<Vec<_>>();
413
414                content.extend(
415                    tool_calls
416                        .into_iter()
417                        .map(|tool_call| Ok(message::AssistantContent::ToolCall(tool_call.into())))
418                        .collect::<Result<Vec<_>, _>>()?,
419                );
420
421                message::Message::Assistant {
422                    id: None,
423                    content: OneOrMany::many(content).map_err(|_| {
424                        message::MessageError::ConversionError(
425                            "Neither `content` nor `tool_calls` was provided to the Message"
426                                .to_owned(),
427                        )
428                    })?,
429                }
430            }
431
432            Message::ToolResult { name, content, .. } => message::Message::User {
433                content: OneOrMany::one(message::UserContent::tool_result(
434                    name,
435                    content.map(message::ToolResultContent::text),
436                )),
437            },
438
439            // System messages should get stripped out when converting message's, this is just a
440            // stop gap to avoid obnoxious error handling or panic occurring.
441            Message::System { content, .. } => message::Message::User {
442                content: content.map(|c| match c {
443                    SystemContent::Text { text } => message::UserContent::text(text),
444                }),
445            },
446        })
447    }
448}
449
450#[derive(Clone, Debug, Deserialize, Serialize)]
451pub struct Choice {
452    pub finish_reason: String,
453    pub index: usize,
454    #[serde(default)]
455    pub logprobs: serde_json::Value,
456    pub message: Message,
457}
458
459#[derive(Debug, Deserialize, Clone, Serialize)]
460pub struct Usage {
461    pub completion_tokens: i32,
462    pub prompt_tokens: i32,
463    pub total_tokens: i32,
464}
465
466impl GetTokenUsage for Usage {
467    fn token_usage(&self) -> Option<crate::completion::Usage> {
468        let mut usage = crate::completion::Usage::new();
469        usage.input_tokens = self.prompt_tokens as u64;
470        usage.output_tokens = self.completion_tokens as u64;
471        usage.total_tokens = self.total_tokens as u64;
472
473        Some(usage)
474    }
475}
476
477#[derive(Clone, Debug, Deserialize, Serialize)]
478pub struct CompletionResponse {
479    pub created: i32,
480    pub id: String,
481    pub model: String,
482    pub choices: Vec<Choice>,
483    #[serde(default, deserialize_with = "default_string_on_null")]
484    pub system_fingerprint: String,
485    pub usage: Usage,
486}
487
488impl crate::telemetry::ProviderResponseExt for CompletionResponse {
489    type OutputMessage = Choice;
490    type Usage = Usage;
491
492    fn get_response_id(&self) -> Option<String> {
493        Some(self.id.clone())
494    }
495
496    fn get_response_model_name(&self) -> Option<String> {
497        Some(self.model.clone())
498    }
499
500    fn get_output_messages(&self) -> Vec<Self::OutputMessage> {
501        self.choices.clone()
502    }
503
504    fn get_text_response(&self) -> Option<String> {
505        let text_response = self
506            .choices
507            .iter()
508            .filter_map(|x| {
509                let Message::User { ref content } = x.message else {
510                    return None;
511                };
512
513                let text = content
514                    .iter()
515                    .filter_map(|x| {
516                        if let UserContent::Text { text } = x {
517                            Some(text.clone())
518                        } else {
519                            None
520                        }
521                    })
522                    .collect::<Vec<String>>();
523
524                if text.is_empty() {
525                    None
526                } else {
527                    Some(text.join("\n"))
528                }
529            })
530            .collect::<Vec<String>>()
531            .join("\n");
532
533        if text_response.is_empty() {
534            None
535        } else {
536            Some(text_response)
537        }
538    }
539
540    fn get_usage(&self) -> Option<Self::Usage> {
541        Some(self.usage.clone())
542    }
543}
544
545fn default_string_on_null<'de, D>(deserializer: D) -> Result<String, D::Error>
546where
547    D: Deserializer<'de>,
548{
549    match Option::<String>::deserialize(deserializer)? {
550        Some(value) => Ok(value),      // Use provided value
551        None => Ok(String::default()), // Use `Default` implementation
552    }
553}
554
555impl TryFrom<CompletionResponse> for completion::CompletionResponse<CompletionResponse> {
556    type Error = CompletionError;
557
558    fn try_from(response: CompletionResponse) -> Result<Self, Self::Error> {
559        let choice = response.choices.first().ok_or_else(|| {
560            CompletionError::ResponseError("Response contained no choices".to_owned())
561        })?;
562
563        let content = match &choice.message {
564            Message::Assistant {
565                content,
566                tool_calls,
567                ..
568            } => {
569                let mut content = content
570                    .iter()
571                    .map(|c| match c {
572                        AssistantContent::Text { text } => message::AssistantContent::text(text),
573                    })
574                    .collect::<Vec<_>>();
575
576                content.extend(
577                    tool_calls
578                        .iter()
579                        .map(|call| {
580                            completion::AssistantContent::tool_call(
581                                &call.id,
582                                &call.function.name,
583                                call.function.arguments.clone(),
584                            )
585                        })
586                        .collect::<Vec<_>>(),
587                );
588                Ok(content)
589            }
590            _ => Err(CompletionError::ResponseError(
591                "Response did not contain a valid message or tool call".into(),
592            )),
593        }?;
594
595        let choice = OneOrMany::many(content).map_err(|_| {
596            CompletionError::ResponseError(
597                "Response contained no message or tool call (empty)".to_owned(),
598            )
599        })?;
600
601        let usage = completion::Usage {
602            input_tokens: response.usage.prompt_tokens as u64,
603            output_tokens: response.usage.completion_tokens as u64,
604            total_tokens: response.usage.total_tokens as u64,
605        };
606
607        Ok(completion::CompletionResponse {
608            choice,
609            usage,
610            raw_response: response,
611        })
612    }
613}
614
615#[derive(Debug, Serialize, Deserialize)]
616pub(super) struct HuggingfaceCompletionRequest {
617    model: String,
618    pub messages: Vec<Message>,
619    #[serde(skip_serializing_if = "Option::is_none")]
620    temperature: Option<f64>,
621    #[serde(skip_serializing_if = "Vec::is_empty")]
622    tools: Vec<ToolDefinition>,
623    #[serde(skip_serializing_if = "Option::is_none")]
624    tool_choice: Option<crate::providers::openai::completion::ToolChoice>,
625    #[serde(flatten, skip_serializing_if = "Option::is_none")]
626    pub additional_params: Option<serde_json::Value>,
627}
628
629impl TryFrom<(&str, CompletionRequest)> for HuggingfaceCompletionRequest {
630    type Error = CompletionError;
631
632    fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
633        let mut full_history: Vec<Message> = match &req.preamble {
634            Some(preamble) => vec![Message::system(preamble)],
635            None => vec![],
636        };
637        if let Some(docs) = req.normalized_documents() {
638            let docs: Vec<Message> = docs.try_into()?;
639            full_history.extend(docs);
640        }
641
642        let chat_history: Vec<Message> = req
643            .chat_history
644            .clone()
645            .into_iter()
646            .map(|message| message.try_into())
647            .collect::<Result<Vec<Vec<Message>>, _>>()?
648            .into_iter()
649            .flatten()
650            .collect();
651
652        full_history.extend(chat_history);
653
654        let tool_choice = req
655            .tool_choice
656            .clone()
657            .map(crate::providers::openai::completion::ToolChoice::try_from)
658            .transpose()?;
659
660        Ok(Self {
661            model: model.to_string(),
662            messages: full_history,
663            temperature: req.temperature,
664            tools: req
665                .tools
666                .clone()
667                .into_iter()
668                .map(ToolDefinition::from)
669                .collect::<Vec<_>>(),
670            tool_choice,
671            additional_params: req.additional_params,
672        })
673    }
674}
675
676#[derive(Clone)]
677pub struct CompletionModel<T = reqwest::Client> {
678    pub(crate) client: Client<T>,
679    /// Name of the model (e.g: google/gemma-2-2b-it)
680    pub model: String,
681}
682
683impl<T> CompletionModel<T> {
684    pub fn new(client: Client<T>, model: &str) -> Self {
685        Self {
686            client,
687            model: model.to_string(),
688        }
689    }
690}
691
692impl<T> completion::CompletionModel for CompletionModel<T>
693where
694    T: HttpClientExt + Clone + 'static,
695{
696    type Response = CompletionResponse;
697    type StreamingResponse = StreamingCompletionResponse;
698
699    type Client = Client<T>;
700
701    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
702        Self::new(client.clone(), &model.into())
703    }
704
705    async fn completion(
706        &self,
707        completion_request: CompletionRequest,
708    ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
709        let span = if tracing::Span::current().is_disabled() {
710            info_span!(
711                target: "rig::completions",
712                "chat",
713                gen_ai.operation.name = "chat",
714                gen_ai.provider.name = "huggingface",
715                gen_ai.request.model = self.model,
716                gen_ai.system_instructions = &completion_request.preamble,
717                gen_ai.response.id = tracing::field::Empty,
718                gen_ai.response.model = tracing::field::Empty,
719                gen_ai.usage.output_tokens = tracing::field::Empty,
720                gen_ai.usage.input_tokens = tracing::field::Empty,
721            )
722        } else {
723            tracing::Span::current()
724        };
725
726        let model = self.client.subprovider().model_identifier(&self.model);
727        let request = HuggingfaceCompletionRequest::try_from((model.as_ref(), completion_request))?;
728
729        if enabled!(Level::TRACE) {
730            tracing::trace!(
731                target: "rig::completions",
732                "Huggingface completion request: {}",
733                serde_json::to_string_pretty(&request)?
734            );
735        }
736
737        let request = serde_json::to_vec(&request)?;
738
739        let path = self.client.subprovider().completion_endpoint(&self.model);
740        let request = self
741            .client
742            .post(&path)?
743            .header("Content-Type", "application/json")
744            .body(request)
745            .map_err(|e| CompletionError::HttpError(e.into()))?;
746
747        async move {
748            let response = self.client.send(request).await?;
749
750            if response.status().is_success() {
751                let bytes: Vec<u8> = response.into_body().await?;
752                let text = String::from_utf8_lossy(&bytes);
753
754                tracing::debug!(target: "rig", "Huggingface completion error: {}", text);
755
756                match serde_json::from_slice::<ApiResponse<CompletionResponse>>(&bytes)? {
757                    ApiResponse::Ok(response) => {
758                        if enabled!(Level::TRACE) {
759                            tracing::trace!(
760                                target: "rig::completions",
761                                "Huggingface completion response: {}",
762                                serde_json::to_string_pretty(&response)?
763                            );
764                        }
765
766                        let span = tracing::Span::current();
767                        span.record_token_usage(&response.usage);
768                        span.record_response_metadata(&response);
769
770                        response.try_into()
771                    }
772                    ApiResponse::Err(err) => Err(CompletionError::ProviderError(err.to_string())),
773                }
774            } else {
775                let status = response.status();
776                let text: Vec<u8> = response.into_body().await?;
777                let text: String = String::from_utf8_lossy(&text).into();
778
779                Err(CompletionError::ProviderError(format!(
780                    "{}: {}",
781                    status, text
782                )))
783            }
784        }
785        .instrument(span)
786        .await
787    }
788
789    async fn stream(
790        &self,
791        request: CompletionRequest,
792    ) -> Result<
793        crate::streaming::StreamingCompletionResponse<Self::StreamingResponse>,
794        CompletionError,
795    > {
796        CompletionModel::stream(self, request).await
797    }
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803    use serde_path_to_error::deserialize;
804
805    #[test]
806    fn test_deserialize_message() {
807        let assistant_message_json = r#"
808        {
809            "role": "assistant",
810            "content": "\n\nHello there, how may I assist you today?"
811        }
812        "#;
813
814        let assistant_message_json2 = r#"
815        {
816            "role": "assistant",
817            "content": [
818                {
819                    "type": "text",
820                    "text": "\n\nHello there, how may I assist you today?"
821                }
822            ],
823            "tool_calls": null
824        }
825        "#;
826
827        let assistant_message_json3 = r#"
828        {
829            "role": "assistant",
830            "tool_calls": [
831                {
832                    "id": "call_h89ipqYUjEpCPI6SxspMnoUU",
833                    "type": "function",
834                    "function": {
835                        "name": "subtract",
836                        "arguments": {"x": 2, "y": 5}
837                    }
838                }
839            ],
840            "content": null,
841            "refusal": null
842        }
843        "#;
844
845        let user_message_json = r#"
846        {
847            "role": "user",
848            "content": [
849                {
850                    "type": "text",
851                    "text": "What's in this image?"
852                },
853                {
854                    "type": "image_url",
855                    "image_url": {
856                        "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
857                    }
858                }
859            ]
860        }
861        "#;
862
863        let assistant_message: Message = {
864            let jd = &mut serde_json::Deserializer::from_str(assistant_message_json);
865            deserialize(jd).unwrap_or_else(|err| {
866                panic!(
867                    "Deserialization error at {} ({}:{}): {}",
868                    err.path(),
869                    err.inner().line(),
870                    err.inner().column(),
871                    err
872                );
873            })
874        };
875
876        let assistant_message2: Message = {
877            let jd = &mut serde_json::Deserializer::from_str(assistant_message_json2);
878            deserialize(jd).unwrap_or_else(|err| {
879                panic!(
880                    "Deserialization error at {} ({}:{}): {}",
881                    err.path(),
882                    err.inner().line(),
883                    err.inner().column(),
884                    err
885                );
886            })
887        };
888
889        let assistant_message3: Message = {
890            let jd: &mut serde_json::Deserializer<serde_json::de::StrRead<'_>> =
891                &mut serde_json::Deserializer::from_str(assistant_message_json3);
892            deserialize(jd).unwrap_or_else(|err| {
893                panic!(
894                    "Deserialization error at {} ({}:{}): {}",
895                    err.path(),
896                    err.inner().line(),
897                    err.inner().column(),
898                    err
899                );
900            })
901        };
902
903        let user_message: Message = {
904            let jd = &mut serde_json::Deserializer::from_str(user_message_json);
905            deserialize(jd).unwrap_or_else(|err| {
906                panic!(
907                    "Deserialization error at {} ({}:{}): {}",
908                    err.path(),
909                    err.inner().line(),
910                    err.inner().column(),
911                    err
912                );
913            })
914        };
915
916        match assistant_message {
917            Message::Assistant { content, .. } => {
918                assert_eq!(
919                    content[0],
920                    AssistantContent::Text {
921                        text: "\n\nHello there, how may I assist you today?".to_string()
922                    }
923                );
924            }
925            _ => panic!("Expected assistant message"),
926        }
927
928        match assistant_message2 {
929            Message::Assistant {
930                content,
931                tool_calls,
932                ..
933            } => {
934                assert_eq!(
935                    content[0],
936                    AssistantContent::Text {
937                        text: "\n\nHello there, how may I assist you today?".to_string()
938                    }
939                );
940
941                assert_eq!(tool_calls, vec![]);
942            }
943            _ => panic!("Expected assistant message"),
944        }
945
946        match assistant_message3 {
947            Message::Assistant {
948                content,
949                tool_calls,
950                ..
951            } => {
952                assert!(content.is_empty());
953                assert_eq!(
954                    tool_calls[0],
955                    ToolCall {
956                        id: "call_h89ipqYUjEpCPI6SxspMnoUU".to_string(),
957                        r#type: ToolType::Function,
958                        function: Function {
959                            name: "subtract".to_string(),
960                            arguments: serde_json::json!({"x": 2, "y": 5}),
961                        },
962                    }
963                );
964            }
965            _ => panic!("Expected assistant message"),
966        }
967
968        match user_message {
969            Message::User { content, .. } => {
970                let (first, second) = {
971                    let mut iter = content.into_iter();
972                    (iter.next().unwrap(), iter.next().unwrap())
973                };
974                assert_eq!(
975                    first,
976                    UserContent::Text {
977                        text: "What's in this image?".to_string()
978                    }
979                );
980                assert_eq!(second, UserContent::ImageUrl { image_url: ImageUrl { url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg".to_string() } });
981            }
982            _ => panic!("Expected user message"),
983        }
984    }
985
986    #[test]
987    fn test_message_to_message_conversion() {
988        let user_message = message::Message::User {
989            content: OneOrMany::one(message::UserContent::text("Hello")),
990        };
991
992        let assistant_message = message::Message::Assistant {
993            id: None,
994            content: OneOrMany::one(message::AssistantContent::text("Hi there!")),
995        };
996
997        let converted_user_message: Vec<Message> = user_message.clone().try_into().unwrap();
998        let converted_assistant_message: Vec<Message> =
999            assistant_message.clone().try_into().unwrap();
1000
1001        match converted_user_message[0].clone() {
1002            Message::User { content, .. } => {
1003                assert_eq!(
1004                    content.first(),
1005                    UserContent::Text {
1006                        text: "Hello".to_string()
1007                    }
1008                );
1009            }
1010            _ => panic!("Expected user message"),
1011        }
1012
1013        match converted_assistant_message[0].clone() {
1014            Message::Assistant { content, .. } => {
1015                assert_eq!(
1016                    content[0],
1017                    AssistantContent::Text {
1018                        text: "Hi there!".to_string()
1019                    }
1020                );
1021            }
1022            _ => panic!("Expected assistant message"),
1023        }
1024
1025        let original_user_message: message::Message =
1026            converted_user_message[0].clone().try_into().unwrap();
1027        let original_assistant_message: message::Message =
1028            converted_assistant_message[0].clone().try_into().unwrap();
1029
1030        assert_eq!(original_user_message, user_message);
1031        assert_eq!(original_assistant_message, assistant_message);
1032    }
1033
1034    #[test]
1035    fn test_message_from_message_conversion() {
1036        let user_message = Message::User {
1037            content: OneOrMany::one(UserContent::Text {
1038                text: "Hello".to_string(),
1039            }),
1040        };
1041
1042        let assistant_message = Message::Assistant {
1043            content: vec![AssistantContent::Text {
1044                text: "Hi there!".to_string(),
1045            }],
1046            tool_calls: vec![],
1047        };
1048
1049        let converted_user_message: message::Message = user_message.clone().try_into().unwrap();
1050        let converted_assistant_message: message::Message =
1051            assistant_message.clone().try_into().unwrap();
1052
1053        match converted_user_message.clone() {
1054            message::Message::User { content } => {
1055                assert_eq!(content.first(), message::UserContent::text("Hello"));
1056            }
1057            _ => panic!("Expected user message"),
1058        }
1059
1060        match converted_assistant_message.clone() {
1061            message::Message::Assistant { content, .. } => {
1062                assert_eq!(
1063                    content.first(),
1064                    message::AssistantContent::text("Hi there!")
1065                );
1066            }
1067            _ => panic!("Expected assistant message"),
1068        }
1069
1070        let original_user_message: Vec<Message> = converted_user_message.try_into().unwrap();
1071        let original_assistant_message: Vec<Message> =
1072            converted_assistant_message.try_into().unwrap();
1073
1074        assert_eq!(original_user_message[0], user_message);
1075        assert_eq!(original_assistant_message[0], assistant_message);
1076    }
1077
1078    #[test]
1079    fn test_responses() {
1080        let fireworks_response_json = r#"
1081        {
1082            "choices": [
1083                {
1084                    "finish_reason": "tool_calls",
1085                    "index": 0,
1086                    "message": {
1087                        "role": "assistant",
1088                        "tool_calls": [
1089                            {
1090                                "function": {
1091                                "arguments": "{\"x\": 2, \"y\": 5}",
1092                                "name": "subtract"
1093                                },
1094                                "id": "call_1BspL6mQqjKgvsQbH1TIYkHf",
1095                                "index": 0,
1096                                "type": "function"
1097                            }
1098                        ]
1099                    }
1100                }
1101            ],
1102            "created": 1740704000,
1103            "id": "2a81f6a1-4866-42fb-9902-2655a2b5b1ff",
1104            "model": "accounts/fireworks/models/deepseek-v3",
1105            "object": "chat.completion",
1106            "usage": {
1107                "completion_tokens": 26,
1108                "prompt_tokens": 248,
1109                "total_tokens": 274
1110            }
1111        }
1112        "#;
1113
1114        let novita_response_json = r#"
1115        {
1116            "choices": [
1117                {
1118                    "finish_reason": "tool_calls",
1119                    "index": 0,
1120                    "logprobs": null,
1121                    "message": {
1122                        "audio": null,
1123                        "content": null,
1124                        "function_call": null,
1125                        "reasoning_content": null,
1126                        "refusal": null,
1127                        "role": "assistant",
1128                        "tool_calls": [
1129                            {
1130                                "function": {
1131                                    "arguments": "{\"x\": \"2\", \"y\": \"5\"}",
1132                                    "name": "subtract"
1133                                },
1134                                "id": "chatcmpl-tool-f6d2af7c8dc041058f95e2c2eede45c5",
1135                                "type": "function"
1136                            }
1137                        ]
1138                    },
1139                    "stop_reason": 128008
1140                }
1141            ],
1142            "created": 1740704592,
1143            "id": "chatcmpl-a92c60ae125c47c998ecdcb53387fed4",
1144            "model": "meta-llama/Meta-Llama-3.1-8B-Instruct-fast",
1145            "object": "chat.completion",
1146            "prompt_logprobs": null,
1147            "service_tier": null,
1148            "system_fingerprint": null,
1149            "usage": {
1150                "completion_tokens": 28,
1151                "completion_tokens_details": null,
1152                "prompt_tokens": 335,
1153                "prompt_tokens_details": null,
1154                "total_tokens": 363
1155            }
1156        }
1157        "#;
1158
1159        let _firework_response: CompletionResponse = {
1160            let jd = &mut serde_json::Deserializer::from_str(fireworks_response_json);
1161            deserialize(jd).unwrap_or_else(|err| {
1162                panic!(
1163                    "Deserialization error at {} ({}:{}): {}",
1164                    err.path(),
1165                    err.inner().line(),
1166                    err.inner().column(),
1167                    err
1168                );
1169            })
1170        };
1171
1172        let _novita_response: CompletionResponse = {
1173            let jd = &mut serde_json::Deserializer::from_str(novita_response_json);
1174            deserialize(jd).unwrap_or_else(|err| {
1175                panic!(
1176                    "Deserialization error at {} ({}:{}): {}",
1177                    err.path(),
1178                    err.inner().line(),
1179                    err.inner().column(),
1180                    err
1181                );
1182            })
1183        };
1184    }
1185}