From 6bb7acc34df8da9ef845a100859d80040462d743 Mon Sep 17 00:00:00 2001 From: wonderful <3269753363@qq.com> Date: Sun, 12 Nov 2023 02:55:57 +0800 Subject: [PATCH] Handled possible unclear IndexError in ConversableAgent.last_message method (#622) * Handled possible IndexError in ConversableAgent.last_message method with more clear error message and added test in test_conversable_agent.py. * Fix code formatting issues. --------- Co-authored-by: Chi Wang --- autogen/agentchat/conversable_agent.py | 4 ++++ test/agentchat/test_conversable_agent.py | 8 ++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/autogen/agentchat/conversable_agent.py b/autogen/agentchat/conversable_agent.py index 157e11c39bef..3146403ac6b2 100644 --- a/autogen/agentchat/conversable_agent.py +++ b/autogen/agentchat/conversable_agent.py @@ -240,6 +240,10 @@ def last_message(self, agent: Optional[Agent] = None) -> Dict: for conversation in self._oai_messages.values(): return conversation[-1] raise ValueError("More than one conversation is found. Please specify the sender to get the last message.") + if agent not in self._oai_messages.keys(): + raise KeyError( + f"The agent '{agent.name}' is not present in any conversation. No history available for this agent." + ) return self._oai_messages[agent][-1] @property diff --git a/test/agentchat/test_conversable_agent.py b/test/agentchat/test_conversable_agent.py index 2d26027a34ab..4ba92cbc4c6f 100644 --- a/test/agentchat/test_conversable_agent.py +++ b/test/agentchat/test_conversable_agent.py @@ -206,6 +206,10 @@ def test_conversable_agent(): dummy_agent_1.update_system_message("new system message") assert dummy_agent_1.system_message == "new system message" + dummy_agent_3 = ConversableAgent(name="dummy_agent_3", llm_config=False, human_input_mode="TERMINATE") + with pytest.raises(KeyError): + dummy_agent_1.last_message(dummy_agent_3) + def test_generate_reply(): def add_num(num_to_be_added): @@ -242,7 +246,7 @@ async def test_a_generate_reply_raises_on_messages_and_sender_none(conversable_a if __name__ == "__main__": - test_trigger() + # test_trigger() # test_context() # test_max_consecutive_auto_reply() - # test_conversable_agent(pytest.monkeypatch) + test_conversable_agent()