Compare commits

..

3 Commits

Author SHA1 Message Date
theCyberTech
df00876f7a Linting:
- Improved code formatting for better clarity.
- These changes aim to improve maintainability and clarity of the code.
2025-01-05 11:35:58 +08:00
theCyberTech
47121316d4 Merge branch 'main' into pydantic_fixup 2025-01-05 11:27:18 +08:00
theCyberTech
79e428aff8 refactor: improve code readability and update model schema access in tool_usage.py
- Reformatted the OPENAI_BIGGER_MODELS list for better readability.
- Updated the method for accessing the model schema in ToolUsage class to use model_json_schema() instead of schema().
- Enhanced conditional formatting for clarity in the add_image tool check.

These changes aim to enhance maintainability and clarity of the code.
2025-01-05 11:04:47 +08:00
3 changed files with 17 additions and 148 deletions

View File

@@ -137,18 +137,6 @@ class Agent(BaseAgent):
@model_validator(mode="after")
def post_init_setup(self):
# Handle case-insensitive LLM parameter
if hasattr(self, 'LLM'):
import warnings
warnings.warn(
"Using 'LLM' parameter is deprecated. Use lowercase 'llm' instead.",
DeprecationWarning,
stacklevel=2
)
# Transfer LLM value to llm
self.llm = getattr(self, 'LLM')
delattr(self, 'LLM')
self._set_knowledge()
self.agent_ops_agent_name = self.role
unaccepted_attributes = [
@@ -156,9 +144,6 @@ class Agent(BaseAgent):
"AWS_SECRET_ACCESS_KEY",
"AWS_REGION_NAME",
]
# Initialize LLM parameters
llm_params: Dict[str, Any] = {}
# Handle different cases for self.llm
if isinstance(self.llm, str):
@@ -205,71 +190,7 @@ class Agent(BaseAgent):
if key not in ["prompt", "key_name", "default"]:
# Only add default if the key is already set in os.environ
if key in os.environ:
# Convert environment variables to proper types
try:
param_value = None
# Integer parameters
if key in ['timeout', 'max_tokens', 'n', 'max_completion_tokens']:
try:
param_value = int(str(value)) if value else None
except (ValueError, TypeError):
continue
# Float parameters
elif key in ['temperature', 'top_p', 'presence_penalty', 'frequency_penalty']:
try:
param_value = float(str(value)) if value else None
except (ValueError, TypeError):
continue
# Boolean parameters
elif key == 'logprobs':
if isinstance(value, bool):
param_value = value
elif isinstance(value, str):
param_value = value.lower() == 'true'
# Dict parameters
elif key == 'logit_bias' and value:
try:
if isinstance(value, dict):
param_value = {int(k): float(v) for k, v in value.items()}
elif isinstance(value, str):
import json
bias_dict = json.loads(value)
param_value = {int(k): float(v) for k, v in bias_dict.items()}
except (ValueError, TypeError, json.JSONDecodeError):
continue
elif key == 'response_format' and value:
try:
if isinstance(value, dict):
param_value = value
elif isinstance(value, str):
import json
param_value = json.loads(value)
except (ValueError, json.JSONDecodeError):
continue
# List parameters
elif key == 'callbacks':
if isinstance(value, (list, tuple)):
param_value = list(value)
elif isinstance(value, str):
param_value = [cb.strip() for cb in value.split(',') if cb.strip()]
else:
param_value = []
# String and other parameters
else:
param_value = value
if param_value is not None:
llm_params[key] = param_value
except Exception:
# Skip any invalid values
continue
llm_params[key] = value
self.llm = LLM(**llm_params)
else:

View File

@@ -19,7 +19,15 @@ try:
import agentops # type: ignore
except ImportError:
agentops = None
OPENAI_BIGGER_MODELS = ["gpt-4", "gpt-4o", "o1-preview", "o1-mini", "o1", "o3", "o3-mini"]
OPENAI_BIGGER_MODELS = [
"gpt-4",
"gpt-4o",
"o1-preview",
"o1-mini",
"o1",
"o3",
"o3-mini",
]
class ToolUsageErrorException(Exception):
@@ -104,7 +112,10 @@ class ToolUsage:
self._printer.print(content=f"\n\n{error}\n", color="red")
return error
if isinstance(tool, CrewStructuredTool) and tool.name == self._i18n.tools("add_image")["name"]: # type: ignore
if (
isinstance(tool, CrewStructuredTool)
and tool.name == self._i18n.tools("add_image")["name"]
): # type: ignore
try:
result = self._use(tool_string=tool_string, tool=tool, calling=calling)
return result
@@ -169,7 +180,9 @@ class ToolUsage:
if calling.arguments:
try:
acceptable_args = tool.args_schema.model_json_schema()["properties"].keys() # type: ignore
acceptable_args = tool.args_schema.model_json_schema()[
"properties"
].keys() # type: ignore # Item "None" of "type[BaseModel] | None" has no attribute "schema"
arguments = {
k: v
for k, v in calling.arguments.items()

View File

@@ -1,65 +0,0 @@
import os
from unittest import mock
import pytest
from crewai.agent import Agent
from crewai.llm import LLM
def test_agent_with_custom_llm():
"""Test creating an agent with a custom LLM."""
custom_llm = LLM(model="gpt-4")
agent = Agent()
agent.role = "test"
agent.goal = "test"
agent.backstory = "test"
agent.llm = custom_llm
agent.allow_delegation = False
agent.post_init_setup()
assert isinstance(agent.llm, LLM)
assert agent.llm.model == "gpt-4"
def test_agent_with_uppercase_llm_param():
"""Test creating an agent with uppercase 'LLM' parameter."""
custom_llm = LLM(model="gpt-4")
with pytest.warns(DeprecationWarning):
agent = Agent()
agent.role = "test"
agent.goal = "test"
agent.backstory = "test"
setattr(agent, 'LLM', custom_llm) # Using uppercase LLM
agent.allow_delegation = False
agent.post_init_setup()
assert isinstance(agent.llm, LLM)
assert agent.llm.model == "gpt-4"
assert not hasattr(agent, 'LLM')
def test_agent_llm_parameter_types():
"""Test LLM parameter type handling."""
env_vars = {
"temperature": "0.7",
"max_tokens": "100",
"presence_penalty": "0.5",
"logprobs": "true",
"logit_bias": '{"50256": -100}',
"callbacks": "callback1,callback2",
}
with mock.patch.dict(os.environ, env_vars):
agent = Agent()
agent.role = "test"
agent.goal = "test"
agent.backstory = "test"
agent.llm = "gpt-4"
agent.allow_delegation = False
agent.post_init_setup()
assert isinstance(agent.llm, LLM)
assert agent.llm.temperature == 0.7
assert agent.llm.max_tokens == 100
assert agent.llm.presence_penalty == 0.5
assert agent.llm.logprobs is True
assert agent.llm.logit_bias == {50256: -100.0}
assert agent.llm.callbacks == ["callback1", "callback2"]