-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathcontext.rs
More file actions
1824 lines (1587 loc) · 65.8 KB
/
Copy pathcontext.rs
File metadata and controls
1824 lines (1587 loc) · 65.8 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fmt::Display;
use std::ops::Deref;
use derive_more::derive::{Display, From};
use derive_setters::Setters;
use forge_template::Element;
use serde::{Deserialize, Serialize};
use tracing::debug;
use super::{ToolCallFull, ToolResult};
/// Helper function for serde to skip serializing false boolean values
fn is_false(value: &bool) -> bool {
!value
}
use crate::temperature::Temperature;
use crate::top_k::TopK;
use crate::top_p::TopP;
use crate::{
Attachment, AttachmentContent, ConversationId, EventValue, Image, MessagePhase, ModelId,
ReasoningFull, ToolChoice, ToolDefinition, ToolOutput, ToolValue, Usage,
};
/// Response format for structured output
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ResponseFormat {
/// Plain text response
#[default]
Text,
/// JSON response with schema
JsonSchema(Box<schemars::Schema>),
}
/// Represents a message being sent to the LLM provider
/// NOTE: ToolResults message are part of the larger Request object and not part
/// of the message.
#[derive(Clone, Debug, Deserialize, From, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ContextMessage {
Text(TextMessage),
Tool(ToolResult),
Image(Image),
}
/// Creates a filtered version of ToolOutput that excludes base64 images to
/// avoid serializing large image data in the context output
fn filter_base64_images_from_tool_output(output: &ToolOutput) -> ToolOutput {
let filtered_values: Vec<ToolValue> = output
.values
.iter()
.map(|value| match value {
ToolValue::Image(image) => {
// Skip base64 images (URLs that start with "data:")
if image.url().starts_with("data:") {
ToolValue::Text(format!("[base64 image: {}]", image.mime_type()))
} else {
value.clone()
}
}
_ => value.clone(),
})
.collect();
ToolOutput { is_error: output.is_error, values: filtered_values }
}
impl ContextMessage {
pub fn content(&self) -> Option<&str> {
match self {
ContextMessage::Text(text_message) => Some(&text_message.content),
ContextMessage::Tool(_) => None,
ContextMessage::Image(_) => None,
}
}
/// Returns the raw content before template rendering (only for User
/// messages)
pub fn as_value(&self) -> Option<&EventValue> {
match self {
ContextMessage::Text(text_message) => text_message.raw_content.as_ref(),
ContextMessage::Tool(_) => None,
ContextMessage::Image(_) => None,
}
}
/// Estimates the number of tokens in a message using character-based
/// approximation.
/// ref: https://github.com/openai/codex/blob/main/codex-cli/src/utils/approximate-tokens-used.ts
pub fn token_count_approx(&self) -> usize {
let char_count = match self {
ContextMessage::Text(text_message) => {
text_message.content.chars().count()
+ tool_call_content_char_count(text_message)
+ reasoning_content_char_count(text_message)
}
ContextMessage::Tool(tool_result) => tool_result
.output
.values
.iter()
.map(|result| match result {
ToolValue::Text(text) => text.chars().count(),
_ => 0,
})
.sum(),
_ => 0,
};
char_count.div_ceil(4)
}
pub fn to_text(&self) -> String {
match self {
ContextMessage::Text(message) => {
let mut message_element = Element::new("message").attr("role", message.role);
message_element =
message_element.append(Element::new("content").text(&message.content));
if let Some(tool_calls) = &message.tool_calls {
for call in tool_calls {
message_element = message_element.append(
Element::new("forge_tool_call")
.attr("name", &call.name)
.cdata(call.arguments.clone().into_string()),
);
}
}
if let Some(thought_signature) = &message.thought_signature {
message_element = message_element
.append(Element::new("thought_signature").text(thought_signature));
}
if let Some(reasoning_details) = &message.reasoning_details {
for reasoning_detail in reasoning_details {
if let Some(text) = &reasoning_detail.text {
message_element =
message_element.append(Element::new("reasoning_detail").text(text));
}
}
}
message_element.render()
}
ContextMessage::Tool(result) => {
let filtered_output = filter_base64_images_from_tool_output(&result.output);
Element::new("message")
.attr("role", "tool")
.append(
Element::new("forge_tool_result")
.attr("name", &result.name)
.cdata(serde_json::to_string(&filtered_output).unwrap()),
)
.render()
}
ContextMessage::Image(_) => Element::new("image").attr("path", "[base64 URL]").render(),
}
}
pub fn user(content: impl ToString, model: Option<ModelId>) -> Self {
TextMessage {
role: Role::User,
content: content.to_string(),
raw_content: None,
tool_calls: None,
thought_signature: None,
reasoning_details: None,
model,
droppable: false,
phase: None,
}
.into()
}
pub fn system(content: impl ToString) -> Self {
TextMessage {
role: Role::System,
content: content.to_string(),
raw_content: None,
tool_calls: None,
thought_signature: None,
model: None,
reasoning_details: None,
droppable: false,
phase: None,
}
.into()
}
pub fn assistant(
content: impl ToString,
thought_signature: Option<String>,
reasoning_details: Option<Vec<ReasoningFull>>,
tool_calls: Option<Vec<ToolCallFull>>,
) -> Self {
let tool_calls = tool_calls.filter(|calls| !calls.is_empty());
TextMessage {
role: Role::Assistant,
content: content.to_string(),
raw_content: None,
tool_calls,
thought_signature,
reasoning_details,
model: None,
droppable: false,
phase: None,
}
.into()
}
pub fn tool_result(result: ToolResult) -> Self {
Self::Tool(result)
}
pub fn has_role(&self, role: Role) -> bool {
match self {
ContextMessage::Text(message) => message.role == role,
ContextMessage::Tool(_) => false,
ContextMessage::Image(_) => Role::User == role,
}
}
pub fn is_droppable(&self) -> bool {
match self {
ContextMessage::Text(message) => message.droppable,
ContextMessage::Tool(_) => false,
ContextMessage::Image(_) => false,
}
}
pub fn has_tool_result(&self) -> bool {
match self {
ContextMessage::Text(_) => false,
ContextMessage::Tool(_) => true,
ContextMessage::Image(_) => false,
}
}
pub fn has_tool_call(&self) -> bool {
match self {
ContextMessage::Text(message) => message.tool_calls.is_some(),
ContextMessage::Tool(_) => false,
ContextMessage::Image(_) => false,
}
}
pub fn has_reasoning_details(&self) -> bool {
match self {
ContextMessage::Text(message) => message.reasoning_details.is_some(),
ContextMessage::Tool(_) => false,
ContextMessage::Image(_) => false,
}
}
/// Returns the tool result if this message is a Tool variant
pub fn as_tool_result(&self) -> Option<&ToolResult> {
match self {
ContextMessage::Tool(result) => Some(result),
_ => None,
}
}
}
fn tool_call_content_char_count(text_message: &TextMessage) -> usize {
text_message
.tool_calls
.as_ref()
.map(|tool_calls| {
tool_calls
.iter()
.map(|tc| {
tc.arguments.to_owned().into_string().chars().count()
+ tc.name.as_str().chars().count()
})
.sum()
})
.unwrap_or(0)
}
fn reasoning_content_char_count(text_message: &TextMessage) -> usize {
text_message
.reasoning_details
.as_ref()
.map_or(0, |details| {
details
.iter()
.map(|rd| rd.text.as_ref().map_or(0, |text| text.chars().count()))
.sum::<usize>()
})
}
//TODO: Rename to TextMessage
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, Setters)]
#[setters(strip_option, into)]
#[serde(rename_all = "snake_case")]
pub struct TextMessage {
pub role: Role,
pub content: String,
/// The raw content before any template rendering (only for User messages)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw_content: Option<EventValue>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_calls: Option<Vec<ToolCallFull>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thought_signature: Option<String>,
// note: this used to track model used for this message.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<ModelId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_details: Option<Vec<ReasoningFull>>,
/// Indicates whether this message can be dropped during context compaction
#[serde(default, skip_serializing_if = "is_false")]
pub droppable: bool,
/// Phase label for assistant messages (`Commentary` or `FinalAnswer`).
/// Preserved from OpenAI Responses API and replayed back on subsequent
/// requests.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub phase: Option<MessagePhase>,
}
impl TextMessage {
/// Creates a new TextMessage with the given role and content
pub fn new(role: Role, content: impl Into<String>) -> Self {
Self {
role,
content: content.into(),
raw_content: None,
tool_calls: None,
thought_signature: None,
model: None,
reasoning_details: None,
droppable: false,
phase: None,
}
}
pub fn has_role(&self, role: Role) -> bool {
self.role == role
}
pub fn assistant(
content: impl ToString,
reasoning_details: Option<Vec<ReasoningFull>>,
model: Option<ModelId>,
) -> Self {
Self {
role: Role::Assistant,
content: content.to_string(),
raw_content: None,
tool_calls: None,
thought_signature: None,
reasoning_details,
model,
droppable: false,
phase: None,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize, Display)]
pub enum Role {
System,
User,
Assistant,
}
#[derive(Clone, Debug, Serialize, Deserialize, Setters, PartialEq)]
#[setters(into, strip_option)]
pub struct MessageEntry {
#[serde(flatten)]
pub message: ContextMessage,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage: Option<Usage>,
}
impl From<ContextMessage> for MessageEntry {
fn from(value: ContextMessage) -> Self {
MessageEntry { message: value, usage: Default::default() }
}
}
impl Deref for MessageEntry {
type Target = ContextMessage;
fn deref(&self) -> &Self::Target {
&self.message
}
}
impl std::ops::DerefMut for MessageEntry {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.message
}
}
/// Represents a request being made to the LLM provider. By default the request
/// is created with assuming the model supports use of external tools.
#[derive(Clone, Debug, Deserialize, Serialize, Setters, Default, PartialEq)]
#[setters(into, strip_option)]
pub struct Context {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub conversation_id: Option<ConversationId>,
/// Indicates who initiated the conversation: "user" or "agent".
/// Used for GitHub Copilot billing optimization.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub initiator: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub messages: Vec<MessageEntry>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<ToolDefinition>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tool_choice: Option<ToolChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub temperature: Option<Temperature>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub top_p: Option<TopP>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub top_k: Option<TopK>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning: Option<crate::ReasoningConfig>,
/// Controls whether responses should be streamed. When `true`, responses
/// are delivered incrementally as they're generated. When `false`, the
/// complete response is returned at once. Defaults to `true` if not
/// specified.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stream: Option<bool>,
/// Response format for structured output (JSON schema)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_format: Option<ResponseFormat>,
}
impl Context {
pub fn accumulate_usage(&self) -> Option<Usage> {
self.messages
.iter()
.filter_map(|msg| msg.usage.as_ref())
.cloned()
.reduce(|a, b| a.accumulate(&b))
}
pub fn system_prompt(&self) -> Option<&str> {
self.messages
.iter()
.find(|message| message.has_role(Role::System))
.and_then(|msg| msg.content())
}
pub fn add_base64_url(mut self, image: Image) -> Self {
self.messages.push(ContextMessage::Image(image).into());
self
}
pub fn add_tool(mut self, tool: impl Into<ToolDefinition>) -> Self {
let tool: ToolDefinition = tool.into();
self.tools.push(tool);
self
}
pub fn add_message(self, content: impl Into<ContextMessage>) -> Self {
self.add_entry(content.into())
}
pub fn add_entry(mut self, content: impl Into<MessageEntry>) -> Self {
let content = content.into();
self.messages.push(content);
self
}
pub fn add_attachments(self, attachments: Vec<Attachment>, model_id: Option<ModelId>) -> Self {
attachments.into_iter().fold(self, |ctx, attachment| {
ctx.add_message(match attachment.content {
AttachmentContent::Image(image) => ContextMessage::Image(image),
AttachmentContent::FileContent { content, info } => {
let elm = Element::new("file_content")
.attr("path", attachment.path)
.attr("start_line", info.start_line)
.attr("end_line", info.end_line)
.attr("total_lines", info.total_lines)
.cdata(content);
let mut message = TextMessage::new(Role::User, elm.to_string()).droppable(true);
if let Some(model) = model_id.clone() {
message = message.model(model);
}
message.into()
}
AttachmentContent::DirectoryListing { entries } => {
let elm = Element::new("directory_listing")
.attr("path", attachment.path)
.append(entries.into_iter().map(|entry| {
let tag_name = if entry.is_dir { "dir" } else { "file" };
Element::new(tag_name).text(entry.path)
}));
let mut message = TextMessage::new(Role::User, elm.to_string()).droppable(true);
if let Some(model) = model_id.clone() {
message = message.model(model);
}
message.into()
}
})
})
}
pub fn add_tool_results(mut self, results: Vec<ToolResult>) -> Self {
if !results.is_empty() {
debug!(results = ?results, "Adding tool results to context");
self.messages.extend(
results
.into_iter()
.map(ContextMessage::tool_result)
.map(MessageEntry::from),
);
}
self
}
/// Replaces any existing system messages with the provided content.
///
/// All entries in `content` are joined into a single system message
/// (separated by `\n\n`) and inserted at position 0 of the message list.
/// This is required for compatibility with chat templates — such as
/// Qwen3.5/3.6 (llama.cpp, vLLM) — that only allow a single system
/// message at `messages[0]` and raise `raise_exception('System message
/// must be at the beginning.')` for any additional system message.
pub fn set_system_messages<S: Into<String>>(mut self, content: Vec<S>) -> Self {
// Drop every existing system message regardless of the new payload.
self.messages.retain(|m| !m.has_role(Role::System));
// Combine all provided system message entries into a single block.
let combined: String = content
.into_iter()
.map(Into::into)
.filter(|s: &String| !s.is_empty())
.collect::<Vec<_>>()
.join("\n\n");
if combined.is_empty() {
return self;
}
// Insert the single, combined system message at the beginning of the
// message list, so chat templates that require `messages[0]` to be the
// (only) system message continue to work.
self.messages
.insert(0, ContextMessage::system(combined).into());
self
}
/// Converts the context to textual format
pub fn to_text(&self) -> String {
let mut lines = String::new();
for message in self.messages.iter() {
lines.push_str(&message.to_text());
}
format!("<chat_history>{lines}</chat_history>")
}
/// Will append a message to the context. This method always assumes tools
/// are supported and uses the appropriate format. For models that don't
/// support tools, use the TransformToolCalls transformer to convert the
/// context afterward.
#[allow(clippy::too_many_arguments)]
pub fn append_message(
self,
content: impl ToString,
thought_signature: Option<String>,
reasoning: Option<String>,
reasoning_details: Option<Vec<ReasoningFull>>,
usage: Usage,
tool_records: Vec<(ToolCallFull, ToolResult)>,
phase: Option<MessagePhase>,
) -> Self {
// Convert flat reasoning string to reasoning_details only when no structured
// reasoning_details are present. When reasoning_details already exists it
// already contains the text (with its cryptographic signature), so adding
// another entry from the raw `reasoning` string would produce a duplicate
// thinking block with a null signature, which Anthropic rejects.
let merged_reasoning_details = match (reasoning, reasoning_details) {
(_, Some(details)) => Some(details),
(Some(reasoning_text), None) => Some(vec![ReasoningFull {
text: Some(reasoning_text),
type_of: Some("reasoning.text".to_string()),
..Default::default()
}]),
(None, None) => None,
};
// Adding tool calls
let mut message: MessageEntry = ContextMessage::assistant(
content,
thought_signature,
merged_reasoning_details,
Some(
tool_records
.iter()
.map(|record| record.0.clone())
.collect::<Vec<_>>(),
),
)
.into();
// Set phase on the assistant TextMessage if provided
if let ContextMessage::Text(ref mut text_msg) = message.message {
text_msg.phase = phase;
}
let tool_results = tool_records
.iter()
.map(|record| record.1.clone())
.collect::<Vec<_>>();
self.add_entry(message.usage(usage))
.add_tool_results(tool_results)
}
/// Returns the token count for context
pub fn token_count(&self) -> TokenCount {
let actual = self
.messages
.last()
.as_ref()
.and_then(|u| u.usage)
.map(|u| u.total_tokens)
.unwrap_or_default();
match actual {
TokenCount::Actual(actual) if actual > 0 => TokenCount::Actual(actual),
_ => TokenCount::Approx(self.token_count_approx()),
}
}
pub fn token_count_approx(&self) -> usize {
self.messages
.iter()
.map(|m| m.token_count_approx())
.sum::<usize>()
}
/// Checks if reasoning is enabled by user or not.
pub fn is_reasoning_supported(&self) -> bool {
self.reasoning.as_ref().is_some_and(|reasoning| {
// `Effort::None` is a strong opt-out that wins over `enabled` and
// `max_tokens`.
if matches!(reasoning.effort, Some(crate::Effort::None)) {
return false;
}
// When enabled parameter is defined then return it's value directly.
if reasoning.enabled.is_some() {
return reasoning.enabled.unwrap_or_default();
}
// If not defined (None), check other parameters
reasoning.effort.is_some() || reasoning.max_tokens.is_some_and(|token| token > 0)
})
}
/// Returns a vector of user messages, selecting the first message from
/// each consecutive sequence of user messages.
pub fn first_user_messages(&self) -> Vec<&ContextMessage> {
if self.messages.is_empty() {
return Vec::new();
}
let mut result = Vec::new();
let mut is_user = false;
for msg in &self.messages {
if msg.has_role(Role::User) {
// Only add the first message of each consecutive user sequence
if !is_user {
result.push(&**msg);
is_user = true;
}
} else {
is_user = false;
}
}
result
}
/// Returns the total number of messages in the context
pub fn total_messages(&self) -> usize {
self.messages.len()
}
/// Returns the count of user messages in the context
pub fn user_message_count(&self) -> usize {
self.messages
.iter()
.filter(|msg| msg.has_role(Role::User))
.count()
}
/// Returns the count of assistant messages in the context
pub fn assistant_message_count(&self) -> usize {
self.messages
.iter()
.filter(|msg| msg.has_role(Role::Assistant))
.count()
}
/// Returns the total count of tool calls across all messages
pub fn tool_call_count(&self) -> usize {
self.messages
.iter()
.filter(|msg| msg.has_tool_call())
.map(|msg| {
if let ContextMessage::Text(text_msg) = &**msg {
text_msg.tool_calls.as_ref().map_or(0, |calls| calls.len())
} else {
0
}
})
.sum()
}
/// Checks if the model has changed from the previous assistant message.
/// Returns true if the previous assistant message has a different model
/// than the provided current_model, or if there is no previous
/// assistant message with a model.
///
/// This is used to determine whether to apply reasoning normalization - we
/// only want to strip reasoning when switching models, not when
/// continuing with the same model.
pub fn has_model_changed(&self, current_model: &ModelId) -> bool {
// Find the last assistant message with a model field
let last_assistant_model = self.messages.iter().rev().find_map(|msg| {
if let ContextMessage::Text(text_msg) = &**msg
&& text_msg.has_role(Role::Assistant)
{
return text_msg.model.as_ref();
}
None
});
// If there's no previous assistant model, consider it as changed
// If there is a previous model, check if it differs from current
match last_assistant_model {
None => true,
Some(prev_model) => prev_model != current_model,
}
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum TokenCount {
Actual(usize),
Approx(usize),
}
impl Display for TokenCount {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenCount::Actual(count) => write!(f, "{count}"),
TokenCount::Approx(count) => write!(f, "~{count}"),
}
}
}
impl std::ops::Add for TokenCount {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
match (self, other) {
(TokenCount::Actual(a), TokenCount::Actual(b)) => TokenCount::Actual(a + b),
(TokenCount::Approx(a), TokenCount::Approx(b)) => TokenCount::Approx(a + b),
(TokenCount::Actual(a), TokenCount::Approx(b)) => TokenCount::Approx(a + b),
(TokenCount::Approx(a), TokenCount::Actual(b)) => TokenCount::Approx(a + b),
}
}
}
impl Default for TokenCount {
fn default() -> Self {
TokenCount::Actual(0)
}
}
impl TokenCount {
/// Returns the larger of two TokenCount values by their inner count.
/// If both are `Actual`, the result is `Actual`. If either is `Approx`,
/// the result is `Approx`.
pub fn max(self, other: TokenCount) -> TokenCount {
use TokenCount::*;
match (self, other) {
(Actual(a), Actual(b)) => Actual(a.max(b)),
(Actual(a), Approx(b)) => Approx(a.max(b)),
(Approx(a), Actual(b)) => Approx(a.max(b)),
(Approx(a), Approx(b)) => Approx(a.max(b)),
}
}
}
impl Deref for TokenCount {
type Target = usize;
fn deref(&self) -> &Self::Target {
match self {
TokenCount::Actual(i) => i,
TokenCount::Approx(i) => i,
}
}
}
#[cfg(test)]
mod tests {
use insta::assert_yaml_snapshot;
use pretty_assertions::assert_eq;
use super::*;
use crate::transformer::Transformer;
use crate::{DirectoryEntry, FileInfo, estimate_token_count};
#[test]
fn test_override_system_message() {
let request = Context::default()
.add_message(ContextMessage::system("Initial system message"))
.set_system_messages(vec!["Updated system message"]);
assert_eq!(
request.messages[0],
ContextMessage::system("Updated system message").into(),
);
}
#[test]
fn test_set_system_message() {
let request = Context::default().set_system_messages(vec!["A system message"]);
assert_eq!(
request.messages[0],
ContextMessage::system("A system message").into(),
);
}
#[test]
fn test_insert_system_message() {
let model = ModelId::new("test-model");
let request = Context::default()
.add_message(ContextMessage::user("Do something", Some(model)))
.set_system_messages(vec!["A system message"]);
assert_eq!(
request.messages[0],
ContextMessage::system("A system message").into(),
);
}
/// Regression test for #2894: chat templates such as Qwen3.5/3.6 (used by
/// llama.cpp and vLLM) only allow a single system message at
/// `messages[0]` and raise `raise_exception('System message must be at the
/// beginning.')` for any additional one. Therefore `set_system_messages`
/// must always produce exactly one system message in the context, no
/// matter how many entries are passed in.
#[test]
fn test_set_system_messages_collapses_into_single_message() {
// Fixture: multiple distinct system message blocks (mirroring what
// `system_prompt.rs` passes: the static agent prompt + the
// non-static agent template).
let request = Context::default().set_system_messages(vec![
"Static agent prompt",
"Non-static agent template",
]);
let expected = ContextMessage::system("Static agent prompt\n\nNon-static agent template")
.into();
// The first message must be the single, combined system message.
assert_eq!(request.messages[0], expected);
// And there must be exactly one system message in the whole context.
let system_count = request
.messages
.iter()
.filter(|m| m.has_role(Role::System))
.count();
assert_eq!(system_count, 1);
}
/// Regression test for #2894: when called on a context that already
/// contains a pre-existing system message (e.g. an injected one from
/// earlier in the pipeline), the call must replace ALL of them with a
/// single combined message — never append a second one.
#[test]
fn test_set_system_messages_replaces_existing_single_system_message() {
let model = ModelId::new("test-model");
let request = Context::default()
.add_message(ContextMessage::system("Pre-existing system message"))
.add_message(ContextMessage::user("Do something", Some(model)))
.set_system_messages(vec!["First", "Second"]);
// The pre-existing system message must have been replaced (not
// retained or duplicated).
let system_count = request
.messages
.iter()
.filter(|m| m.has_role(Role::System))
.count();
assert_eq!(system_count, 1);
// The single remaining system message must be the combined payload.
assert_eq!(
request.messages[0],
ContextMessage::system("First\n\nSecond").into(),
);
}
#[test]
fn test_estimate_token_count() {
// Create a context with some messages
let model = ModelId::new("test-model");
let context = Context::default()
.add_message(ContextMessage::system("System message"))
.add_message(ContextMessage::user("User message", model.into()))
.add_message(ContextMessage::assistant(
"Assistant message",
None,
None,
None,
));
// Get the token count
let token_count = estimate_token_count(context.to_text().len());
// Validate the token count is reasonable
// The exact value will depend on the implementation of estimate_token_count
assert!(token_count > 0, "Token count should be greater than 0");
}
#[test]
fn test_update_image_tool_calls_empty_context() {
let fixture = Context::default();
let mut transformer = crate::transformer::ImageHandling::new();
let actual = transformer.transform(fixture);
assert_yaml_snapshot!(actual);
}
#[test]
fn test_update_image_tool_calls_no_tool_results() {
let fixture = Context::default()
.add_message(ContextMessage::system("System message"))
.add_message(ContextMessage::user("User message", None))
.add_message(ContextMessage::assistant(
"Assistant message",
None,
None,
None,
));
let mut transformer = crate::transformer::ImageHandling::new();
let actual = transformer.transform(fixture);
assert_yaml_snapshot!(actual);
}
#[test]
fn test_update_image_tool_calls_tool_results_no_images() {
let fixture = Context::default()
.add_message(ContextMessage::system("System message"))
.add_tool_results(vec![
ToolResult {
name: crate::ToolName::new("text_tool"),
call_id: Some(crate::ToolCallId::new("call1")),
output: crate::ToolOutput::text("Text output".to_string()),
},
ToolResult {
name: crate::ToolName::new("empty_tool"),
call_id: Some(crate::ToolCallId::new("call2")),
output: crate::ToolOutput {
values: vec![crate::ToolValue::Empty],
is_error: false,
},
},
]);
let mut transformer = crate::transformer::ImageHandling::new();
let actual = transformer.transform(fixture);
assert_yaml_snapshot!(actual);
}
#[test]
fn test_update_image_tool_calls_single_image() {
let image = Image::new_base64("test123".to_string(), "image/png");