Compare commits

..

2 Commits

Author SHA1 Message Date
lucasgomide
8a4f3c8cfc feat: cleanup Pydantic warning
A several warnings were addressed following by  https://docs.pydantic.dev/2.10/migration
2025-04-01 10:33:24 -03:00
Lucas Gomide
3c24350306 fix: remove logs we don't need to see from UserMemory initializion (#2497) 2025-03-31 08:27:36 -07:00
4 changed files with 17 additions and 110 deletions

View File

@@ -1,24 +1,12 @@
import asyncio
import json
import re
import sys
import uuid
import warnings
from concurrent.futures import Future
from copy import copy as shallow_copy
from hashlib import md5
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Set,
Tuple,
TypeAlias,
Union,
cast,
)
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union, cast
from pydantic import (
UUID4,
@@ -302,25 +290,18 @@ class Crew(BaseModel):
else EntityMemory(crew=self, embedder_config=self.embedder)
)
if (
self.memory_config and "user_memory" in self.memory_config and self.memory_config.get('provider') == 'mem0'
self.memory_config
and "user_memory" in self.memory_config
and self.memory_config.get("provider") == "mem0"
): # Check for user_memory in config
user_memory_config = self.memory_config["user_memory"]
if isinstance(
user_memory_config, dict
): # Check if it's a configuration dict
self._user_memory = UserMemory(
crew=self
)
self._user_memory = UserMemory(crew=self)
else:
raise TypeError(
"user_memory must be a configuration dictionary"
)
raise TypeError("user_memory must be a configuration dictionary")
else:
self._logger.log(
"warning",
"User memory initialization failed. For setup instructions, please refer to the memory documentation: https://docs.crewai.com/concepts/memory#integrating-mem0-for-enhanced-user-memory",
color="yellow"
)
self._user_memory = None # No user memory if not in config
return self
@@ -1171,7 +1152,7 @@ class Crew(BaseModel):
def copy(self):
"""
Creates a deep copy of the Crew instance.
Returns:
Crew: A new instance with copied components
"""
@@ -1193,7 +1174,6 @@ class Crew(BaseModel):
"knowledge",
"manager_agent",
"manager_llm",
}
cloned_agents = [agent.copy() for agent in self.agents]
@@ -1396,19 +1376,3 @@ class Crew(BaseModel):
memory_system.reset()
except Exception as e:
raise RuntimeError(f"Failed to reset {name} memory") from e
class Crewai(Crew):
"""Alias for Crew class to provide backward compatibility.
This class inherits from Crew and provides the same functionality,
but emits a deprecation warning when used.
"""
def __new__(cls, *args, **kwargs):
warnings.warn(
"Crewai is deprecated, use Crew instead.",
DeprecationWarning,
stacklevel=2
)
return super().__new__(cls)

View File

@@ -7,29 +7,27 @@ from pydantic import (
BaseModel,
ConfigDict,
Field,
PydanticDeprecatedSince20,
create_model,
validator,
field_validator,
)
from pydantic import BaseModel as PydanticBaseModel
from crewai.tools.structured_tool import CrewStructuredTool
# Ignore all "PydanticDeprecatedSince20" warnings globally
warnings.filterwarnings("ignore", category=PydanticDeprecatedSince20)
class BaseTool(BaseModel, ABC):
class _ArgsSchemaPlaceholder(PydanticBaseModel):
pass
model_config = ConfigDict()
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str
"""The unique name of the tool that clearly communicates its purpose."""
description: str
"""Used to tell the model how/when/why to use the tool."""
args_schema: Type[PydanticBaseModel] = Field(default_factory=_ArgsSchemaPlaceholder)
args_schema: Type[PydanticBaseModel] = Field(
default_factory=_ArgsSchemaPlaceholder, validate_default=True
)
"""The schema for the arguments that the tool accepts."""
description_updated: bool = False
"""Flag to check if the description has been updated."""
@@ -38,7 +36,8 @@ class BaseTool(BaseModel, ABC):
result_as_answer: bool = False
"""Flag to check if the tool should be the final agent answer."""
@validator("args_schema", always=True, pre=True)
@field_validator("args_schema", mode="before")
@classmethod
def _default_args_schema(
cls, v: Type[PydanticBaseModel]
) -> Type[PydanticBaseModel]:

View File

@@ -287,8 +287,9 @@ def generate_model_description(model: Type[BaseModel]) -> str:
else:
return str(field_type)
fields = model.__annotations__
fields = model.model_fields
field_descriptions = [
f'"{name}": {describe_field(type_)}' for name, type_ in fields.items()
f'"{name}": {describe_field(field.annotation)}'
for name, field in fields.items()
]
return "{\n " + ",\n ".join(field_descriptions) + "\n}"

View File

@@ -1,57 +0,0 @@
import unittest
class TestCrewaiAlias(unittest.TestCase):
"""Tests validating the Crewai alias and its backward compatibility.
These tests ensure that the Crewai alias works correctly for both
import scenarios and practical usage, providing backward compatibility
for existing code that uses the 'Crewai' name.
"""
def test_crewai_alias_import(self):
"""Test that Crewai can be imported from crewai.crew."""
try:
from crewai.crew import Crew, Crewai
self.assertEqual(Crewai, Crew)
except ImportError:
self.fail("Failed to import Crewai from crewai.crew")
def test_crewai_instance_creation(self):
"""Ensure Crewai can be instantiated just like Crew."""
from crewai.agent import Agent
from crewai.crew import Crew, Crewai
test_agent = Agent(
role="Test Agent",
goal="Testing",
backstory="Created for testing"
)
crewai_instance = Crewai(agents=[test_agent], tasks=[])
crew_instance = Crew(agents=[test_agent], tasks=[])
self.assertIsInstance(crewai_instance, Crew)
self.assertEqual(type(crewai_instance), type(crew_instance))
def test_crewai_deprecation_warning(self):
"""Test that using Crewai emits a deprecation warning."""
import importlib
import warnings
import crewai.crew
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
importlib.reload(crewai.crew)
self.assertTrue(len(w) > 0, "No deprecation warning was captured")
self.assertTrue(any(issubclass(warning.category, DeprecationWarning) for warning in w),
"No DeprecationWarning was found")
self.assertTrue(any("Crewai is deprecated" in str(warning.message) for warning in w),
"Warning message doesn't contain expected text")
if __name__ == "__main__":
unittest.main()