1use std::{convert::Infallible, str::FromStr};
2
3use crate::OneOrMany;
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7use super::CompletionError;
8
9pub trait ConvertMessage: Sized + Send + Sync {
19 type Error: std::error::Error + Send;
20
21 fn convert_from_message(message: Message) -> Result<Vec<Self>, Self::Error>;
22}
23
24#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
35#[serde(tag = "role", rename_all = "lowercase")]
36pub enum Message {
37 User { content: OneOrMany<UserContent> },
39
40 Assistant {
42 id: Option<String>,
43 content: OneOrMany<AssistantContent>,
44 },
45}
46
47#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
51#[serde(tag = "type", rename_all = "lowercase")]
52pub enum UserContent {
53 Text(Text),
54 ToolResult(ToolResult),
55 Image(Image),
56 Audio(Audio),
57 Video(Video),
58 Document(Document),
59}
60
61#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
63#[serde(untagged)]
64pub enum AssistantContent {
65 Text(Text),
66 ToolCall(ToolCall),
67 Reasoning(Reasoning),
68 Image(Image),
69}
70
71#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
72#[serde(tag = "type", content = "content", rename_all = "snake_case")]
73#[non_exhaustive]
74pub enum ReasoningContent {
76 Text {
78 text: String,
79 #[serde(skip_serializing_if = "Option::is_none")]
80 signature: Option<String>,
81 },
82 Encrypted(String),
84 Redacted { data: String },
86 Summary(String),
88}
89
90#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
91#[non_exhaustive]
92pub struct Reasoning {
94 pub id: Option<String>,
96 pub content: Vec<ReasoningContent>,
98}
99
100impl Reasoning {
101 pub fn new(input: &str) -> Self {
103 Self::new_with_signature(input, None)
104 }
105
106 pub fn new_with_signature(input: &str, signature: Option<String>) -> Self {
108 Self {
109 id: None,
110 content: vec![ReasoningContent::Text {
111 text: input.to_string(),
112 signature,
113 }],
114 }
115 }
116
117 pub fn optional_id(mut self, id: Option<String>) -> Self {
119 self.id = id;
120 self
121 }
122
123 pub fn with_id(mut self, id: String) -> Self {
125 self.id = Some(id);
126 self
127 }
128
129 #[deprecated(note = "Use `new_with_signature` or content-level signature handling instead")]
130 pub fn with_signature(mut self, signature: Option<String>) -> Self {
131 if let Some(existing_signature) =
132 self.content.iter_mut().find_map(|content| match content {
133 ReasoningContent::Text { signature, .. } => Some(signature),
134 _ => None,
135 })
136 {
137 *existing_signature = signature;
138 }
139 self
140 }
141
142 pub fn multi(input: Vec<String>) -> Self {
144 Self {
145 id: None,
146 content: input
147 .into_iter()
148 .map(|text| ReasoningContent::Text {
149 text,
150 signature: None,
151 })
152 .collect(),
153 }
154 }
155
156 pub fn redacted(data: impl Into<String>) -> Self {
158 Self {
159 id: None,
160 content: vec![ReasoningContent::Redacted { data: data.into() }],
161 }
162 }
163
164 pub fn encrypted(data: impl Into<String>) -> Self {
166 Self {
167 id: None,
168 content: vec![ReasoningContent::Encrypted(data.into())],
169 }
170 }
171
172 pub fn summaries(input: Vec<String>) -> Self {
174 Self {
175 id: None,
176 content: input.into_iter().map(ReasoningContent::Summary).collect(),
177 }
178 }
179
180 pub fn display_text(&self) -> String {
182 self.content
183 .iter()
184 .filter_map(|content| match content {
185 ReasoningContent::Text { text, .. } => Some(text.as_str()),
186 ReasoningContent::Summary(summary) => Some(summary.as_str()),
187 ReasoningContent::Redacted { data } => Some(data.as_str()),
188 ReasoningContent::Encrypted(_) => None,
189 })
190 .collect::<Vec<_>>()
191 .join("\n")
192 }
193
194 pub fn first_text(&self) -> Option<&str> {
196 self.content.iter().find_map(|content| match content {
197 ReasoningContent::Text { text, .. } => Some(text.as_str()),
198 _ => None,
199 })
200 }
201
202 pub fn first_signature(&self) -> Option<&str> {
204 self.content.iter().find_map(|content| match content {
205 ReasoningContent::Text {
206 signature: Some(signature),
207 ..
208 } => Some(signature.as_str()),
209 _ => None,
210 })
211 }
212
213 pub fn encrypted_content(&self) -> Option<&str> {
215 self.content.iter().find_map(|content| match content {
216 ReasoningContent::Encrypted(data) => Some(data.as_str()),
217 _ => None,
218 })
219 }
220}
221
222#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
224pub struct ToolResult {
225 pub id: String,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 pub call_id: Option<String>,
228 pub content: OneOrMany<ToolResultContent>,
229}
230
231#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
233#[serde(tag = "type", rename_all = "lowercase")]
234pub enum ToolResultContent {
235 Text(Text),
236 Image(Image),
237}
238
239#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
241pub struct ToolCall {
242 pub id: String,
243 pub call_id: Option<String>,
244 pub function: ToolFunction,
245 pub signature: Option<String>,
255 pub additional_params: Option<serde_json::Value>,
257}
258
259impl ToolCall {
260 pub fn new(id: String, function: ToolFunction) -> Self {
261 Self {
262 id,
263 call_id: None,
264 function,
265 signature: None,
266 additional_params: None,
267 }
268 }
269
270 pub fn with_call_id(mut self, call_id: String) -> Self {
271 self.call_id = Some(call_id);
272 self
273 }
274
275 pub fn with_signature(mut self, signature: Option<String>) -> Self {
276 self.signature = signature;
277 self
278 }
279
280 pub fn with_additional_params(mut self, additional_params: Option<serde_json::Value>) -> Self {
281 self.additional_params = additional_params;
282 self
283 }
284}
285
286#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
288pub struct ToolFunction {
289 pub name: String,
290 pub arguments: serde_json::Value,
291}
292
293impl ToolFunction {
294 pub fn new(name: String, arguments: serde_json::Value) -> Self {
295 Self { name, arguments }
296 }
297}
298
299#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
305pub struct Text {
306 pub text: String,
307}
308
309impl Text {
310 pub fn text(&self) -> &str {
311 &self.text
312 }
313}
314
315impl std::fmt::Display for Text {
316 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317 let Self { text } = self;
318 write!(f, "{text}")
319 }
320}
321
322#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
324pub struct Image {
325 pub data: DocumentSourceKind,
326 #[serde(skip_serializing_if = "Option::is_none")]
327 pub media_type: Option<ImageMediaType>,
328 #[serde(skip_serializing_if = "Option::is_none")]
329 pub detail: Option<ImageDetail>,
330 #[serde(flatten, skip_serializing_if = "Option::is_none")]
331 pub additional_params: Option<serde_json::Value>,
332}
333
334impl Image {
335 pub fn try_into_url(self) -> Result<String, MessageError> {
336 match self.data {
337 DocumentSourceKind::Url(url) => Ok(url),
338 DocumentSourceKind::Base64(data) => {
339 let Some(media_type) = self.media_type else {
340 return Err(MessageError::ConversionError(
341 "A media type is required to create a valid base64-encoded image URL"
342 .to_string(),
343 ));
344 };
345
346 Ok(format!(
347 "data:image/{ty};base64,{data}",
348 ty = media_type.to_mime_type()
349 ))
350 }
351 unknown => Err(MessageError::ConversionError(format!(
352 "Tried to convert unknown type to a URL: {unknown:?}"
353 ))),
354 }
355 }
356}
357
358#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Default)]
360#[serde(tag = "type", content = "value", rename_all = "camelCase")]
361#[non_exhaustive]
362pub enum DocumentSourceKind {
363 Url(String),
365 Base64(String),
367 Raw(Vec<u8>),
369 String(String),
371 #[default]
372 Unknown,
374}
375
376impl DocumentSourceKind {
377 pub fn url(url: &str) -> Self {
378 Self::Url(url.to_string())
379 }
380
381 pub fn base64(base64_string: &str) -> Self {
382 Self::Base64(base64_string.to_string())
383 }
384
385 pub fn raw(bytes: impl Into<Vec<u8>>) -> Self {
386 Self::Raw(bytes.into())
387 }
388
389 pub fn string(input: &str) -> Self {
390 Self::String(input.into())
391 }
392
393 pub fn unknown() -> Self {
394 Self::Unknown
395 }
396
397 pub fn try_into_inner(self) -> Option<String> {
398 match self {
399 Self::Url(s) | Self::Base64(s) => Some(s),
400 _ => None,
401 }
402 }
403}
404
405impl std::fmt::Display for DocumentSourceKind {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 match self {
408 Self::Url(string) => write!(f, "{string}"),
409 Self::Base64(string) => write!(f, "{string}"),
410 Self::String(string) => write!(f, "{string}"),
411 Self::Raw(_) => write!(f, "<binary data>"),
412 Self::Unknown => write!(f, "<unknown>"),
413 }
414 }
415}
416
417#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
419pub struct Audio {
420 pub data: DocumentSourceKind,
421 #[serde(skip_serializing_if = "Option::is_none")]
422 pub media_type: Option<AudioMediaType>,
423 #[serde(flatten, skip_serializing_if = "Option::is_none")]
424 pub additional_params: Option<serde_json::Value>,
425}
426
427#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
429pub struct Video {
430 pub data: DocumentSourceKind,
431 #[serde(skip_serializing_if = "Option::is_none")]
432 pub media_type: Option<VideoMediaType>,
433 #[serde(flatten, skip_serializing_if = "Option::is_none")]
434 pub additional_params: Option<serde_json::Value>,
435}
436
437#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
439pub struct Document {
440 pub data: DocumentSourceKind,
441 #[serde(skip_serializing_if = "Option::is_none")]
442 pub media_type: Option<DocumentMediaType>,
443 #[serde(flatten, skip_serializing_if = "Option::is_none")]
444 pub additional_params: Option<serde_json::Value>,
445}
446
447#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
449#[serde(rename_all = "lowercase")]
450pub enum ContentFormat {
451 #[default]
452 Base64,
453 String,
454 Url,
455}
456
457#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
459pub enum MediaType {
460 Image(ImageMediaType),
461 Audio(AudioMediaType),
462 Document(DocumentMediaType),
463 Video(VideoMediaType),
464}
465
466#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
469#[serde(rename_all = "lowercase")]
470pub enum ImageMediaType {
471 JPEG,
472 PNG,
473 GIF,
474 WEBP,
475 HEIC,
476 HEIF,
477 SVG,
478}
479
480#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
484#[serde(rename_all = "lowercase")]
485pub enum DocumentMediaType {
486 PDF,
487 TXT,
488 RTF,
489 HTML,
490 CSS,
491 MARKDOWN,
492 CSV,
493 XML,
494 Javascript,
495 Python,
496}
497
498impl DocumentMediaType {
499 pub fn is_code(&self) -> bool {
500 matches!(self, Self::Javascript | Self::Python)
501 }
502}
503
504#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
507#[serde(rename_all = "lowercase")]
508pub enum AudioMediaType {
509 WAV,
510 MP3,
511 AIFF,
512 AAC,
513 OGG,
514 FLAC,
515}
516
517#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
520#[serde(rename_all = "lowercase")]
521pub enum VideoMediaType {
522 AVI,
523 MP4,
524 MPEG,
525}
526
527#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
529#[serde(rename_all = "lowercase")]
530pub enum ImageDetail {
531 Low,
532 High,
533 #[default]
534 Auto,
535}
536
537impl Message {
542 pub(crate) fn rag_text(&self) -> Option<String> {
545 match self {
546 Message::User { content } => {
547 for item in content.iter() {
548 if let UserContent::Text(Text { text }) = item {
549 return Some(text.clone());
550 }
551 }
552 None
553 }
554 _ => None,
555 }
556 }
557
558 pub fn user(text: impl Into<String>) -> Self {
560 Message::User {
561 content: OneOrMany::one(UserContent::text(text)),
562 }
563 }
564
565 pub fn assistant(text: impl Into<String>) -> Self {
567 Message::Assistant {
568 id: None,
569 content: OneOrMany::one(AssistantContent::text(text)),
570 }
571 }
572
573 pub fn assistant_with_id(id: String, text: impl Into<String>) -> Self {
575 Message::Assistant {
576 id: Some(id),
577 content: OneOrMany::one(AssistantContent::text(text)),
578 }
579 }
580
581 pub fn tool_result(id: impl Into<String>, content: impl Into<String>) -> Self {
583 Message::User {
584 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
585 id: id.into(),
586 call_id: None,
587 content: OneOrMany::one(ToolResultContent::text(content)),
588 })),
589 }
590 }
591
592 pub fn tool_result_with_call_id(
593 id: impl Into<String>,
594 call_id: Option<String>,
595 content: impl Into<String>,
596 ) -> Self {
597 Message::User {
598 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
599 id: id.into(),
600 call_id,
601 content: OneOrMany::one(ToolResultContent::text(content)),
602 })),
603 }
604 }
605}
606
607impl UserContent {
608 pub fn text(text: impl Into<String>) -> Self {
610 UserContent::Text(text.into().into())
611 }
612
613 pub fn image_base64(
615 data: impl Into<String>,
616 media_type: Option<ImageMediaType>,
617 detail: Option<ImageDetail>,
618 ) -> Self {
619 UserContent::Image(Image {
620 data: DocumentSourceKind::Base64(data.into()),
621 media_type,
622 detail,
623 additional_params: None,
624 })
625 }
626
627 pub fn image_raw(
629 data: impl Into<Vec<u8>>,
630 media_type: Option<ImageMediaType>,
631 detail: Option<ImageDetail>,
632 ) -> Self {
633 UserContent::Image(Image {
634 data: DocumentSourceKind::Raw(data.into()),
635 media_type,
636 detail,
637 ..Default::default()
638 })
639 }
640
641 pub fn image_url(
643 url: impl Into<String>,
644 media_type: Option<ImageMediaType>,
645 detail: Option<ImageDetail>,
646 ) -> Self {
647 UserContent::Image(Image {
648 data: DocumentSourceKind::Url(url.into()),
649 media_type,
650 detail,
651 additional_params: None,
652 })
653 }
654
655 pub fn audio(data: impl Into<String>, media_type: Option<AudioMediaType>) -> Self {
657 UserContent::Audio(Audio {
658 data: DocumentSourceKind::Base64(data.into()),
659 media_type,
660 additional_params: None,
661 })
662 }
663
664 pub fn audio_raw(data: impl Into<Vec<u8>>, media_type: Option<AudioMediaType>) -> Self {
666 UserContent::Audio(Audio {
667 data: DocumentSourceKind::Raw(data.into()),
668 media_type,
669 ..Default::default()
670 })
671 }
672
673 pub fn audio_url(url: impl Into<String>, media_type: Option<AudioMediaType>) -> Self {
675 UserContent::Audio(Audio {
676 data: DocumentSourceKind::Url(url.into()),
677 media_type,
678 ..Default::default()
679 })
680 }
681
682 pub fn document(data: impl Into<String>, media_type: Option<DocumentMediaType>) -> Self {
685 let data: String = data.into();
686 UserContent::Document(Document {
687 data: DocumentSourceKind::string(&data),
688 media_type,
689 additional_params: None,
690 })
691 }
692
693 pub fn document_raw(data: impl Into<Vec<u8>>, media_type: Option<DocumentMediaType>) -> Self {
695 UserContent::Document(Document {
696 data: DocumentSourceKind::Raw(data.into()),
697 media_type,
698 ..Default::default()
699 })
700 }
701
702 pub fn document_url(url: impl Into<String>, media_type: Option<DocumentMediaType>) -> Self {
704 UserContent::Document(Document {
705 data: DocumentSourceKind::Url(url.into()),
706 media_type,
707 ..Default::default()
708 })
709 }
710
711 pub fn tool_result(id: impl Into<String>, content: OneOrMany<ToolResultContent>) -> Self {
713 UserContent::ToolResult(ToolResult {
714 id: id.into(),
715 call_id: None,
716 content,
717 })
718 }
719
720 pub fn tool_result_with_call_id(
722 id: impl Into<String>,
723 call_id: String,
724 content: OneOrMany<ToolResultContent>,
725 ) -> Self {
726 UserContent::ToolResult(ToolResult {
727 id: id.into(),
728 call_id: Some(call_id),
729 content,
730 })
731 }
732}
733
734impl AssistantContent {
735 pub fn text(text: impl Into<String>) -> Self {
737 AssistantContent::Text(text.into().into())
738 }
739
740 pub fn image_base64(
742 data: impl Into<String>,
743 media_type: Option<ImageMediaType>,
744 detail: Option<ImageDetail>,
745 ) -> Self {
746 AssistantContent::Image(Image {
747 data: DocumentSourceKind::Base64(data.into()),
748 media_type,
749 detail,
750 additional_params: None,
751 })
752 }
753
754 pub fn tool_call(
756 id: impl Into<String>,
757 name: impl Into<String>,
758 arguments: serde_json::Value,
759 ) -> Self {
760 AssistantContent::ToolCall(ToolCall::new(
761 id.into(),
762 ToolFunction {
763 name: name.into(),
764 arguments,
765 },
766 ))
767 }
768
769 pub fn tool_call_with_call_id(
770 id: impl Into<String>,
771 call_id: String,
772 name: impl Into<String>,
773 arguments: serde_json::Value,
774 ) -> Self {
775 AssistantContent::ToolCall(
776 ToolCall::new(
777 id.into(),
778 ToolFunction {
779 name: name.into(),
780 arguments,
781 },
782 )
783 .with_call_id(call_id),
784 )
785 }
786
787 pub fn reasoning(reasoning: impl AsRef<str>) -> Self {
788 AssistantContent::Reasoning(Reasoning::new(reasoning.as_ref()))
789 }
790}
791
792impl ToolResultContent {
793 pub fn text(text: impl Into<String>) -> Self {
795 ToolResultContent::Text(text.into().into())
796 }
797
798 pub fn image_base64(
800 data: impl Into<String>,
801 media_type: Option<ImageMediaType>,
802 detail: Option<ImageDetail>,
803 ) -> Self {
804 ToolResultContent::Image(Image {
805 data: DocumentSourceKind::Base64(data.into()),
806 media_type,
807 detail,
808 additional_params: None,
809 })
810 }
811
812 pub fn image_raw(
814 data: impl Into<Vec<u8>>,
815 media_type: Option<ImageMediaType>,
816 detail: Option<ImageDetail>,
817 ) -> Self {
818 ToolResultContent::Image(Image {
819 data: DocumentSourceKind::Raw(data.into()),
820 media_type,
821 detail,
822 ..Default::default()
823 })
824 }
825
826 pub fn image_url(
828 url: impl Into<String>,
829 media_type: Option<ImageMediaType>,
830 detail: Option<ImageDetail>,
831 ) -> Self {
832 ToolResultContent::Image(Image {
833 data: DocumentSourceKind::Url(url.into()),
834 media_type,
835 detail,
836 additional_params: None,
837 })
838 }
839
840 pub fn from_tool_output(output: impl Into<String>) -> OneOrMany<ToolResultContent> {
849 let output_str = output.into();
850
851 if let Ok(json) = serde_json::from_str::<serde_json::Value>(&output_str) {
852 if json.get("response").is_some() || json.get("parts").is_some() {
853 let mut results: Vec<ToolResultContent> = Vec::new();
854
855 if let Some(response) = json.get("response") {
856 results.push(ToolResultContent::Text(Text {
857 text: response.to_string(),
858 }));
859 }
860
861 if let Some(parts) = json.get("parts").and_then(|p| p.as_array()) {
862 for part in parts {
863 let is_image = part
864 .get("type")
865 .and_then(|t| t.as_str())
866 .is_some_and(|t| t == "image");
867
868 if !is_image {
869 continue;
870 }
871
872 if let (Some(data), Some(mime_type)) = (
873 part.get("data").and_then(|v| v.as_str()),
874 part.get("mimeType").and_then(|v| v.as_str()),
875 ) {
876 let data_kind =
877 if data.starts_with("http://") || data.starts_with("https://") {
878 DocumentSourceKind::Url(data.to_string())
879 } else {
880 DocumentSourceKind::Base64(data.to_string())
881 };
882
883 results.push(ToolResultContent::Image(Image {
884 data: data_kind,
885 media_type: ImageMediaType::from_mime_type(mime_type),
886 detail: None,
887 additional_params: None,
888 }));
889 }
890 }
891 }
892
893 if !results.is_empty() {
894 return OneOrMany::many(results).unwrap_or_else(|_| {
895 OneOrMany::one(ToolResultContent::Text(output_str.into()))
896 });
897 }
898 }
899
900 let is_image = json
901 .get("type")
902 .and_then(|v| v.as_str())
903 .is_some_and(|t| t == "image");
904
905 if is_image
906 && let (Some(data), Some(mime_type)) = (
907 json.get("data").and_then(|v| v.as_str()),
908 json.get("mimeType").and_then(|v| v.as_str()),
909 )
910 {
911 let data_kind = if data.starts_with("http://") || data.starts_with("https://") {
912 DocumentSourceKind::Url(data.to_string())
913 } else {
914 DocumentSourceKind::Base64(data.to_string())
915 };
916
917 return OneOrMany::one(ToolResultContent::Image(Image {
918 data: data_kind,
919 media_type: ImageMediaType::from_mime_type(mime_type),
920 detail: None,
921 additional_params: None,
922 }));
923 }
924 }
925
926 OneOrMany::one(ToolResultContent::Text(output_str.into()))
927 }
928}
929
930pub trait MimeType {
932 fn from_mime_type(mime_type: &str) -> Option<Self>
933 where
934 Self: Sized;
935 fn to_mime_type(&self) -> &'static str;
936}
937
938impl MimeType for MediaType {
939 fn from_mime_type(mime_type: &str) -> Option<Self> {
940 ImageMediaType::from_mime_type(mime_type)
941 .map(MediaType::Image)
942 .or_else(|| {
943 DocumentMediaType::from_mime_type(mime_type)
944 .map(MediaType::Document)
945 .or_else(|| {
946 AudioMediaType::from_mime_type(mime_type)
947 .map(MediaType::Audio)
948 .or_else(|| {
949 VideoMediaType::from_mime_type(mime_type).map(MediaType::Video)
950 })
951 })
952 })
953 }
954
955 fn to_mime_type(&self) -> &'static str {
956 match self {
957 MediaType::Image(media_type) => media_type.to_mime_type(),
958 MediaType::Audio(media_type) => media_type.to_mime_type(),
959 MediaType::Document(media_type) => media_type.to_mime_type(),
960 MediaType::Video(media_type) => media_type.to_mime_type(),
961 }
962 }
963}
964
965impl MimeType for ImageMediaType {
966 fn from_mime_type(mime_type: &str) -> Option<Self> {
967 match mime_type {
968 "image/jpeg" => Some(ImageMediaType::JPEG),
969 "image/png" => Some(ImageMediaType::PNG),
970 "image/gif" => Some(ImageMediaType::GIF),
971 "image/webp" => Some(ImageMediaType::WEBP),
972 "image/heic" => Some(ImageMediaType::HEIC),
973 "image/heif" => Some(ImageMediaType::HEIF),
974 "image/svg+xml" => Some(ImageMediaType::SVG),
975 _ => None,
976 }
977 }
978
979 fn to_mime_type(&self) -> &'static str {
980 match self {
981 ImageMediaType::JPEG => "image/jpeg",
982 ImageMediaType::PNG => "image/png",
983 ImageMediaType::GIF => "image/gif",
984 ImageMediaType::WEBP => "image/webp",
985 ImageMediaType::HEIC => "image/heic",
986 ImageMediaType::HEIF => "image/heif",
987 ImageMediaType::SVG => "image/svg+xml",
988 }
989 }
990}
991
992impl MimeType for DocumentMediaType {
993 fn from_mime_type(mime_type: &str) -> Option<Self> {
994 match mime_type {
995 "application/pdf" => Some(DocumentMediaType::PDF),
996 "text/plain" => Some(DocumentMediaType::TXT),
997 "text/rtf" => Some(DocumentMediaType::RTF),
998 "text/html" => Some(DocumentMediaType::HTML),
999 "text/css" => Some(DocumentMediaType::CSS),
1000 "text/md" | "text/markdown" => Some(DocumentMediaType::MARKDOWN),
1001 "text/csv" => Some(DocumentMediaType::CSV),
1002 "text/xml" => Some(DocumentMediaType::XML),
1003 "application/x-javascript" | "text/x-javascript" => Some(DocumentMediaType::Javascript),
1004 "application/x-python" | "text/x-python" => Some(DocumentMediaType::Python),
1005 _ => None,
1006 }
1007 }
1008
1009 fn to_mime_type(&self) -> &'static str {
1010 match self {
1011 DocumentMediaType::PDF => "application/pdf",
1012 DocumentMediaType::TXT => "text/plain",
1013 DocumentMediaType::RTF => "text/rtf",
1014 DocumentMediaType::HTML => "text/html",
1015 DocumentMediaType::CSS => "text/css",
1016 DocumentMediaType::MARKDOWN => "text/markdown",
1017 DocumentMediaType::CSV => "text/csv",
1018 DocumentMediaType::XML => "text/xml",
1019 DocumentMediaType::Javascript => "application/x-javascript",
1020 DocumentMediaType::Python => "application/x-python",
1021 }
1022 }
1023}
1024
1025impl MimeType for AudioMediaType {
1026 fn from_mime_type(mime_type: &str) -> Option<Self> {
1027 match mime_type {
1028 "audio/wav" => Some(AudioMediaType::WAV),
1029 "audio/mp3" => Some(AudioMediaType::MP3),
1030 "audio/aiff" => Some(AudioMediaType::AIFF),
1031 "audio/aac" => Some(AudioMediaType::AAC),
1032 "audio/ogg" => Some(AudioMediaType::OGG),
1033 "audio/flac" => Some(AudioMediaType::FLAC),
1034 _ => None,
1035 }
1036 }
1037
1038 fn to_mime_type(&self) -> &'static str {
1039 match self {
1040 AudioMediaType::WAV => "audio/wav",
1041 AudioMediaType::MP3 => "audio/mp3",
1042 AudioMediaType::AIFF => "audio/aiff",
1043 AudioMediaType::AAC => "audio/aac",
1044 AudioMediaType::OGG => "audio/ogg",
1045 AudioMediaType::FLAC => "audio/flac",
1046 }
1047 }
1048}
1049
1050impl MimeType for VideoMediaType {
1051 fn from_mime_type(mime_type: &str) -> Option<Self>
1052 where
1053 Self: Sized,
1054 {
1055 match mime_type {
1056 "video/avi" => Some(VideoMediaType::AVI),
1057 "video/mp4" => Some(VideoMediaType::MP4),
1058 "video/mpeg" => Some(VideoMediaType::MPEG),
1059 &_ => None,
1060 }
1061 }
1062
1063 fn to_mime_type(&self) -> &'static str {
1064 match self {
1065 VideoMediaType::AVI => "video/avi",
1066 VideoMediaType::MP4 => "video/mp4",
1067 VideoMediaType::MPEG => "video/mpeg",
1068 }
1069 }
1070}
1071
1072impl std::str::FromStr for ImageDetail {
1073 type Err = ();
1074
1075 fn from_str(s: &str) -> Result<Self, Self::Err> {
1076 match s.to_lowercase().as_str() {
1077 "low" => Ok(ImageDetail::Low),
1078 "high" => Ok(ImageDetail::High),
1079 "auto" => Ok(ImageDetail::Auto),
1080 _ => Err(()),
1081 }
1082 }
1083}
1084
1085impl From<String> for Text {
1090 fn from(text: String) -> Self {
1091 Text { text }
1092 }
1093}
1094
1095impl From<&String> for Text {
1096 fn from(text: &String) -> Self {
1097 text.to_owned().into()
1098 }
1099}
1100
1101impl From<&str> for Text {
1102 fn from(text: &str) -> Self {
1103 text.to_owned().into()
1104 }
1105}
1106
1107impl FromStr for Text {
1108 type Err = Infallible;
1109
1110 fn from_str(s: &str) -> Result<Self, Self::Err> {
1111 Ok(s.into())
1112 }
1113}
1114
1115impl From<String> for Message {
1116 fn from(text: String) -> Self {
1117 Message::User {
1118 content: OneOrMany::one(UserContent::Text(text.into())),
1119 }
1120 }
1121}
1122
1123impl From<&str> for Message {
1124 fn from(text: &str) -> Self {
1125 Message::User {
1126 content: OneOrMany::one(UserContent::Text(text.into())),
1127 }
1128 }
1129}
1130
1131impl From<&String> for Message {
1132 fn from(text: &String) -> Self {
1133 Message::User {
1134 content: OneOrMany::one(UserContent::Text(text.into())),
1135 }
1136 }
1137}
1138
1139impl From<Text> for Message {
1140 fn from(text: Text) -> Self {
1141 Message::User {
1142 content: OneOrMany::one(UserContent::Text(text)),
1143 }
1144 }
1145}
1146
1147impl From<Image> for Message {
1148 fn from(image: Image) -> Self {
1149 Message::User {
1150 content: OneOrMany::one(UserContent::Image(image)),
1151 }
1152 }
1153}
1154
1155impl From<Audio> for Message {
1156 fn from(audio: Audio) -> Self {
1157 Message::User {
1158 content: OneOrMany::one(UserContent::Audio(audio)),
1159 }
1160 }
1161}
1162
1163impl From<Document> for Message {
1164 fn from(document: Document) -> Self {
1165 Message::User {
1166 content: OneOrMany::one(UserContent::Document(document)),
1167 }
1168 }
1169}
1170
1171impl From<String> for ToolResultContent {
1172 fn from(text: String) -> Self {
1173 ToolResultContent::text(text)
1174 }
1175}
1176
1177impl From<String> for AssistantContent {
1178 fn from(text: String) -> Self {
1179 AssistantContent::text(text)
1180 }
1181}
1182
1183impl From<String> for UserContent {
1184 fn from(text: String) -> Self {
1185 UserContent::text(text)
1186 }
1187}
1188
1189impl From<AssistantContent> for Message {
1190 fn from(content: AssistantContent) -> Self {
1191 Message::Assistant {
1192 id: None,
1193 content: OneOrMany::one(content),
1194 }
1195 }
1196}
1197
1198impl From<UserContent> for Message {
1199 fn from(content: UserContent) -> Self {
1200 Message::User {
1201 content: OneOrMany::one(content),
1202 }
1203 }
1204}
1205
1206impl From<OneOrMany<AssistantContent>> for Message {
1207 fn from(content: OneOrMany<AssistantContent>) -> Self {
1208 Message::Assistant { id: None, content }
1209 }
1210}
1211
1212impl From<OneOrMany<UserContent>> for Message {
1213 fn from(content: OneOrMany<UserContent>) -> Self {
1214 Message::User { content }
1215 }
1216}
1217
1218impl From<ToolCall> for Message {
1219 fn from(tool_call: ToolCall) -> Self {
1220 Message::Assistant {
1221 id: None,
1222 content: OneOrMany::one(AssistantContent::ToolCall(tool_call)),
1223 }
1224 }
1225}
1226
1227impl From<ToolResult> for Message {
1228 fn from(tool_result: ToolResult) -> Self {
1229 Message::User {
1230 content: OneOrMany::one(UserContent::ToolResult(tool_result)),
1231 }
1232 }
1233}
1234
1235impl From<ToolResultContent> for Message {
1236 fn from(tool_result_content: ToolResultContent) -> Self {
1237 Message::User {
1238 content: OneOrMany::one(UserContent::ToolResult(ToolResult {
1239 id: String::new(),
1240 call_id: None,
1241 content: OneOrMany::one(tool_result_content),
1242 })),
1243 }
1244 }
1245}
1246
1247#[derive(Default, Clone, Debug, Deserialize, Serialize, PartialEq)]
1248#[serde(rename_all = "snake_case")]
1249pub enum ToolChoice {
1250 #[default]
1251 Auto,
1252 None,
1253 Required,
1254 Specific {
1255 function_names: Vec<String>,
1256 },
1257}
1258
1259#[derive(Debug, Error)]
1265pub enum MessageError {
1266 #[error("Message conversion error: {0}")]
1267 ConversionError(String),
1268}
1269
1270impl From<MessageError> for CompletionError {
1271 fn from(error: MessageError) -> Self {
1272 CompletionError::RequestError(error.into())
1273 }
1274}
1275
1276#[cfg(test)]
1277mod tests {
1278 use super::{Reasoning, ReasoningContent};
1279
1280 #[test]
1281 fn reasoning_constructors_and_accessors_work() {
1282 let single = Reasoning::new("think");
1283 assert_eq!(single.first_text(), Some("think"));
1284 assert_eq!(single.first_signature(), None);
1285
1286 let signed = Reasoning::new_with_signature("signed", Some("sig-1".to_string()));
1287 assert_eq!(signed.first_text(), Some("signed"));
1288 assert_eq!(signed.first_signature(), Some("sig-1"));
1289
1290 let multi = Reasoning::multi(vec!["a".to_string(), "b".to_string()]);
1291 assert_eq!(multi.display_text(), "a\nb");
1292 assert_eq!(multi.first_text(), Some("a"));
1293
1294 let redacted = Reasoning::redacted("redacted-value");
1295 assert_eq!(redacted.display_text(), "redacted-value");
1296 assert_eq!(redacted.first_text(), None);
1297
1298 let encrypted = Reasoning::encrypted("enc");
1299 assert_eq!(encrypted.encrypted_content(), Some("enc"));
1300 assert_eq!(encrypted.display_text(), "");
1301
1302 let summaries = Reasoning::summaries(vec!["s1".to_string(), "s2".to_string()]);
1303 assert_eq!(summaries.display_text(), "s1\ns2");
1304 assert_eq!(summaries.encrypted_content(), None);
1305 }
1306
1307 #[test]
1308 fn reasoning_content_serde_roundtrip() {
1309 let variants = vec![
1310 ReasoningContent::Text {
1311 text: "plain".to_string(),
1312 signature: Some("sig".to_string()),
1313 },
1314 ReasoningContent::Encrypted("opaque".to_string()),
1315 ReasoningContent::Redacted {
1316 data: "redacted".to_string(),
1317 },
1318 ReasoningContent::Summary("summary".to_string()),
1319 ];
1320
1321 for variant in variants {
1322 let json = serde_json::to_string(&variant).expect("serialize");
1323 let roundtrip: ReasoningContent = serde_json::from_str(&json).expect("deserialize");
1324 assert_eq!(roundtrip, variant);
1325 }
1326 }
1327}