mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-04-30 23:02:50 +00:00
Compare commits
2 Commits
devin/1757
...
devin/1757
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f06765c86d | ||
|
|
4e19ecbf7b |
@@ -1,25 +1,25 @@
|
||||
from typing import Any, ClassVar
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from rich.console import Console
|
||||
from rich.live import Live
|
||||
from rich.panel import Panel
|
||||
from rich.syntax import Syntax
|
||||
from rich.text import Text
|
||||
from rich.tree import Tree
|
||||
from rich.live import Live
|
||||
from rich.syntax import Syntax
|
||||
|
||||
|
||||
class ConsoleFormatter:
|
||||
current_crew_tree: Tree | None = None
|
||||
current_task_branch: Tree | None = None
|
||||
current_agent_branch: Tree | None = None
|
||||
current_tool_branch: Tree | None = None
|
||||
current_flow_tree: Tree | None = None
|
||||
current_method_branch: Tree | None = None
|
||||
current_lite_agent_branch: Tree | None = None
|
||||
tool_usage_counts: ClassVar[dict[str, int]] = {}
|
||||
current_reasoning_branch: Tree | None = None # Track reasoning status
|
||||
current_crew_tree: Optional[Tree] = None
|
||||
current_task_branch: Optional[Tree] = None
|
||||
current_agent_branch: Optional[Tree] = None
|
||||
current_tool_branch: Optional[Tree] = None
|
||||
current_flow_tree: Optional[Tree] = None
|
||||
current_method_branch: Optional[Tree] = None
|
||||
current_lite_agent_branch: Optional[Tree] = None
|
||||
tool_usage_counts: Dict[str, int] = {}
|
||||
current_reasoning_branch: Optional[Tree] = None # Track reasoning status
|
||||
_live_paused: bool = False
|
||||
current_llm_tool_tree: Tree | None = None
|
||||
current_llm_tool_tree: Optional[Tree] = None
|
||||
|
||||
def __init__(self, verbose: bool = False):
|
||||
self.console = Console(width=None)
|
||||
@@ -29,7 +29,7 @@ class ConsoleFormatter:
|
||||
# instance so the previous render is replaced instead of writing a new one.
|
||||
# Once any non-Tree renderable is printed we stop the Live session so the
|
||||
# final Tree persists on the terminal.
|
||||
self._live: Live | None = None
|
||||
self._live: Optional[Live] = None
|
||||
|
||||
def create_panel(self, content: Text, title: str, style: str = "blue") -> Panel:
|
||||
"""Create a standardized panel with consistent styling."""
|
||||
@@ -45,7 +45,7 @@ class ConsoleFormatter:
|
||||
title: str,
|
||||
name: str,
|
||||
status_style: str = "blue",
|
||||
tool_args: dict[str, Any] | str = "",
|
||||
tool_args: Dict[str, Any] | str = "",
|
||||
**fields,
|
||||
) -> Text:
|
||||
"""Create standardized status content with consistent formatting."""
|
||||
@@ -70,7 +70,7 @@ class ConsoleFormatter:
|
||||
prefix: str,
|
||||
name: str,
|
||||
style: str = "blue",
|
||||
status: str | None = None,
|
||||
status: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Update tree label with consistent formatting."""
|
||||
label = Text()
|
||||
@@ -115,7 +115,7 @@ class ConsoleFormatter:
|
||||
self._live.update(tree, refresh=True)
|
||||
return # Nothing else to do
|
||||
|
||||
# Case 2: blank line while a live session is running - ignore so we
|
||||
# Case 2: blank line while a live session is running – ignore so we
|
||||
# don't break the in-place rendering behaviour
|
||||
if len(args) == 0 and self._live:
|
||||
return
|
||||
@@ -156,7 +156,7 @@ class ConsoleFormatter:
|
||||
|
||||
def update_crew_tree(
|
||||
self,
|
||||
tree: Tree | None,
|
||||
tree: Optional[Tree],
|
||||
crew_name: str,
|
||||
source_id: str,
|
||||
status: str = "completed",
|
||||
@@ -196,7 +196,7 @@ class ConsoleFormatter:
|
||||
|
||||
self.print_panel(content, title, style)
|
||||
|
||||
def create_crew_tree(self, crew_name: str, source_id: str) -> Tree | None:
|
||||
def create_crew_tree(self, crew_name: str, source_id: str) -> Optional[Tree]:
|
||||
"""Create and initialize a new crew tree with initial status."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -220,8 +220,8 @@ class ConsoleFormatter:
|
||||
return tree
|
||||
|
||||
def create_task_branch(
|
||||
self, crew_tree: Tree | None, task_id: str, task_name: str | None = None
|
||||
) -> Tree | None:
|
||||
self, crew_tree: Optional[Tree], task_id: str, task_name: Optional[str] = None
|
||||
) -> Optional[Tree]:
|
||||
"""Create and initialize a task branch."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -255,11 +255,11 @@ class ConsoleFormatter:
|
||||
|
||||
def update_task_status(
|
||||
self,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
task_id: str,
|
||||
agent_role: str,
|
||||
status: str = "completed",
|
||||
task_name: str | None = None,
|
||||
task_name: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Update task status in the tree."""
|
||||
if not self.verbose or crew_tree is None:
|
||||
@@ -306,8 +306,8 @@ class ConsoleFormatter:
|
||||
self.print_panel(content, panel_title, style)
|
||||
|
||||
def create_agent_branch(
|
||||
self, task_branch: Tree | None, agent_role: str, crew_tree: Tree | None
|
||||
) -> Tree | None:
|
||||
self, task_branch: Optional[Tree], agent_role: str, crew_tree: Optional[Tree]
|
||||
) -> Optional[Tree]:
|
||||
"""Create and initialize an agent branch."""
|
||||
if not self.verbose or not task_branch or not crew_tree:
|
||||
return None
|
||||
@@ -325,9 +325,9 @@ class ConsoleFormatter:
|
||||
|
||||
def update_agent_status(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
agent_role: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
status: str = "completed",
|
||||
) -> None:
|
||||
"""Update agent status in the tree."""
|
||||
@@ -336,7 +336,7 @@ class ConsoleFormatter:
|
||||
# altering the tree. Keeping it a no-op avoids duplicate status lines.
|
||||
return
|
||||
|
||||
def create_flow_tree(self, flow_name: str, flow_id: str) -> Tree | None:
|
||||
def create_flow_tree(self, flow_name: str, flow_id: str) -> Optional[Tree]:
|
||||
"""Create and initialize a flow tree."""
|
||||
content = self.create_status_content(
|
||||
"Starting Flow Execution", flow_name, "blue", ID=flow_id
|
||||
@@ -356,7 +356,7 @@ class ConsoleFormatter:
|
||||
|
||||
return flow_tree
|
||||
|
||||
def start_flow(self, flow_name: str, flow_id: str) -> Tree | None:
|
||||
def start_flow(self, flow_name: str, flow_id: str) -> Optional[Tree]:
|
||||
"""Initialize a flow execution tree."""
|
||||
flow_tree = Tree("")
|
||||
flow_label = Text()
|
||||
@@ -376,7 +376,7 @@ class ConsoleFormatter:
|
||||
|
||||
def update_flow_status(
|
||||
self,
|
||||
flow_tree: Tree | None,
|
||||
flow_tree: Optional[Tree],
|
||||
flow_name: str,
|
||||
flow_id: str,
|
||||
status: str = "completed",
|
||||
@@ -423,11 +423,11 @@ class ConsoleFormatter:
|
||||
|
||||
def update_method_status(
|
||||
self,
|
||||
method_branch: Tree | None,
|
||||
flow_tree: Tree | None,
|
||||
method_branch: Optional[Tree],
|
||||
flow_tree: Optional[Tree],
|
||||
method_name: str,
|
||||
status: str = "running",
|
||||
) -> Tree | None:
|
||||
) -> Optional[Tree]:
|
||||
"""Update method status in the flow tree."""
|
||||
if not flow_tree:
|
||||
return None
|
||||
@@ -480,7 +480,7 @@ class ConsoleFormatter:
|
||||
def handle_llm_tool_usage_started(
|
||||
self,
|
||||
tool_name: str,
|
||||
tool_args: dict[str, Any] | str,
|
||||
tool_args: Dict[str, Any] | str,
|
||||
):
|
||||
# Create status content for the tool usage
|
||||
content = self.create_status_content(
|
||||
@@ -520,11 +520,11 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_tool_usage_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
tool_name: str,
|
||||
crew_tree: Tree | None,
|
||||
tool_args: dict[str, Any] | str = "",
|
||||
) -> Tree | None:
|
||||
crew_tree: Optional[Tree],
|
||||
tool_args: Dict[str, Any] | str = "",
|
||||
) -> Optional[Tree]:
|
||||
"""Handle tool usage started event."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -569,9 +569,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_tool_usage_finished(
|
||||
self,
|
||||
tool_branch: Tree | None,
|
||||
tool_branch: Optional[Tree],
|
||||
tool_name: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle tool usage finished event."""
|
||||
if not self.verbose or tool_branch is None:
|
||||
@@ -600,10 +600,10 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_tool_usage_error(
|
||||
self,
|
||||
tool_branch: Tree | None,
|
||||
tool_branch: Optional[Tree],
|
||||
tool_name: str,
|
||||
error: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle tool usage error event."""
|
||||
if not self.verbose:
|
||||
@@ -631,9 +631,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_llm_call_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
) -> Tree | None:
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
) -> Optional[Tree]:
|
||||
"""Handle LLM call started event."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -672,9 +672,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_llm_call_completed(
|
||||
self,
|
||||
tool_branch: Tree | None,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
tool_branch: Optional[Tree],
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle LLM call completed event."""
|
||||
if not self.verbose:
|
||||
@@ -693,7 +693,7 @@ class ConsoleFormatter:
|
||||
if tool_branch is not None and "Thinking" in str(tool_branch.label):
|
||||
thinking_branch_to_remove = tool_branch
|
||||
|
||||
# Method 2: Fallback - search for any thinking node if tool_branch is None
|
||||
# Method 2: Fallback - search for any thinking node if tool_branch is None or not thinking
|
||||
if thinking_branch_to_remove is None:
|
||||
parents = [
|
||||
self.current_lite_agent_branch,
|
||||
@@ -736,7 +736,7 @@ class ConsoleFormatter:
|
||||
self.print()
|
||||
|
||||
def handle_llm_call_failed(
|
||||
self, tool_branch: Tree | None, error: str, crew_tree: Tree | None
|
||||
self, tool_branch: Optional[Tree], error: str, crew_tree: Optional[Tree]
|
||||
) -> None:
|
||||
"""Handle LLM call failed event."""
|
||||
if not self.verbose:
|
||||
@@ -752,7 +752,7 @@ class ConsoleFormatter:
|
||||
if tool_branch is not None and "Thinking" in str(tool_branch.label):
|
||||
thinking_branch_to_update = tool_branch
|
||||
|
||||
# Method 2: Fallback - search for any thinking node if tool_branch is None
|
||||
# Method 2: Fallback - search for any thinking node if tool_branch is None or not thinking
|
||||
if thinking_branch_to_update is None:
|
||||
parents = [
|
||||
self.current_lite_agent_branch,
|
||||
@@ -789,7 +789,7 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_crew_test_started(
|
||||
self, crew_name: str, source_id: str, n_iterations: int
|
||||
) -> Tree | None:
|
||||
) -> Optional[Tree]:
|
||||
"""Handle crew test started event."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -823,7 +823,7 @@ class ConsoleFormatter:
|
||||
return test_tree
|
||||
|
||||
def handle_crew_test_completed(
|
||||
self, flow_tree: Tree | None, crew_name: str
|
||||
self, flow_tree: Optional[Tree], crew_name: str
|
||||
) -> None:
|
||||
"""Handle crew test completed event."""
|
||||
if not self.verbose:
|
||||
@@ -913,7 +913,7 @@ class ConsoleFormatter:
|
||||
self.print_panel(failure_content, "Test Failure", "red")
|
||||
self.print()
|
||||
|
||||
def create_lite_agent_branch(self, lite_agent_role: str) -> Tree | None:
|
||||
def create_lite_agent_branch(self, lite_agent_role: str) -> Optional[Tree]:
|
||||
"""Create and initialize a lite agent branch."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -935,10 +935,10 @@ class ConsoleFormatter:
|
||||
|
||||
def update_lite_agent_status(
|
||||
self,
|
||||
lite_agent_branch: Tree | None,
|
||||
lite_agent_branch: Optional[Tree],
|
||||
lite_agent_role: str,
|
||||
status: str = "completed",
|
||||
**fields: dict[str, Any],
|
||||
**fields: Dict[str, Any],
|
||||
) -> None:
|
||||
"""Update lite agent status in the tree."""
|
||||
if not self.verbose or lite_agent_branch is None:
|
||||
@@ -981,7 +981,7 @@ class ConsoleFormatter:
|
||||
lite_agent_role: str,
|
||||
status: str = "started",
|
||||
error: Any = None,
|
||||
**fields: dict[str, Any],
|
||||
**fields: Dict[str, Any],
|
||||
) -> None:
|
||||
"""Handle lite agent execution events with consistent formatting."""
|
||||
if not self.verbose:
|
||||
@@ -1006,9 +1006,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_retrieval_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
) -> Tree | None:
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
) -> Optional[Tree]:
|
||||
"""Handle knowledge retrieval started event."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -1034,13 +1034,13 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_retrieval_completed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
retrieved_knowledge: Any,
|
||||
) -> None:
|
||||
"""Handle knowledge retrieval completed event."""
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
@@ -1062,7 +1062,7 @@ class ConsoleFormatter:
|
||||
)
|
||||
self.print(knowledge_panel)
|
||||
self.print()
|
||||
return
|
||||
return None
|
||||
|
||||
knowledge_branch_found = False
|
||||
for child in branch_to_use.children:
|
||||
@@ -1111,18 +1111,18 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_query_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
task_prompt: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle knowledge query generated event."""
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
if branch_to_use is None or tree_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
query_branch = branch_to_use.add("")
|
||||
self.update_tree_label(
|
||||
@@ -1134,9 +1134,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_query_failed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
error: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle knowledge query failed event."""
|
||||
if not self.verbose:
|
||||
@@ -1159,18 +1159,18 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_query_completed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle knowledge query completed event."""
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
|
||||
if branch_to_use is None or tree_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
query_branch = branch_to_use.add("")
|
||||
self.update_tree_label(query_branch, "✅", "Knowledge Query Completed", "green")
|
||||
@@ -1180,9 +1180,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_knowledge_search_query_failed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
error: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle knowledge search query failed event."""
|
||||
if not self.verbose:
|
||||
@@ -1207,10 +1207,10 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_reasoning_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
attempt: int,
|
||||
crew_tree: Tree | None,
|
||||
) -> Tree | None:
|
||||
crew_tree: Optional[Tree],
|
||||
) -> Optional[Tree]:
|
||||
"""Handle agent reasoning started (or refinement) event."""
|
||||
if not self.verbose:
|
||||
return None
|
||||
@@ -1249,7 +1249,7 @@ class ConsoleFormatter:
|
||||
self,
|
||||
plan: str,
|
||||
ready: bool,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle agent reasoning completed event."""
|
||||
if not self.verbose:
|
||||
@@ -1292,7 +1292,7 @@ class ConsoleFormatter:
|
||||
def handle_reasoning_failed(
|
||||
self,
|
||||
error: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
"""Handle agent reasoning failure event."""
|
||||
if not self.verbose:
|
||||
@@ -1329,7 +1329,7 @@ class ConsoleFormatter:
|
||||
def handle_agent_logs_started(
|
||||
self,
|
||||
agent_role: str,
|
||||
task_description: str | None = None,
|
||||
task_description: Optional[str] = None,
|
||||
verbose: bool = False,
|
||||
) -> None:
|
||||
"""Handle agent logs started event."""
|
||||
@@ -1367,29 +1367,19 @@ class ConsoleFormatter:
|
||||
if not verbose:
|
||||
return
|
||||
|
||||
from crewai.agents.parser import AgentAction, AgentFinish
|
||||
import json
|
||||
import re
|
||||
|
||||
from crewai.agents.parser import AgentAction, AgentFinish
|
||||
|
||||
agent_role = agent_role.partition("\n")[0]
|
||||
|
||||
if isinstance(formatted_answer, AgentAction):
|
||||
thought = re.sub(r"\n+", "\n", formatted_answer.thought)
|
||||
|
||||
try:
|
||||
parsed_input = json.loads(formatted_answer.tool_input)
|
||||
formatted_json = json.dumps(
|
||||
parsed_input,
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
formatted_json = json.dumps(
|
||||
formatted_answer.tool_input,
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
formatted_json = json.dumps(
|
||||
formatted_answer.tool_input,
|
||||
indent=2,
|
||||
ensure_ascii=False,
|
||||
)
|
||||
|
||||
# Create content for the action panel
|
||||
content = Text()
|
||||
@@ -1483,9 +1473,9 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_retrieval_started(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
) -> Tree | None:
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
) -> Optional[Tree]:
|
||||
if not self.verbose:
|
||||
return None
|
||||
|
||||
@@ -1507,13 +1497,13 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_retrieval_completed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
memory_content: str,
|
||||
retrieval_time_ms: float,
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
@@ -1538,7 +1528,7 @@ class ConsoleFormatter:
|
||||
|
||||
if branch_to_use is None or tree_to_use is None:
|
||||
add_panel()
|
||||
return
|
||||
return None
|
||||
|
||||
memory_branch_found = False
|
||||
for child in branch_to_use.children:
|
||||
@@ -1575,13 +1565,13 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_query_completed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
source_type: str,
|
||||
query_time_ms: float,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
@@ -1590,15 +1580,15 @@ class ConsoleFormatter:
|
||||
branch_to_use = tree_to_use
|
||||
|
||||
if branch_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
memory_type = source_type.replace("_", " ").title()
|
||||
|
||||
for child in branch_to_use.children:
|
||||
if "Memory Retrieval" in str(child.label):
|
||||
for inner_child in child.children:
|
||||
sources_branch = inner_child
|
||||
if "Sources Used" in str(inner_child.label):
|
||||
for child in child.children:
|
||||
sources_branch = child
|
||||
if "Sources Used" in str(child.label):
|
||||
sources_branch.add(f"✅ {memory_type} ({query_time_ms:.2f}ms)")
|
||||
break
|
||||
else:
|
||||
@@ -1608,13 +1598,13 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_query_failed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
error: str,
|
||||
source_type: str,
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = self.current_lite_agent_branch or agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
@@ -1623,15 +1613,15 @@ class ConsoleFormatter:
|
||||
branch_to_use = tree_to_use
|
||||
|
||||
if branch_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
memory_type = source_type.replace("_", " ").title()
|
||||
|
||||
for child in branch_to_use.children:
|
||||
if "Memory Retrieval" in str(child.label):
|
||||
for inner_child in child.children:
|
||||
sources_branch = inner_child
|
||||
if "Sources Used" in str(inner_child.label):
|
||||
for child in child.children:
|
||||
sources_branch = child
|
||||
if "Sources Used" in str(child.label):
|
||||
sources_branch.add(f"❌ {memory_type} - Error: {error}")
|
||||
break
|
||||
else:
|
||||
@@ -1640,16 +1630,16 @@ class ConsoleFormatter:
|
||||
break
|
||||
|
||||
def handle_memory_save_started(
|
||||
self, agent_branch: Tree | None, crew_tree: Tree | None
|
||||
self, agent_branch: Optional[Tree], crew_tree: Optional[Tree]
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = agent_branch or self.current_lite_agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
|
||||
if tree_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
for child in tree_to_use.children:
|
||||
if "Memory Update" in str(child.label):
|
||||
@@ -1665,19 +1655,19 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_save_completed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
crew_tree: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
crew_tree: Optional[Tree],
|
||||
save_time_ms: float,
|
||||
source_type: str,
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = agent_branch or self.current_lite_agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
|
||||
if tree_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
memory_type = source_type.replace("_", " ").title()
|
||||
content = f"✅ {memory_type} Memory Saved ({save_time_ms:.2f}ms)"
|
||||
@@ -1695,19 +1685,19 @@ class ConsoleFormatter:
|
||||
|
||||
def handle_memory_save_failed(
|
||||
self,
|
||||
agent_branch: Tree | None,
|
||||
agent_branch: Optional[Tree],
|
||||
error: str,
|
||||
source_type: str,
|
||||
crew_tree: Tree | None,
|
||||
crew_tree: Optional[Tree],
|
||||
) -> None:
|
||||
if not self.verbose:
|
||||
return
|
||||
return None
|
||||
|
||||
branch_to_use = agent_branch or self.current_lite_agent_branch
|
||||
tree_to_use = branch_to_use or crew_tree
|
||||
|
||||
if branch_to_use is None or tree_to_use is None:
|
||||
return
|
||||
return None
|
||||
|
||||
memory_type = source_type.replace("_", " ").title()
|
||||
content = f"❌ {memory_type} Memory Save Failed"
|
||||
@@ -1748,7 +1738,7 @@ class ConsoleFormatter:
|
||||
def handle_guardrail_completed(
|
||||
self,
|
||||
success: bool,
|
||||
error: str | None,
|
||||
error: Optional[str],
|
||||
retry_count: int,
|
||||
) -> None:
|
||||
"""Display guardrail evaluation result.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import inspect
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, TypeVar, cast, List
|
||||
from typing import Any, Callable, Dict, TypeVar, cast, List, Optional
|
||||
from crewai.tools import BaseTool
|
||||
|
||||
import yaml
|
||||
@@ -86,15 +86,15 @@ def CrewBase(cls: T) -> T:
|
||||
import types
|
||||
return types.MethodType(_close_mcp_server, self)
|
||||
|
||||
def get_mcp_tools(self, *tool_names: list[str]) -> List[BaseTool]:
|
||||
def get_mcp_tools(self, *tool_names: list[str], connect_timeout: Optional[int] = 30) -> List[BaseTool]:
|
||||
if not self.mcp_server_params:
|
||||
return []
|
||||
|
||||
from crewai_tools import MCPServerAdapter
|
||||
from crewai_tools import MCPServerAdapter # type: ignore[import-untyped]
|
||||
|
||||
adapter = getattr(self, '_mcp_server_adapter', None)
|
||||
if not adapter:
|
||||
self._mcp_server_adapter = MCPServerAdapter(self.mcp_server_params)
|
||||
self._mcp_server_adapter = MCPServerAdapter(self.mcp_server_params, connect_timeout=connect_timeout)
|
||||
|
||||
return self._mcp_server_adapter.tools.filter_by_names(tool_names or None)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import List
|
||||
from typing import ClassVar
|
||||
from unittest.mock import Mock, patch
|
||||
import pytest
|
||||
|
||||
@@ -284,4 +285,59 @@ def test_internal_crew_with_mcp():
|
||||
assert crew.reporting_analyst().tools == [simple_tool, another_simple_tool]
|
||||
assert crew.researcher().tools == [simple_tool]
|
||||
|
||||
adapter_mock.assert_called_once_with({"host": "localhost", "port": 8000})
|
||||
adapter_mock.assert_called_once_with(
|
||||
{"host": "localhost", "port": 8000}, connect_timeout=30
|
||||
)
|
||||
|
||||
def test_internal_crew_with_mcp_custom_timeout():
|
||||
with patch("embedchain.client.Client.setup"):
|
||||
from crewai_tools import MCPServerAdapter
|
||||
from crewai_tools.adapters.mcp_adapter import ToolCollection
|
||||
|
||||
@CrewBase
|
||||
class CrewWithCustomTimeout(InternalCrew):
|
||||
mcp_server_params: ClassVar = {"host": "localhost", "port": 8000}
|
||||
|
||||
@agent
|
||||
def test_agent(self):
|
||||
return Agent(
|
||||
config=self.agents_config["researcher"],
|
||||
tools=self.get_mcp_tools("simple_tool", connect_timeout=60),
|
||||
)
|
||||
|
||||
mock = Mock(spec=MCPServerAdapter)
|
||||
mock.tools = ToolCollection([simple_tool])
|
||||
with patch("crewai_tools.MCPServerAdapter", return_value=mock) as adapter_mock:
|
||||
crew = CrewWithCustomTimeout()
|
||||
assert crew.test_agent().tools == [simple_tool]
|
||||
|
||||
adapter_mock.assert_called_once_with(
|
||||
{"host": "localhost", "port": 8000}, connect_timeout=60
|
||||
)
|
||||
|
||||
|
||||
def test_internal_crew_with_mcp_backward_compatibility():
|
||||
with patch("embedchain.client.Client.setup"):
|
||||
from crewai_tools import MCPServerAdapter
|
||||
from crewai_tools.adapters.mcp_adapter import ToolCollection
|
||||
|
||||
@CrewBase
|
||||
class CrewWithoutTimeout(InternalCrew):
|
||||
mcp_server_params: ClassVar = {"host": "localhost", "port": 8000}
|
||||
|
||||
@agent
|
||||
def test_agent(self):
|
||||
return Agent(
|
||||
config=self.agents_config["researcher"],
|
||||
tools=self.get_mcp_tools("simple_tool"),
|
||||
)
|
||||
|
||||
mock = Mock(spec=MCPServerAdapter)
|
||||
mock.tools = ToolCollection([simple_tool])
|
||||
with patch("crewai_tools.MCPServerAdapter", return_value=mock) as adapter_mock:
|
||||
crew = CrewWithoutTimeout()
|
||||
assert crew.test_agent().tools == [simple_tool]
|
||||
|
||||
adapter_mock.assert_called_once_with(
|
||||
{"host": "localhost", "port": 8000}, connect_timeout=30
|
||||
)
|
||||
|
||||
@@ -1,174 +0,0 @@
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
from crewai.agents.parser import AgentAction, AgentFinish
|
||||
from crewai.events.utils.console_formatter import ConsoleFormatter
|
||||
|
||||
|
||||
class TestConsoleFormatterJSON:
|
||||
"""Test ConsoleFormatter JSON formatting functionality."""
|
||||
|
||||
def test_handle_agent_logs_execution_with_json_tool_input(self):
|
||||
"""Test that JSON tool inputs are properly formatted."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
json_input = (
|
||||
'{"task": "Research AI", "context": "Machine Learning", '
|
||||
'"priority": "high"}'
|
||||
)
|
||||
agent_action = AgentAction(
|
||||
thought="I need to research this topic",
|
||||
tool="research_tool",
|
||||
tool_input=json_input,
|
||||
text="Full agent text",
|
||||
result="Research completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_handle_agent_logs_execution_with_malformed_json(self):
|
||||
"""Test that malformed JSON falls back to string formatting."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
malformed_json = (
|
||||
'{"task": "Research AI", "context": "Machine Learning"'
|
||||
)
|
||||
agent_action = AgentAction(
|
||||
thought="I need to research this topic",
|
||||
tool="research_tool",
|
||||
tool_input=malformed_json,
|
||||
text="Full agent text",
|
||||
result="Research completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_handle_agent_logs_execution_with_non_json_string(self):
|
||||
"""Test that non-JSON strings are handled properly."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
plain_string = "search for weather in San Francisco"
|
||||
agent_action = AgentAction(
|
||||
thought="I need to search for weather",
|
||||
tool="search_tool",
|
||||
tool_input=plain_string,
|
||||
text="Full agent text",
|
||||
result="Weather found"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_handle_agent_logs_execution_with_complex_json(self):
|
||||
"""Test with complex nested JSON structures."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
complex_json = json.dumps({
|
||||
"query": {
|
||||
"type": "research",
|
||||
"parameters": {
|
||||
"topic": "AI in healthcare",
|
||||
"depth": "comprehensive",
|
||||
"sources": ["academic", "industry", "news"]
|
||||
}
|
||||
},
|
||||
"filters": ["recent", "peer-reviewed"],
|
||||
"limit": 50
|
||||
})
|
||||
|
||||
agent_action = AgentAction(
|
||||
thought="Complex research query",
|
||||
tool="advanced_search",
|
||||
tool_input=complex_json,
|
||||
text="Full agent text",
|
||||
result="Complex search completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_handle_agent_logs_execution_with_agent_finish(self):
|
||||
"""Test that AgentFinish objects are handled correctly."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
agent_finish = AgentFinish(
|
||||
thought="Task completed",
|
||||
output="Final result of the task",
|
||||
text="Full agent text"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_finish, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_json_parsing_preserves_structure(self):
|
||||
"""Test that JSON parsing preserves the original structure."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
original_data = {
|
||||
"nested": {
|
||||
"array": [1, 2, 3],
|
||||
"string": "test",
|
||||
"boolean": True,
|
||||
"null": None
|
||||
}
|
||||
}
|
||||
json_string = json.dumps(original_data)
|
||||
|
||||
agent_action = AgentAction(
|
||||
thought="Testing structure preservation",
|
||||
tool="test_tool",
|
||||
tool_input=json_string,
|
||||
text="Full agent text",
|
||||
result="Test completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_empty_tool_input_handling(self):
|
||||
"""Test handling of empty tool input."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
agent_action = AgentAction(
|
||||
thought="Empty input test",
|
||||
tool="test_tool",
|
||||
tool_input="",
|
||||
text="Full agent text",
|
||||
result="Test completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
|
||||
def test_numeric_tool_input_handling(self):
|
||||
"""Test handling of numeric tool input."""
|
||||
formatter = ConsoleFormatter()
|
||||
|
||||
agent_action = AgentAction(
|
||||
thought="Numeric input test",
|
||||
tool="test_tool",
|
||||
tool_input="42",
|
||||
text="Full agent text",
|
||||
result="Test completed"
|
||||
)
|
||||
|
||||
with patch.object(formatter, 'print') as mock_print:
|
||||
formatter.handle_agent_logs_execution(agent_action, "Test Agent")
|
||||
|
||||
mock_print.assert_called()
|
||||
Reference in New Issue
Block a user