1use crate::error::{Error, Result};
2use crate::types::{ChatRequest, Message, Part, ProviderStateFormat, Role, ToolResult, ToolSpec};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum Protocol {
7 OpenAiChat,
9 OpenAiResponses,
11 AnthropicMessages,
13 GeminiGenerateContent,
15}
16
17impl Protocol {
18 pub fn provider_state_format(self) -> ProviderStateFormat {
21 match self {
22 Self::OpenAiChat => ProviderStateFormat::OpenAiChat,
23 Self::OpenAiResponses => ProviderStateFormat::OpenAiResponses,
24 Self::AnthropicMessages => ProviderStateFormat::AnthropicMessages,
25 Self::GeminiGenerateContent => ProviderStateFormat::GeminiGenerateContent,
26 }
27 }
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum ExternalRole {
33 System,
34 Developer,
40 User,
41 Assistant,
42 Tool,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum OrphanToolResultPolicy {
48 Drop,
50 DowngradeToUser,
52 Error,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum MissingToolResultPolicy {
59 Synthesize,
61 DropToolCall,
63 Error,
65}
66
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
69pub enum SystemPlacement {
70 #[default]
73 MergeIntoTop,
74 FirstToTopRestInPlace,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct NormalizeOptions {
86 pub protocol: Protocol,
88 pub developer_to_system: bool,
91 pub custom_to_user: bool,
93 pub orphan_tool_result: OrphanToolResultPolicy,
96 pub missing_tool_result: MissingToolResultPolicy,
99 pub merge_adjacent_same_role: bool,
102 pub system_placement: SystemPlacement,
104 pub preserve_foreign_reasoning: bool,
109}
110
111impl NormalizeOptions {
112 pub fn for_protocol(protocol: Protocol) -> Self {
118 let merge_adjacent_same_role = matches!(
119 protocol,
120 Protocol::AnthropicMessages | Protocol::GeminiGenerateContent
121 );
122
123 Self {
124 protocol,
125 developer_to_system: true,
126 custom_to_user: true,
127 orphan_tool_result: OrphanToolResultPolicy::Drop,
128 missing_tool_result: MissingToolResultPolicy::Synthesize,
129 merge_adjacent_same_role,
130 preserve_foreign_reasoning: false,
131 system_placement: SystemPlacement::MergeIntoTop,
132 }
133 }
134}
135
136#[derive(Debug, Clone, PartialEq)]
138pub struct NormalizedMessage {
139 pub role: ExternalRole,
141 pub parts: Vec<Part>,
143}
144
145#[derive(Debug, Clone, PartialEq)]
147pub struct NormalizedChat {
148 pub system: Option<String>,
152 pub messages: Vec<NormalizedMessage>,
154 pub tools: Vec<ToolSpec>,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum NormalizeAction {
161 DowngradedDeveloper,
163 DowngradedCustomRole {
165 role: String,
167 },
168 AssignedToolCallId {
170 name: String,
172 id: String,
174 },
175 FilledToolResultId {
178 name: String,
180 id: String,
182 },
183 ReconciledToolResultId {
187 name: String,
189 from: String,
191 to: String,
193 },
194 FlattenedToolCallIntoText {
197 name: String,
199 },
200 FlattenedToolResultIntoText {
203 name: String,
205 },
206 DroppedOrphanToolResult {
209 name: String,
211 },
212 SynthesizedMissingToolResult {
215 call_id: String,
217 name: String,
219 },
220 DroppedUnpairedToolCall {
223 call_id: String,
225 name: String,
227 },
228 DroppedForeignReasoning {
231 format: ProviderStateFormat,
233 expected: ProviderStateFormat,
235 },
236 DroppedForeignToolState {
239 format: ProviderStateFormat,
241 expected: ProviderStateFormat,
243 },
244 DroppedForeignTextState {
247 format: ProviderStateFormat,
249 expected: ProviderStateFormat,
251 },
252 DroppedForeignProviderItem {
254 format: ProviderStateFormat,
256 expected: ProviderStateFormat,
258 },
259 DroppedReasoningFromNonAssistant {
261 role: ExternalRole,
263 },
264 MergedAdjacent {
266 role: ExternalRole,
268 },
269}
270
271#[derive(Debug, Clone, Default, PartialEq, Eq)]
273pub struct NormalizeReport {
274 pub actions: Vec<NormalizeAction>,
276}
277
278impl NormalizeReport {
279 pub fn is_clean(&self) -> bool {
281 self.actions.is_empty()
282 }
283
284 pub fn stats(&self) -> NormalizeStats {
290 let mut stats = NormalizeStats::default();
291 for action in &self.actions {
292 stats.total += 1;
293 match action {
294 NormalizeAction::DowngradedDeveloper => stats.downgraded_developer += 1,
295 NormalizeAction::DowngradedCustomRole { .. } => {
296 stats.downgraded_custom_role += 1;
297 }
298 NormalizeAction::AssignedToolCallId { .. } => stats.assigned_tool_call_id += 1,
299 NormalizeAction::FilledToolResultId { .. } => stats.filled_tool_result_id += 1,
300 NormalizeAction::ReconciledToolResultId { .. } => {
301 stats.reconciled_tool_result_id += 1;
302 }
303 NormalizeAction::FlattenedToolCallIntoText { .. } => {
304 stats.flattened_tool_call += 1;
305 }
306 NormalizeAction::FlattenedToolResultIntoText { .. } => {
307 stats.flattened_tool_result += 1;
308 }
309 NormalizeAction::DroppedOrphanToolResult { .. } => {
310 stats.dropped_orphan_tool_result += 1;
311 }
312 NormalizeAction::SynthesizedMissingToolResult { .. } => {
313 stats.synthesized_missing_tool_result += 1;
314 }
315 NormalizeAction::DroppedUnpairedToolCall { .. } => {
316 stats.dropped_unpaired_tool_call += 1;
317 }
318 NormalizeAction::DroppedForeignReasoning { .. } => {
319 stats.dropped_foreign_reasoning += 1;
320 }
321 NormalizeAction::DroppedForeignToolState { .. } => {
322 stats.dropped_foreign_tool_state += 1;
323 }
324 NormalizeAction::DroppedForeignTextState { .. } => {
325 stats.dropped_foreign_text_state += 1;
326 }
327 NormalizeAction::DroppedForeignProviderItem { .. } => {
328 stats.dropped_foreign_provider_item += 1;
329 }
330 NormalizeAction::DroppedReasoningFromNonAssistant { .. } => {
331 stats.dropped_reasoning_from_non_assistant += 1;
332 }
333 NormalizeAction::MergedAdjacent { .. } => stats.merged_adjacent += 1,
334 }
335 }
336 stats
337 }
338}
339
340#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
342pub struct NormalizeStats {
343 pub total: u32,
345 pub downgraded_developer: u32,
347 pub downgraded_custom_role: u32,
349 pub assigned_tool_call_id: u32,
351 pub filled_tool_result_id: u32,
353 pub reconciled_tool_result_id: u32,
356 pub flattened_tool_call: u32,
358 pub flattened_tool_result: u32,
360 pub dropped_orphan_tool_result: u32,
362 pub synthesized_missing_tool_result: u32,
364 pub dropped_unpaired_tool_call: u32,
366 pub dropped_foreign_reasoning: u32,
368 pub dropped_foreign_tool_state: u32,
370 pub dropped_foreign_text_state: u32,
372 pub dropped_foreign_provider_item: u32,
374 pub dropped_reasoning_from_non_assistant: u32,
376 pub merged_adjacent: u32,
378}
379
380impl NormalizeStats {
381 pub const fn is_clean(self) -> bool {
383 self.total == 0
384 }
385}
386
387#[derive(Debug, Clone)]
388struct PendingCall {
389 id: String,
390 name: String,
391 message_index: usize,
392 fulfilled: bool,
393 synthetic: bool,
397 native: bool,
398}
399
400pub fn normalize(
407 request: &ChatRequest,
408 protocol: Protocol,
409) -> Result<(NormalizedChat, NormalizeReport)> {
410 normalize_with_options(request, NormalizeOptions::for_protocol(protocol))
411}
412
413pub fn normalize_with_options(
426 request: &ChatRequest,
427 options: NormalizeOptions,
428) -> Result<(NormalizedChat, NormalizeReport)> {
429 if request.messages.iter().any(|message| {
430 message.role != Role::Assistant
431 && message
432 .parts
433 .iter()
434 .any(|part| matches!(part, Part::NativeToolCall(_)))
435 }) {
436 return Err(Error::Normalize(
437 "tool_identity_conflict: native calls require assistant role".into(),
438 ));
439 }
440 if !request.tool_declarations.is_empty() {
441 let mut declarations: Vec<_> = request
442 .tools
443 .iter()
444 .cloned()
445 .map(|tool| crate::types::ToolDeclaration::Tool { tool: tool.into() })
446 .collect();
447 declarations.extend(request.tool_declarations.iter().cloned());
448 crate::types::validate_tool_declarations(&declarations)?;
449 if options.protocol != Protocol::OpenAiResponses {
450 return Err(Error::Unsupported(format!(
451 "unsupported_tool_representation: native tool declarations require Responses, got {:?}",
452 options.protocol
453 )));
454 }
455 }
456 let expected_reasoning_format = options.protocol.provider_state_format();
457 let occupied_call_ids = request
458 .messages
459 .iter()
460 .flat_map(|message| &message.parts)
461 .filter_map(|part| match part {
462 Part::ToolCall(call) => call.id.clone(),
463 Part::NativeToolCall(call) => Some(call.call_id.clone()),
464 _ => None,
465 })
466 .collect();
467 let mut normalizer = Normalizer {
468 options,
469 report: NormalizeReport::default(),
470 system: Vec::new(),
471 messages: Vec::new(),
472 pending_calls: Vec::new(),
473 next_call_id: 1,
474 occupied_call_ids,
475 seen_call_ids: std::collections::HashSet::new(),
476 seen_native_ids: std::collections::HashSet::new(),
477 expected_reasoning_format,
478 top_taken: false,
479 };
480
481 for message in &request.messages {
482 normalizer.push(message)?;
483 }
484 normalizer.finish_pending_calls()?;
485 normalizer.merge_adjacent_messages();
486
487 Ok((
488 NormalizedChat {
489 system: normalizer.join_system(),
490 messages: normalizer.messages,
491 tools: request.tools.clone(),
492 },
493 normalizer.report,
494 ))
495}
496
497struct Normalizer {
498 options: NormalizeOptions,
499 report: NormalizeReport,
500 system: Vec<String>,
501 messages: Vec<NormalizedMessage>,
502 pending_calls: Vec<PendingCall>,
503 next_call_id: u64,
504 occupied_call_ids: std::collections::HashSet<String>,
505 seen_call_ids: std::collections::HashSet<String>,
506 seen_native_ids: std::collections::HashSet<String>,
507 expected_reasoning_format: ProviderStateFormat,
508 top_taken: bool,
511}
512
513impl Normalizer {
514 fn push(&mut self, message: &Message) -> Result<()> {
515 match &message.role {
516 Role::System => {
517 if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace
518 && self.top_taken
519 {
520 self.place_in_place(message, ExternalRole::System);
521 return Ok(());
522 }
523 if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace {
524 self.top_taken = true;
525 }
526 self.push_system(message);
527 Ok(())
528 }
529 Role::Developer => {
530 if self.options.system_placement == SystemPlacement::FirstToTopRestInPlace {
531 self.place_in_place(message, ExternalRole::Developer);
532 return Ok(());
533 }
534 self.report
535 .actions
536 .push(NormalizeAction::DowngradedDeveloper);
537 if self.options.developer_to_system {
538 self.push_system(message);
539 } else {
540 self.push_user(message);
541 }
542 Ok(())
543 }
544 Role::Custom(role) => {
545 self.report
546 .actions
547 .push(NormalizeAction::DowngradedCustomRole { role: role.clone() });
548 if self.options.custom_to_user {
549 self.push_user(message);
550 } else {
551 self.push_system(message);
552 }
553 Ok(())
554 }
555 Role::User => {
556 self.finish_pending_calls()?;
557 self.push_user(message);
558 Ok(())
559 }
560 Role::Assistant => {
561 self.finish_pending_calls()?;
562 self.push_assistant(message)
563 }
564 Role::Tool => self.push_tool(message),
565 }
566 }
567
568 fn push_system(&mut self, message: &Message) {
569 self.report_non_assistant_reasoning(ExternalRole::System, &message.parts);
570 let text = text_parts_joined(&message.parts);
571 if !text.is_empty() {
572 self.system.push(text);
573 }
574 }
575
576 fn place_in_place(&mut self, message: &Message, role: ExternalRole) {
577 self.report_non_assistant_reasoning(role.clone(), &message.parts);
578 let parts = normalize_non_tool_parts(&message.parts, &mut self.report);
579 if !parts.is_empty() {
580 self.messages.push(NormalizedMessage { role, parts });
581 }
582 }
583
584 fn push_user(&mut self, message: &Message) {
585 self.report_non_assistant_reasoning(ExternalRole::User, &message.parts);
586 let parts = normalize_non_tool_parts(&message.parts, &mut self.report);
587 if !parts.is_empty() {
588 self.messages.push(NormalizedMessage {
589 role: ExternalRole::User,
590 parts,
591 });
592 }
593 }
594
595 fn push_assistant(&mut self, message: &Message) -> Result<()> {
596 let pending_start = self.pending_calls.len();
597 let mut parts = Vec::new();
598
599 for part in &message.parts {
600 match part {
601 Part::Text {
602 text,
603 provider_state,
604 } => {
605 let text = text.clone();
606 let mut provider_state = provider_state.clone();
607 if !self.options.preserve_foreign_reasoning
608 && let Some(state) = &provider_state
609 && state.format != self.expected_reasoning_format
610 {
611 self.report
612 .actions
613 .push(NormalizeAction::DroppedForeignTextState {
614 format: state.format.clone(),
615 expected: self.expected_reasoning_format.clone(),
616 });
617 provider_state = None;
618 }
619 parts.push(Part::Text {
620 text,
621 provider_state,
622 });
623 }
624 Part::ImageUrl { .. } | Part::Image { .. } => parts.push(part.clone()),
625 Part::Reasoning(reasoning) => {
626 if !self.options.preserve_foreign_reasoning
627 && let Some(state) = &reasoning.state
628 && state.format != self.expected_reasoning_format
629 {
630 self.report
631 .actions
632 .push(NormalizeAction::DroppedForeignReasoning {
633 format: state.format.clone(),
634 expected: self.expected_reasoning_format.clone(),
635 });
636 continue;
637 }
638 parts.push(Part::Reasoning(reasoning.clone()));
639 }
640 Part::ToolCall(call) => {
641 let mut call = call.clone();
642 if !self.options.preserve_foreign_reasoning
643 && let Some(state) = &call.provider_state
644 && state.format != self.expected_reasoning_format
645 {
646 self.report
647 .actions
648 .push(NormalizeAction::DroppedForeignToolState {
649 format: state.format.clone(),
650 expected: self.expected_reasoning_format.clone(),
651 });
652 call.provider_state = None;
653 }
654 let mut synthetic_id = false;
655 if call.id.is_none() {
656 let id = loop {
657 let id = format!("call_{}", self.next_call_id);
658 self.next_call_id += 1;
659 if self.occupied_call_ids.insert(id.clone()) {
660 break id;
661 }
662 };
663 call.id = Some(id.clone());
664 synthetic_id = true;
665 self.report
666 .actions
667 .push(NormalizeAction::AssignedToolCallId {
668 name: call.name.clone(),
669 id: id.clone(),
670 });
671 }
672
673 let id = call.id.clone().expect("id was assigned above");
674 if id.trim().is_empty() || !self.seen_call_ids.insert(id.clone()) {
675 return Err(Error::Normalize(
676 "tool call IDs must be non-empty and unique".into(),
677 ));
678 }
679 self.pending_calls.push(PendingCall {
680 id: id.clone(),
681 name: call.name.clone(),
682 message_index: usize::MAX,
684 fulfilled: false,
685 synthetic: synthetic_id,
686 native: false,
687 });
688 parts.push(Part::ToolCall(call));
689 }
690 Part::NativeToolCall(call) => {
691 if self.options.protocol != Protocol::OpenAiResponses {
692 return Err(Error::Unsupported("unsupported_tool_representation: native tool history requires Responses".into()));
693 }
694 call.validate_completed()?;
695 if !self.seen_call_ids.insert(call.call_id.clone()) {
696 return Err(Error::Normalize(
697 "tool_identity_conflict: duplicate call_id".into(),
698 ));
699 }
700 self.seen_native_ids.insert(call.call_id.clone());
701 self.pending_calls.push(PendingCall {
702 id: call.call_id.clone(),
703 name: call.name.clone(),
704 message_index: usize::MAX,
705 fulfilled: false,
706 synthetic: false,
707 native: true,
708 });
709 parts.push(part.clone());
710 }
711 Part::ToolResult(result) => {
712 self.handle_orphan_tool_result(result)?;
714 }
715 Part::ProviderItem(item) => {
716 if item.provider_state.format == ProviderStateFormat::OpenAiResponses
717 && matches!(
718 item.provider_state
719 .data
720 .get("type")
721 .and_then(serde_json::Value::as_str),
722 Some(
723 "custom_tool_call"
724 | "function_call"
725 | "custom_tool_call_output"
726 | "function_call_output"
727 )
728 )
729 {
730 return Err(Error::Normalize("unsupported_tool_representation: client tool calls and results must use typed parts".into()));
731 }
732 if self.options.preserve_foreign_reasoning
733 || item.provider_state.format == self.expected_reasoning_format
734 {
735 parts.push(part.clone());
736 } else {
737 self.report
738 .actions
739 .push(NormalizeAction::DroppedForeignProviderItem {
740 format: item.provider_state.format.clone(),
741 expected: self.expected_reasoning_format.clone(),
742 });
743 }
744 }
745 }
746 }
747
748 if !parts.is_empty() {
749 let message_index = self.messages.len();
750 self.messages.push(NormalizedMessage {
751 role: ExternalRole::Assistant,
752 parts,
753 });
754 for pending in &mut self.pending_calls[pending_start..] {
755 pending.message_index = message_index;
756 }
757 }
758
759 Ok(())
760 }
761
762 fn push_tool(&mut self, message: &Message) -> Result<()> {
763 self.report_non_assistant_reasoning(ExternalRole::Tool, &message.parts);
764 let mut accepted = Vec::new();
765
766 for part in &message.parts {
767 let Part::ToolResult(result) = part else {
768 continue;
769 };
770
771 let Some(index) = self.find_pending_call(result) else {
772 if self.pending_calls.iter().any(|call| call.native)
773 || result
774 .call_id
775 .as_ref()
776 .is_some_and(|id| self.seen_native_ids.contains(id))
777 {
778 return Err(Error::Normalize(
779 "orphan_tool_result: native history requires explicit call_id pairing"
780 .into(),
781 ));
782 }
783 self.handle_orphan_tool_result(result)?;
784 continue;
785 };
786
787 let pending = &mut self.pending_calls[index];
788 pending.fulfilled = true;
789 let call_id = pending.id.clone();
790 let name = pending.name.clone();
791
792 let mut result = result.clone();
793 let previous_id = result.call_id.clone();
794 if previous_id.as_deref() != Some(call_id.as_str()) {
795 result.call_id = Some(call_id.clone());
796 self.report.actions.push(match previous_id {
797 None => NormalizeAction::FilledToolResultId {
798 name: result.name.clone(),
799 id: call_id.clone(),
800 },
801 Some(previous) => NormalizeAction::ReconciledToolResultId {
802 name: result.name.clone(),
803 from: previous,
804 to: call_id.clone(),
805 },
806 });
807 }
808 result.name = name;
809 accepted.push(Part::ToolResult(result));
810 }
811
812 if !accepted.is_empty() {
813 self.messages.push(NormalizedMessage {
814 role: ExternalRole::Tool,
815 parts: accepted,
816 });
817 }
818
819 Ok(())
820 }
821
822 fn report_non_assistant_reasoning(&mut self, role: ExternalRole, parts: &[Part]) {
823 if parts.iter().any(|part| matches!(part, Part::Reasoning(_))) {
824 self.report
825 .actions
826 .push(NormalizeAction::DroppedReasoningFromNonAssistant { role });
827 }
828 }
829
830 fn find_pending_call(&self, result: &ToolResult) -> Option<usize> {
831 if let Some(call_id) = &result.call_id {
832 if let Some(index) = self
833 .pending_calls
834 .iter()
835 .position(|call| call.id == *call_id && !call.fulfilled)
836 {
837 return Some(index);
838 }
839
840 if self.seen_native_ids.contains(call_id)
841 || self
842 .pending_calls
843 .iter()
844 .any(|call| call.native && !call.fulfilled)
845 {
846 return None;
847 }
848
849 return self
853 .pending_calls
854 .iter()
855 .position(|call| call.synthetic && call.name == result.name && !call.fulfilled);
856 }
857
858 self.pending_calls
859 .iter()
860 .position(|call| !call.native && call.name == result.name && !call.fulfilled)
861 }
862
863 fn handle_orphan_tool_result(&mut self, result: &ToolResult) -> Result<()> {
864 match self.options.orphan_tool_result {
865 OrphanToolResultPolicy::Drop => {
866 self.report
867 .actions
868 .push(NormalizeAction::DroppedOrphanToolResult {
869 name: result.name.clone(),
870 });
871 Ok(())
872 }
873 OrphanToolResultPolicy::DowngradeToUser => {
874 self.messages.push(NormalizedMessage {
875 role: ExternalRole::User,
876 parts: vec![Part::text(format!(
877 "Orphan tool result from `{}`: {}",
878 result.name, result.content
879 ))],
880 });
881 Ok(())
882 }
883 OrphanToolResultPolicy::Error => Err(Error::Normalize(format!(
884 "tool result `{}` has no matching assistant tool call",
885 result.name
886 ))),
887 }
888 }
889
890 fn finish_pending_calls(&mut self) -> Result<()> {
891 let missing: Vec<(String, String, usize)> = self
892 .pending_calls
893 .iter()
894 .filter(|call| !call.fulfilled)
895 .map(|call| (call.id.clone(), call.name.clone(), call.message_index))
896 .collect();
897
898 if missing.is_empty() {
899 self.pending_calls.clear();
900 return Ok(());
901 }
902
903 if self
904 .pending_calls
905 .iter()
906 .any(|call| call.native && !call.fulfilled)
907 {
908 return Err(Error::Normalize(
909 "tool_call_incomplete: native tool result missing".into(),
910 ));
911 }
912
913 match self.options.missing_tool_result {
914 MissingToolResultPolicy::Synthesize => {
915 let mut results = Vec::new();
916 for (call_id, name, _) in missing {
917 self.report
918 .actions
919 .push(NormalizeAction::SynthesizedMissingToolResult {
920 call_id: call_id.clone(),
921 name: name.clone(),
922 });
923 results.push(Part::ToolResult(ToolResult::error(
924 Some(call_id),
925 name,
926 "missing tool result",
927 )));
928 }
929 self.messages.push(NormalizedMessage {
930 role: ExternalRole::Tool,
931 parts: results,
932 });
933 self.pending_calls.clear();
934 Ok(())
935 }
936 MissingToolResultPolicy::DropToolCall => {
937 for (call_id, name, message_index) in missing {
938 if let Some(message) = self.messages.get_mut(message_index) {
939 message.parts.retain(|part| {
940 !matches!(
941 part,
942 Part::ToolCall(call)
943 if call.id.as_deref() == Some(call_id.as_str())
944 )
945 });
946 }
947 self.report
948 .actions
949 .push(NormalizeAction::DroppedUnpairedToolCall { call_id, name });
950 }
951 self.messages.retain(|message| !message.parts.is_empty());
954 self.pending_calls.clear();
955 Ok(())
956 }
957 MissingToolResultPolicy::Error => Err(Error::Normalize(format!(
958 "{} assistant tool call(s) have no matching tool result",
959 self.pending_calls.iter().filter(|c| !c.fulfilled).count()
960 ))),
961 }
962 }
963
964 fn merge_adjacent_messages(&mut self) {
965 if !self.options.merge_adjacent_same_role {
966 return;
967 }
968
969 let mut merged: Vec<NormalizedMessage> = Vec::with_capacity(self.messages.len());
970 for message in self.messages.drain(..) {
971 if let Some(last) = merged.last_mut()
972 && last.role == message.role
973 {
974 last.parts.extend(message.parts);
975 self.report.actions.push(NormalizeAction::MergedAdjacent {
976 role: last.role.clone(),
977 });
978 } else {
979 merged.push(message);
980 }
981 }
982 self.messages = merged;
983 }
984
985 fn join_system(&self) -> Option<String> {
986 if self.system.is_empty() {
987 None
988 } else {
989 Some(self.system.join("\n\n"))
990 }
991 }
992}
993
994fn text_parts_joined(parts: &[Part]) -> String {
995 parts
996 .iter()
997 .filter_map(|part| match part {
998 Part::Text { text, .. } => Some(text.as_str()),
999 _ => None,
1000 })
1001 .collect::<Vec<_>>()
1002 .join("\n")
1003}
1004
1005fn normalize_non_tool_parts(parts: &[Part], report: &mut NormalizeReport) -> Vec<Part> {
1006 parts
1007 .iter()
1008 .filter_map(|part| match part {
1009 Part::Text { text, .. } => Some(Part::text(text)),
1010 Part::ImageUrl { .. } | Part::Image { .. } => Some(part.clone()),
1011 Part::Reasoning(_) => None,
1012 Part::ToolCall(call) => {
1013 report
1014 .actions
1015 .push(NormalizeAction::FlattenedToolCallIntoText {
1016 name: call.name.clone(),
1017 });
1018 Some(Part::text(format!(
1019 "Unpaired tool call `{}` with arguments {}",
1020 call.name, call.arguments
1021 )))
1022 }
1023 Part::NativeToolCall(_) => None,
1024 Part::ToolResult(result) => {
1025 report
1026 .actions
1027 .push(NormalizeAction::FlattenedToolResultIntoText {
1028 name: result.name.clone(),
1029 });
1030 Some(Part::text(format!(
1031 "Orphan tool result from `{}`: {}",
1032 result.name, result.content
1033 )))
1034 }
1035 Part::ProviderItem(_) => None,
1036 })
1037 .collect()
1038}