From 372874fb3a0fce7359954926ca7bdf3262e7ef17 Mon Sep 17 00:00:00 2001 From: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com> Date: Wed, 4 Jun 2025 06:47:15 -0700 Subject: [PATCH] agent add knowledge sources fix and test (#2948) --- src/crewai/agent.py | 45 ++++++++++++++++++++++++++++++++------------- tests/agent_test.py | 16 +++++++++------- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/src/crewai/agent.py b/src/crewai/agent.py index 9a7373336..c4be058ec 100644 --- a/src/crewai/agent.py +++ b/src/crewai/agent.py @@ -200,6 +200,7 @@ class Agent(BaseAgent): collection_name=self.role, storage=self.knowledge_storage or None, ) + self.knowledge.add_sources() except (TypeError, ValueError) as e: raise ValueError(f"Invalid Knowledge Configuration: {str(e)}") @@ -243,21 +244,28 @@ class Agent(BaseAgent): """ if self.reasoning: try: - from crewai.utilities.reasoning_handler import AgentReasoning, AgentReasoningOutput - + from crewai.utilities.reasoning_handler import ( + AgentReasoning, + AgentReasoningOutput, + ) + reasoning_handler = AgentReasoning(task=task, agent=self) - reasoning_output: AgentReasoningOutput = reasoning_handler.handle_agent_reasoning() - + reasoning_output: AgentReasoningOutput = ( + reasoning_handler.handle_agent_reasoning() + ) + # Add the reasoning plan to the task description task.description += f"\n\nReasoning Plan:\n{reasoning_output.plan.plan}" except Exception as e: - if hasattr(self, '_logger'): - self._logger.log("error", f"Error during reasoning process: {str(e)}") + if hasattr(self, "_logger"): + self._logger.log( + "error", f"Error during reasoning process: {str(e)}" + ) else: print(f"Error during reasoning process: {str(e)}") - + self._inject_date_to_task(task) - + if self.tools_handler: self.tools_handler.last_used_tool = {} # type: ignore # Incompatible types in assignment (expression has type "dict[Never, Never]", variable has type "ToolCalling") @@ -622,22 +630,33 @@ class Agent(BaseAgent): """Inject the current date into the task description if inject_date is enabled.""" if self.inject_date: from datetime import datetime + try: - valid_format_codes = ['%Y', '%m', '%d', '%H', '%M', '%S', '%B', '%b', '%A', '%a'] + valid_format_codes = [ + "%Y", + "%m", + "%d", + "%H", + "%M", + "%S", + "%B", + "%b", + "%A", + "%a", + ] is_valid = any(code in self.date_format for code in valid_format_codes) - + if not is_valid: raise ValueError(f"Invalid date format: {self.date_format}") - + current_date: str = datetime.now().strftime(self.date_format) task.description += f"\n\nCurrent Date: {current_date}" except Exception as e: - if hasattr(self, '_logger'): + if hasattr(self, "_logger"): self._logger.log("warning", f"Failed to inject date: {str(e)}") else: print(f"Warning: Failed to inject date: {str(e)}") - def _validate_docker_installation(self) -> None: """Check if Docker is installed and running.""" if not shutil.which("docker"): diff --git a/tests/agent_test.py b/tests/agent_test.py index 800860c9f..22748ab2e 100644 --- a/tests/agent_test.py +++ b/tests/agent_test.py @@ -309,7 +309,9 @@ def test_cache_hitting(): def handle_tool_end(source, event): received_events.append(event) - with (patch.object(CacheHandler, "read") as read,): + with ( + patch.object(CacheHandler, "read") as read, + ): read.return_value = "0" task = Task( description="What is 2 times 6? Ignore correctness and just return the result of the multiplication tool, you must use the tool.", @@ -1628,13 +1630,13 @@ def test_agent_execute_task_with_ollama(): @pytest.mark.vcr(filter_headers=["authorization"]) def test_agent_with_knowledge_sources(): - # Create a knowledge source with some content content = "Brandon's favorite color is red and he likes Mexican food." string_source = StringKnowledgeSource(content=content) with patch("crewai.knowledge") as MockKnowledge: mock_knowledge_instance = MockKnowledge.return_value mock_knowledge_instance.sources = [string_source] mock_knowledge_instance.search.return_value = [{"content": content}] + MockKnowledge.add_sources.return_value = [string_source] agent = Agent( role="Information Agent", @@ -1644,7 +1646,6 @@ def test_agent_with_knowledge_sources(): knowledge_sources=[string_source], ) - # Create a task that requires the agent to use the knowledge task = Task( description="What is Brandon's favorite color?", expected_output="Brandon's favorite color.", @@ -1652,10 +1653,11 @@ def test_agent_with_knowledge_sources(): ) crew = Crew(agents=[agent], tasks=[task]) - result = crew.kickoff() - - # Assert that the agent provides the correct information - assert "red" in result.raw.lower() + with patch.object(Knowledge, "add_sources") as mock_add_sources: + result = crew.kickoff() + assert mock_add_sources.called, "add_sources() should have been called" + mock_add_sources.assert_called_once() + assert "red" in result.raw.lower() @pytest.mark.vcr(filter_headers=["authorization"])