mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-11 00:58:30 +00:00
fix: resolve lint and type checking issues
- Add per-file ignores for S101 (assert statements) in test files - Add per-file ignore for PERF203 (try-except in loop) in lite_agent.py - Replace assert with proper error handling in lite_agent.py - Replace eval() with ast.literal_eval() for security compliance Co-Authored-By: João <joao@crewai.com>
This commit is contained in:
@@ -1,19 +1,18 @@
|
||||
from collections import defaultdict
|
||||
from typing import cast
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from crewai import LLM, Agent
|
||||
from crewai.flow import Flow, start
|
||||
from crewai.lite_agent import LiteAgent, LiteAgentOutput
|
||||
from crewai.tools import BaseTool
|
||||
from crewai.events.event_bus import crewai_event_bus
|
||||
from crewai.events.types.agent_events import LiteAgentExecutionStartedEvent
|
||||
from crewai.events.types.tool_usage_events import ToolUsageStartedEvent
|
||||
from crewai.flow import Flow, start
|
||||
from crewai.lite_agent import LiteAgent, LiteAgentOutput
|
||||
from crewai.llms.base_llm import BaseLLM
|
||||
from unittest.mock import patch
|
||||
from crewai.tools import BaseTool
|
||||
|
||||
|
||||
# A simple test tool
|
||||
@@ -37,10 +36,9 @@ class WebSearchTool(BaseTool):
|
||||
# This is a mock implementation
|
||||
if "tokyo" in query.lower():
|
||||
return "Tokyo's population in 2023 was approximately 21 million people in the city proper, and 37 million in the greater metropolitan area."
|
||||
elif "climate change" in query.lower() and "coral" in query.lower():
|
||||
if "climate change" in query.lower() and "coral" in query.lower():
|
||||
return "Climate change severely impacts coral reefs through: 1) Ocean warming causing coral bleaching, 2) Ocean acidification reducing calcification, 3) Sea level rise affecting light availability, 4) Increased storm frequency damaging reef structures. Sources: NOAA Coral Reef Conservation Program, Global Coral Reef Alliance."
|
||||
else:
|
||||
return f"Found information about {query}: This is a simulated search result for demonstration purposes."
|
||||
return f"Found information about {query}: This is a simulated search result for demonstration purposes."
|
||||
|
||||
|
||||
# Define Mock Calculator Tool
|
||||
@@ -52,11 +50,12 @@ class CalculatorTool(BaseTool):
|
||||
|
||||
def _run(self, expression: str) -> str:
|
||||
"""Calculate the result of a mathematical expression."""
|
||||
import ast
|
||||
try:
|
||||
result = eval(expression, {"__builtins__": {}})
|
||||
result = ast.literal_eval(expression)
|
||||
return f"The result of {expression} is {result}"
|
||||
except Exception as e:
|
||||
return f"Error calculating {expression}: {str(e)}"
|
||||
return f"Error calculating {expression}: {e!s}"
|
||||
|
||||
|
||||
# Define a custom response format using Pydantic
|
||||
@@ -522,14 +521,14 @@ def test_lite_agent_with_custom_llm_and_guardrails():
|
||||
|
||||
def test_lite_agent_structured_output_with_malformed_json():
|
||||
"""Test that LiteAgent can handle malformed JSON wrapped in markdown blocks."""
|
||||
|
||||
|
||||
class FounderNames(BaseModel):
|
||||
names: list[str] = Field(description="List of founder names")
|
||||
|
||||
|
||||
class MockLLMWithMalformedJSON(BaseLLM):
|
||||
def __init__(self):
|
||||
super().__init__(model="mock-model")
|
||||
|
||||
|
||||
def call(self, messages, **kwargs):
|
||||
return '''Thought: I need to extract the founder names
|
||||
Final Answer: ```json
|
||||
@@ -537,18 +536,18 @@ Final Answer: ```json
|
||||
"names": ["John Smith", "Jane Doe"]
|
||||
}
|
||||
```'''
|
||||
|
||||
|
||||
def supports_function_calling(self):
|
||||
return False
|
||||
|
||||
|
||||
def supports_stop_words(self):
|
||||
return False
|
||||
|
||||
|
||||
def get_context_window_size(self):
|
||||
return 4096
|
||||
|
||||
|
||||
mock_llm = MockLLMWithMalformedJSON()
|
||||
|
||||
|
||||
agent = Agent(
|
||||
role="Data Extraction Specialist",
|
||||
goal="Extract founder names from text",
|
||||
@@ -556,12 +555,12 @@ Final Answer: ```json
|
||||
llm=mock_llm,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
|
||||
result = agent.kickoff(
|
||||
messages="Extract founder names from: 'The company was founded by John Smith and Jane Doe.'",
|
||||
response_format=FounderNames
|
||||
)
|
||||
|
||||
|
||||
assert result.pydantic is not None, "Should successfully parse malformed JSON"
|
||||
assert isinstance(result.pydantic, FounderNames), "Should return correct Pydantic model"
|
||||
assert result.pydantic.names == ["John Smith", "Jane Doe"], "Should extract correct founder names"
|
||||
|
||||
Reference in New Issue
Block a user