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
26pub const GEMMA_2: &str = "google/gemma-2-2b-it";
33pub const META_LLAMA_3_1: &str = "meta-llama/Meta-Llama-3.1-8B-Instruct";
35pub const SMALLTHINKER_PREVIEW: &str = "PowerInfer/SmallThinker-3B-Preview";
37pub const QWEN2_5: &str = "Qwen/Qwen2.5-7B-Instruct";
39pub const QWEN2_5_CODER: &str = "Qwen/Qwen2.5-Coder-32B-Instruct";
41
42pub const QWEN2_VL: &str = "Qwen/Qwen2-VL-7B-Instruct";
46pub 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 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 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 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), None => Ok(String::default()), }
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 cached_input_tokens: 0,
606 };
607
608 Ok(completion::CompletionResponse {
609 choice,
610 usage,
611 raw_response: response,
612 })
613 }
614}
615
616#[derive(Debug, Serialize, Deserialize)]
617pub(super) struct HuggingfaceCompletionRequest {
618 model: String,
619 pub messages: Vec<Message>,
620 #[serde(skip_serializing_if = "Option::is_none")]
621 temperature: Option<f64>,
622 #[serde(skip_serializing_if = "Vec::is_empty")]
623 tools: Vec<ToolDefinition>,
624 #[serde(skip_serializing_if = "Option::is_none")]
625 tool_choice: Option<crate::providers::openai::completion::ToolChoice>,
626 #[serde(flatten, skip_serializing_if = "Option::is_none")]
627 pub additional_params: Option<serde_json::Value>,
628}
629
630impl TryFrom<(&str, CompletionRequest)> for HuggingfaceCompletionRequest {
631 type Error = CompletionError;
632
633 fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
634 let mut full_history: Vec<Message> = match &req.preamble {
635 Some(preamble) => vec![Message::system(preamble)],
636 None => vec![],
637 };
638 if let Some(docs) = req.normalized_documents() {
639 let docs: Vec<Message> = docs.try_into()?;
640 full_history.extend(docs);
641 }
642
643 let chat_history: Vec<Message> = req
644 .chat_history
645 .clone()
646 .into_iter()
647 .map(|message| message.try_into())
648 .collect::<Result<Vec<Vec<Message>>, _>>()?
649 .into_iter()
650 .flatten()
651 .collect();
652
653 full_history.extend(chat_history);
654
655 let tool_choice = req
656 .tool_choice
657 .clone()
658 .map(crate::providers::openai::completion::ToolChoice::try_from)
659 .transpose()?;
660
661 Ok(Self {
662 model: model.to_string(),
663 messages: full_history,
664 temperature: req.temperature,
665 tools: req
666 .tools
667 .clone()
668 .into_iter()
669 .map(ToolDefinition::from)
670 .collect::<Vec<_>>(),
671 tool_choice,
672 additional_params: req.additional_params,
673 })
674 }
675}
676
677#[derive(Clone)]
678pub struct CompletionModel<T = reqwest::Client> {
679 pub(crate) client: Client<T>,
680 pub model: String,
682}
683
684impl<T> CompletionModel<T> {
685 pub fn new(client: Client<T>, model: &str) -> Self {
686 Self {
687 client,
688 model: model.to_string(),
689 }
690 }
691}
692
693impl<T> completion::CompletionModel for CompletionModel<T>
694where
695 T: HttpClientExt + Clone + 'static,
696{
697 type Response = CompletionResponse;
698 type StreamingResponse = StreamingCompletionResponse;
699
700 type Client = Client<T>;
701
702 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
703 Self::new(client.clone(), &model.into())
704 }
705
706 async fn completion(
707 &self,
708 completion_request: CompletionRequest,
709 ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
710 let span = if tracing::Span::current().is_disabled() {
711 info_span!(
712 target: "rig::completions",
713 "chat",
714 gen_ai.operation.name = "chat",
715 gen_ai.provider.name = "huggingface",
716 gen_ai.request.model = self.model,
717 gen_ai.system_instructions = &completion_request.preamble,
718 gen_ai.response.id = tracing::field::Empty,
719 gen_ai.response.model = tracing::field::Empty,
720 gen_ai.usage.output_tokens = tracing::field::Empty,
721 gen_ai.usage.input_tokens = tracing::field::Empty,
722 )
723 } else {
724 tracing::Span::current()
725 };
726
727 let model = self.client.subprovider().model_identifier(&self.model);
728 let request = HuggingfaceCompletionRequest::try_from((model.as_ref(), completion_request))?;
729
730 if enabled!(Level::TRACE) {
731 tracing::trace!(
732 target: "rig::completions",
733 "Huggingface completion request: {}",
734 serde_json::to_string_pretty(&request)?
735 );
736 }
737
738 let request = serde_json::to_vec(&request)?;
739
740 let path = self.client.subprovider().completion_endpoint(&self.model);
741 let request = self
742 .client
743 .post(&path)?
744 .header("Content-Type", "application/json")
745 .body(request)
746 .map_err(|e| CompletionError::HttpError(e.into()))?;
747
748 async move {
749 let response = self.client.send(request).await?;
750
751 if response.status().is_success() {
752 let bytes: Vec<u8> = response.into_body().await?;
753 let text = String::from_utf8_lossy(&bytes);
754
755 tracing::debug!(target: "rig", "Huggingface completion error: {}", text);
756
757 match serde_json::from_slice::<ApiResponse<CompletionResponse>>(&bytes)? {
758 ApiResponse::Ok(response) => {
759 if enabled!(Level::TRACE) {
760 tracing::trace!(
761 target: "rig::completions",
762 "Huggingface completion response: {}",
763 serde_json::to_string_pretty(&response)?
764 );
765 }
766
767 let span = tracing::Span::current();
768 span.record_token_usage(&response.usage);
769 span.record_response_metadata(&response);
770
771 response.try_into()
772 }
773 ApiResponse::Err(err) => Err(CompletionError::ProviderError(err.to_string())),
774 }
775 } else {
776 let status = response.status();
777 let text: Vec<u8> = response.into_body().await?;
778 let text: String = String::from_utf8_lossy(&text).into();
779
780 Err(CompletionError::ProviderError(format!(
781 "{}: {}",
782 status, text
783 )))
784 }
785 }
786 .instrument(span)
787 .await
788 }
789
790 async fn stream(
791 &self,
792 request: CompletionRequest,
793 ) -> Result<
794 crate::streaming::StreamingCompletionResponse<Self::StreamingResponse>,
795 CompletionError,
796 > {
797 CompletionModel::stream(self, request).await
798 }
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804 use serde_path_to_error::deserialize;
805
806 #[test]
807 fn test_deserialize_message() {
808 let assistant_message_json = r#"
809 {
810 "role": "assistant",
811 "content": "\n\nHello there, how may I assist you today?"
812 }
813 "#;
814
815 let assistant_message_json2 = r#"
816 {
817 "role": "assistant",
818 "content": [
819 {
820 "type": "text",
821 "text": "\n\nHello there, how may I assist you today?"
822 }
823 ],
824 "tool_calls": null
825 }
826 "#;
827
828 let assistant_message_json3 = r#"
829 {
830 "role": "assistant",
831 "tool_calls": [
832 {
833 "id": "call_h89ipqYUjEpCPI6SxspMnoUU",
834 "type": "function",
835 "function": {
836 "name": "subtract",
837 "arguments": {"x": 2, "y": 5}
838 }
839 }
840 ],
841 "content": null,
842 "refusal": null
843 }
844 "#;
845
846 let user_message_json = r#"
847 {
848 "role": "user",
849 "content": [
850 {
851 "type": "text",
852 "text": "What's in this image?"
853 },
854 {
855 "type": "image_url",
856 "image_url": {
857 "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"
858 }
859 }
860 ]
861 }
862 "#;
863
864 let assistant_message: Message = {
865 let jd = &mut serde_json::Deserializer::from_str(assistant_message_json);
866 deserialize(jd).unwrap_or_else(|err| {
867 panic!(
868 "Deserialization error at {} ({}:{}): {}",
869 err.path(),
870 err.inner().line(),
871 err.inner().column(),
872 err
873 );
874 })
875 };
876
877 let assistant_message2: Message = {
878 let jd = &mut serde_json::Deserializer::from_str(assistant_message_json2);
879 deserialize(jd).unwrap_or_else(|err| {
880 panic!(
881 "Deserialization error at {} ({}:{}): {}",
882 err.path(),
883 err.inner().line(),
884 err.inner().column(),
885 err
886 );
887 })
888 };
889
890 let assistant_message3: Message = {
891 let jd: &mut serde_json::Deserializer<serde_json::de::StrRead<'_>> =
892 &mut serde_json::Deserializer::from_str(assistant_message_json3);
893 deserialize(jd).unwrap_or_else(|err| {
894 panic!(
895 "Deserialization error at {} ({}:{}): {}",
896 err.path(),
897 err.inner().line(),
898 err.inner().column(),
899 err
900 );
901 })
902 };
903
904 let user_message: Message = {
905 let jd = &mut serde_json::Deserializer::from_str(user_message_json);
906 deserialize(jd).unwrap_or_else(|err| {
907 panic!(
908 "Deserialization error at {} ({}:{}): {}",
909 err.path(),
910 err.inner().line(),
911 err.inner().column(),
912 err
913 );
914 })
915 };
916
917 match assistant_message {
918 Message::Assistant { content, .. } => {
919 assert_eq!(
920 content[0],
921 AssistantContent::Text {
922 text: "\n\nHello there, how may I assist you today?".to_string()
923 }
924 );
925 }
926 _ => panic!("Expected assistant message"),
927 }
928
929 match assistant_message2 {
930 Message::Assistant {
931 content,
932 tool_calls,
933 ..
934 } => {
935 assert_eq!(
936 content[0],
937 AssistantContent::Text {
938 text: "\n\nHello there, how may I assist you today?".to_string()
939 }
940 );
941
942 assert_eq!(tool_calls, vec![]);
943 }
944 _ => panic!("Expected assistant message"),
945 }
946
947 match assistant_message3 {
948 Message::Assistant {
949 content,
950 tool_calls,
951 ..
952 } => {
953 assert!(content.is_empty());
954 assert_eq!(
955 tool_calls[0],
956 ToolCall {
957 id: "call_h89ipqYUjEpCPI6SxspMnoUU".to_string(),
958 r#type: ToolType::Function,
959 function: Function {
960 name: "subtract".to_string(),
961 arguments: serde_json::json!({"x": 2, "y": 5}),
962 },
963 }
964 );
965 }
966 _ => panic!("Expected assistant message"),
967 }
968
969 match user_message {
970 Message::User { content, .. } => {
971 let (first, second) = {
972 let mut iter = content.into_iter();
973 (iter.next().unwrap(), iter.next().unwrap())
974 };
975 assert_eq!(
976 first,
977 UserContent::Text {
978 text: "What's in this image?".to_string()
979 }
980 );
981 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() } });
982 }
983 _ => panic!("Expected user message"),
984 }
985 }
986
987 #[test]
988 fn test_message_to_message_conversion() {
989 let user_message = message::Message::User {
990 content: OneOrMany::one(message::UserContent::text("Hello")),
991 };
992
993 let assistant_message = message::Message::Assistant {
994 id: None,
995 content: OneOrMany::one(message::AssistantContent::text("Hi there!")),
996 };
997
998 let converted_user_message: Vec<Message> = user_message.clone().try_into().unwrap();
999 let converted_assistant_message: Vec<Message> =
1000 assistant_message.clone().try_into().unwrap();
1001
1002 match converted_user_message[0].clone() {
1003 Message::User { content, .. } => {
1004 assert_eq!(
1005 content.first(),
1006 UserContent::Text {
1007 text: "Hello".to_string()
1008 }
1009 );
1010 }
1011 _ => panic!("Expected user message"),
1012 }
1013
1014 match converted_assistant_message[0].clone() {
1015 Message::Assistant { content, .. } => {
1016 assert_eq!(
1017 content[0],
1018 AssistantContent::Text {
1019 text: "Hi there!".to_string()
1020 }
1021 );
1022 }
1023 _ => panic!("Expected assistant message"),
1024 }
1025
1026 let original_user_message: message::Message =
1027 converted_user_message[0].clone().try_into().unwrap();
1028 let original_assistant_message: message::Message =
1029 converted_assistant_message[0].clone().try_into().unwrap();
1030
1031 assert_eq!(original_user_message, user_message);
1032 assert_eq!(original_assistant_message, assistant_message);
1033 }
1034
1035 #[test]
1036 fn test_message_from_message_conversion() {
1037 let user_message = Message::User {
1038 content: OneOrMany::one(UserContent::Text {
1039 text: "Hello".to_string(),
1040 }),
1041 };
1042
1043 let assistant_message = Message::Assistant {
1044 content: vec![AssistantContent::Text {
1045 text: "Hi there!".to_string(),
1046 }],
1047 tool_calls: vec![],
1048 };
1049
1050 let converted_user_message: message::Message = user_message.clone().try_into().unwrap();
1051 let converted_assistant_message: message::Message =
1052 assistant_message.clone().try_into().unwrap();
1053
1054 match converted_user_message.clone() {
1055 message::Message::User { content } => {
1056 assert_eq!(content.first(), message::UserContent::text("Hello"));
1057 }
1058 _ => panic!("Expected user message"),
1059 }
1060
1061 match converted_assistant_message.clone() {
1062 message::Message::Assistant { content, .. } => {
1063 assert_eq!(
1064 content.first(),
1065 message::AssistantContent::text("Hi there!")
1066 );
1067 }
1068 _ => panic!("Expected assistant message"),
1069 }
1070
1071 let original_user_message: Vec<Message> = converted_user_message.try_into().unwrap();
1072 let original_assistant_message: Vec<Message> =
1073 converted_assistant_message.try_into().unwrap();
1074
1075 assert_eq!(original_user_message[0], user_message);
1076 assert_eq!(original_assistant_message[0], assistant_message);
1077 }
1078
1079 #[test]
1080 fn test_responses() {
1081 let fireworks_response_json = r#"
1082 {
1083 "choices": [
1084 {
1085 "finish_reason": "tool_calls",
1086 "index": 0,
1087 "message": {
1088 "role": "assistant",
1089 "tool_calls": [
1090 {
1091 "function": {
1092 "arguments": "{\"x\": 2, \"y\": 5}",
1093 "name": "subtract"
1094 },
1095 "id": "call_1BspL6mQqjKgvsQbH1TIYkHf",
1096 "index": 0,
1097 "type": "function"
1098 }
1099 ]
1100 }
1101 }
1102 ],
1103 "created": 1740704000,
1104 "id": "2a81f6a1-4866-42fb-9902-2655a2b5b1ff",
1105 "model": "accounts/fireworks/models/deepseek-v3",
1106 "object": "chat.completion",
1107 "usage": {
1108 "completion_tokens": 26,
1109 "prompt_tokens": 248,
1110 "total_tokens": 274
1111 }
1112 }
1113 "#;
1114
1115 let novita_response_json = r#"
1116 {
1117 "choices": [
1118 {
1119 "finish_reason": "tool_calls",
1120 "index": 0,
1121 "logprobs": null,
1122 "message": {
1123 "audio": null,
1124 "content": null,
1125 "function_call": null,
1126 "reasoning_content": null,
1127 "refusal": null,
1128 "role": "assistant",
1129 "tool_calls": [
1130 {
1131 "function": {
1132 "arguments": "{\"x\": \"2\", \"y\": \"5\"}",
1133 "name": "subtract"
1134 },
1135 "id": "chatcmpl-tool-f6d2af7c8dc041058f95e2c2eede45c5",
1136 "type": "function"
1137 }
1138 ]
1139 },
1140 "stop_reason": 128008
1141 }
1142 ],
1143 "created": 1740704592,
1144 "id": "chatcmpl-a92c60ae125c47c998ecdcb53387fed4",
1145 "model": "meta-llama/Meta-Llama-3.1-8B-Instruct-fast",
1146 "object": "chat.completion",
1147 "prompt_logprobs": null,
1148 "service_tier": null,
1149 "system_fingerprint": null,
1150 "usage": {
1151 "completion_tokens": 28,
1152 "completion_tokens_details": null,
1153 "prompt_tokens": 335,
1154 "prompt_tokens_details": null,
1155 "total_tokens": 363
1156 }
1157 }
1158 "#;
1159
1160 let _firework_response: CompletionResponse = {
1161 let jd = &mut serde_json::Deserializer::from_str(fireworks_response_json);
1162 deserialize(jd).unwrap_or_else(|err| {
1163 panic!(
1164 "Deserialization error at {} ({}:{}): {}",
1165 err.path(),
1166 err.inner().line(),
1167 err.inner().column(),
1168 err
1169 );
1170 })
1171 };
1172
1173 let _novita_response: CompletionResponse = {
1174 let jd = &mut serde_json::Deserializer::from_str(novita_response_json);
1175 deserialize(jd).unwrap_or_else(|err| {
1176 panic!(
1177 "Deserialization error at {} ({}:{}): {}",
1178 err.path(),
1179 err.inner().line(),
1180 err.inner().column(),
1181 err
1182 );
1183 })
1184 };
1185 }
1186}