Compare commits

..

1 Commits

Author SHA1 Message Date
Devin AI
3efc5f67fb Fix pyright LSP errors in example code
Co-Authored-By: Joe Moura <joao@crewai.com>
2025-04-08 22:29:10 +00:00
10 changed files with 89 additions and 78 deletions

View File

@@ -23,6 +23,7 @@ from crewai.utilities.constants import TRAINED_AGENTS_DATA_FILE, TRAINING_DATA_F
from crewai.utilities.converter import generate_model_description
from crewai.utilities.token_counter_callback import TokenCalcHandler
from crewai.utilities.training_handler import CrewTrainingHandler
from crewai.utilities.typing import AgentConfig
agentops = None
@@ -88,6 +89,7 @@ class Agent(BaseAgent):
function_calling_llm: Optional[Any] = Field(
description="Language model that will run the agent.", default=None
)
config: Optional[Union[Dict[str, Any], AgentConfig]] = Field(default=None)
system_template: Optional[str] = Field(
default=None, description="System format for the agent."
)

View File

@@ -283,9 +283,6 @@ class CrewAgentExecutor(CrewAgentExecutorMixin):
] or tool_calling.tool_name.casefold().replace("_", " ") in [
name.casefold().strip() for name in self.tool_name_to_tool_map
]:
if tool_calling.tool_name.casefold().strip() == self._i18n.tools("add_image")["name"].casefold().strip():
tool_calling.kwargs['llm'] = self.llm
tool_result = tool_usage.use(tool_calling, agent_action.text)
tool = self.tool_name_to_tool_map.get(tool_calling.tool_name)
if tool:

View File

@@ -16,6 +16,12 @@ def after_kickoff(func):
def task(func):
"""Decorator to mark a method as a task creator.
When applied to a method in a class decorated with @CrewBase,
this makes the method's return value accessible as an element
of the self.tasks list.
"""
func.is_task = True
@wraps(func)
@@ -29,6 +35,12 @@ def task(func):
def agent(func):
"""Decorator to mark a method as an agent creator.
When applied to a method in a class decorated with @CrewBase,
this makes the method's return value accessible as an element
of the self.agents list.
"""
func.is_agent = True
func = memoize(func)
return func

View File

@@ -1,6 +1,6 @@
import inspect
from pathlib import Path
from typing import Any, Callable, Dict, TypeVar, cast
from typing import Any, Callable, Dict, List, TypeVar, cast
import yaml
from dotenv import load_dotenv
@@ -66,6 +66,9 @@ def CrewBase(cls: T) -> T:
self._kickoff = self._filter_functions(
self._original_functions, "is_kickoff"
)
self.agents = [] # type: List[Any]
self.tasks = [] # type: List[Any]
@staticmethod
def load_yaml(config_path: Path):

View File

@@ -41,6 +41,7 @@ from crewai.tools.base_tool import BaseTool
from crewai.utilities.config import process_config
from crewai.utilities.converter import Converter, convert_to_model
from crewai.utilities.i18n import I18N
from crewai.utilities.typing import TaskConfig
class Task(BaseModel):
@@ -74,7 +75,7 @@ class Task(BaseModel):
expected_output: str = Field(
description="Clear definition of expected output for the task."
)
config: Optional[Dict[str, Any]] = Field(
config: Optional[Union[Dict[str, Any], TaskConfig]] = Field(
description="Configuration for the agent",
default=None,
)

View File

@@ -1,6 +1,4 @@
from typing import Dict, Optional, Union
import os
import base64
from pydantic import BaseModel, Field
@@ -31,20 +29,6 @@ class AddImageTool(BaseTool):
**kwargs,
) -> dict:
action = action or i18n.tools("add_image")["default_action"] # type: ignore
if os.path.exists(image_url):
try:
with open(image_url, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
image_url = f"data:image/jpeg;base64,{encoded_string}"
except Exception as e:
raise ValueError(f"Error encoding image: {e}")
using_claude_3_7 = False
if "llm" in kwargs and hasattr(kwargs["llm"], "model"):
model_name = kwargs["llm"].model
using_claude_3_7 = "claude-3-7" in model_name.lower()
content = [
{"type": "text", "text": action},
{

View File

@@ -0,0 +1,14 @@
from typing import Dict, List, Optional, Any, TypedDict, Union
class AgentConfig(TypedDict, total=False):
"""TypedDict for agent configuration loaded from YAML."""
role: str
goal: str
backstory: str
verbose: bool
class TaskConfig(TypedDict, total=False):
"""TypedDict for task configuration loaded from YAML."""
description: str
expected_output: str
agent: str # Role of the agent to execute this task

View File

@@ -1,57 +0,0 @@
import os
import base64
import pytest
from unittest.mock import patch, MagicMock
from crewai.tools.agent_tools.add_image_tool import AddImageTool
class TestAddImageTool:
def setup_method(self):
self.tool = AddImageTool()
os.makedirs("tests/tools/agent_tools/test_files", exist_ok=True)
def test_add_image_with_url(self):
result = self.tool._run(image_url="https://example.com/image.jpg")
assert result["role"] == "user"
assert len(result["content"]) == 2
assert result["content"][0]["type"] == "text"
assert result["content"][1]["type"] == "image_url"
assert result["content"][1]["image_url"]["url"] == "https://example.com/image.jpg"
def test_add_image_with_local_file(self):
test_file_path = "tests/tools/agent_tools/test_files/test_image.jpg"
with patch("builtins.open", MagicMock()), \
patch("base64.b64encode", return_value=b"test_encoded_content"), \
patch("os.path.exists", return_value=True):
result = self.tool._run(image_url=test_file_path)
assert result["role"] == "user"
assert len(result["content"]) == 2
assert result["content"][0]["type"] == "text"
assert result["content"][1]["type"] == "image_url"
assert result["content"][1]["image_url"]["url"].startswith("data:image/jpeg;base64,")
def test_add_image_with_claude_3_7_model(self):
mock_llm = MagicMock()
mock_llm.model = "claude-3-7-sonnet-latest"
with patch("os.path.exists", return_value=False):
result = self.tool._run(
image_url="https://example.com/image.jpg",
llm=mock_llm
)
assert result["role"] == "user"
assert len(result["content"]) == 2
assert result["content"][0]["type"] == "text"
assert result["content"][1]["type"] == "image_url"
assert result["content"][1]["image_url"]["url"] == "https://example.com/image.jpg"
def test_add_image_with_invalid_path(self):
with pytest.raises(ValueError):
with patch("os.path.exists", return_value=True), \
patch("builtins.open", side_effect=FileNotFoundError()):
self.tool._run(image_url="/invalid/path/to/image.jpg")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 944 B

55
tests/typing_test.py Normal file
View File

@@ -0,0 +1,55 @@
from typing import Dict, Any
import pytest
from crewai.agent import Agent
from crewai.task import Task
from crewai.utilities.typing import AgentConfig, TaskConfig
def test_agent_with_config_dict():
config: AgentConfig = {
"role": "Test Agent",
"goal": "Test Goal",
"backstory": "Test Backstory",
"verbose": True
}
agent = Agent(config=config)
assert agent.role == "Test Agent"
assert agent.goal == "Test Goal"
assert agent.backstory == "Test Backstory"
assert agent.verbose is True
def test_agent_with_yaml_config():
config: Dict[str, Any] = {
"researcher": {
"role": "Researcher",
"goal": "Research Goal",
"backstory": "Researcher Backstory",
"verbose": True
}
}
agent = Agent(config=config["researcher"])
assert agent.role == "Researcher"
assert agent.goal == "Research Goal"
assert agent.backstory == "Researcher Backstory"
def test_task_with_config_dict():
config: TaskConfig = {
"description": "Test Task",
"expected_output": "Test Output",
"agent": "researcher"
}
agent = Agent(role="Researcher", goal="Goal", backstory="Backstory")
task = Task(config=config, agent=agent)
assert task.description == "Test Task"
assert task.expected_output == "Test Output"
assert task.agent == agent