This commit is contained in:
João Moura
2025-05-28 20:49:05 -07:00
parent 224ba1fb69
commit e0cd41e9f9
7 changed files with 307 additions and 114 deletions

View File

@@ -195,7 +195,7 @@ class CrewAgentExecutor(CrewAgentExecutorMixin):
self._handle_mid_execution_reasoning()
else:
self.steps_since_reasoning += 1
self._invoke_step_callback(formatted_answer)
self._append_message(formatted_answer.text, role="assistant")
@@ -243,7 +243,7 @@ class CrewAgentExecutor(CrewAgentExecutorMixin):
if hasattr(formatted_answer, 'tool') and formatted_answer.tool:
if formatted_answer.tool not in self.tools_used:
self.tools_used.append(formatted_answer.tool)
# Special case for add_image_tool
add_image_tool = self._i18n.tools("add_image")
if (
@@ -462,48 +462,63 @@ class CrewAgentExecutor(CrewAgentExecutorMixin):
),
color="red",
)
def _should_trigger_reasoning(self) -> bool:
"""
Determine if mid-execution reasoning should be triggered.
Returns:
bool: True if reasoning should be triggered, False otherwise.
"""
if not hasattr(self.agent, "reasoning") or not self.agent.reasoning:
return False
if hasattr(self.agent, "reasoning_interval") and self.agent.reasoning_interval is not None:
return self.steps_since_reasoning >= self.agent.reasoning_interval
if hasattr(self.agent, "adaptive_reasoning") and self.agent.adaptive_reasoning:
return self._should_adaptive_reason()
return False
def _should_adaptive_reason(self) -> bool:
"""
Determine if adaptive reasoning should be triggered using LLM decision.
Fallback to error detection if LLM decision fails.
Returns:
bool: True if adaptive reasoning should be triggered, False otherwise.
"""
if self._has_recent_errors():
try:
from crewai.utilities.events.reasoning_events import AgentAdaptiveReasoningDecisionEvent
from crewai.utilities.events.crewai_event_bus import crewai_event_bus
crewai_event_bus.emit(
self.agent,
AgentAdaptiveReasoningDecisionEvent(
agent_role=self.agent.role,
task_id=str(self.task.id),
should_reason=True,
reasoning="Recent error indicators detected in previous messages.",
),
)
except Exception:
pass
return True
try:
from crewai.utilities.reasoning_handler import AgentReasoning
from crewai.agent import Agent
current_progress = self._summarize_current_progress()
reasoning_handler = AgentReasoning(task=self.task, agent=cast(Agent, self.agent))
return reasoning_handler.should_adaptive_reason_llm(
current_steps=self.iterations,
tools_used=list(self.tools_used),
current_progress=current_progress
current_progress=current_progress,
)
except Exception as e:
self._printer.print(
@@ -511,75 +526,77 @@ class CrewAgentExecutor(CrewAgentExecutorMixin):
color="yellow",
)
return False
def _has_recent_errors(self) -> bool:
"""Check for error indicators in recent messages."""
error_indicators = ["error", "exception", "failed", "unable to", "couldn't"]
recent_messages = self.messages[-3:] if len(self.messages) >= 3 else self.messages
for message in recent_messages:
content = message.get("content", "").lower()
if any(indicator in content for indicator in error_indicators):
return True
return False
def _handle_mid_execution_reasoning(self) -> None:
"""
Handle mid-execution reasoning by calling the reasoning handler.
"""
if not hasattr(self.agent, "reasoning") or not self.agent.reasoning:
return
try:
from crewai.utilities.reasoning_handler import AgentReasoning
current_progress = self._summarize_current_progress()
from crewai.agent import Agent
reasoning_handler = AgentReasoning(task=self.task, agent=cast(Agent, self.agent))
reasoning_output = reasoning_handler.handle_mid_execution_reasoning(
current_steps=self.iterations,
tools_used=list(self.tools_used),
current_progress=current_progress,
iteration_messages=self.messages
)
self.messages.append({
"role": "system",
"content": self._i18n.retrieve("reasoning", "mid_execution_reasoning_update").format(plan=reasoning_output.plan.plan)
})
self._append_message(
self._i18n.retrieve("reasoning", "mid_execution_reasoning_update").format(
plan=reasoning_output.plan.plan
),
role="assistant",
)
self.steps_since_reasoning = 0
except Exception as e:
self._printer.print(
content=f"Error during mid-execution reasoning: {str(e)}",
color="red",
)
def _summarize_current_progress(self) -> str:
"""
Create a summary of the current execution progress.
Returns:
str: A summary of the current progress.
"""
recent_messages = self.messages[-5:] if len(self.messages) >= 5 else self.messages
summary = f"After {self.iterations} steps, "
if self.tools_used:
unique_tools = set(self.tools_used)
summary += f"I've used {len(self.tools_used)} tools ({', '.join(unique_tools)}). "
else:
summary += "I haven't used any tools yet. "
if recent_messages:
last_message = recent_messages[-1].get("content", "")
if len(last_message) > 100:
last_message = last_message[:100] + "..."
summary += f"Most recent action: {last_message}"
return summary