1use std::fmt::{self, Debug, Formatter};
4
5use crate::opaque::Envelope;
6use crate::redact;
7use crate::value::content::{self, Metadata, Part, Segment};
8use crate::value::tool_call::{self, Id};
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum ModelVisibility {
29 Visible,
31 Hidden,
33}
34
35#[derive(Clone, Debug)]
48pub enum Item {
49 User(User),
51 Assistant(Assistant),
53 ToolResult(ToolResult),
55 System(System),
57}
58
59impl Item {
60 #[must_use]
120 pub fn to_plain_text(&self) -> String {
121 match self {
122 Self::User(user) => {
123 content::join_blocks(user.parts().iter().map(|part| part.fields().text()))
124 }
125 Self::Assistant(assistant) => {
126 content::join_blocks(assistant.content().iter().filter_map(
127 |segment| match segment {
128 Segment::Text { text, .. } => Some(text.as_str()),
129 Segment::Thinking { .. } | Segment::ToolCall { .. } => None,
130 },
131 ))
132 }
133 Self::ToolResult(record) => record.result().to_plain_text(),
134 Self::System(system) => system.text().to_owned(),
135 }
136 }
137}
138
139#[derive(Clone, Debug)]
146pub struct User {
147 parts: Vec<Part>,
148 visibility: ModelVisibility,
149}
150
151impl User {
152 #[must_use]
154 pub const fn new(parts: Vec<Part>, visibility: ModelVisibility) -> Self {
155 Self { parts, visibility }
156 }
157
158 #[must_use]
160 pub fn parts(&self) -> &[Part] {
161 &self.parts
162 }
163
164 #[must_use]
166 pub const fn visibility(&self) -> ModelVisibility {
167 self.visibility
168 }
169}
170
171#[derive(Clone, Debug)]
212pub struct Assistant {
213 content: Vec<Segment>,
214 provider_data: Option<Vec<Envelope>>,
215 visibility: ModelVisibility,
216}
217
218impl Assistant {
219 #[must_use]
222 pub const fn new(content: Vec<Segment>, provider_data: Option<Vec<Envelope>>) -> Self {
223 Self {
224 content,
225 provider_data,
226 visibility: ModelVisibility::Visible,
227 }
228 }
229
230 #[must_use]
232 pub const fn with_visibility(mut self, visibility: ModelVisibility) -> Self {
233 self.visibility = visibility;
234 self
235 }
236
237 #[must_use]
239 pub fn content(&self) -> &[Segment] {
240 &self.content
241 }
242
243 #[must_use]
245 pub fn provider_data(&self) -> Option<&[Envelope]> {
246 self.provider_data.as_deref()
247 }
248
249 #[must_use]
251 pub const fn visibility(&self) -> ModelVisibility {
252 self.visibility
253 }
254}
255
256#[derive(Clone, Debug)]
287pub struct ToolResult {
288 call_id: Id,
289 tool_name: tool_call::Name,
290 result: tool_call::ToolResult,
291 visibility: ModelVisibility,
292 metadata: Option<Metadata>,
293}
294
295impl ToolResult {
296 #[must_use]
298 pub const fn new(
299 call_id: Id,
300 tool_name: tool_call::Name,
301 result: tool_call::ToolResult,
302 visibility: ModelVisibility,
303 metadata: Option<Metadata>,
304 ) -> Self {
305 Self {
306 call_id,
307 tool_name,
308 result,
309 visibility,
310 metadata,
311 }
312 }
313
314 #[must_use]
316 pub const fn call_id(&self) -> &Id {
317 &self.call_id
318 }
319
320 #[must_use]
322 pub const fn tool_name(&self) -> &tool_call::Name {
323 &self.tool_name
324 }
325
326 #[must_use]
328 pub const fn result(&self) -> &tool_call::ToolResult {
329 &self.result
330 }
331
332 #[must_use]
334 pub const fn visibility(&self) -> ModelVisibility {
335 self.visibility
336 }
337
338 #[must_use]
340 pub const fn metadata(&self) -> Option<&Metadata> {
341 self.metadata.as_ref()
342 }
343
344 #[must_use]
346 pub const fn is_business_error(&self) -> bool {
347 self.result.is_business_error()
348 }
349}
350
351#[derive(Clone)]
363pub struct System {
364 subtype: String,
365 text: String,
366 visibility: ModelVisibility,
367}
368
369impl Debug for System {
370 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
376 formatter
377 .debug_struct("System")
378 .field("subtype", &self.subtype)
379 .field("text", &redact::Bytes(self.text.len()))
380 .field("visibility", &self.visibility)
381 .finish()
382 }
383}
384
385impl System {
386 #[must_use]
388 pub const fn new(subtype: String, text: String, visibility: ModelVisibility) -> Self {
389 Self {
390 subtype,
391 text,
392 visibility,
393 }
394 }
395
396 #[must_use]
398 pub fn subtype(&self) -> &str {
399 &self.subtype
400 }
401
402 #[must_use]
404 pub fn text(&self) -> &str {
405 &self.text
406 }
407
408 #[must_use]
410 pub const fn visibility(&self) -> ModelVisibility {
411 self.visibility
412 }
413}
414
415#[cfg(feature = "serde")]
429mod serde_impl {
430 use std::fmt::{self, Formatter};
431
432 use serde_core::de::{
433 Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
434 VariantAccess, Visitor,
435 };
436 use serde_core::ser::{Serialize, SerializeStruct, Serializer};
437
438 use super::{Assistant, Item, ModelVisibility, System, ToolResult, User};
439 use crate::wire::{self, IdentifierSeed};
440
441 const VISIBILITY_NAME: &str = "ModelVisibility";
442 const VISIBILITY_VARIANTS: &[&str] = &["both", "user_only"];
443 const USER_FIELDS: &[&str] = &["parts", "visibility"];
444 const ASSISTANT_FIELDS: &[&str] = &["content", "provider_data", "visibility"];
445 const TOOL_RESULT_FIELDS: &[&str] =
446 &["call_id", "tool_name", "result", "visibility", "metadata"];
447 const SYSTEM_FIELDS: &[&str] = &["subtype", "text", "visibility"];
448 const ITEM_NAME: &str = "Item";
449 const ITEM_VARIANTS: &[&str] = &["user", "assistant", "tool_result", "system"];
450
451 impl Serialize for ModelVisibility {
454 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
455 where
456 S: Serializer,
457 {
458 let (index, tag) = match self {
459 Self::Visible => (0, "both"),
460 Self::Hidden => (1, "user_only"),
461 };
462 serializer.serialize_unit_variant(VISIBILITY_NAME, index, tag)
463 }
464 }
465
466 impl<'de> Deserialize<'de> for ModelVisibility {
467 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
468 where
469 D: Deserializer<'de>,
470 {
471 deserializer.deserialize_enum(VISIBILITY_NAME, VISIBILITY_VARIANTS, VisibilityVisitor)
472 }
473 }
474
475 struct VisibilityVisitor;
476
477 impl<'de> Visitor<'de> for VisibilityVisitor {
478 type Value = ModelVisibility;
479
480 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
481 formatter.write_str("a record visibility")
482 }
483
484 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
485 where
486 A: EnumAccess<'de>,
487 {
488 let (tag, variant) = data.variant_seed(IdentifierSeed(VISIBILITY_VARIANTS))?;
489 variant.unit_variant()?;
490 match tag.0.as_str() {
491 "both" => Ok(ModelVisibility::Visible),
492 "user_only" => Ok(ModelVisibility::Hidden),
493 unknown => Err(A::Error::unknown_variant(unknown, VISIBILITY_VARIANTS)),
494 }
495 }
496 }
497
498 impl Serialize for User {
501 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
502 where
503 S: Serializer,
504 {
505 let mut record = serializer.serialize_struct("User", 2)?;
506 record.serialize_field("parts", &self.parts)?;
507 record.serialize_field("visibility", &self.visibility)?;
508 record.end()
509 }
510 }
511
512 impl<'de> Deserialize<'de> for User {
513 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
514 where
515 D: Deserializer<'de>,
516 {
517 deserializer.deserialize_struct("User", USER_FIELDS, UserVisitor)
518 }
519 }
520
521 struct UserVisitor;
522
523 impl<'de> Visitor<'de> for UserVisitor {
524 type Value = User;
525
526 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
527 formatter.write_str("a user record")
528 }
529
530 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
531 where
532 A: SeqAccess<'de>,
533 {
534 let parts = wire::element(&mut sequence, 0)?;
535 let visibility = wire::element(&mut sequence, 1)?;
536 Ok(User::new(parts, visibility))
537 }
538
539 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
540 where
541 A: MapAccess<'de>,
542 {
543 let mut parts = None;
544 let mut visibility = None;
545 while let Some(field) = entries.next_key_seed(IdentifierSeed(USER_FIELDS))? {
546 match field.0.as_str() {
547 "parts" => wire::accept(&mut parts, entries.next_value()?, "parts")?,
548 "visibility" => {
549 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
550 }
551 unknown => return Err(A::Error::unknown_field(unknown, USER_FIELDS)),
552 }
553 }
554 Ok(User::new(
555 wire::require(parts, "parts")?,
556 wire::require(visibility, "visibility")?,
557 ))
558 }
559 }
560
561 impl Serialize for Assistant {
564 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
565 where
566 S: Serializer,
567 {
568 let mut record = serializer.serialize_struct("Assistant", 3)?;
569 record.serialize_field("content", &self.content)?;
570 record.serialize_field("provider_data", &self.provider_data)?;
571 record.serialize_field("visibility", &self.visibility)?;
572 record.end()
573 }
574 }
575
576 impl<'de> Deserialize<'de> for Assistant {
577 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
578 where
579 D: Deserializer<'de>,
580 {
581 deserializer.deserialize_struct("Assistant", ASSISTANT_FIELDS, AssistantVisitor)
582 }
583 }
584
585 struct AssistantVisitor;
586
587 impl<'de> Visitor<'de> for AssistantVisitor {
588 type Value = Assistant;
589
590 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
591 formatter.write_str("an assistant record")
592 }
593
594 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
595 where
596 A: SeqAccess<'de>,
597 {
598 let content = wire::element(&mut sequence, 0)?;
599 let provider_data = wire::element(&mut sequence, 1)?;
600 let visibility = wire::element(&mut sequence, 2)?;
601 Ok(Assistant::new(content, provider_data).with_visibility(visibility))
602 }
603
604 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
605 where
606 A: MapAccess<'de>,
607 {
608 let mut content = None;
609 let mut provider_data = None;
610 let mut visibility = None;
611 while let Some(field) = entries.next_key_seed(IdentifierSeed(ASSISTANT_FIELDS))? {
612 match field.0.as_str() {
613 "content" => wire::accept(&mut content, entries.next_value()?, "content")?,
614 "provider_data" => {
615 wire::accept(&mut provider_data, entries.next_value()?, "provider_data")?;
616 }
617 "visibility" => {
618 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
619 }
620 unknown => return Err(A::Error::unknown_field(unknown, ASSISTANT_FIELDS)),
621 }
622 }
623 Ok(Assistant::new(
624 wire::require(content, "content")?,
625 wire::require(provider_data, "provider_data")?,
626 )
627 .with_visibility(wire::require(visibility, "visibility")?))
628 }
629 }
630
631 impl Serialize for ToolResult {
634 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
635 where
636 S: Serializer,
637 {
638 let mut record = serializer.serialize_struct("ToolResult", 5)?;
639 record.serialize_field("call_id", &self.call_id)?;
640 record.serialize_field("tool_name", &self.tool_name)?;
641 record.serialize_field("result", &self.result)?;
642 record.serialize_field("visibility", &self.visibility)?;
643 record.serialize_field("metadata", &self.metadata)?;
644 record.end()
645 }
646 }
647
648 impl<'de> Deserialize<'de> for ToolResult {
649 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
650 where
651 D: Deserializer<'de>,
652 {
653 deserializer.deserialize_struct("ToolResult", TOOL_RESULT_FIELDS, ToolResultVisitor)
654 }
655 }
656
657 struct ToolResultVisitor;
658
659 impl<'de> Visitor<'de> for ToolResultVisitor {
660 type Value = ToolResult;
661
662 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
663 formatter.write_str("a tool-result record")
664 }
665
666 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
667 where
668 A: SeqAccess<'de>,
669 {
670 let call_id = wire::element(&mut sequence, 0)?;
671 let tool_name = wire::element(&mut sequence, 1)?;
672 let result = wire::element(&mut sequence, 2)?;
673 let visibility = wire::element(&mut sequence, 3)?;
674 let metadata = wire::element(&mut sequence, 4)?;
675 Ok(ToolResult::new(
676 call_id, tool_name, result, visibility, metadata,
677 ))
678 }
679
680 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
681 where
682 A: MapAccess<'de>,
683 {
684 let mut call_id = None;
685 let mut tool_name = None;
686 let mut result = None;
687 let mut visibility = None;
688 let mut metadata = None;
689 while let Some(field) = entries.next_key_seed(IdentifierSeed(TOOL_RESULT_FIELDS))? {
690 match field.0.as_str() {
691 "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
692 "tool_name" => {
693 wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
694 }
695 "result" => wire::accept(&mut result, entries.next_value()?, "result")?,
696 "visibility" => {
697 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
698 }
699 "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
700 unknown => return Err(A::Error::unknown_field(unknown, TOOL_RESULT_FIELDS)),
701 }
702 }
703 Ok(ToolResult::new(
704 wire::require(call_id, "call_id")?,
705 wire::require(tool_name, "tool_name")?,
706 wire::require(result, "result")?,
707 wire::require(visibility, "visibility")?,
708 wire::require(metadata, "metadata")?,
709 ))
710 }
711 }
712
713 impl Serialize for System {
716 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
717 where
718 S: Serializer,
719 {
720 let mut record = serializer.serialize_struct("System", 3)?;
721 record.serialize_field("subtype", &self.subtype)?;
722 record.serialize_field("text", &self.text)?;
723 record.serialize_field("visibility", &self.visibility)?;
724 record.end()
725 }
726 }
727
728 impl<'de> Deserialize<'de> for System {
729 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
730 where
731 D: Deserializer<'de>,
732 {
733 deserializer.deserialize_struct("System", SYSTEM_FIELDS, SystemVisitor)
734 }
735 }
736
737 struct SystemVisitor;
738
739 impl<'de> Visitor<'de> for SystemVisitor {
740 type Value = System;
741
742 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
743 formatter.write_str("a system record")
744 }
745
746 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
747 where
748 A: SeqAccess<'de>,
749 {
750 let subtype = wire::element(&mut sequence, 0)?;
751 let text = wire::element(&mut sequence, 1)?;
752 let visibility = wire::element(&mut sequence, 2)?;
753 Ok(System::new(subtype, text, visibility))
754 }
755
756 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
757 where
758 A: MapAccess<'de>,
759 {
760 let mut subtype = None;
761 let mut text = None;
762 let mut visibility = None;
763 while let Some(field) = entries.next_key_seed(IdentifierSeed(SYSTEM_FIELDS))? {
764 match field.0.as_str() {
765 "subtype" => wire::accept(&mut subtype, entries.next_value()?, "subtype")?,
766 "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
767 "visibility" => {
768 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
769 }
770 unknown => return Err(A::Error::unknown_field(unknown, SYSTEM_FIELDS)),
771 }
772 }
773 Ok(System::new(
774 wire::require(subtype, "subtype")?,
775 wire::require(text, "text")?,
776 wire::require(visibility, "visibility")?,
777 ))
778 }
779 }
780
781 impl Serialize for Item {
784 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
785 where
786 S: Serializer,
787 {
788 match self {
789 Self::User(record) => {
790 serializer.serialize_newtype_variant(ITEM_NAME, 0, "user", record)
791 }
792 Self::Assistant(record) => {
793 serializer.serialize_newtype_variant(ITEM_NAME, 1, "assistant", record)
794 }
795 Self::ToolResult(record) => {
796 serializer.serialize_newtype_variant(ITEM_NAME, 2, "tool_result", record)
797 }
798 Self::System(record) => {
799 serializer.serialize_newtype_variant(ITEM_NAME, 3, "system", record)
800 }
801 }
802 }
803 }
804
805 impl<'de> Deserialize<'de> for Item {
806 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
807 where
808 D: Deserializer<'de>,
809 {
810 deserializer.deserialize_enum(ITEM_NAME, ITEM_VARIANTS, ItemVisitor)
811 }
812 }
813
814 struct ItemVisitor;
815
816 impl<'de> Visitor<'de> for ItemVisitor {
817 type Value = Item;
818
819 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
820 formatter.write_str("a transcript record")
821 }
822
823 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
824 where
825 A: EnumAccess<'de>,
826 {
827 let (tag, variant) = data.variant_seed(IdentifierSeed(ITEM_VARIANTS))?;
828 match tag.0.as_str() {
829 "user" => variant.newtype_variant().map(Item::User),
830 "assistant" => variant.newtype_variant().map(Item::Assistant),
831 "tool_result" => variant.newtype_variant().map(Item::ToolResult),
832 "system" => variant.newtype_variant().map(Item::System),
833 unknown => Err(A::Error::unknown_variant(unknown, ITEM_VARIANTS)),
834 }
835 }
836 }
837}