Skip to content

Commit

Permalink
chore: logging and add config to the agent invocation
Browse files Browse the repository at this point in the history
  • Loading branch information
thompsonson committed Jul 22, 2024
1 parent c982366 commit b7b4274
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/crewai/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class Agent(BaseAgent):
)
llm: Any = Field(
default_factory=lambda: ChatOpenAI(
model=os.environ.get("OPENAI_MODEL_NAME", "gpt-4o")
model=os.environ.get("OPENAI_MODEL_NAME", "gpt-4o-mini")
),
description="Language model that will run the agent.",
)
Expand Down Expand Up @@ -179,13 +179,41 @@ def execute_task(
else:
task_prompt = self._use_trained_data(task_prompt=task_prompt)

logger.info(
f"[CrewAI.Agent.execute_task] Starting task execution for agent: {self.role}"
)

if hasattr(self, "callbacks") and self.callbacks:
logger.info(
f"[CrewAI.Agent.execute_task] Callbacks found for agent {self.role}: {self.callbacks}"
)
config = {"callbacks": self.callbacks}
else:
logger.warning(
f"[CrewAI.Agent.execute_task] No callbacks found for agent {self.role}"
)
config = {}

logger.info(
f"[CrewAI.Agent.execute_task] Invoking agent_executor with config: {config}"
)

result = self.agent_executor.invoke(
{
"input": task_prompt,
"tool_names": self.agent_executor.tools_names,
"tools": self.agent_executor.tools_description,
}
},
config=config,
)["output"]

logger.info(
f"[CrewAI.Agent.execute_task] Task execution completed for agent {self.role}"
)
logger.debug(
f"[CrewAI.Agent.execute_task] Task result: {result[:100]}..."
) # Log first 100 chars of result

if self.max_rpm:
self._rpm_controller.stop_rpm_counter()
return result
Expand Down
28 changes: 28 additions & 0 deletions src/crewai/task.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from copy import deepcopy
import os
import re
Expand All @@ -14,6 +15,8 @@
from crewai.utilities.pydantic_schema_parser import PydanticSchemaParser
from crewai.agents.agent_builder.base_agent import BaseAgent

logger = logging.getLogger(__name__)


class Task(BaseModel):
"""Class that represents a task to be executed.
Expand Down Expand Up @@ -101,6 +104,12 @@ class Config:
def __init__(__pydantic_self__, **data):
config = data.pop("config", {})
super().__init__(**config, **data)
logger.info(
f"[CrewAI.Task.__init__]: Task initialized with description: {__pydantic_self__.description[:50]}..."
)
logger.info(
f"[CrewAI.Task.__init__]: Task has {len(__pydantic_self__.tools)} tools"
)

@field_validator("id", mode="before")
@classmethod
Expand All @@ -124,13 +133,17 @@ def set_attributes_based_on_config(self) -> "Task":
if self.config:
for key, value in self.config.items():
setattr(self, key, value)
logger.info("[CrewAI.Task.set_attributes_based_on_config]: Task config applied")
return self

@model_validator(mode="after")
def check_tools(self):
"""Check if the tools are set."""
if not self.tools and self.agent and self.agent.tools:
self.tools.extend(self.agent.tools)
logger.info(
f"[CrewAI.Task.check_tools]: Task has {len(self.tools)} tools after check"
)
return self

@model_validator(mode="after")
Expand All @@ -143,6 +156,7 @@ def check_output(self):
"Only one output type can be set, either output_pydantic or output_json.",
{},
)
logger.info("[CrewAI.Task.check_output]: Task output type checked")
return self

def execute( # type: ignore # Missing return statement
Expand All @@ -156,9 +170,13 @@ def execute( # type: ignore # Missing return statement
Returns:
Output of the task.
"""
logger.info(
f"[CrewAI.Task.execute]: Starting execution of task: {self.description[:50]}..."
)

agent = agent or self.agent
if not agent:
logger.error("[CrewAI.Task.execute]: No agent assigned to task")
raise Exception(
f"The task '{self.description}' has no agent assigned, therefore it can't be executed directly and should be executed in a Crew using a specific process that support that, like hierarchical."
)
Expand All @@ -175,15 +193,19 @@ def execute( # type: ignore # Missing return statement
# type: ignore # Argument 1 to "join" of "str" has incompatible type "str | None"; expected "Iterable[str]"
context = "\n".join(context)

logger.info("[CrewAI.Task.execute]: Context prepared for task")

self.prompt_context = context
tools = tools or self.tools

if self.async_execution:
logger.info("[CrewAI.Task.execute]: Starting asynchronous execution")
self.thread = threading.Thread(
target=self._execute, args=(agent, self, context, tools)
)
self.thread.start()
else:
logger.info("[CrewAI.Task.execute]: Starting synchronous execution")
result = self._execute(
task=self,
agent=agent,
Expand All @@ -193,6 +215,7 @@ def execute( # type: ignore # Missing return statement
return result

def _execute(self, agent, task, context, tools):
logger.info(f"[CrewAI.Task._execute]: Executing task with agent: {agent.role}")
result = agent.execute_task(
task=task,
context=context,
Expand All @@ -209,8 +232,10 @@ def _execute(self, agent, task, context, tools):
)

if self.callback:
logger.info("[CrewAI.Task._execute]: Executing callback for task")
self.callback(self.output)

logger.info("[CrewAI.Task._execute]: Task execution completed")
return exported_output

def prompt(self) -> str:
Expand Down Expand Up @@ -350,3 +375,6 @@ def _save_file(self, result: Any) -> None:

def __repr__(self):
return f"Task(description={self.description}, expected_output={self.expected_output})"

def __str__(self):
return f"Task(description={self.description[:50]}[:50])"

0 comments on commit b7b4274

Please sign in to comment.