Compare commits

..

2 Commits

Author SHA1 Message Date
Devin AI
b579cb2cce Address code review comments and fix lint error
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-02-25 13:36:50 +00:00
Devin AI
a46fa50f73 Fix issue #2219: Handle callable agents in CrewBase decorator
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-02-25 13:24:35 +00:00
7 changed files with 113 additions and 118 deletions

View File

@@ -134,6 +134,19 @@ class BaseAgent(ABC, BaseModel):
@model_validator(mode="before")
@classmethod
def process_model_config(cls, values):
"""
Process model configuration values.
Args:
values: Configuration values or callable agent
When using CrewBase decorator, this can be a callable that returns an agent
Returns:
Processed configuration or callable agent
"""
# Handle case where values is a function (can happen with CrewBase decorator)
if callable(values) and not isinstance(values, dict):
return values
return process_config(values, cls)
@field_validator("tools")

View File

@@ -65,6 +65,27 @@ def cache_handler(func):
return memoize(func)
def _resolve_agent(task_instance):
"""
Resolve an agent from a task instance.
If the agent is a callable (e.g., a method from CrewBase), call it to get the agent instance.
Args:
task_instance: The task instance containing the agent
Returns:
The resolved agent instance or None if no agent is present
"""
if not hasattr(task_instance, 'agent') or not task_instance.agent:
return None
if callable(task_instance.agent) and not isinstance(task_instance.agent, type):
return task_instance.agent()
return task_instance.agent
def crew(func) -> Callable[..., Crew]:
@wraps(func)
@@ -79,7 +100,14 @@ def crew(func) -> Callable[..., Crew]:
# Instantiate tasks in order
for task_name, task_method in tasks:
# Get the task instance
task_instance = task_method(self)
# Resolve the agent
agent = _resolve_agent(task_instance)
if agent:
task_instance.agent = agent
instantiated_tasks.append(task_instance)
agent_instance = getattr(task_instance, "agent", None)
if agent_instance and agent_instance.role not in agent_roles:

View File

@@ -61,6 +61,25 @@ class Task(BaseModel):
output_pydantic: Pydantic model for task output.
tools: List of tools/resources limited for task execution.
"""
def __init__(self, **data):
# Handle case where agent is a callable (can happen with CrewBase decorator)
if 'agent' in data and callable(data['agent']) and not isinstance(data['agent'], type):
try:
# Call the agent method to get the agent instance
agent = data['agent']()
# Verify that the agent is a valid instance
from crewai.agents.agent_builder.base_agent import BaseAgent
if agent is not None and not isinstance(agent, BaseAgent):
raise ValueError(f"Expected BaseAgent instance, got {type(agent)}")
data['agent'] = agent
except Exception as e:
raise ValueError(f"Failed to initialize agent from callable: {e}")
# Call the parent class __init__ method
super().__init__(**data)
__hash__ = object.__hash__ # type: ignore
logger: ClassVar[logging.Logger] = logging.getLogger(__name__)

View File

@@ -135,42 +135,13 @@ class EmbeddingConfigurator:
)
@staticmethod
def _normalize_api_url(api_url: str) -> str:
"""
Normalize API URL by ensuring it has a protocol.
Args:
api_url: The API URL to normalize
Returns:
Normalized URL with protocol (defaults to http:// if missing)
"""
if not (api_url.startswith("http://") or api_url.startswith("https://")):
return f"http://{api_url}"
return api_url
@staticmethod
def _configure_huggingface(config: dict, model_name: str):
"""
Configure Huggingface embedding function with the provided config.
Args:
config: Configuration dictionary for the Huggingface embedder
model_name: Name of the model to use
Returns:
Configured HuggingFaceEmbeddingServer instance
"""
def _configure_huggingface(config, model_name):
from chromadb.utils.embedding_functions.huggingface_embedding_function import (
HuggingFaceEmbeddingServer,
)
api_url = config.get("api_url")
if api_url:
api_url = EmbeddingConfigurator._normalize_api_url(api_url)
return HuggingFaceEmbeddingServer(
url=api_url,
url=config.get("api_url"),
)
@staticmethod

View File

@@ -584,84 +584,3 @@ def test_docling_source_with_local_file():
docling_source = CrewDoclingSource(file_paths=[pdf_path])
assert docling_source.file_paths == [pdf_path]
assert docling_source.content is not None
def test_huggingface_url_validation():
"""Test that Huggingface embedder properly handles URLs without protocol."""
from crewai.utilities.embedding_configurator import EmbeddingConfigurator
config_missing_protocol = {
"api_url": "localhost:8080/embed"
}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config_missing_protocol, "test-model"
)
# Verify that the URL now has a protocol
assert embedding_function._api_url.startswith("http://")
config_with_protocol = {
"api_url": "https://localhost:8080/embed"
}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config_with_protocol, "test-model"
)
# Verify that the URL remains unchanged
assert embedding_function._api_url == "https://localhost:8080/embed"
config_with_other_protocol = {
"api_url": "http://localhost:8080/embed"
}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config_with_other_protocol, "test-model"
)
# Verify that the URL remains unchanged
assert embedding_function._api_url == "http://localhost:8080/embed"
config_no_url = {}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config_no_url, "test-model"
)
# Verify that no exception is raised when URL is None
assert embedding_function._api_url == 'None'
def test_huggingface_missing_protocol_with_json_source():
"""Test that JSONKnowledgeSource works with Huggingface embedder without URL protocol."""
import os
import json
import tempfile
from crewai.knowledge.source.json_knowledge_source import JSONKnowledgeSource
from crewai.utilities.embedding_configurator import EmbeddingConfigurator
# Create a temporary JSON file
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as temp:
json.dump({"test": "data", "nested": {"value": 123}}, temp)
json_path = temp.name
# Test that the URL validation works in the embedder configurator
config = {
"api_url": "localhost:8080/embed" # Missing protocol
}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config, "test-model"
)
# Verify that the URL now has a protocol
assert embedding_function._api_url.startswith("http://")
os.unlink(json_path)
def test_huggingface_missing_protocol_with_string_source():
"""Test that StringKnowledgeSource works with Huggingface embedder without URL protocol."""
from crewai.knowledge.source.string_knowledge_source import StringKnowledgeSource
from crewai.utilities.embedding_configurator import EmbeddingConfigurator
# Test that the URL validation works in the embedder configurator
config = {
"api_url": "localhost:8080/embed" # Missing protocol
}
embedding_function = EmbeddingConfigurator()._configure_huggingface(
config, "test-model"
)
# Verify that the URL now has a protocol
assert embedding_function._api_url.startswith("http://")

View File

@@ -1,6 +0,0 @@
{
"test": "data",
"nested": {
"value": 123
}
}

View File

@@ -0,0 +1,51 @@
import unittest
from crewai import Agent, Task
class TestTaskInitFix(unittest.TestCase):
"""Test the fix for issue #2219 where agent methods are not handled correctly in tasks."""
def test_task_init_handles_callable_agent(self):
"""Test that the Task.__init__ method correctly handles callable agents."""
# Create an agent instance
agent_instance = Agent(
role="Test Agent",
goal="Test Goal",
backstory="Test Backstory"
)
# Create a callable that returns the agent instance
def callable_agent():
return agent_instance
# Create a task with the callable agent
task = Task(
description="Test Task",
expected_output="Test Output",
agent=callable_agent
)
# Verify that the agent in the task is an instance, not a callable
self.assertIsInstance(task.agent, Agent)
self.assertEqual(task.agent.role, "Test Agent")
self.assertIs(task.agent, agent_instance)
def test_task_init_handles_invalid_callable_agent(self):
"""Test that the Task.__init__ method correctly handles invalid callable agents."""
# Create a callable that returns an invalid agent (not an Agent instance)
def invalid_callable_agent():
return "Not an agent"
# Create a task with the invalid callable agent
with self.assertRaises(ValueError) as context:
task = Task(
description="Test Task",
expected_output="Test Output",
agent=invalid_callable_agent
)
# Verify that the error message is correct
self.assertIn("Expected BaseAgent instance", str(context.exception))