1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
//! Turbofish LLM message
use crate::model::{StreamChunk, ToolCall};
pub use crabllm_core::Role;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// A message in the chat
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Message {
/// The role of the message
pub role: Role,
/// The content of the message
#[serde(default, skip_serializing_if = "String::is_empty")]
pub content: String,
/// The reasoning content
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reasoning_content: String,
/// The function name (set on tool-result messages for providers that
/// require it, e.g. Gemini's `function_response.name`).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
/// The tool call id
#[serde(default, skip_serializing_if = "String::is_empty")]
pub tool_call_id: String,
/// The tool calls
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tool_calls: Vec<ToolCall>,
/// Which agent produced this assistant message. Empty = the conversation's
/// primary agent. Non-empty = a guest agent that was pulled into the
/// conversation via an @ mention or guest turn.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub agent: String,
/// The sender identity (runtime-only, never serialized to providers).
///
/// Convention: empty = local/owner, `"tg:12345"` = Telegram user.
#[serde(skip)]
pub sender: String,
/// Whether this message was auto-injected by the runtime (e.g. recall).
/// Auto-injected messages are stripped before each new run.
#[serde(skip)]
pub auto_injected: bool,
}
impl Message {
/// Create a new system message
pub fn system(content: impl Into<String>) -> Self {
Self {
role: Role::System,
content: content.into(),
..Default::default()
}
}
/// Create a new user message
pub fn user(content: impl Into<String>) -> Self {
Self {
role: Role::User,
content: content.into(),
..Default::default()
}
}
/// Create a new user message with sender identity.
pub fn user_with_sender(content: impl Into<String>, sender: impl Into<String>) -> Self {
Self {
role: Role::User,
content: content.into(),
sender: sender.into(),
..Default::default()
}
}
/// Create a new assistant message
pub fn assistant(
content: impl Into<String>,
reasoning: Option<String>,
tool_calls: Option<&[ToolCall]>,
) -> Self {
Self {
role: Role::Assistant,
content: content.into(),
reasoning_content: reasoning.unwrap_or_default(),
tool_calls: tool_calls.map(|tc| tc.to_vec()).unwrap_or_default(),
..Default::default()
}
}
/// Create a new tool message
pub fn tool(
content: impl Into<String>,
call: impl Into<String>,
name: impl Into<String>,
) -> Self {
Self {
role: Role::Tool,
content: content.into(),
tool_call_id: call.into(),
name: name.into(),
..Default::default()
}
}
/// Create a new message builder
pub fn builder(role: Role) -> MessageBuilder {
MessageBuilder::new(role)
}
/// Estimate the number of tokens in this message.
///
/// Uses a simple heuristic: ~4 characters per token.
/// Return a clone with the content wrapped in `<from agent="...">` tags
/// if this is a guest assistant message. Used when building LLM requests
/// so agents can distinguish speakers in multi-agent conversations.
pub fn with_agent_tag(&self) -> Self {
if self.role == Role::Assistant && !self.agent.is_empty() {
let mut m = self.clone();
m.content = format!("<from agent=\"{}\">\n{}\n</from>", self.agent, self.content);
m
} else {
self.clone()
}
}
pub fn estimate_tokens(&self) -> usize {
let chars = self.content.len()
+ self.reasoning_content.len()
+ self.tool_call_id.len()
+ self
.tool_calls
.iter()
.map(|tc| tc.function.name.len() + tc.function.arguments.len())
.sum::<usize>();
(chars / 4).max(1)
}
}
/// Estimate total tokens across a slice of messages.
pub fn estimate_tokens(messages: &[Message]) -> usize {
messages.iter().map(|m| m.estimate_tokens()).sum()
}
/// A builder for messages
pub struct MessageBuilder {
/// The message
message: Message,
/// The tool calls
calls: BTreeMap<u32, ToolCall>,
}
impl MessageBuilder {
/// Create a new message builder
pub fn new(role: Role) -> Self {
Self {
message: Message {
role,
..Default::default()
},
calls: BTreeMap::new(),
}
}
/// Accept a chunk from the stream
pub fn accept(&mut self, chunk: &StreamChunk) -> bool {
if let Some(calls) = chunk.tool_calls() {
for call in calls {
let entry = self.calls.entry(call.index).or_default();
entry.merge(call);
}
}
let mut has_content = false;
if let Some(content) = chunk.content() {
self.message.content.push_str(content);
has_content = true;
}
if let Some(reason) = chunk.reasoning_content() {
self.message.reasoning_content.push_str(reason);
}
has_content
}
/// Peek at accumulated tool calls with non-empty names.
/// Returns clones of the current state (args may be partial).
pub fn peek_tool_calls(&self) -> Vec<ToolCall> {
self.calls
.values()
.filter(|c| !c.function.name.is_empty())
.cloned()
.collect()
}
/// Build the message
pub fn build(mut self) -> Message {
if !self.calls.is_empty() {
self.message.tool_calls = self.calls.into_values().collect();
}
self.message
}
}
impl Default for Message {
fn default() -> Self {
Self {
role: Role::User,
content: String::new(),
reasoning_content: String::new(),
name: String::new(),
tool_call_id: String::new(),
tool_calls: Vec::new(),
agent: String::new(),
sender: String::new(),
auto_injected: false,
}
}
}