1use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::JsonObject;
7use crate::ids::{MessageId, SubagentRunId, ToolCallId};
8use crate::tool::ToolCall;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
14#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
15pub enum Role {
16 Developer,
18 System,
20 Assistant,
22 User,
24 Tool,
26 Activity,
28 Reasoning,
30}
31
32impl Role {
33 pub const fn as_str(&self) -> &'static str {
35 match self {
36 Self::Developer => "developer",
37 Self::System => "system",
38 Self::Assistant => "assistant",
39 Self::User => "user",
40 Self::Tool => "tool",
41 Self::Activity => "activity",
42 Self::Reasoning => "reasoning",
43 }
44 }
45}
46
47impl std::fmt::Display for Role {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.write_str(self.as_str())
50 }
51}
52
53#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(tag = "type", rename_all = "lowercase")]
56#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
57#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
58pub enum InputContentSource {
59 Data {
61 value: String,
63 #[serde(rename = "mimeType")]
65 mime_type: String,
66 },
67 Url {
69 value: String,
71 #[serde(
73 rename = "mimeType",
74 default,
75 deserialize_with = "crate::serde_util::reject_null",
76 skip_serializing_if = "Option::is_none"
77 )]
78 mime_type: Option<String>,
79 },
80 File {
82 value: String,
84 #[serde(
86 default,
87 deserialize_with = "crate::serde_util::reject_null",
88 skip_serializing_if = "Option::is_none"
89 )]
90 provider: Option<String>,
91 #[serde(
93 rename = "mimeType",
94 default,
95 deserialize_with = "crate::serde_util::reject_null",
96 skip_serializing_if = "Option::is_none"
97 )]
98 mime_type: Option<String>,
99 },
100}
101
102#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
105#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
106pub struct TextInputContent {
107 #[serde(
109 default,
110 deserialize_with = "crate::serde_util::reject_null",
111 skip_serializing_if = "Option::is_none"
112 )]
113 pub id: Option<String>,
114 pub text: String,
116 #[serde(
118 default,
119 deserialize_with = "crate::serde_util::reject_null",
120 skip_serializing_if = "crate::serde_util::is_none_or_null"
121 )]
122 pub metadata: Option<Value>,
123}
124
125#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
130#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
131#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
132pub struct MediaInputContent {
133 #[serde(
135 default,
136 deserialize_with = "crate::serde_util::reject_null",
137 skip_serializing_if = "Option::is_none"
138 )]
139 pub id: Option<String>,
140 pub source: InputContentSource,
142 #[serde(
144 default,
145 deserialize_with = "crate::serde_util::reject_null",
146 skip_serializing_if = "crate::serde_util::is_none_or_null"
147 )]
148 pub metadata: Option<Value>,
149}
150
151impl MediaInputContent {
152 pub fn new(source: InputContentSource) -> Self {
154 Self {
155 id: None,
156 source,
157 metadata: None,
158 }
159 }
160}
161
162#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
171#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
172pub struct BinaryInputContent {
173 pub mime_type: String,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub id: Option<String>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub url: Option<String>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub data: Option<String>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub filename: Option<String>,
187}
188
189impl BinaryInputContent {
190 pub fn has_payload(&self) -> bool {
192 self.id.is_some() || self.url.is_some() || self.data.is_some()
193 }
194
195 #[cfg(any(feature = "client", feature = "axum"))]
200 fn upgraded(&self) -> Option<InputContent> {
201 let mime_type = self.mime_type.clone();
202 let filled = |value: &Option<String>| value.clone().filter(|value| !value.is_empty());
203 let source = if let Some(value) = filled(&self.data) {
204 InputContentSource::Data { value, mime_type }
205 } else {
206 InputContentSource::Url {
207 value: filled(&self.url)?,
208 mime_type: Some(mime_type),
209 }
210 };
211 let media = MediaInputContent {
212 id: None,
213 source,
214 metadata: filled(&self.filename)
215 .map(|filename| serde_json::json!({ "filename": filename })),
216 };
217 let modality = self.mime_type.split_once('/').map(|(kind, _)| kind);
218 Some(match modality {
219 Some(kind) if kind.eq_ignore_ascii_case("image") => InputContent::Image(media),
220 Some(kind) if kind.eq_ignore_ascii_case("audio") => InputContent::Audio(media),
221 Some(kind) if kind.eq_ignore_ascii_case("video") => InputContent::Video(media),
222 _ => InputContent::Document(media),
223 })
224 }
225}
226
227#[cfg(feature = "client")]
234pub(crate) fn upgrade_legacy_content(messages: &mut [Message]) {
235 for message in messages {
236 let parts = match message {
237 Message::User(user) => match &mut user.content {
238 UserContent::Parts(parts) => parts,
239 UserContent::Text(_) => continue,
240 },
241 Message::Tool(tool) => match &mut tool.content {
242 ToolContent::Parts(parts) => parts,
243 ToolContent::Text(_) => continue,
244 },
245 _ => continue,
246 };
247 if !parts
248 .iter()
249 .any(|part| matches!(part, InputContent::Binary(_)))
250 {
251 continue;
252 }
253 let original = std::mem::take(parts);
254 for part in &original {
255 let InputContent::Binary(binary) = part else {
256 parts.push(part.clone());
257 continue;
258 };
259 match binary.upgraded() {
260 Some(media) if original.iter().any(|other| mirrors(other, &media, binary)) => {}
263 Some(media) => parts.push(media),
264 None => parts.push(part.clone()),
265 }
266 }
267 }
268}
269
270#[cfg(feature = "client")]
275pub(crate) fn upgrade_legacy_event_content(
276 event: &mut Value,
277 tag: &str,
278 warnings: &mut Vec<String>,
279) {
280 let (messages, at) = match tag {
281 "TOOL_CALL_RESULT" => {
282 return upgrade_wire_parts(event.get_mut("content"), "/content", warnings);
283 }
284 "MESSAGES_SNAPSHOT" => (event.get_mut("messages"), "/messages"),
285 "RUN_STARTED" => (event.pointer_mut("/input/messages"), "/input/messages"),
286 _ => return,
287 };
288 upgrade_wire_messages(messages, at, warnings);
289}
290
291#[cfg(any(feature = "client", feature = "axum"))]
292pub(crate) fn upgrade_wire_messages(
293 messages: Option<&mut Value>,
294 at: &str,
295 warnings: &mut Vec<String>,
296) {
297 for (index, message) in messages
298 .and_then(Value::as_array_mut)
299 .into_iter()
300 .flatten()
301 .enumerate()
302 {
303 if matches!(
304 message.get("role").and_then(Value::as_str),
305 Some("user" | "tool")
306 ) && message.get("content").is_some_and(Value::is_array)
307 {
308 let at = format!("{at}/{index}/content");
309 upgrade_wire_parts(message.get_mut("content"), &at, warnings);
310 }
311 }
312}
313
314#[cfg(any(feature = "client", feature = "axum"))]
317fn upgrade_wire_parts(content: Option<&mut Value>, at: &str, warnings: &mut Vec<String>) {
318 let Some(parts) = content.and_then(Value::as_array_mut) else {
319 return;
320 };
321 let legacy = |part: &Value| -> Option<BinaryInputContent> {
322 (part.get("type").and_then(Value::as_str) == Some("binary"))
323 .then(|| serde_json::from_value(part.clone()).ok())
324 .flatten()
325 };
326 if !parts.iter().any(|part| legacy(part).is_some()) {
327 return;
328 }
329 let original = std::mem::take(parts);
330 let modern: Vec<InputContent> = original
332 .iter()
333 .filter(|part| legacy(part).is_none())
334 .filter_map(|part| serde_json::from_value(part.clone()).ok())
335 .collect();
336 for (index, part) in original.iter().enumerate() {
337 let translated = legacy(part).and_then(|binary| {
338 let media = binary.upgraded()?;
339 Some((serde_json::to_value(&media).ok()?, media, binary))
340 });
341 let Some((wire, media, binary)) = translated else {
342 parts.push(part.clone());
343 continue;
344 };
345 let modality = wire.get("type").and_then(Value::as_str).unwrap_or("media");
346 if modern.iter().any(|other| mirrors(other, &media, &binary)) {
347 warnings.push(format!(
348 "dropped retired binary content part at {at}/{index}: the {modality} part \
349 beside it carries the same payload"
350 ));
351 } else {
352 warnings.push(format!(
353 "translated retired binary content part at {at}/{index} to {modality}"
354 ));
355 parts.push(wire);
356 }
357 }
358}
359
360#[cfg(any(feature = "client", feature = "axum"))]
363fn mirrors(part: &InputContent, media: &InputContent, legacy: &BinaryInputContent) -> bool {
364 let (part, media) = match (part, media) {
365 (InputContent::Image(part), InputContent::Image(media))
366 | (InputContent::Audio(part), InputContent::Audio(media))
367 | (InputContent::Video(part), InputContent::Video(media))
368 | (InputContent::Document(part), InputContent::Document(media)) => (part, media),
369 _ => return false,
370 };
371 let kept_name = part
372 .metadata
373 .as_ref()
374 .and_then(|metadata| metadata.get("filename"))
375 .and_then(Value::as_str);
376 let same_mime = |a: &str, b: &str| {
377 let (kind_a, params_a) = a.split_once(';').unwrap_or((a, ""));
378 let (kind_b, params_b) = b.split_once(';').unwrap_or((b, ""));
379 kind_a.eq_ignore_ascii_case(kind_b) && params_a == params_b
380 };
381 let same_source = match (&part.source, &media.source) {
384 (
385 InputContentSource::Url {
386 value: a,
387 mime_type: Some(mime_a),
388 },
389 InputContentSource::Url {
390 value: b,
391 mime_type: Some(mime_b),
392 },
393 )
394 | (
395 InputContentSource::Data {
396 value: a,
397 mime_type: mime_a,
398 },
399 InputContentSource::Data {
400 value: b,
401 mime_type: mime_b,
402 },
403 ) => a == b && same_mime(mime_a, mime_b),
404 _ => false,
405 };
406 same_source
407 && legacy
408 .filename
409 .as_deref()
410 .filter(|filename| !filename.is_empty())
411 .is_none_or(|filename| kept_name == Some(filename))
412}
413
414#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
416#[serde(tag = "type", rename_all = "lowercase")]
417#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
418#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
419pub enum InputContent {
420 Text(TextInputContent),
422 Image(MediaInputContent),
424 Audio(MediaInputContent),
426 Video(MediaInputContent),
428 Document(MediaInputContent),
430 Binary(BinaryInputContent),
432}
433
434impl InputContent {
435 pub fn text(text: impl Into<String>) -> Self {
437 Self::Text(TextInputContent {
438 text: text.into(),
439 ..Default::default()
440 })
441 }
442}
443
444#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
447#[serde(untagged)]
448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
449#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
450pub enum UserContent {
451 Text(String),
453 Parts(Vec<InputContent>),
455}
456
457impl UserContent {
458 pub fn as_text(&self) -> Option<&str> {
464 match self {
465 Self::Text(text) => Some(text),
466 Self::Parts(_) => None,
467 }
468 }
469
470 pub fn to_text(&self) -> String {
495 match self {
496 Self::Text(text) => text.clone(),
497 Self::Parts(parts) => parts
498 .iter()
499 .filter_map(|part| match part {
500 InputContent::Text(part) => Some(part.text.as_str()),
501 _ => None,
502 })
503 .collect::<Vec<_>>()
504 .join("\n"),
505 }
506 }
507}
508
509impl Default for UserContent {
510 fn default() -> Self {
511 Self::Text(String::new())
512 }
513}
514
515impl From<String> for UserContent {
516 fn from(value: String) -> Self {
517 Self::Text(value)
518 }
519}
520
521impl From<&str> for UserContent {
522 fn from(value: &str) -> Self {
523 Self::Text(value.to_owned())
524 }
525}
526
527impl From<Vec<InputContent>> for UserContent {
528 fn from(value: Vec<InputContent>) -> Self {
529 Self::Parts(value)
530 }
531}
532
533#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
535#[serde(untagged)]
536#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
537#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
538pub enum ToolContent {
539 Text(String),
541 Parts(Vec<InputContent>),
543}
544
545impl ToolContent {
546 pub fn as_text(&self) -> Option<&str> {
548 match self {
549 Self::Text(text) => Some(text),
550 Self::Parts(_) => None,
551 }
552 }
553
554 pub fn to_text(&self) -> String {
556 match self {
557 Self::Text(text) => text.clone(),
558 Self::Parts(parts) => parts
559 .iter()
560 .filter_map(|part| match part {
561 InputContent::Text(part) => Some(part.text.as_str()),
562 _ => None,
563 })
564 .collect::<Vec<_>>()
565 .join("\n"),
566 }
567 }
568}
569
570impl Default for ToolContent {
571 fn default() -> Self {
572 Self::Text(String::new())
573 }
574}
575
576impl From<String> for ToolContent {
577 fn from(value: String) -> Self {
578 Self::Text(value)
579 }
580}
581
582impl From<&str> for ToolContent {
583 fn from(value: &str) -> Self {
584 Self::Text(value.to_owned())
585 }
586}
587
588impl From<Vec<InputContent>> for ToolContent {
589 fn from(value: Vec<InputContent>) -> Self {
590 Self::Parts(value)
591 }
592}
593
594#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
598#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
599pub struct DeveloperMessage {
600 pub id: MessageId,
602 pub content: String,
604 #[serde(default, skip_serializing_if = "Option::is_none")]
606 pub name: Option<String>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub encrypted_value: Option<String>,
610 #[serde(
613 default,
614 deserialize_with = "crate::serde_util::reject_null",
615 skip_serializing_if = "Option::is_none"
616 )]
617 pub subagent_run_id: Option<SubagentRunId>,
618 #[serde(
621 default,
622 deserialize_with = "crate::serde_util::reject_null",
623 skip_serializing_if = "Option::is_none"
624 )]
625 #[cfg_attr(
626 feature = "schemars",
627 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
628 )]
629 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
630 pub metadata: Option<JsonObject>,
631}
632
633#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
635#[serde(rename_all = "camelCase")]
636#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
637#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
638pub struct SystemMessage {
639 pub id: MessageId,
641 pub content: String,
643 #[serde(default, skip_serializing_if = "Option::is_none")]
645 pub name: Option<String>,
646 #[serde(default, skip_serializing_if = "Option::is_none")]
648 pub encrypted_value: Option<String>,
649 #[serde(
652 default,
653 deserialize_with = "crate::serde_util::reject_null",
654 skip_serializing_if = "Option::is_none"
655 )]
656 pub subagent_run_id: Option<SubagentRunId>,
657 #[serde(
660 default,
661 deserialize_with = "crate::serde_util::reject_null",
662 skip_serializing_if = "Option::is_none"
663 )]
664 #[cfg_attr(
665 feature = "schemars",
666 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
667 )]
668 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
669 pub metadata: Option<JsonObject>,
670}
671
672#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
674#[serde(rename_all = "camelCase")]
675#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
676#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
677pub struct AssistantMessage {
678 pub id: MessageId,
680 #[serde(default, skip_serializing_if = "Option::is_none")]
682 pub content: Option<String>,
683 #[serde(default, skip_serializing_if = "Option::is_none")]
685 pub name: Option<String>,
686 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub encrypted_value: Option<String>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub tool_calls: Option<Vec<ToolCall>>,
692 #[serde(
695 default,
696 deserialize_with = "crate::serde_util::reject_null",
697 skip_serializing_if = "Option::is_none"
698 )]
699 pub subagent_run_id: Option<SubagentRunId>,
700 #[serde(
703 default,
704 deserialize_with = "crate::serde_util::reject_null",
705 skip_serializing_if = "Option::is_none"
706 )]
707 #[cfg_attr(
708 feature = "schemars",
709 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
710 )]
711 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
712 pub metadata: Option<JsonObject>,
713}
714
715#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
717#[serde(rename_all = "camelCase")]
718#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
719#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
720pub struct UserMessage {
721 pub id: MessageId,
723 pub content: UserContent,
725 #[serde(default, skip_serializing_if = "Option::is_none")]
727 pub name: Option<String>,
728 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub encrypted_value: Option<String>,
731 #[serde(
734 default,
735 deserialize_with = "crate::serde_util::reject_null",
736 skip_serializing_if = "Option::is_none"
737 )]
738 pub subagent_run_id: Option<SubagentRunId>,
739 #[serde(
742 default,
743 deserialize_with = "crate::serde_util::reject_null",
744 skip_serializing_if = "Option::is_none"
745 )]
746 #[cfg_attr(
747 feature = "schemars",
748 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
749 )]
750 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
751 pub metadata: Option<JsonObject>,
752}
753
754#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
756#[serde(rename_all = "camelCase")]
757#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
758#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
759pub struct ToolMessage {
760 pub id: MessageId,
762 pub content: ToolContent,
764 pub tool_call_id: ToolCallId,
766 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub error: Option<String>,
770 #[serde(default, skip_serializing_if = "Option::is_none")]
772 pub encrypted_value: Option<String>,
773 #[serde(
778 default,
779 deserialize_with = "crate::serde_util::reject_null",
780 skip_serializing_if = "Option::is_none"
781 )]
782 pub subagent_run_id: Option<SubagentRunId>,
783 #[serde(
786 default,
787 deserialize_with = "crate::serde_util::reject_null",
788 skip_serializing_if = "Option::is_none"
789 )]
790 #[cfg_attr(
791 feature = "schemars",
792 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
793 )]
794 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
795 pub metadata: Option<JsonObject>,
796}
797
798#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
800#[serde(rename_all = "camelCase")]
801#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
802#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
803pub struct ActivityMessage {
804 pub id: MessageId,
806 pub activity_type: String,
808 #[cfg_attr(
810 feature = "schemars",
811 schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
812 )]
813 #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
814 pub content: JsonObject,
815 #[serde(
818 default,
819 deserialize_with = "crate::serde_util::reject_null",
820 skip_serializing_if = "Option::is_none"
821 )]
822 pub subagent_run_id: Option<SubagentRunId>,
823 #[serde(
826 default,
827 deserialize_with = "crate::serde_util::reject_null",
828 skip_serializing_if = "Option::is_none"
829 )]
830 #[cfg_attr(
831 feature = "schemars",
832 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
833 )]
834 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
835 pub metadata: Option<JsonObject>,
836}
837
838#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
840#[serde(rename_all = "camelCase")]
841#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
842#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
843pub struct ReasoningMessage {
844 pub id: MessageId,
846 pub content: String,
849 #[serde(default, skip_serializing_if = "Option::is_none")]
851 pub encrypted_value: Option<String>,
852 #[serde(
855 default,
856 deserialize_with = "crate::serde_util::reject_null",
857 skip_serializing_if = "Option::is_none"
858 )]
859 pub subagent_run_id: Option<SubagentRunId>,
860 #[serde(
863 default,
864 deserialize_with = "crate::serde_util::reject_null",
865 skip_serializing_if = "Option::is_none"
866 )]
867 #[cfg_attr(
868 feature = "schemars",
869 schemars(with = "Option<std::collections::BTreeMap<String, serde_json::Value>>")
870 )]
871 #[cfg_attr(feature = "utoipa", schema(value_type = Option<Object>))]
872 pub metadata: Option<JsonObject>,
873}
874
875#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
877#[serde(tag = "role", rename_all = "lowercase")]
878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
879#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
880pub enum Message {
881 Developer(DeveloperMessage),
883 System(SystemMessage),
885 Assistant(AssistantMessage),
887 User(UserMessage),
889 Tool(ToolMessage),
891 Activity(ActivityMessage),
893 Reasoning(ReasoningMessage),
895}
896
897impl Message {
898 pub fn user(id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
900 Self::User(UserMessage {
901 id: id.into(),
902 content: content.into(),
903 ..Default::default()
904 })
905 }
906
907 pub fn assistant(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
909 Self::Assistant(AssistantMessage {
910 id: id.into(),
911 content: Some(content.into()),
912 ..Default::default()
913 })
914 }
915
916 pub fn system(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
918 Self::System(SystemMessage {
919 id: id.into(),
920 content: content.into(),
921 ..Default::default()
922 })
923 }
924
925 pub fn developer(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
927 Self::Developer(DeveloperMessage {
928 id: id.into(),
929 content: content.into(),
930 ..Default::default()
931 })
932 }
933
934 pub fn tool(
936 id: impl Into<MessageId>,
937 tool_call_id: impl Into<ToolCallId>,
938 content: impl Into<ToolContent>,
939 ) -> Self {
940 Self::Tool(ToolMessage {
941 id: id.into(),
942 content: content.into(),
943 tool_call_id: tool_call_id.into(),
944 ..Default::default()
945 })
946 }
947
948 pub const fn id(&self) -> &MessageId {
950 match self {
951 Self::Developer(m) => &m.id,
952 Self::System(m) => &m.id,
953 Self::Assistant(m) => &m.id,
954 Self::User(m) => &m.id,
955 Self::Tool(m) => &m.id,
956 Self::Activity(m) => &m.id,
957 Self::Reasoning(m) => &m.id,
958 }
959 }
960
961 pub const fn role(&self) -> Role {
963 match self {
964 Self::Developer(_) => Role::Developer,
965 Self::System(_) => Role::System,
966 Self::Assistant(_) => Role::Assistant,
967 Self::User(_) => Role::User,
968 Self::Tool(_) => Role::Tool,
969 Self::Activity(_) => Role::Activity,
970 Self::Reasoning(_) => Role::Reasoning,
971 }
972 }
973
974 pub const fn subagent_run_id(&self) -> Option<&SubagentRunId> {
977 match self {
978 Self::Developer(m) => m.subagent_run_id.as_ref(),
979 Self::System(m) => m.subagent_run_id.as_ref(),
980 Self::Assistant(m) => m.subagent_run_id.as_ref(),
981 Self::User(m) => m.subagent_run_id.as_ref(),
982 Self::Tool(m) => m.subagent_run_id.as_ref(),
983 Self::Activity(m) => m.subagent_run_id.as_ref(),
984 Self::Reasoning(m) => m.subagent_run_id.as_ref(),
985 }
986 }
987
988 pub fn set_subagent_run_id(&mut self, subagent_run_id: Option<SubagentRunId>) {
990 match self {
991 Self::Developer(m) => m.subagent_run_id = subagent_run_id,
992 Self::System(m) => m.subagent_run_id = subagent_run_id,
993 Self::Assistant(m) => m.subagent_run_id = subagent_run_id,
994 Self::User(m) => m.subagent_run_id = subagent_run_id,
995 Self::Tool(m) => m.subagent_run_id = subagent_run_id,
996 Self::Activity(m) => m.subagent_run_id = subagent_run_id,
997 Self::Reasoning(m) => m.subagent_run_id = subagent_run_id,
998 }
999 }
1000
1001 pub const fn metadata(&self) -> Option<&JsonObject> {
1003 match self {
1004 Self::Developer(m) => m.metadata.as_ref(),
1005 Self::System(m) => m.metadata.as_ref(),
1006 Self::Assistant(m) => m.metadata.as_ref(),
1007 Self::User(m) => m.metadata.as_ref(),
1008 Self::Tool(m) => m.metadata.as_ref(),
1009 Self::Activity(m) => m.metadata.as_ref(),
1010 Self::Reasoning(m) => m.metadata.as_ref(),
1011 }
1012 }
1013
1014 pub fn metadata_mut(&mut self) -> &mut Option<JsonObject> {
1018 match self {
1019 Self::Developer(m) => &mut m.metadata,
1020 Self::System(m) => &mut m.metadata,
1021 Self::Assistant(m) => &mut m.metadata,
1022 Self::User(m) => &mut m.metadata,
1023 Self::Tool(m) => &mut m.metadata,
1024 Self::Activity(m) => &mut m.metadata,
1025 Self::Reasoning(m) => &mut m.metadata,
1026 }
1027 }
1028}
1029
1030macro_rules! message_from {
1031 ($($ty:ident => $variant:ident),* $(,)?) => {
1032 $(
1033 impl From<$ty> for Message {
1034 fn from(value: $ty) -> Self {
1035 Self::$variant(value)
1036 }
1037 }
1038 )*
1039 };
1040}
1041
1042message_from! {
1043 DeveloperMessage => Developer,
1044 SystemMessage => System,
1045 AssistantMessage => Assistant,
1046 UserMessage => User,
1047 ToolMessage => Tool,
1048 ActivityMessage => Activity,
1049 ReasoningMessage => Reasoning,
1050}