diff --git a/autogen/agentchat/contrib/capabilities/transforms.py b/autogen/agentchat/contrib/capabilities/transforms.py index 7893f76e540..ad00d7380db 100644 --- a/autogen/agentchat/contrib/capabilities/transforms.py +++ b/autogen/agentchat/contrib/capabilities/transforms.py @@ -102,6 +102,9 @@ def apply_transform(self, messages: List[Dict]) -> List[Dict]: if remaining_count == 0: break + if not transforms_util.is_tool_call_valid(truncated_messages): + truncated_messages.pop() + return truncated_messages def get_logs(self, pre_transform_messages: List[Dict], post_transform_messages: List[Dict]) -> Tuple[str, bool]: @@ -229,6 +232,9 @@ def apply_transform(self, messages: List[Dict]) -> List[Dict]: processed_messages_tokens += msg_tokens processed_messages.insert(0, msg) + if not transforms_util.is_tool_call_valid(processed_messages): + processed_messages.pop() + return processed_messages def get_logs(self, pre_transform_messages: List[Dict], post_transform_messages: List[Dict]) -> Tuple[str, bool]: diff --git a/autogen/agentchat/contrib/capabilities/transforms_util.py b/autogen/agentchat/contrib/capabilities/transforms_util.py index 8678dec654c..f6ed5f732ee 100644 --- a/autogen/agentchat/contrib/capabilities/transforms_util.py +++ b/autogen/agentchat/contrib/capabilities/transforms_util.py @@ -112,3 +112,7 @@ def should_transform_message(message: Dict[str, Any], filter_dict: Optional[Dict return True return len(filter_config([message], filter_dict, exclude)) > 0 + + +def is_tool_call_valid(messages: List[Dict[str, Any]]) -> bool: + return messages[0].get("role") != "tool"