rune_chain_core/message.rs
1use serde::{Deserialize, Serialize};
2
3/// The originator of a [`Message`] in a conversation turn.
4#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(rename_all = "lowercase")]
6pub enum Role {
7 /// Instructions that frame the model's behaviour for the whole conversation.
8 System,
9 /// A turn sent by the end user or caller.
10 Human,
11 /// A turn generated by the AI model.
12 Ai,
13 /// A synthetic turn injected by a tool or function-call result.
14 Tool,
15}
16
17impl std::fmt::Display for Role {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 match self {
20 Role::System => write!(f, "system"),
21 Role::Human => write!(f, "human"),
22 Role::Ai => write!(f, "ai"),
23 Role::Tool => write!(f, "tool"),
24 }
25 }
26}
27
28/// A single turn in a conversation, carrying a [`Role`] and text content.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct Message {
31 /// Who produced this message.
32 pub role: Role,
33 /// The text of the message.
34 pub content: String,
35}
36
37impl Message {
38 /// Create a new [`Message`] with an explicit role and content.
39 ///
40 /// # Example
41 ///
42 /// ```rust
43 /// use rune_chain_core::{Message, Role};
44 ///
45 /// let msg = Message::new(Role::Human, "Hello!");
46 /// assert_eq!(msg.role, Role::Human);
47 /// assert_eq!(msg.content, "Hello!");
48 /// ```
49 pub fn new(role: Role, content: impl Into<String>) -> Self {
50 Self {
51 role,
52 content: content.into(),
53 }
54 }
55
56 /// Shorthand for a [`Role::System`] message.
57 ///
58 /// # Example
59 ///
60 /// ```rust
61 /// use rune_chain_core::{Message, Role};
62 ///
63 /// let msg = Message::system("You are a helpful assistant.");
64 /// assert_eq!(msg.role, Role::System);
65 /// ```
66 pub fn system(content: impl Into<String>) -> Self {
67 Self::new(Role::System, content)
68 }
69
70 /// Shorthand for a [`Role::Human`] message.
71 ///
72 /// # Example
73 ///
74 /// ```rust
75 /// use rune_chain_core::{Message, Role};
76 ///
77 /// let msg = Message::human("What is 2 + 2?");
78 /// assert_eq!(msg.role, Role::Human);
79 /// ```
80 pub fn human(content: impl Into<String>) -> Self {
81 Self::new(Role::Human, content)
82 }
83
84 /// Shorthand for a [`Role::Ai`] message.
85 ///
86 /// # Example
87 ///
88 /// ```rust
89 /// use rune_chain_core::{Message, Role};
90 ///
91 /// let msg = Message::ai("The answer is 4.");
92 /// assert_eq!(msg.role, Role::Ai);
93 /// ```
94 pub fn ai(content: impl Into<String>) -> Self {
95 Self::new(Role::Ai, content)
96 }
97}