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 wire::end(&mut sequence, 2)?;
537 Ok(User::new(parts, visibility))
538 }
539
540 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
541 where
542 A: MapAccess<'de>,
543 {
544 let mut parts = None;
545 let mut visibility = None;
546 while let Some(field) = entries.next_key_seed(IdentifierSeed(USER_FIELDS))? {
547 match field.0.as_str() {
548 "parts" => wire::accept(&mut parts, entries.next_value()?, "parts")?,
549 "visibility" => {
550 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
551 }
552 unknown => return Err(A::Error::unknown_field(unknown, USER_FIELDS)),
553 }
554 }
555 Ok(User::new(
556 wire::require(parts, "parts")?,
557 wire::require(visibility, "visibility")?,
558 ))
559 }
560 }
561
562 impl Serialize for Assistant {
565 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
566 where
567 S: Serializer,
568 {
569 let mut record = serializer.serialize_struct("Assistant", 3)?;
570 record.serialize_field("content", &self.content)?;
571 record.serialize_field("provider_data", &self.provider_data)?;
572 record.serialize_field("visibility", &self.visibility)?;
573 record.end()
574 }
575 }
576
577 impl<'de> Deserialize<'de> for Assistant {
578 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
579 where
580 D: Deserializer<'de>,
581 {
582 deserializer.deserialize_struct("Assistant", ASSISTANT_FIELDS, AssistantVisitor)
583 }
584 }
585
586 struct AssistantVisitor;
587
588 impl<'de> Visitor<'de> for AssistantVisitor {
589 type Value = Assistant;
590
591 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
592 formatter.write_str("an assistant record")
593 }
594
595 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
596 where
597 A: SeqAccess<'de>,
598 {
599 let content = wire::element(&mut sequence, 0)?;
600 let provider_data = wire::element(&mut sequence, 1)?;
601 let visibility = wire::element(&mut sequence, 2)?;
602 wire::end(&mut sequence, 3)?;
603 Ok(Assistant::new(content, provider_data).with_visibility(visibility))
604 }
605
606 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
607 where
608 A: MapAccess<'de>,
609 {
610 let mut content = None;
611 let mut provider_data = None;
612 let mut visibility = None;
613 while let Some(field) = entries.next_key_seed(IdentifierSeed(ASSISTANT_FIELDS))? {
614 match field.0.as_str() {
615 "content" => wire::accept(&mut content, entries.next_value()?, "content")?,
616 "provider_data" => {
617 wire::accept(&mut provider_data, entries.next_value()?, "provider_data")?;
618 }
619 "visibility" => {
620 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
621 }
622 unknown => return Err(A::Error::unknown_field(unknown, ASSISTANT_FIELDS)),
623 }
624 }
625 Ok(Assistant::new(
626 wire::require(content, "content")?,
627 wire::require(provider_data, "provider_data")?,
628 )
629 .with_visibility(wire::require(visibility, "visibility")?))
630 }
631 }
632
633 impl Serialize for ToolResult {
636 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
637 where
638 S: Serializer,
639 {
640 let mut record = serializer.serialize_struct("ToolResult", 5)?;
641 record.serialize_field("call_id", &self.call_id)?;
642 record.serialize_field("tool_name", &self.tool_name)?;
643 record.serialize_field("result", &self.result)?;
644 record.serialize_field("visibility", &self.visibility)?;
645 record.serialize_field("metadata", &self.metadata)?;
646 record.end()
647 }
648 }
649
650 impl<'de> Deserialize<'de> for ToolResult {
651 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
652 where
653 D: Deserializer<'de>,
654 {
655 deserializer.deserialize_struct("ToolResult", TOOL_RESULT_FIELDS, ToolResultVisitor)
656 }
657 }
658
659 struct ToolResultVisitor;
660
661 impl<'de> Visitor<'de> for ToolResultVisitor {
662 type Value = ToolResult;
663
664 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
665 formatter.write_str("a tool-result record")
666 }
667
668 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
669 where
670 A: SeqAccess<'de>,
671 {
672 let call_id = wire::element(&mut sequence, 0)?;
673 let tool_name = wire::element(&mut sequence, 1)?;
674 let result = wire::element(&mut sequence, 2)?;
675 let visibility = wire::element(&mut sequence, 3)?;
676 let metadata = wire::element(&mut sequence, 4)?;
677 wire::end(&mut sequence, 5)?;
678 Ok(ToolResult::new(
679 call_id, tool_name, result, visibility, metadata,
680 ))
681 }
682
683 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
684 where
685 A: MapAccess<'de>,
686 {
687 let mut call_id = None;
688 let mut tool_name = None;
689 let mut result = None;
690 let mut visibility = None;
691 let mut metadata = None;
692 while let Some(field) = entries.next_key_seed(IdentifierSeed(TOOL_RESULT_FIELDS))? {
693 match field.0.as_str() {
694 "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
695 "tool_name" => {
696 wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
697 }
698 "result" => wire::accept(&mut result, entries.next_value()?, "result")?,
699 "visibility" => {
700 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
701 }
702 "metadata" => wire::accept(&mut metadata, entries.next_value()?, "metadata")?,
703 unknown => return Err(A::Error::unknown_field(unknown, TOOL_RESULT_FIELDS)),
704 }
705 }
706 Ok(ToolResult::new(
707 wire::require(call_id, "call_id")?,
708 wire::require(tool_name, "tool_name")?,
709 wire::require(result, "result")?,
710 wire::require(visibility, "visibility")?,
711 wire::require(metadata, "metadata")?,
712 ))
713 }
714 }
715
716 impl Serialize for System {
719 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
720 where
721 S: Serializer,
722 {
723 let mut record = serializer.serialize_struct("System", 3)?;
724 record.serialize_field("subtype", &self.subtype)?;
725 record.serialize_field("text", &self.text)?;
726 record.serialize_field("visibility", &self.visibility)?;
727 record.end()
728 }
729 }
730
731 impl<'de> Deserialize<'de> for System {
732 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
733 where
734 D: Deserializer<'de>,
735 {
736 deserializer.deserialize_struct("System", SYSTEM_FIELDS, SystemVisitor)
737 }
738 }
739
740 struct SystemVisitor;
741
742 impl<'de> Visitor<'de> for SystemVisitor {
743 type Value = System;
744
745 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
746 formatter.write_str("a system record")
747 }
748
749 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
750 where
751 A: SeqAccess<'de>,
752 {
753 let subtype = wire::element(&mut sequence, 0)?;
754 let text = wire::element(&mut sequence, 1)?;
755 let visibility = wire::element(&mut sequence, 2)?;
756 wire::end(&mut sequence, 3)?;
757 Ok(System::new(subtype, text, visibility))
758 }
759
760 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
761 where
762 A: MapAccess<'de>,
763 {
764 let mut subtype = None;
765 let mut text = None;
766 let mut visibility = None;
767 while let Some(field) = entries.next_key_seed(IdentifierSeed(SYSTEM_FIELDS))? {
768 match field.0.as_str() {
769 "subtype" => wire::accept(&mut subtype, entries.next_value()?, "subtype")?,
770 "text" => wire::accept(&mut text, entries.next_value()?, "text")?,
771 "visibility" => {
772 wire::accept(&mut visibility, entries.next_value()?, "visibility")?;
773 }
774 unknown => return Err(A::Error::unknown_field(unknown, SYSTEM_FIELDS)),
775 }
776 }
777 Ok(System::new(
778 wire::require(subtype, "subtype")?,
779 wire::require(text, "text")?,
780 wire::require(visibility, "visibility")?,
781 ))
782 }
783 }
784
785 impl Serialize for Item {
788 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
789 where
790 S: Serializer,
791 {
792 match self {
793 Self::User(record) => {
794 serializer.serialize_newtype_variant(ITEM_NAME, 0, "user", record)
795 }
796 Self::Assistant(record) => {
797 serializer.serialize_newtype_variant(ITEM_NAME, 1, "assistant", record)
798 }
799 Self::ToolResult(record) => {
800 serializer.serialize_newtype_variant(ITEM_NAME, 2, "tool_result", record)
801 }
802 Self::System(record) => {
803 serializer.serialize_newtype_variant(ITEM_NAME, 3, "system", record)
804 }
805 }
806 }
807 }
808
809 impl<'de> Deserialize<'de> for Item {
810 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
811 where
812 D: Deserializer<'de>,
813 {
814 deserializer.deserialize_enum(ITEM_NAME, ITEM_VARIANTS, ItemVisitor)
815 }
816 }
817
818 struct ItemVisitor;
819
820 impl<'de> Visitor<'de> for ItemVisitor {
821 type Value = Item;
822
823 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
824 formatter.write_str("a transcript record")
825 }
826
827 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
828 where
829 A: EnumAccess<'de>,
830 {
831 let (tag, variant) = data.variant_seed(IdentifierSeed(ITEM_VARIANTS))?;
832 match tag.0.as_str() {
833 "user" => variant.newtype_variant().map(Item::User),
834 "assistant" => variant.newtype_variant().map(Item::Assistant),
835 "tool_result" => variant.newtype_variant().map(Item::ToolResult),
836 "system" => variant.newtype_variant().map(Item::System),
837 unknown => Err(A::Error::unknown_variant(unknown, ITEM_VARIANTS)),
838 }
839 }
840 }
841}