Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

feat(agents): promote AgentExecutor out of experimental (#8192)

Vidit Ostwalc661df981655
diff --git a/docs/edge/ar/learn/llm-hooks.mdx b/docs/edge/ar/learn/llm-hooks.mdx
index 445f99349..c181b6ffc 100644
--- a/docs/edge/ar/learn/llm-hooks.mdx
+++ b/docs/edge/ar/learn/llm-hooks.mdx
@@ -54,7 +54,7 @@ def after_hook(context: LLMCallHookContext) -> str | None:
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor # Full executor reference
+ executor: AgentExecutor # Full executor reference
messages: list # Mutable message list
agent: Agent # Current agent
task: Task # Current task
@@ -64,6 +64,8 @@ class LLMCallHookContext:
response: str | None # LLM response (after hooks only)
```
+يُستورَد `AgentExecutor` من `crewai.agents`. تمت إزالة `CrewAgentExecutor` ومسار الاستيراد `crewai.experimental.agent_executor`.
+
### تعديل الرسائل
**مهم:** قم دائماً بتعديل الرسائل في مكانها:
diff --git a/docs/edge/en/learn/llm-hooks.mdx b/docs/edge/en/learn/llm-hooks.mdx
index 738097385..f26a92521 100644
--- a/docs/edge/en/learn/llm-hooks.mdx
+++ b/docs/edge/en/learn/llm-hooks.mdx
@@ -56,7 +56,7 @@ The `LLMCallHookContext` object provides comprehensive access to execution state
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor | LiteAgent | None # Executor (None for direct LLM calls)
+ executor: AgentExecutor | LiteAgent | None # Executor (None for direct LLM calls)
messages: list # Mutable message list
agent: Agent | None # Current agent (None for direct LLM calls)
task: Task | None # Current task (None for direct calls or LiteAgent)
@@ -66,6 +66,8 @@ class LLMCallHookContext:
response: str | None # LLM response (POST_MODEL_CALL only)
```
+`AgentExecutor` is imported from `crewai.agents`. `CrewAgentExecutor` and the `crewai.experimental.agent_executor` import path have been removed.
+
The context also exposes `request_human_input(prompt, default_message)`, which
pauses live console updates and collects input from the terminal — useful for
approval gates.
diff --git a/docs/edge/ko/learn/execution-hooks.mdx b/docs/edge/ko/learn/execution-hooks.mdx
index 4254f053c..fd722eb02 100644
--- a/docs/edge/ko/learn/execution-hooks.mdx
+++ b/docs/edge/ko/learn/execution-hooks.mdx
@@ -173,7 +173,7 @@ LLM 실행 상태에 대한 액세스를 제공합니다:
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor # 전체 실행자 액세스
+ executor: AgentExecutor # 전체 실행자 액세스
messages: list # 변경 가능한 메시지 목록
agent: Agent # 현재 에이전트
task: Task # 현재 작업
diff --git a/docs/edge/ko/learn/llm-hooks.mdx b/docs/edge/ko/learn/llm-hooks.mdx
index 92a4e3cea..7519a4964 100644
--- a/docs/edge/ko/learn/llm-hooks.mdx
+++ b/docs/edge/ko/learn/llm-hooks.mdx
@@ -54,7 +54,7 @@ def after_hook(context: LLMCallHookContext) -> str | None:
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor # 전체 실행자 참조
+ executor: AgentExecutor # 전체 실행자 참조
messages: list # 변경 가능한 메시지 목록
agent: Agent # 현재 에이전트
task: Task # 현재 작업
@@ -64,6 +64,8 @@ class LLMCallHookContext:
response: str | None # LLM 응답 (후 훅용)
```
+`AgentExecutor`는 `crewai.agents`에서 가져옵니다. `CrewAgentExecutor`와 `crewai.experimental.agent_executor` 가져오기 경로는 제거되었습니다.
+
### 메시지 수정
**중요:** 항상 메시지를 제자리에서 수정하세요:
diff --git a/docs/edge/pt-BR/learn/execution-hooks.mdx b/docs/edge/pt-BR/learn/execution-hooks.mdx
index 0e70edfbd..649819d5c 100644
--- a/docs/edge/pt-BR/learn/execution-hooks.mdx
+++ b/docs/edge/pt-BR/learn/execution-hooks.mdx
@@ -173,7 +173,7 @@ Fornece acesso ao estado de execução do LLM:
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor # Acesso completo ao executor
+ executor: AgentExecutor # Acesso completo ao executor
messages: list # Lista de mensagens mutável
agent: Agent # Agente atual
task: Task # Tarefa atual
diff --git a/docs/edge/pt-BR/learn/llm-hooks.mdx b/docs/edge/pt-BR/learn/llm-hooks.mdx
index 9122d0d32..a5100d961 100644
--- a/docs/edge/pt-BR/learn/llm-hooks.mdx
+++ b/docs/edge/pt-BR/learn/llm-hooks.mdx
@@ -54,7 +54,7 @@ O objeto `LLMCallHookContext` fornece acesso abrangente ao estado de execução:
```python
class LLMCallHookContext:
- executor: CrewAgentExecutor # Referência completa ao executor
+ executor: AgentExecutor # Referência completa ao executor
messages: list # Lista de mensagens mutável
agent: Agent # Agente atual
task: Task # Tarefa atual
@@ -64,6 +64,8 @@ class LLMCallHookContext:
response: str | None # Resposta do LLM (apenas hooks posteriores)
```
+`AgentExecutor` é importado de `crewai.agents`. `CrewAgentExecutor` e o caminho de importação `crewai.experimental.agent_executor` foram removidos.
+
### Modificando Mensagens
**Importante:** Sempre modifique mensagens in-place:
diff --git a/lib/crewai/src/crewai/__init__.py b/lib/crewai/src/crewai/__init__.py
index b4854f2a0..60a11e090 100644
--- a/lib/crewai/src/crewai/__init__.py
+++ b/lib/crewai/src/crewai/__init__.py
@@ -71,8 +71,8 @@ try:
from crewai.agents.agent_builder.base_agent_executor import (
BaseAgentExecutor as _BaseAgentExecutor,
)
+ from crewai.agents.agent_executor import AgentExecutor as _AgentExecutor
from crewai.agents.tools_handler import ToolsHandler as _ToolsHandler
- from crewai.experimental.agent_executor import AgentExecutor as _AgentExecutor
from crewai.hooks.llm_hooks import LLMCallHookContext as _LLMCallHookContext
from crewai.tools.tool_types import ToolResult as _ToolResult
from crewai.utilities.prompts import (
@@ -138,22 +138,17 @@ try:
Crew.__module__,
Flow.__module__,
Task.__module__,
- "crewai.agents.crew_agent_executor",
_runtime_state_mod.__name__,
_AgentExecutor.__module__,
):
sys.modules[_mod_name].__dict__.update(_resolve_namespace)
- from crewai.agents.crew_agent_executor import (
- CrewAgentExecutor as _CrewAgentExecutor,
- )
from crewai.tasks.conditional_task import ConditionalTask as _ConditionalTask
_BaseAgentExecutor.model_rebuild(force=True, _types_namespace=_full_namespace)
_BaseAgent.model_rebuild(force=True, _types_namespace=_full_namespace)
Task.model_rebuild(force=True, _types_namespace=_full_namespace)
_ConditionalTask.model_rebuild(force=True, _types_namespace=_full_namespace)
- _CrewAgentExecutor.model_rebuild(force=True, _types_namespace=_full_namespace)
Crew.model_rebuild(force=True, _types_namespace=_full_namespace)
Flow.model_rebuild(force=True, _types_namespace=_full_namespace)
_AgentExecutor.model_rebuild(force=True, _types_namespace=_full_namespace)
diff --git a/lib/crewai/src/crewai/agent/core.py b/lib/crewai/src/crewai/agent/core.py
index 929edf781..a24ca152a 100644
--- a/lib/crewai/src/crewai/agent/core.py
+++ b/lib/crewai/src/crewai/agent/core.py
@@ -51,8 +51,8 @@ from crewai.agents.agent_builder.base_agent import (
_serialize_llm_ref,
_validate_llm_ref,
)
+from crewai.agents.agent_executor import AgentExecutor
from crewai.agents.cache.cache_handler import CacheHandler
-from crewai.agents.crew_agent_executor import CrewAgentExecutor
from crewai.events.event_bus import crewai_event_bus
from crewai.events.types.agent_events import (
AgentExecutionCompletedEvent,
@@ -74,7 +74,6 @@ from crewai.events.types.memory_events import (
)
from crewai.events.types.skill_events import SkillUsedEvent
from crewai.execution import begin_execution, end_execution
-from crewai.experimental.agent_executor import AgentExecutor
from crewai.hooks.dispatch import HookAborted
from crewai.knowledge.knowledge import Knowledge
from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource
@@ -148,34 +147,30 @@ _passthrough_exceptions: tuple[type[Exception], ...] = (
)
_EXECUTOR_CLASS_MAP: dict[str, type] = {
- "CrewAgentExecutor": CrewAgentExecutor,
"AgentExecutor": AgentExecutor,
}
def _is_resuming_agent_executor(
- executor: CrewAgentExecutor | AgentExecutor | None,
+ executor: AgentExecutor | None,
) -> TypeIs[AgentExecutor]:
"""Type guard: True when the executor is resuming from a checkpoint."""
return isinstance(executor, AgentExecutor) and executor._resuming
def _validate_executor_class(value: Any) -> Any:
+ if getattr(value, "__name__", None) == "CrewAgentExecutor" or (
+ isinstance(value, str) and value == "CrewAgentExecutor"
+ ):
+ raise ValueError(
+ "CrewAgentExecutor has been removed. Use "
+ "crewai.agents.agent_executor.AgentExecutor."
+ )
if isinstance(value, str):
cls = _EXECUTOR_CLASS_MAP.get(value)
if cls is None:
raise ValueError(f"Unknown executor class: {value}")
- value = cls
- import warnings
-
- if value is CrewAgentExecutor:
- warnings.warn(
- "CrewAgentExecutor is deprecated and will be removed in a future release. "
- "Agents inside Crews now use AgentExecutor by default. "
- "Switch to crewai.experimental.AgentExecutor.",
- DeprecationWarning,
- stacklevel=3,
- )
+ return cls
return value
@@ -222,7 +217,7 @@ class Agent(BaseAgent):
The agent can also have memory, can operate in verbose mode, and can delegate tasks to other agents.
Attributes:
- agent_executor: An instance of the CrewAgentExecutor or AgentExecutor class.
+ agent_executor: The AgentExecutor running this agent.
role: The role of the agent.
goal: The objective of the agent.
backstory: The backstory of the agent.
@@ -390,16 +385,17 @@ class Agent(BaseAgent):
Can be a single A2AConfig/A2AClientConfig/A2AServerConfig, or a list of any number of A2AConfig/A2AClientConfig with a single A2AServerConfig.
""",
)
- agent_executor: CrewAgentExecutor | AgentExecutor | None = Field(
- default=None, description="An instance of the CrewAgentExecutor class."
+ agent_executor: AgentExecutor | None = Field(
+ default=None,
+ description="Executor running this agent.",
)
executor_class: Annotated[
- type[CrewAgentExecutor] | type[AgentExecutor],
+ type[AgentExecutor],
BeforeValidator(_validate_executor_class),
PlainSerializer(_serialize_executor_class, return_type=str, when_used="json"),
] = Field(
default=AgentExecutor,
- description="Class to use for the agent executor. Defaults to AgentExecutor, can optionally use CrewAgentExecutor.",
+ description="Class to use for the agent executor. CrewAgentExecutor has been removed.",
)
@model_validator(mode="before")
@@ -1262,11 +1258,7 @@ class Agent(BaseAgent):
def create_agent_executor(
self, tools: list[BaseTool] | None = None, task: Task | None = None
) -> None:
- """Create an agent executor for the agent.
-
- Returns:
- An instance of the CrewAgentExecutor class.
- """
+ """Create the AgentExecutor for the agent."""
configured_tools = tools if tools is not None else self.tools or []
raw_tools = self._add_skill_loader_tool(list(configured_tools), task=task)
parsed_tools = parse_tools(raw_tools)
@@ -1346,10 +1338,7 @@ class Agent(BaseAgent):
self.agent_executor.tools = tools
self.agent_executor.original_tools = raw_tools
self.agent_executor.prompt = prompt
- if isinstance(self.agent_executor, AgentExecutor):
- self.agent_executor.stop_words = stop_words
- else:
- self.agent_executor.stop = stop_words
+ self.agent_executor.stop_words = stop_words
self.agent_executor.tools_names = get_tool_names(tools)
self.agent_executor.tools_description = render_text_description_and_args(tools)
self.agent_executor.response_model = (
diff --git a/lib/crewai/src/crewai/agent/utils.py b/lib/crewai/src/crewai/agent/utils.py
index 297322a0c..f5378c7ef 100644
--- a/lib/crewai/src/crewai/agent/utils.py
+++ b/lib/crewai/src/crewai/agent/utils.py
@@ -33,8 +33,7 @@ def handle_reasoning(agent: Agent, task: Task) -> None:
This function checks if planning is enabled for the agent and, if so,
creates a plan that gets appended to the task description.
- Note: This function is used by CrewAgentExecutor (legacy path).
- For AgentExecutor, planning is handled in AgentExecutor.generate_plan().
+ AgentExecutor handles planning in AgentExecutor.generate_plan().
Args:
agent: The agent performing the task.
diff --git a/lib/crewai/src/crewai/agents/__init__.py b/lib/crewai/src/crewai/agents/__init__.py
index 228136710..32985c40c 100644
--- a/lib/crewai/src/crewai/agents/__init__.py
+++ b/lib/crewai/src/crewai/agents/__init__.py
@@ -6,23 +6,32 @@ from crewai.agents.tools_handler import ToolsHandler
if TYPE_CHECKING:
- from crewai.agents.crew_agent_executor import CrewAgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor, AgentExecutorState
__all__ = [
"AgentAction",
+ "AgentExecutor",
+ "AgentExecutorState",
"AgentFinish",
"CacheHandler",
- "CrewAgentExecutor",
"OutputParserError",
"ToolsHandler",
"parse",
]
+_LAZY_EXPORTS = {
+ "AgentExecutor": ("crewai.agents.agent_executor", "AgentExecutor"),
+ "AgentExecutorState": ("crewai.agents.agent_executor", "AgentExecutorState"),
+}
+
def __getattr__(name: str) -> Any:
- if name == "CrewAgentExecutor":
- from crewai.agents.crew_agent_executor import CrewAgentExecutor
+ if name in _LAZY_EXPORTS:
+ import importlib
- return CrewAgentExecutor
+ module_path, attr = _LAZY_EXPORTS[name]
+ value = getattr(importlib.import_module(module_path), attr)
+ globals()[name] = value
+ return value
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/lib/crewai/src/crewai/agents/agent_builder/base_agent.py b/lib/crewai/src/crewai/agents/agent_builder/base_agent.py
index 46d858287..f4c03d4ea 100644
--- a/lib/crewai/src/crewai/agents/agent_builder/base_agent.py
+++ b/lib/crewai/src/crewai/agents/agent_builder/base_agent.py
@@ -138,8 +138,7 @@ def _resolve_agent(value: Any, info: Any) -> Any:
_EXECUTOR_TYPE_REGISTRY: dict[str, str] = {
"base": "crewai.agents.agent_builder.base_agent_executor.BaseAgentExecutor",
- "crew": "crewai.agents.crew_agent_executor.CrewAgentExecutor",
- "experimental": "crewai.experimental.agent_executor.AgentExecutor",
+ "agent": "crewai.agents.agent_executor.AgentExecutor",
}
@@ -203,7 +202,7 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
allow_delegation (bool): Allow delegation of tasks to agents.
tools (list[Any] | None): Tools at the agent's disposal.
max_iter (int): Maximum iterations for an agent to execute a task.
- agent_executor: An instance of the CrewAgentExecutor class.
+ agent_executor: The executor running this agent. Defaults to AgentExecutor.
i18n (I18N): Internationalization settings.
llm (Any): Language model that will run the agent.
crew (Any): Crew to which the agent belongs.
@@ -301,7 +300,10 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
PlainSerializer(
_serialize_executor_ref, return_type=dict | None, when_used="json"
),
- ] = Field(default=None, description="An instance of the CrewAgentExecutor class.")
+ ] = Field(
+ default=None,
+ description="Executor running this agent. Defaults to AgentExecutor.",
+ )
i18n: I18N = Field(
default_factory=get_i18n,
description="Internationalization settings.",
diff --git a/lib/crewai/src/crewai/experimental/agent_executor.py b/lib/crewai/src/crewai/agents/agent_executor.py
similarity index 99%
rename from lib/crewai/src/crewai/experimental/agent_executor.py
rename to lib/crewai/src/crewai/agents/agent_executor.py
index 154b457a4..0974ae7cc 100644
--- a/lib/crewai/src/crewai/experimental/agent_executor.py
+++ b/lib/crewai/src/crewai/agents/agent_executor.py
@@ -201,7 +201,7 @@ class AgentExecutor(Flow[AgentExecutorState], BaseAgentExecutor):
_skip_auto_memory: bool = True
- executor_type: Literal["experimental"] = "experimental"
+ executor_type: Literal["agent"] = "agent"
suppress_flow_events: bool = True # always suppress for executor
is_crewai_internal: ClassVar[bool] = True
llm: BaseLLM | None = Field(default=None, exclude=True)
@@ -3539,7 +3539,3 @@ class AgentExecutor(Flow[AgentExecutorState], BaseAgentExecutor):
return format_message_for_llm(
I18N_DEFAULT.slice("feedback_instructions").format(feedback=feedback)
)
-
-
-# Backward compatibility alias (deprecated)
-CrewAgentExecutorFlow = AgentExecutor
diff --git a/lib/crewai/src/crewai/agents/crew_agent_executor.py b/lib/crewai/src/crewai/agents/crew_agent_executor.py
deleted file mode 100644
index ec16fa1ac..000000000
--- a/lib/crewai/src/crewai/agents/crew_agent_executor.py
+++ /dev/null
@@ -1,1659 +0,0 @@
-# mypy: disable-error-code="union-attr,arg-type"
-"""Agent executor for crew AI agents.
-
-Handles agent execution flow including LLM interactions, tool execution,
-and memory management.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from collections.abc import Callable
-from concurrent.futures import ThreadPoolExecutor, as_completed
-import contextvars
-import inspect
-import logging
-from typing import TYPE_CHECKING, Annotated, Any, Literal, cast
-import warnings
-
-from crewai_core.printer import PRINTER
-from pydantic import (
- AliasChoices,
- BaseModel,
- BeforeValidator,
- ConfigDict,
- Field,
- ValidationError,
-)
-from pydantic.functional_serializers import PlainSerializer
-
-from crewai.agents.agent_builder.base_agent import _serialize_llm_ref, _validate_llm_ref
-from crewai.agents.agent_builder.base_agent_executor import BaseAgentExecutor
-from crewai.agents.parser import (
- AgentAction,
- AgentFinish,
- OutputParserError,
-)
-from crewai.core.providers.human_input import ExecutorContext, get_provider
-from crewai.events.event_bus import crewai_event_bus
-from crewai.events.types.logging_events import (
- AgentLogsExecutionEvent,
- AgentLogsStartedEvent,
-)
-from crewai.hooks.llm_hooks import (
- get_after_llm_call_hooks,
- get_before_llm_call_hooks,
-)
-from crewai.hooks.tool_hooks import (
- ToolCallHookContext,
- run_after_tool_call_hooks,
- run_before_tool_call_hooks,
-)
-from crewai.types.callback import SerializableCallable
-from crewai.utilities.agent_utils import (
- _llm_stop_words_applied,
- aget_llm_response,
- build_text_tool_calling_fallback_message,
- convert_tools_to_openai_schema,
- enforce_rpm_limit,
- format_message_for_llm,
- format_native_tool_output_for_agent,
- get_llm_response,
- handle_agent_action_core,
- handle_context_length,
- handle_max_iterations_exceeded,
- handle_output_parser_exception,
- handle_unknown_error,
- has_reached_max_iterations,
- is_context_length_exceeded,
- is_native_tool_calling_unsupported_error,
- parse_tool_call_args,
- process_llm_response,
- track_delegation_if_needed,
-)
-from crewai.utilities.constants import TRAINING_DATA_FILE
-from crewai.utilities.file_store import aget_all_files, get_all_files
-from crewai.utilities.i18n import I18N_DEFAULT
-from crewai.utilities.string_utils import sanitize_tool_name
-from crewai.utilities.token_counter_callback import TokenCalcHandler
-from crewai.utilities.tool_utils import (
- aexecute_tool_and_check_finality,
- execute_tool_and_check_finality,
-)
-from crewai.utilities.training_handler import CrewTrainingHandler
-
-
-logger = logging.getLogger(__name__)
-
-if TYPE_CHECKING:
- from crewai.agents.tools_handler import ToolsHandler
- from crewai.llms.base_llm import BaseLLM
- from crewai.tools.base_tool import BaseTool
- from crewai.tools.structured_tool import CrewStructuredTool
- from crewai.tools.tool_types import ToolResult
- from crewai.utilities.prompts import StandardPromptResult, SystemPromptResult
- from crewai.utilities.types import LLMMessage
-
-
-class CrewAgentExecutor(BaseAgentExecutor):
- """Executor for crew agents.
-
- Manages the execution lifecycle of an agent including prompt formatting,
- LLM interactions, tool execution, and feedback handling.
- """
-
- executor_type: Literal["crew"] = "crew"
- llm: Annotated[
- BaseLLM | str | None,
- BeforeValidator(_validate_llm_ref),
- PlainSerializer(_serialize_llm_ref, return_type=dict | None, when_used="json"),
- ] = Field(default=None)
- prompt: SystemPromptResult | StandardPromptResult | None = Field(default=None)
- tools: list[CrewStructuredTool] = Field(default_factory=list)
- tools_names: str = Field(default="")
- stop: list[str] = Field(
- default_factory=list, validation_alias=AliasChoices("stop", "stop_words")
- )
- tools_description: str = Field(default="")
- tools_handler: ToolsHandler | None = Field(default=None)
- step_callback: SerializableCallable | None = Field(default=None, exclude=True)
- original_tools: list[BaseTool] = Field(default_factory=list)
- function_calling_llm: Annotated[
- BaseLLM | str | None,
- BeforeValidator(_validate_llm_ref),
- PlainSerializer(_serialize_llm_ref, return_type=dict | None, when_used="json"),
- ] = Field(default=None)
- respect_context_window: bool = Field(default=False)
- request_within_rpm_limit: SerializableCallable | None = Field(
- default=None, exclude=True
- )
- callbacks: list[TokenCalcHandler] = Field(default_factory=list, exclude=True)
- response_model: type[BaseModel] | None = Field(default=None, exclude=True)
- ask_for_human_input: bool = Field(default=False)
- log_error_after: int = Field(default=3)
- before_llm_call_hooks: list[SerializableCallable] = Field(
- default_factory=list, exclude=True
- )
- after_llm_call_hooks: list[SerializableCallable] = Field(
- default_factory=list, exclude=True
- )
-
- model_config = ConfigDict(arbitrary_types_allowed=True, populate_by_name=True)
-
- def __init__(self, **kwargs: Any) -> None:
- super().__init__(**kwargs)
- warnings.warn(
- "CrewAgentExecutor is deprecated and will be removed in a future release.\n"
- "Agents inside Crews now use AgentExecutor (crewai.experimental.AgentExecutor) by default.\n"
- "To suppress this warning, migrate to AgentExecutor.",
- DeprecationWarning,
- stacklevel=2,
- )
- if not self.before_llm_call_hooks:
- self.before_llm_call_hooks.extend(get_before_llm_call_hooks())
- if not self.after_llm_call_hooks:
- self.after_llm_call_hooks.extend(get_after_llm_call_hooks())
-
- @property
- def use_stop_words(self) -> bool:
- """Check to determine if stop words are being used.
-
- Returns:
- bool: True if tool should be used or not.
- """
- from crewai.llms.base_llm import BaseLLM
-
- return (
- self.llm.supports_stop_words() if isinstance(self.llm, BaseLLM) else False
- )
-
- def _append_history(self, inputs: dict[str, Any]) -> None:
- """Add prior turns, with their roles, before this turn's request."""
- for message in inputs.get("history", []):
- self.messages.append(dict(message))
-
- def _append_trailing(self, inputs: dict[str, Any]) -> None:
- """Add turns that followed the request, keeping them after it.
-
- A conversation can end past its last user message -- an assistant
- tool call and its result, or an agent's own scratch thread. Those
- belong after the question they answer, not hoisted above it.
- """
- for message in inputs.get("trailing", []):
- self.messages.append(dict(message))
-
- def _setup_messages(self, inputs: dict[str, Any]) -> None:
- """Set up messages for the agent execution.
-
- Args:
- inputs: Input dictionary containing prompt variables.
- """
- provider = get_provider()
- if provider.setup_messages(cast(ExecutorContext, cast(object, self))):
- return
-
- from crewai.llms.cache import mark_cache_breakpoint
-
- if self.prompt is not None and "system" in self.prompt:
- system_prompt = self._format_prompt(
- cast(str, self.prompt.get("system", "")), inputs
- )
- user_prompt = self._format_prompt(
- cast(str, self.prompt.get("user", "")), inputs
- )
- # Cache breakpoints: end-of-system caches the per-agent stable
- # prefix; end-of-user caches the per-task stable prefix across
- # ReAct-loop iterations.
- self.messages.append(
- mark_cache_breakpoint(
- format_message_for_llm(system_prompt, role="system")
- )
- )
- self._append_history(inputs)
- self.messages.append(
- mark_cache_breakpoint(format_message_for_llm(user_prompt))
- )
- self._append_trailing(inputs)
- elif self.prompt is not None:
- user_prompt = self._format_prompt(self.prompt.get("prompt", ""), inputs)
- # Also here: with the system prompt disabled or a custom template
- # this is the only branch, and skipping history would drop every
- # turn but the last.
- self._append_history(inputs)
- self.messages.append(
- mark_cache_breakpoint(format_message_for_llm(user_prompt))
- )
- self._append_trailing(inputs)
-
- provider.post_setup_messages(cast(ExecutorContext, cast(object, self)))
-
- def invoke(self, inputs: dict[str, Any]) -> dict[str, Any]:
- """Execute the agent with given inputs.
-
- Args:
- inputs: Input dictionary containing prompt variables.
-
- Returns:
- Dictionary with agent output.
- """
- if self._resuming:
- self._resuming = False
- else:
- self.messages = []
- self.iterations = 0
- self._setup_messages(inputs)
- self._inject_multimodal_files(inputs)
-
- self._show_start_logs()
-
- self.ask_for_human_input = bool(inputs.get("ask_for_human_input", False))
-
- with _llm_stop_words_applied(self.llm, self):
- try:
- formatted_answer = self._invoke_loop()
- except AssertionError:
- if self.agent.verbose:
- PRINTER.print(
- content="Agent failed to reach a final answer. This is likely a bug - please report it.",
- color="red",
- )
- raise
- except Exception as e:
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise
-
- if self.ask_for_human_input:
- formatted_answer = self._handle_human_feedback(formatted_answer)
-
- self._save_to_memory(formatted_answer)
- return {"output": formatted_answer.output}
-
- def _inject_multimodal_files(self, inputs: dict[str, Any] | None = None) -> None:
- """Attach files to the last user message for LLM-layer formatting.
-
- Merges files from crew/task store and inputs dict, then attaches them
- to the message's `files` field. Input files take precedence over
- crew/task files with the same name.
-
- Args:
- inputs: Optional inputs dict that may contain files.
- """
- files: dict[str, Any] = {}
-
- if self.crew and self.task:
- crew_files = get_all_files(self.crew.id, self.task.id)
- if crew_files:
- files.update(crew_files)
-
- if inputs and inputs.get("files"):
- files.update(inputs["files"])
-
- if not files:
- return
-
- for i in range(len(self.messages) - 1, -1, -1):
- msg = self.messages[i]
- if msg.get("role") == "user":
- msg["files"] = files
- break
-
- async def _ainject_multimodal_files(
- self, inputs: dict[str, Any] | None = None
- ) -> None:
- """Async attach files to the last user message for LLM-layer formatting.
-
- Merges files from crew/task store and inputs dict, then attaches them
- to the message's `files` field. Input files take precedence over
- crew/task files with the same name.
-
- Args:
- inputs: Optional inputs dict that may contain files.
- """
- files: dict[str, Any] = {}
-
- if self.crew and self.task:
- crew_files = await aget_all_files(self.crew.id, self.task.id)
- if crew_files:
- files.update(crew_files)
-
- if inputs and inputs.get("files"):
- files.update(inputs["files"])
-
- if not files:
- return
-
- for i in range(len(self.messages) - 1, -1, -1):
- msg = self.messages[i]
- if msg.get("role") == "user":
- msg["files"] = files
- break
-
- def _invoke_loop(self) -> AgentFinish:
- """Execute agent loop until completion.
-
- Checks if the LLM supports native function calling and uses that
- approach if available, otherwise falls back to the ReAct text pattern.
-
- Returns:
- Final answer from the agent.
- """
- use_native_tools = (
- hasattr(self.llm, "supports_function_calling")
- and callable(getattr(self.llm, "supports_function_calling", None))
- and self.llm.supports_function_calling()
- and self.original_tools
- )
-
- if use_native_tools:
- return self._invoke_loop_native_tools()
-
- return self._invoke_loop_react()
-
- def _invoke_loop_react(self) -> AgentFinish:
- """Execute agent loop using ReAct text-based pattern.
-
- This is the traditional approach where tool definitions are embedded
- in the prompt and the LLM outputs Action/Action Input text that is
- parsed to execute tools.
-
- Returns:
- Final answer from the agent.
- """
- formatted_answer = None
- while not isinstance(formatted_answer, AgentFinish):
- try:
- if has_reached_max_iterations(self.iterations, self.max_iter):
- formatted_answer = handle_max_iterations_exceeded(
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- break
-
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- effective_response_model = (
- None if self.original_tools else self.response_model
- )
-
- answer = get_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- from_task=self.task,
- from_agent=self.agent,
- response_model=effective_response_model,
- executor_context=self,
- verbose=self.agent.verbose,
- )
- if effective_response_model is not None:
- try:
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- else:
- self.response_model.model_validate_json(answer)
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=answer,
- )
- except ValidationError:
- answer_str = (
- answer.model_dump_json()
- if isinstance(answer, BaseModel)
- else str(answer)
- )
- formatted_answer = process_llm_response(
- answer_str, self.use_stop_words
- ) # type: ignore[assignment]
- else:
- answer_str = str(answer) if not isinstance(answer, str) else answer
- formatted_answer = process_llm_response(
- answer_str, self.use_stop_words
- ) # type: ignore[assignment]
-
- if isinstance(formatted_answer, AgentAction):
- fingerprint_context = {}
- if (
- self.agent
- and hasattr(self.agent, "security_config")
- and hasattr(self.agent.security_config, "fingerprint")
- ):
- fingerprint_context = {
- "agent_fingerprint": str(
- self.agent.security_config.fingerprint
- )
- }
-
- tool_result = execute_tool_and_check_finality(
- agent_action=formatted_answer,
- fingerprint_context=fingerprint_context,
- tools=self.tools,
- agent_key=self.agent.key if self.agent else None,
- agent_role=self.agent.role if self.agent else None,
- tools_handler=self.tools_handler,
- task=self.task,
- agent=self.agent,
- function_calling_llm=self.function_calling_llm,
- crew=self.crew,
- )
- formatted_answer = self._handle_agent_action(
- formatted_answer, tool_result
- )
-
- self._invoke_step_callback(formatted_answer)
- self._append_message(formatted_answer.text)
-
- except OutputParserError as e:
- formatted_answer = handle_output_parser_exception( # type: ignore[assignment]
- e=e,
- messages=self.messages,
- iterations=self.iterations,
- log_error_after=self.log_error_after,
- printer=PRINTER,
- verbose=self.agent.verbose,
- )
-
- except Exception as e:
- if e.__class__.__module__.startswith("litellm"):
- raise e
- if is_context_length_exceeded(e):
- handle_context_length(
- respect_context_window=self.respect_context_window,
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- continue
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise e
- finally:
- self.iterations += 1
-
- if not isinstance(formatted_answer, AgentFinish):
- raise RuntimeError(
- "Agent execution ended without reaching a final answer. "
- f"Got {type(formatted_answer).__name__} instead of AgentFinish."
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- def _append_text_tool_calling_fallback_message(self) -> None:
- """Add text tool-calling instructions after native tools are rejected."""
- if not self.tools:
- return
- self.messages.append(
- format_message_for_llm(
- build_text_tool_calling_fallback_message(
- self.tools_description,
- self.tools_names,
- ),
- role="user",
- )
- )
-
- def _invoke_loop_native_tools(self) -> AgentFinish:
- """Execute agent loop using native function calling.
-
- This method uses the LLM's native tool/function calling capability
- instead of the text-based ReAct pattern. The LLM directly returns
- structured tool calls which are executed and results fed back.
-
- Returns:
- Final answer from the agent.
- """
- if not self.original_tools:
- return self._invoke_loop_native_no_tools()
-
- openai_tools, available_functions, self._tool_name_mapping = (
- convert_tools_to_openai_schema(self.original_tools)
- )
-
- while True:
- try:
- if has_reached_max_iterations(self.iterations, self.max_iter):
- formatted_answer = handle_max_iterations_exceeded(
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- answer = get_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- tools=openai_tools,
- available_functions=None,
- from_task=self.task,
- from_agent=self.agent,
- response_model=None,
- executor_context=self,
- verbose=self.agent.verbose,
- )
-
- if (
- isinstance(answer, list)
- and answer
- and self._is_tool_call_list(answer)
- ):
- tool_finish = self._handle_native_tool_calls(
- answer, available_functions
- )
- if tool_finish is not None:
- return tool_finish
- continue
-
- if isinstance(answer, str):
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=answer,
- )
- self._invoke_step_callback(formatted_answer)
- self._append_message(answer)
- self._show_logs(formatted_answer)
- return formatted_answer
-
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- self._invoke_step_callback(formatted_answer)
- self._append_message(output_json)
- self._show_logs(formatted_answer)
- return formatted_answer
-
- formatted_answer = AgentFinish(
- thought="",
- output=str(answer),
- text=str(answer),
- )
- self._invoke_step_callback(formatted_answer)
- self._append_message(str(answer))
- self._show_logs(formatted_answer)
- return formatted_answer
-
- except Exception as e:
- if is_native_tool_calling_unsupported_error(e):
- self._append_text_tool_calling_fallback_message()
- return self._invoke_loop_react()
- if e.__class__.__module__.startswith("litellm"):
- raise e
- if is_context_length_exceeded(e):
- handle_context_length(
- respect_context_window=self.respect_context_window,
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- continue
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise e
- finally:
- self.iterations += 1
-
- def _invoke_loop_native_no_tools(self) -> AgentFinish:
- """Execute a simple LLM call when no tools are available.
-
- Returns:
- Final answer from the agent.
- """
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- answer = get_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- from_task=self.task,
- from_agent=self.agent,
- response_model=self.response_model,
- executor_context=self,
- verbose=self.agent.verbose,
- )
-
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- else:
- answer_str = answer if isinstance(answer, str) else str(answer)
- formatted_answer = AgentFinish(
- thought="",
- output=answer_str,
- text=answer_str,
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- def _is_tool_call_list(self, response: list[Any]) -> bool:
- """Check if a response is a list of tool calls.
-
- Args:
- response: The response to check.
-
- Returns:
- True if the response appears to be a list of tool calls.
- """
- if not response:
- return False
- first_item = response[0]
- if hasattr(first_item, "function") or (
- isinstance(first_item, dict) and "function" in first_item
- ):
- return True
- if (
- hasattr(first_item, "type")
- and getattr(first_item, "type", None) == "tool_use"
- ):
- return True
- if hasattr(first_item, "name") and hasattr(first_item, "input"):
- return True
- if (
- isinstance(first_item, dict)
- and "name" in first_item
- and "input" in first_item
- ):
- return True
- if hasattr(first_item, "function_call") and first_item.function_call:
- return True
- return False
-
- def _handle_native_tool_calls(
- self,
- tool_calls: list[Any],
- available_functions: dict[str, Callable[..., Any]],
- ) -> AgentFinish | None:
- """Handle a single native tool call from the LLM.
-
- Executes only the FIRST tool call and appends the result to message history.
- This enables sequential tool execution with reflection after each tool,
- allowing the LLM to reason about results before deciding on next steps.
-
- Args:
- tool_calls: List of tool calls from the LLM (only first is processed).
- available_functions: Dict mapping function names to callables.
-
- Returns:
- AgentFinish if tool has result_as_answer=True, None otherwise.
- """
- if not tool_calls:
- return None
-
- parsed_calls = [
- parsed
- for tool_call in tool_calls
- if (parsed := self._parse_native_tool_call(tool_call)) is not None
- ]
- if not parsed_calls:
- return None
-
- original_tools_by_name: dict[str, Any] = dict(self._tool_name_mapping)
-
- if len(parsed_calls) > 1:
- has_result_as_answer_in_batch = any(
- bool(
- original_tools_by_name.get(func_name)
- and getattr(
- original_tools_by_name.get(func_name), "result_as_answer", False
- )
- )
- for _, func_name, _ in parsed_calls
- )
- has_max_usage_count_in_batch = any(
- bool(
- original_tools_by_name.get(func_name)
- and getattr(
- original_tools_by_name.get(func_name),
- "max_usage_count",
- None,
- )
- is not None
- )
- for _, func_name, _ in parsed_calls
- )
-
- if has_result_as_answer_in_batch or has_max_usage_count_in_batch:
- logger.debug(
- "Skipping parallel native execution because batch includes result_as_answer or max_usage_count tool"
- )
- else:
- execution_plan: list[
- tuple[str, str, str | dict[str, Any], Any | None]
- ] = []
- for call_id, func_name, func_args in parsed_calls:
- original_tool = original_tools_by_name.get(func_name)
- execution_plan.append(
- (call_id, func_name, func_args, original_tool)
- )
-
- self._append_assistant_tool_calls_message(
- [
- (call_id, func_name, func_args)
- for call_id, func_name, func_args, _ in execution_plan
- ]
- )
-
- max_workers = min(8, len(execution_plan))
- ordered_results: list[dict[str, Any] | None] = [None] * len(
- execution_plan
- )
- with ThreadPoolExecutor(max_workers=max_workers) as pool:
- futures = {
- pool.submit(
- contextvars.copy_context().run,
- self._execute_single_native_tool_call,
- call_id=call_id,
- func_name=func_name,
- func_args=func_args,
- available_functions=available_functions,
- original_tool=original_tool,
- should_execute=True,
- ): idx
- for idx, (
- call_id,
- func_name,
- func_args,
- original_tool,
- ) in enumerate(execution_plan)
- }
- for future in as_completed(futures):
- idx = futures[future]
- ordered_results[idx] = future.result()
-
- for execution_result in ordered_results:
- if not execution_result:
- continue
- tool_finish = self._append_tool_result_and_check_finality(
- execution_result
- )
- if tool_finish:
- return tool_finish
-
- reasoning_prompt = I18N_DEFAULT.slice("post_tool_reasoning")
- reasoning_message: LLMMessage = {
- "role": "user",
- "content": reasoning_prompt,
- }
- self.messages.append(reasoning_message)
- return None
-
- call_id, func_name, func_args = parsed_calls[0]
- self._append_assistant_tool_calls_message([(call_id, func_name, func_args)])
-
- execution_result = self._execute_single_native_tool_call(
- call_id=call_id,
- func_name=func_name,
- func_args=func_args,
- available_functions=available_functions,
- original_tool=original_tools_by_name.get(func_name),
- should_execute=True,
- )
- tool_finish = self._append_tool_result_and_check_finality(execution_result)
- if tool_finish:
- return tool_finish
-
- reasoning_prompt = I18N_DEFAULT.slice("post_tool_reasoning")
- reasoning_message = {
- "role": "user",
- "content": reasoning_prompt,
- }
- self.messages.append(reasoning_message)
- return None
-
- def _parse_native_tool_call(
- self, tool_call: Any
- ) -> tuple[str, str, str | dict[str, Any]] | None:
- if hasattr(tool_call, "function"):
- call_id = getattr(tool_call, "id", f"call_{id(tool_call)}")
- func_name = sanitize_tool_name(tool_call.function.name)
- return call_id, func_name, tool_call.function.arguments
- if hasattr(tool_call, "function_call") and tool_call.function_call:
- call_id = f"call_{id(tool_call)}"
- func_name = sanitize_tool_name(tool_call.function_call.name)
- func_args = (
- dict(tool_call.function_call.args)
- if tool_call.function_call.args
- else {}
- )
- return call_id, func_name, func_args
- if hasattr(tool_call, "name") and hasattr(tool_call, "input"):
- call_id = getattr(tool_call, "id", f"call_{id(tool_call)}")
- func_name = sanitize_tool_name(tool_call.name)
- return call_id, func_name, tool_call.input
- if isinstance(tool_call, dict):
- call_id = (
- tool_call.get("id")
- or tool_call.get("toolUseId")
- or f"call_{id(tool_call)}"
- )
- func_info = tool_call.get("function", {})
- func_name = sanitize_tool_name(
- func_info.get("name", "") or tool_call.get("name", "")
- )
- func_args = func_info.get("arguments") or tool_call.get("input", {})
- return call_id, func_name, func_args
- return None
-
- def _append_assistant_tool_calls_message(
- self,
- parsed_calls: list[tuple[str, str, str | dict[str, Any]]],
- ) -> None:
- import json
-
- assistant_message: LLMMessage = {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": call_id,
- "type": "function",
- "function": {
- "name": func_name,
- "arguments": func_args
- if isinstance(func_args, str)
- else json.dumps(func_args),
- },
- }
- for call_id, func_name, func_args in parsed_calls
- ],
- }
- self.messages.append(assistant_message)
-
- def _execute_single_native_tool_call(
- self,
- *,
- call_id: str,
- func_name: str,
- func_args: str | dict[str, Any],
- available_functions: dict[str, Callable[..., Any]],
- original_tool: Any | None = None,
- should_execute: bool = True,
- ) -> dict[str, Any]:
- from datetime import datetime
- import json
-
- from crewai.events.types.tool_usage_events import (
- ToolUsageErrorEvent,
- ToolUsageFinishedEvent,
- ToolUsageStartedEvent,
- )
-
- args_dict, parse_error = parse_tool_call_args(
- func_args, func_name, call_id, original_tool
- )
- if parse_error is not None:
- return parse_error
-
- if original_tool is None:
- for tool in self.original_tools or []:
- if sanitize_tool_name(tool.name) == func_name:
- original_tool = tool
- break
-
- max_usage_reached = False
- if not should_execute and original_tool:
- max_usage_reached = True
- elif (
- should_execute
- and original_tool
- and (max_count := getattr(original_tool, "max_usage_count", None))
- is not None
- and getattr(original_tool, "current_usage_count", 0) >= max_count
- ):
- max_usage_reached = True
-
- structured_tool: CrewStructuredTool | None = None
- if original_tool is not None:
- for structured in self.tools or []:
- if getattr(structured, "_original_tool", None) is original_tool:
- structured_tool = structured
- break
- if structured_tool is None:
- for structured in self.tools or []:
- if sanitize_tool_name(structured.name) == func_name:
- structured_tool = structured
- break
-
- output_tool = original_tool or structured_tool
-
- from_cache = False
- result: str = "Tool not found"
- raw_tool_result: Any = result
- input_str = json.dumps(args_dict) if args_dict else ""
- if self.tools_handler and self.tools_handler.cache and output_tool is not None:
- cached_result = self.tools_handler.cache.read(
- tool=func_name, input=input_str
- )
- if cached_result is not None:
- raw_tool_result = cached_result
- result = format_native_tool_output_for_agent(output_tool, cached_result)
- from_cache = True
-
- agent_key = getattr(self.agent, "key", "unknown") if self.agent else "unknown"
- started_at = datetime.now()
- crewai_event_bus.emit(
- self,
- event=ToolUsageStartedEvent(
- tool_name=func_name,
- tool_args=args_dict,
- from_agent=self.agent,
- from_task=self.task,
- agent_key=agent_key,
- ),
- )
- error_event_emitted = False
-
- track_delegation_if_needed(func_name, args_dict or {}, self.task)
-
- before_hook_context = ToolCallHookContext(
- tool_name=func_name,
- tool_input=args_dict or {},
- tool=structured_tool,
- agent=self.agent,
- task=self.task,
- crew=self.crew,
- )
- hook_blocked = run_before_tool_call_hooks(before_hook_context)
-
- if hook_blocked:
- result = f"Tool execution blocked by hook. Tool: {func_name}"
- raw_tool_result = result
- elif max_usage_reached and original_tool:
- result = f"Tool '{func_name}' has reached its usage limit of {original_tool.max_usage_count} times and cannot be used anymore."
- raw_tool_result = result
- elif (
- not from_cache
- and func_name in available_functions
- and output_tool is not None
- ):
- try:
- raw_result = available_functions[func_name](**(args_dict or {}))
- raw_tool_result = raw_result
-
- if self.tools_handler and self.tools_handler.cache:
- should_cache = True
- if (
- original_tool
- and hasattr(original_tool, "cache_function")
- and callable(original_tool.cache_function)
- ):
- should_cache = original_tool.cache_function(
- args_dict or {}, raw_result
- )
- if should_cache:
- self.tools_handler.cache.add(
- tool=func_name, input=input_str, output=raw_result
- )
-
- result = format_native_tool_output_for_agent(output_tool, raw_result)
- except Exception as e:
- result = f"Error executing tool: {e}"
- raw_tool_result = result
- if self.task:
- self.task.increment_tools_errors()
- crewai_event_bus.emit(
- self,
- event=ToolUsageErrorEvent(
- tool_name=func_name,
- tool_args=args_dict,
- from_agent=self.agent,
- from_task=self.task,
- agent_key=agent_key,
- error=e,
- ),
- )
- error_event_emitted = True
-
- after_hook_context = ToolCallHookContext(
- tool_name=func_name,
- tool_input=args_dict or {},
- tool=structured_tool,
- agent=self.agent,
- task=self.task,
- crew=self.crew,
- tool_result=result,
- raw_tool_result=raw_tool_result,
- )
- modified_result = run_after_tool_call_hooks(after_hook_context)
- if modified_result is not None:
- result = modified_result
-
- if not error_event_emitted:
- crewai_event_bus.emit(
- self,
- event=ToolUsageFinishedEvent(
- output=result,
- tool_name=func_name,
- tool_args=args_dict,
- from_agent=self.agent,
- from_task=self.task,
- agent_key=agent_key,
- started_at=started_at,
- finished_at=datetime.now(),
- from_cache=from_cache,
- ),
- )
-
- return {
- "call_id": call_id,
- "func_name": func_name,
- "result": result,
- "from_cache": from_cache,
- "original_tool": original_tool,
- }
-
- def _append_tool_result_and_check_finality(
- self, execution_result: dict[str, Any]
- ) -> AgentFinish | None:
- call_id = cast(str, execution_result["call_id"])
- func_name = cast(str, execution_result["func_name"])
- result = cast(str, execution_result["result"])
- original_tool = execution_result["original_tool"]
-
- tool_message: LLMMessage = {
- "role": "tool",
- "tool_call_id": call_id,
- "name": func_name,
- "content": result,
- }
- self.messages.append(tool_message)
-
- if (
- original_tool
- and hasattr(original_tool, "result_as_answer")
- and original_tool.result_as_answer
- ):
- return AgentFinish(
- thought="Tool result is the final answer",
- output=result,
- text=result,
- )
- return None
-
- async def ainvoke(self, inputs: dict[str, Any]) -> dict[str, Any]:
- """Execute the agent asynchronously with given inputs.
-
- Args:
- inputs: Input dictionary containing prompt variables.
-
- Returns:
- Dictionary with agent output.
- """
- if self._resuming:
- self._resuming = False
- else:
- self.messages = []
- self.iterations = 0
- self._setup_messages(inputs)
- await self._ainject_multimodal_files(inputs)
-
- self._show_start_logs()
-
- self.ask_for_human_input = bool(inputs.get("ask_for_human_input", False))
-
- with _llm_stop_words_applied(self.llm, self):
- try:
- formatted_answer = await self._ainvoke_loop()
- except AssertionError:
- if self.agent.verbose:
- PRINTER.print(
- content="Agent failed to reach a final answer. This is likely a bug - please report it.",
- color="red",
- )
- raise
- except Exception as e:
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise
-
- if self.ask_for_human_input:
- formatted_answer = await self._ahandle_human_feedback(formatted_answer)
-
- self._save_to_memory(formatted_answer)
- return {"output": formatted_answer.output}
-
- async def _ainvoke_loop(self) -> AgentFinish:
- """Execute agent loop asynchronously until completion.
-
- Checks if the LLM supports native function calling and uses that
- approach if available, otherwise falls back to the ReAct text pattern.
-
- Returns:
- Final answer from the agent.
- """
- use_native_tools = (
- hasattr(self.llm, "supports_function_calling")
- and callable(getattr(self.llm, "supports_function_calling", None))
- and self.llm.supports_function_calling()
- and self.original_tools
- )
-
- if use_native_tools:
- return await self._ainvoke_loop_native_tools()
-
- return await self._ainvoke_loop_react()
-
- async def _ainvoke_loop_react(self) -> AgentFinish:
- """Execute agent loop asynchronously using ReAct text-based pattern.
-
- Returns:
- Final answer from the agent.
- """
- formatted_answer = None
- while not isinstance(formatted_answer, AgentFinish):
- try:
- if has_reached_max_iterations(self.iterations, self.max_iter):
- formatted_answer = handle_max_iterations_exceeded(
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- break
-
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- effective_response_model = (
- None if self.original_tools else self.response_model
- )
-
- answer = await aget_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- from_task=self.task,
- from_agent=self.agent,
- response_model=effective_response_model,
- executor_context=self,
- verbose=self.agent.verbose,
- )
-
- if effective_response_model is not None:
- try:
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- else:
- self.response_model.model_validate_json(answer)
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=answer,
- )
- except ValidationError:
- answer_str = (
- answer.model_dump_json()
- if isinstance(answer, BaseModel)
- else str(answer)
- )
- formatted_answer = process_llm_response(
- answer_str, self.use_stop_words
- ) # type: ignore[assignment]
- else:
- answer_str = str(answer) if not isinstance(answer, str) else answer
- formatted_answer = process_llm_response(
- answer_str, self.use_stop_words
- ) # type: ignore[assignment]
-
- if isinstance(formatted_answer, AgentAction):
- fingerprint_context = {}
- if (
- self.agent
- and hasattr(self.agent, "security_config")
- and hasattr(self.agent.security_config, "fingerprint")
- ):
- fingerprint_context = {
- "agent_fingerprint": str(
- self.agent.security_config.fingerprint
- )
- }
-
- tool_result = await aexecute_tool_and_check_finality(
- agent_action=formatted_answer,
- fingerprint_context=fingerprint_context,
- tools=self.tools,
- agent_key=self.agent.key if self.agent else None,
- agent_role=self.agent.role if self.agent else None,
- tools_handler=self.tools_handler,
- task=self.task,
- agent=self.agent,
- function_calling_llm=self.function_calling_llm,
- crew=self.crew,
- )
- formatted_answer = self._handle_agent_action(
- formatted_answer, tool_result
- )
-
- await self._ainvoke_step_callback(formatted_answer)
- self._append_message(formatted_answer.text)
-
- except OutputParserError as e:
- formatted_answer = handle_output_parser_exception( # type: ignore[assignment]
- e=e,
- messages=self.messages,
- iterations=self.iterations,
- log_error_after=self.log_error_after,
- printer=PRINTER,
- verbose=self.agent.verbose,
- )
-
- except Exception as e:
- if e.__class__.__module__.startswith("litellm"):
- raise e
- if is_context_length_exceeded(e):
- handle_context_length(
- respect_context_window=self.respect_context_window,
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- continue
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise e
- finally:
- self.iterations += 1
-
- if not isinstance(formatted_answer, AgentFinish):
- raise RuntimeError(
- "Agent execution ended without reaching a final answer. "
- f"Got {type(formatted_answer).__name__} instead of AgentFinish."
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- async def _ainvoke_loop_native_tools(self) -> AgentFinish:
- """Execute agent loop asynchronously using native function calling.
-
- This method uses the LLM's native tool/function calling capability
- instead of the text-based ReAct pattern.
-
- Returns:
- Final answer from the agent.
- """
- if not self.original_tools:
- return await self._ainvoke_loop_native_no_tools()
-
- openai_tools, available_functions, self._tool_name_mapping = (
- convert_tools_to_openai_schema(self.original_tools)
- )
-
- while True:
- try:
- if has_reached_max_iterations(self.iterations, self.max_iter):
- formatted_answer = handle_max_iterations_exceeded(
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- answer = await aget_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- tools=openai_tools,
- available_functions=None,
- from_task=self.task,
- from_agent=self.agent,
- response_model=None,
- executor_context=self,
- verbose=self.agent.verbose,
- )
- if (
- isinstance(answer, list)
- and answer
- and self._is_tool_call_list(answer)
- ):
- tool_finish = self._handle_native_tool_calls(
- answer, available_functions
- )
- if tool_finish is not None:
- return tool_finish
- continue
-
- if isinstance(answer, str):
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=answer,
- )
- await self._ainvoke_step_callback(formatted_answer)
- self._append_message(answer)
- self._show_logs(formatted_answer)
- return formatted_answer
-
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- await self._ainvoke_step_callback(formatted_answer)
- self._append_message(output_json)
- self._show_logs(formatted_answer)
- return formatted_answer
-
- formatted_answer = AgentFinish(
- thought="",
- output=str(answer),
- text=str(answer),
- )
- await self._ainvoke_step_callback(formatted_answer)
- self._append_message(str(answer))
- self._show_logs(formatted_answer)
- return formatted_answer
-
- except Exception as e:
- if is_native_tool_calling_unsupported_error(e):
- self._append_text_tool_calling_fallback_message()
- return await self._ainvoke_loop_react()
- if e.__class__.__module__.startswith("litellm"):
- raise e
- if is_context_length_exceeded(e):
- handle_context_length(
- respect_context_window=self.respect_context_window,
- printer=PRINTER,
- messages=self.messages,
- llm=cast("BaseLLM", self.llm),
- callbacks=self.callbacks,
- verbose=self.agent.verbose,
- )
- continue
- handle_unknown_error(PRINTER, e, verbose=self.agent.verbose)
- raise e
- finally:
- self.iterations += 1
-
- async def _ainvoke_loop_native_no_tools(self) -> AgentFinish:
- """Execute a simple async LLM call when no tools are available.
-
- Returns:
- Final answer from the agent.
- """
- enforce_rpm_limit(self.request_within_rpm_limit)
-
- answer = await aget_llm_response(
- llm=cast("BaseLLM", self.llm),
- messages=self.messages,
- callbacks=self.callbacks,
- printer=PRINTER,
- from_task=self.task,
- from_agent=self.agent,
- response_model=self.response_model,
- executor_context=self,
- verbose=self.agent.verbose,
- )
-
- if isinstance(answer, BaseModel):
- output_json = answer.model_dump_json()
- formatted_answer = AgentFinish(
- thought="",
- output=answer,
- text=output_json,
- )
- else:
- answer_str = answer if isinstance(answer, str) else str(answer)
- formatted_answer = AgentFinish(
- thought="",
- output=answer_str,
- text=answer_str,
- )
- self._show_logs(formatted_answer)
- return formatted_answer
-
- def _handle_agent_action(
- self, formatted_answer: AgentAction, tool_result: ToolResult
- ) -> AgentAction | AgentFinish:
- """Process agent action and tool execution.
-
- Args:
- formatted_answer: Agent's action to execute.
- tool_result: Result from tool execution.
-
- Returns:
- Updated action or final answer.
- """
- add_image_tool = I18N_DEFAULT.tools("add_image")
- if (
- isinstance(add_image_tool, dict)
- and formatted_answer.tool.casefold().strip()
- == add_image_tool.get("name", "").casefold().strip()
- ):
- self.messages.append({"role": "assistant", "content": tool_result.result})
- return formatted_answer
-
- return handle_agent_action_core(
- formatted_answer=formatted_answer,
- tool_result=tool_result,
- messages=self.messages,
- step_callback=self.step_callback,
- show_logs=self._show_logs,
- )
-
- def _invoke_step_callback(
- self, formatted_answer: AgentAction | AgentFinish
- ) -> None:
- """Invoke step callback (sync context).
-
- Args:
- formatted_answer: Current agent response.
- """
- if self.step_callback:
- cb_result = self.step_callback(formatted_answer)
- if inspect.iscoroutine(cb_result):
- asyncio.run(cb_result)
-
- async def _ainvoke_step_callback(
- self, formatted_answer: AgentAction | AgentFinish
- ) -> None:
- """Invoke step callback (async context).
-
- Args:
- formatted_answer: Current agent response.
- """
- if self.step_callback:
- cb_result = self.step_callback(formatted_answer)
- if inspect.iscoroutine(cb_result):
- await cb_result
-
- def _append_message(
- self, text: str, role: Literal["user", "assistant", "system"] = "assistant"
- ) -> None:
- """Add message to conversation history.
-
- Args:
- text: Message content.
- role: Message role (default: assistant).
- """
- self.messages.append(format_message_for_llm(text, role=role))
-
- def _show_start_logs(self) -> None:
- """Emit agent start event."""
- if self.agent is None:
- raise ValueError("Agent cannot be None")
-
- crewai_event_bus.emit(
- self.agent,
- AgentLogsStartedEvent(
- agent_role=self.agent.role,
- task_description=(self.task.description if self.task else "Not Found"),
- verbose=self.agent.verbose
- or (hasattr(self, "crew") and getattr(self.crew, "verbose", False)),
- ),
- )
-
- def _show_logs(self, formatted_answer: AgentAction | AgentFinish) -> None:
- """Emit agent execution event.
-
- Args:
- formatted_answer: Agent's response to log.
- """
- if self.agent is None:
- raise ValueError("Agent cannot be None")
-
- future = crewai_event_bus.emit(
- self.agent,
- AgentLogsExecutionEvent(
- agent_role=self.agent.role,
- formatted_answer=formatted_answer,
- verbose=self.agent.verbose
- or (hasattr(self, "crew") and getattr(self.crew, "verbose", False)),
- ),
- )
-
- if future is not None:
- try:
- future.result(timeout=5.0)
- except Exception as e:
- logger.error(f"Failed to show logs for agent execution event: {e}")
-
- def _handle_crew_training_output(
- self, result: AgentFinish, human_feedback: str | None = None
- ) -> None:
- """Save training data.
-
- Args:
- result: Agent's final output.
- human_feedback: Optional feedback from human.
- """
- agent_id = str(self.agent.id)
- train_iteration = (
- getattr(self.crew, "_train_iteration", None) if self.crew else None
- )
-
- if train_iteration is None or not isinstance(train_iteration, int):
- if self.agent.verbose:
- PRINTER.print(
- content="Invalid or missing train iteration. Cannot save training data.",
- color="red",
- )
- return
-
- training_handler = CrewTrainingHandler(TRAINING_DATA_FILE)
- training_data = training_handler.load() or {}
-
- agent_training_data = training_data.get(agent_id, {})
-
- if human_feedback is not None:
- agent_training_data[train_iteration] = {
- "initial_output": result.output,
- "human_feedback": human_feedback,
- }
- else:
- if train_iteration in agent_training_data:
- agent_training_data[train_iteration]["improved_output"] = result.output
- else:
- if self.agent.verbose:
- PRINTER.print(
- content=(
- f"No existing training data for agent {agent_id} and iteration "
- f"{train_iteration}. Cannot save improved output."
- ),
- color="red",
- )
- return
-
- training_data[agent_id] = agent_training_data
- training_handler.save(training_data)
-
- @staticmethod
- def _format_prompt(prompt: str, inputs: dict[str, str]) -> str:
- """Format prompt with input values.
-
- Args:
- prompt: Template string.
- inputs: Values to substitute.
-
- Returns:
- Formatted prompt.
- """
- prompt = prompt.replace("{input}", inputs["input"])
- prompt = prompt.replace("{tool_names}", inputs["tool_names"])
- return prompt.replace("{tools}", inputs["tools"])
-
- def _handle_human_feedback(self, formatted_answer: AgentFinish) -> AgentFinish:
- """Process human feedback via the configured provider.
-
- Args:
- formatted_answer: Initial agent result.
-
- Returns:
- Final answer after feedback.
- """
- provider = get_provider()
- return provider.handle_feedback(formatted_answer, self)
-
- async def _ahandle_human_feedback(
- self, formatted_answer: AgentFinish
- ) -> AgentFinish:
- """Process human feedback asynchronously via the configured provider.
-
- Args:
- formatted_answer: Initial agent result.
-
- Returns:
- Final answer after feedback.
- """
- provider = get_provider()
- return await provider.handle_feedback_async(formatted_answer, self)
-
- def _is_training_mode(self) -> bool:
- """Check if training mode is active.
-
- Returns:
- True if in training mode.
- """
- return bool(self.crew and self.crew._train)
-
- def _format_feedback_message(self, feedback: str) -> LLMMessage:
- """Format feedback as a message for the LLM.
-
- Args:
- feedback: User feedback string.
-
- Returns:
- Formatted message dict.
- """
- return format_message_for_llm(
- I18N_DEFAULT.slice("feedback_instructions").format(feedback=feedback)
- )
diff --git a/lib/crewai/src/crewai/experimental/__init__.py b/lib/crewai/src/crewai/experimental/__init__.py
index ce2082f05..92e2c1f2a 100644
--- a/lib/crewai/src/crewai/experimental/__init__.py
+++ b/lib/crewai/src/crewai/experimental/__init__.py
@@ -18,8 +18,6 @@ from crewai.flow.conversational import (
)
-_LAZY_FROM_AGENT_EXECUTOR = {"AgentExecutor", "CrewAgentExecutorFlow"}
-
_LAZY_FROM_EVALUATION = {
"AgentEvaluationResult",
"AgentEvaluator",
@@ -45,19 +43,7 @@ def __getattr__(name: str) -> Any:
"""Lazily resolve symbols whose modules import ``Flow`` or ``Task``.
Eager re-exports would deadlock when ``Flow`` or ``Task`` is still loading.
- Callers like ``from crewai.experimental import AgentExecutor`` still work —
- the real import just runs lazily, after the original loader finishes.
"""
- if name in _LAZY_FROM_AGENT_EXECUTOR:
- from crewai.experimental.agent_executor import (
- AgentExecutor,
- CrewAgentExecutorFlow,
- )
-
- globals()["AgentExecutor"] = AgentExecutor
- globals()["CrewAgentExecutorFlow"] = CrewAgentExecutorFlow
- return globals()[name]
-
if name in _LAZY_FROM_EVALUATION:
from crewai.experimental import evaluation as _evaluation_mod
@@ -71,14 +57,12 @@ def __getattr__(name: str) -> Any:
__all__ = [
"AgentEvaluationResult",
"AgentEvaluator",
- "AgentExecutor",
"AgentMessage",
"BaseEvaluator",
"ConversationConfig",
"ConversationEvent",
"ConversationMessage",
"ConversationState",
- "CrewAgentExecutorFlow", # Deprecated alias for AgentExecutor
"EvaluationScore",
"EvaluationTraceCallback",
"ExperimentResult",
diff --git a/lib/crewai/src/crewai/hooks/llm_hooks.py b/lib/crewai/src/crewai/hooks/llm_hooks.py
index 7658bf514..c9325c69d 100644
--- a/lib/crewai/src/crewai/hooks/llm_hooks.py
+++ b/lib/crewai/src/crewai/hooks/llm_hooks.py
@@ -22,8 +22,7 @@ from crewai.hooks.types import (
if TYPE_CHECKING:
- from crewai.agents.crew_agent_executor import CrewAgentExecutor
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.lite_agent import LiteAgent
from crewai.llms.base_llm import BaseLLM
from crewai.utilities.types import LLMMessage
@@ -38,7 +37,7 @@ class LLMCallHookContext:
Supports both executor-based calls (agents in crews/flows) and direct LLM calls.
Attributes:
- executor: Reference to the executor (CrewAgentExecutor/LiteAgent) or None for direct calls
+ executor: Reference to the executor (AgentExecutor or LiteAgent), or None for direct calls
messages: Direct reference to messages (mutable list).
Can be modified in both before_llm_call and after_llm_call hooks.
Modifications in after_llm_call hooks persist to the next iteration,
@@ -56,7 +55,7 @@ class LLMCallHookContext:
Can be modified by returning a new string from after_llm_call hook.
"""
- executor: CrewAgentExecutor | AgentExecutor | LiteAgent | None
+ executor: AgentExecutor | LiteAgent | None
messages: list[LLMMessage]
agent: Any
task: Any
@@ -67,7 +66,7 @@ class LLMCallHookContext:
def __init__(
self,
- executor: CrewAgentExecutor | AgentExecutor | LiteAgent | None = None,
+ executor: AgentExecutor | LiteAgent | None = None,
response: str | None = None,
messages: list[LLMMessage] | None = None,
llm: BaseLLM | str | Any | None = None, # TODO: look into
@@ -78,7 +77,7 @@ class LLMCallHookContext:
"""Initialize hook context with executor reference or direct parameters.
Args:
- executor: The CrewAgentExecutor or LiteAgent instance (None for direct LLM calls)
+ executor: The AgentExecutor or LiteAgent instance (None for direct LLM calls)
response: Optional response string (for after_llm_call hooks)
messages: Optional messages list (for direct LLM calls when executor is None)
llm: Optional LLM instance (for direct LLM calls when executor is None)
@@ -93,8 +92,8 @@ class LLMCallHookContext:
self.iterations = executor.iterations
if hasattr(executor, "agent"):
self.agent = executor.agent
- self.task = cast("CrewAgentExecutor", executor).task
- self.crew = cast("CrewAgentExecutor", executor).crew
+ self.task = cast("AgentExecutor", executor).task
+ self.crew = cast("AgentExecutor", executor).crew
else:
self.agent = (
executor.original_agent
diff --git a/lib/crewai/src/crewai/llm.py b/lib/crewai/src/crewai/llm.py
index 834d94876..36e168842 100644
--- a/lib/crewai/src/crewai/llm.py
+++ b/lib/crewai/src/crewai/llm.py
@@ -1292,7 +1292,7 @@ class LLM(BaseLLM):
try:
# Attempt to make the completion call, but catch context window errors
# and convert them to our own exception type for consistent handling
- # across the codebase. This allows CrewAgentExecutor to handle context
+ # across the codebase. This allows AgentExecutor to handle context
# length issues appropriately.
if response_model:
params["response_model"] = response_model
@@ -1937,7 +1937,7 @@ class LLM(BaseLLM):
return result
except LLMContextLengthExceededError:
# Re-raise LLMContextLengthExceededError as it should be handled
- # by the CrewAgentExecutor._invoke_loop method, which can then decide
+ # by AgentExecutor, which can then decide
# whether to summarize the content or abort based on the respect_context_window flag
raise
except Exception as e:
diff --git a/lib/crewai/src/crewai/llms/base_llm.py b/lib/crewai/src/crewai/llms/base_llm.py
index ea4e0d470..eaf71c2e0 100644
--- a/lib/crewai/src/crewai/llms/base_llm.py
+++ b/lib/crewai/src/crewai/llms/base_llm.py
@@ -990,8 +990,8 @@ class BaseLLM(BaseModel, ABC):
return [{"role": "user", "content": messages}]
# Validate then copy each message, dropping the cache-breakpoint
- # flag in the copy only. The caller (e.g. CrewAgentExecutor,
- # experimental.AgentExecutor) reuses its messages buffer across
+ # flag in the copy only. The caller (AgentExecutor) reuses its
+ # messages buffer across
# many LLM calls in the tool-use loop; mutating their dicts
# in place would erase the markers after the first call and
# break prompt caching for every subsequent iteration.
diff --git a/lib/crewai/src/crewai/utilities/agent_utils.py b/lib/crewai/src/crewai/utilities/agent_utils.py
index e5b93471a..f2ba9d865 100644
--- a/lib/crewai/src/crewai/utilities/agent_utils.py
+++ b/lib/crewai/src/crewai/utilities/agent_utils.py
@@ -64,9 +64,8 @@ from crewai.utilities.types import LLMMessage
if TYPE_CHECKING:
from crewai.agents.agent_builder.base_agent import BaseAgent
- from crewai.agents.crew_agent_executor import CrewAgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.agents.tools_handler import ToolsHandler
- from crewai.experimental.agent_executor import AgentExecutor
from crewai.lite_agent import LiteAgent
from crewai.llm import LLM
from crewai.task import Task
@@ -331,7 +330,7 @@ def extract_task_section(text: str) -> str:
def _executor_stop_words(
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
) -> list[str]:
"""Return the executor's stop words, regardless of which field name it uses."""
if executor_context is None:
@@ -345,7 +344,7 @@ def _executor_stop_words(
@contextlib.contextmanager
def _llm_stop_words_applied(
llm: LLM | BaseLLM,
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
) -> Iterator[None]:
"""Apply the executor's stop words to the LLM for the duration of one call.
@@ -481,7 +480,7 @@ def enforce_rpm_limit(
@contextlib.contextmanager
def _prepare_llm_call(
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
messages: list[LLMMessage],
printer: Printer,
verbose: bool = True,
@@ -518,7 +517,7 @@ def _prepare_llm_call(
def _validate_and_finalize_llm_response(
answer: Any,
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
printer: Printer,
verbose: bool = True,
) -> str | BaseModel | Any:
@@ -672,7 +671,7 @@ def get_llm_response(
from_task: Task | None = None,
from_agent: BaseAgent | None = None,
response_model: type[BaseModel] | None = None,
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None = None,
+ executor_context: AgentExecutor | LiteAgent | None = None,
verbose: bool = True,
) -> str | BaseModel | Any:
"""Call the LLM and return the response, handling any invalid responses.
@@ -738,7 +737,7 @@ async def aget_llm_response(
from_task: Task | None = None,
from_agent: BaseAgent | None = None,
response_model: type[BaseModel] | None = None,
- executor_context: CrewAgentExecutor | AgentExecutor | None = None,
+ executor_context: AgentExecutor | None = None,
verbose: bool = True,
) -> str | BaseModel | Any:
"""Call the LLM asynchronously and return the response.
@@ -2102,7 +2101,7 @@ def parse_tool_call_args(
def _setup_before_llm_call_hooks(
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
printer: Printer,
verbose: bool = True,
) -> bool:
@@ -2179,7 +2178,7 @@ def _setup_before_llm_call_hooks(
def _setup_after_llm_call_hooks(
- executor_context: CrewAgentExecutor | AgentExecutor | LiteAgent | None,
+ executor_context: AgentExecutor | LiteAgent | None,
answer: str | BaseModel,
printer: Printer,
verbose: bool = True,
diff --git a/lib/crewai/tests/agents/test_agent.py b/lib/crewai/tests/agents/test_agent.py
index 94385dc13..6aa12d12c 100644
--- a/lib/crewai/tests/agents/test_agent.py
+++ b/lib/crewai/tests/agents/test_agent.py
@@ -6,11 +6,11 @@ from unittest import mock
from unittest.mock import AsyncMock, MagicMock, patch
import warnings
-from crewai.agents.crew_agent_executor import AgentFinish, CrewAgentExecutor
+from crewai.agents.parser import AgentFinish
from crewai.constants import DEFAULT_LLM_MODEL
from crewai.events.event_bus import crewai_event_bus
from crewai.events.types.tool_usage_events import ToolUsageFinishedEvent
-from crewai.experimental.agent_executor import AgentExecutor
+from crewai.agents.agent_executor import AgentExecutor
from crewai.knowledge.knowledge import Knowledge
from crewai.knowledge.knowledge_config import KnowledgeConfig
from crewai.knowledge.source.base_knowledge_source import BaseKnowledgeSource
@@ -734,7 +734,7 @@ def test_tool_result_as_answer_is_the_final_answer_for_the_agent() -> None:
"function": {"name": "get_greetings", "arguments": "{}"},
}
with patch(
- "crewai.experimental.agent_executor.get_llm_response",
+ "crewai.agents.agent_executor.get_llm_response",
return_value=[tool_call],
) as mock_llm_response:
result = crew.kickoff()
@@ -760,61 +760,6 @@ def test_agent_definition_based_on_dict():
assert agent.tools == []
[email protected]("ignore::DeprecationWarning")
-def test_agent_human_input():
- from crewai.core.providers.human_input import SyncHumanInputProvider
-
- # Agent configuration
- config = {
- "role": "test role",
- "goal": "test goal",
- "backstory": "test backstory",
- "executor_class": CrewAgentExecutor,
- }
-
- agent = Agent(**config)
-
- # Task configuration with human input enabled
- task = Task(
- agent=agent,
- description="Say the word: Hi",
- expected_output="The word: Hi",
- human_input=True,
- )
-
- # Side effect function for _prompt_input to simulate multiple feedback iterations
- feedback_responses = iter(
- [
- "Don't say hi, say Hello instead!",
- "",
- ]
- )
-
- def prompt_input_side_effect(*args, **kwargs):
- return next(feedback_responses)
-
- # Patch both _prompt_input on provider and _invoke_loop to avoid real API/network calls.
- with (
- patch.object(
- SyncHumanInputProvider,
- "_prompt_input",
- side_effect=prompt_input_side_effect,
- ) as mock_prompt_input,
- patch.object(
- CrewAgentExecutor,
- "_invoke_loop",
- return_value=AgentFinish(output="Hello", thought="", text=""),
- ),
- ):
- output = agent.execute_task(task)
-
- # Assertions to ensure the agent behaves correctly.
- # It should have requested feedback twice.
- assert mock_prompt_input.call_count == 2
- assert output.strip().lower() == "hello"
-
-
def test_agent_default_executor_human_input():
from crewai.core.providers.human_input import SyncHumanInputProvider
@@ -1003,7 +948,7 @@ Thought:<|eot_id|>
"""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
with patch.object(AgentExecutor, "_format_prompt") as mock_format_prompt:
mock_format_prompt.return_value = expected_prompt
@@ -1332,7 +1277,7 @@ def test_agent_max_retry_limit():
agent.create_agent_executor(task=task)
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
error_message = "Error happening while sending prompt to model."
with patch.object(
@@ -1511,7 +1456,7 @@ def test_handle_context_length_exceeds_limit_cli_no():
agent.create_agent_executor(task=task)
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
with patch.object(
AgentExecutor, "invoke", wraps=agent.agent_executor.invoke
@@ -2130,60 +2075,6 @@ def test_litellm_auth_error_handling():
mock_llm_call.assert_called_once()
-def test_crew_agent_executor_litellm_auth_error():
- """Test that CrewAgentExecutor handles LiteLLM authentication errors by raising them."""
- from crewai.agents.tools_handler import ToolsHandler
- from litellm.exceptions import AuthenticationError
-
- agent = Agent(
- role="test role",
- goal="test goal",
- backstory="test backstory",
- llm=LLM(model="gpt-4", api_key="invalid_api_key", is_litellm=True),
- )
- task = Task(
- description="Test task",
- expected_output="Test output",
- agent=agent,
- )
-
- executor = CrewAgentExecutor(
- agent=agent,
- task=task,
- llm=agent.llm,
- crew=None,
- prompt={"system": "You are a test agent", "user": "Execute the task: {input}"},
- max_iter=5,
- tools=[],
- tools_names="",
- stop_words=[],
- tools_description="",
- tools_handler=ToolsHandler(),
- )
-
- with (
- patch.object(LLM, "call") as mock_llm_call,
- pytest.raises(AuthenticationError) as exc_info,
- ):
- mock_llm_call.side_effect = AuthenticationError(
- message="Invalid API key", llm_provider="openai", model="gpt-4"
- )
- executor.invoke(
- {
- "input": "test input",
- "tool_names": "",
- "tools": "",
- }
- )
-
- mock_llm_call.assert_called_once()
-
- assert exc_info.type is AuthenticationError
- assert "Invalid API key".lower() in exc_info.value.message.lower()
- assert exc_info.value.llm_provider == "openai"
- assert exc_info.value.model == "gpt-4"
-
-
def test_litellm_anthropic_error_handling():
"""Test that AnthropicError from LiteLLM is handled correctly and not retried."""
from litellm.llms.anthropic.common_utils import AnthropicError
@@ -2839,25 +2730,9 @@ class TestSharedLLMStopWords:
"""
@staticmethod
- def _make_executor(llm: LLM, stop_words: list[str]) -> CrewAgentExecutor:
- """Build a CrewAgentExecutor with minimal deps."""
- from crewai.agents.tools_handler import ToolsHandler
-
- agent = Agent(role="r", goal="g", backstory="b")
- task = Task(description="d", expected_output="o", agent=agent)
- return CrewAgentExecutor(
- agent=agent,
- task=task,
- llm=llm,
- crew=None,
- prompt={"prompt": "p {input} {tool_names} {tools}"},
- max_iter=5,
- tools=[],
- tools_names="",
- stop_words=stop_words,
- tools_description="",
- tools_handler=ToolsHandler(),
- )
+ def _make_executor(llm: LLM, stop_words: list[str]) -> AgentExecutor:
+ """Build an AgentExecutor carrying only the fields this test reads."""
+ return AgentExecutor.model_construct(llm=llm, stop_words=stop_words)
def test_executor_init_does_not_mutate_shared_llm(self) -> None:
"""Constructing executors must not touch the shared LLM's stop list."""
@@ -2933,7 +2808,7 @@ class TestSharedLLMStopWords:
exec_a = self._make_executor(shared, stop_words=["StopA:"])
exec_b = self._make_executor(shared, stop_words=["StopB:"])
- async def run(executor: CrewAgentExecutor, expected: str) -> set[str]:
+ async def run(executor: AgentExecutor, expected: str) -> set[str]:
with _llm_stop_words_applied(shared, executor):
await asyncio.sleep(0)
seen = set(shared.stop_sequences)
@@ -2994,163 +2869,3 @@ class TestSharedLLMStopWords:
assert seen == [{"Original:", "Observation:"}]
assert shared.stop == ["Original:"]
-
-class TestMaxIterationsForcedAnswer:
- """Both sync loops request the forced final answer with a trailing user turn.
-
- Current Claude models reject a request that ends on an assistant message,
- so the nudge must never be sent as assistant prefill.
- """
-
- @staticmethod
- def _make_executor(llm: MagicMock, original_tools: list) -> CrewAgentExecutor:
- from crewai.agents.tools_handler import ToolsHandler
-
- agent = Agent(role="r", goal="g", backstory="b", llm=llm, verbose=False)
- task = Task(description="d", expected_output="o", agent=agent)
- executor = CrewAgentExecutor(
- agent=agent,
- task=task,
- llm=llm,
- crew=None,
- prompt={"prompt": "p {input} {tool_names} {tools}"},
- max_iter=1,
- tools=[],
- original_tools=original_tools,
- tools_names="",
- stop_words=[],
- tools_description="",
- tools_handler=ToolsHandler(),
- )
- executor.iterations = 1
- return executor
-
- def test_react_loop_forces_final_answer_with_user_turn(self) -> None:
- from crewai.utilities.i18n import I18N_DEFAULT
-
- llm = MagicMock(spec=LLM)
- llm.stop = []
- llm.supports_stop_words.return_value = True
- llm.supports_function_calling.return_value = False
- llm.call.return_value = "Final Answer: forced"
- executor = self._make_executor(llm, original_tools=[])
- executor.messages = [
- {"role": "user", "content": "Collect all the data."},
- {"role": "assistant", "content": "Thought: I need data\nObservation: partial"},
- ]
-
- with patch.object(executor, "_show_logs"):
- result = executor._invoke_loop()
-
- sent = llm.call.call_args.args[0]
- assert sent[-1] == {
- "role": "user",
- "content": I18N_DEFAULT.errors("force_final_answer"),
- }
- assert isinstance(result, AgentFinish)
- assert result.output == "forced"
-
- def test_react_loop_summarizes_before_calling_the_llm(self) -> None:
- llm = MagicMock(spec=LLM)
- llm.stop = []
- llm.supports_stop_words.return_value = True
- llm.supports_function_calling.return_value = False
- llm.is_context_window_overflowing_threshold.return_value = True
- llm.call.return_value = "Final Answer: done"
- executor = self._make_executor(llm, original_tools=[])
- executor.iterations = 0
- executor.max_iter = 2
- executor.respect_context_window = True
- executor.messages = [
- {"role": "user", "content": "earlier context"},
- {"role": "assistant", "content": "earlier response"},
- {"role": "user", "content": "large context"},
- ]
- events: list[str] = []
-
- with (
- patch("crewai.utilities.agent_utils.summarize_messages") as summarize,
- patch.object(executor, "_show_logs"),
- ):
- summarize.side_effect = lambda **_: events.append("summarize")
- llm.call.side_effect = (
- lambda *_args, **_kwargs: events.append("call") or "Final Answer: done"
- )
- executor._invoke_loop()
-
- assert events == ["summarize", "call"]
-
- def test_native_tool_loop_summarizes_before_calling_the_llm(self) -> None:
- @tool
- def search(query: str) -> str:
- """Search for a result."""
- return query
-
- llm = MagicMock(spec=LLM)
- llm.stop = []
- llm.supports_stop_words.return_value = True
- llm.supports_function_calling.return_value = True
- llm.is_context_window_overflowing_threshold.return_value = True
- llm.call.return_value = "done"
- executor = self._make_executor(llm, original_tools=[search])
- executor.iterations = 0
- executor.max_iter = 2
- executor.respect_context_window = True
- executor.messages = [
- {"role": "user", "content": "earlier context"},
- {"role": "assistant", "content": "earlier response"},
- {"role": "user", "content": "large context"},
- ]
- events: list[str] = []
-
- with (
- patch("crewai.utilities.agent_utils.summarize_messages") as summarize,
- patch.object(executor, "_show_logs"),
- ):
- summarize.side_effect = lambda **_: events.append("summarize")
- llm.call.side_effect = lambda *_args, **_kwargs: events.append("call") or "done"
- executor._invoke_loop()
-
- assert events == ["summarize", "call"]
-
- def test_native_tools_loop_forces_final_answer_with_user_turn(self) -> None:
- from crewai.utilities.i18n import I18N_DEFAULT
-
- @tool
- def get_data(step: str) -> str:
- """Get data for a step."""
- return f"data for {step}"
-
- llm = MagicMock(spec=LLM)
- llm.stop = []
- llm.supports_stop_words.return_value = True
- llm.supports_function_calling.return_value = True
- llm.call.return_value = "Final Answer: forced"
- executor = self._make_executor(llm, original_tools=[get_data])
- executor.messages = [
- {"role": "user", "content": "Collect all the data."},
- {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": "get_data", "arguments": "{}"},
- }
- ],
- },
- {"role": "tool", "tool_call_id": "call_1", "name": "get_data", "content": "partial"},
- {"role": "user", "content": I18N_DEFAULT.slice("post_tool_reasoning")},
- ]
-
- with patch.object(executor, "_show_logs"):
- result = executor._invoke_loop()
-
- sent = llm.call.call_args.args[0]
- assert sent[-1] == {
- "role": "user",
- "content": I18N_DEFAULT.errors("force_final_answer"),
- }
- assert isinstance(result, AgentFinish)
- assert result.output == "forced"
diff --git a/lib/crewai/tests/agents/test_agent_executor.py b/lib/crewai/tests/agents/test_agent_executor.py
index e810f56e8..e3ea8d89f 100644
--- a/lib/crewai/tests/agents/test_agent_executor.py
+++ b/lib/crewai/tests/agents/test_agent_executor.py
@@ -61,7 +61,7 @@ def _build_executor(**kwargs: Any) -> AgentExecutor:
executor._is_feedback_iteration = False
return executor
from crewai.agents.planner_observer import PlannerObserver
-from crewai.experimental.agent_executor import (
+from crewai.agents.agent_executor import (
AgentExecutorState,
AgentExecutor,
)
@@ -146,7 +146,7 @@ class TestAgentExecutor:
provider.post_setup_messages.side_effect = post_setup
with patch(
- "crewai.experimental.agent_executor.get_provider", return_value=provider
+ "crewai.agents.agent_executor.get_provider", return_value=provider
):
executor._setup_messages(
{"input": "draft this", "tool_names": "", "tools": ""}
@@ -175,7 +175,7 @@ class TestAgentExecutor:
provider.setup_messages.side_effect = setup
with patch(
- "crewai.experimental.agent_executor.get_provider", return_value=provider
+ "crewai.agents.agent_executor.get_provider", return_value=provider
):
executor._setup_messages(
{"input": "draft this", "tool_names": "", "tools": ""}
@@ -349,11 +349,11 @@ class TestAgentExecutor:
with (
patch(
- "crewai.experimental.agent_executor.aget_all_files",
+ "crewai.agents.agent_executor.aget_all_files",
new=AsyncMock(return_value={"document": stored_file}),
) as async_get_files,
patch(
- "crewai.experimental.agent_executor.get_all_files",
+ "crewai.agents.agent_executor.get_all_files",
side_effect=AssertionError("sync file store should not be called"),
),
):
@@ -485,7 +485,7 @@ class TestAgentExecutor:
executor.state.messages = [{"role": "user", "content": "Use a tool"}]
with patch(
- "crewai.experimental.agent_executor.get_llm_response",
+ "crewai.agents.agent_executor.get_llm_response",
return_value="Thought: done\nFinal Answer: complete",
) as get_llm_response_mock:
result = executor.call_llm_and_parse()
@@ -544,7 +544,7 @@ class TestAgentExecutor:
executor.state.messages = [{"role": "user", "content": "Use a tool"}]
with patch(
- "crewai.experimental.agent_executor.get_llm_response",
+ "crewai.agents.agent_executor.get_llm_response",
return_value="complete",
) as get_llm_response_mock:
result = executor.call_llm_native_tools()
@@ -570,7 +570,7 @@ class TestAgentExecutor:
executor.tools_description = "lookup: search for information"
with patch(
- "crewai.experimental.agent_executor.get_llm_response",
+ "crewai.agents.agent_executor.get_llm_response",
side_effect=RuntimeError(
"Error code: 400 - registry.ollama.ai/library/mariner:latest "
"does not support tools"
@@ -758,7 +758,7 @@ class TestAgentExecutor:
executor = _build_executor(**mock_dependencies)
answer = AgentFinish(thought="thinking", output="test", text="final")
- with patch("crewai.experimental.agent_executor.asyncio.run") as mock_run:
+ with patch("crewai.agents.agent_executor.asyncio.run") as mock_run:
executor._invoke_step_callback(answer)
await asyncio.sleep(0)
@@ -1057,7 +1057,7 @@ class TestStepExecutorCriticalFixes:
assert completed_events[0].result == "Error: no result"
assert completed_events[0].error == "No result"
- @patch("crewai.experimental.agent_executor.handle_output_parser_exception")
+ @patch("crewai.agents.agent_executor.handle_output_parser_exception")
def test_recover_from_parser_error(
self, mock_handle_exception, mock_dependencies
):
@@ -1076,7 +1076,7 @@ class TestStepExecutorCriticalFixes:
assert executor.state.iterations == initial_iterations + 1
mock_handle_exception.assert_called_once()
- @patch("crewai.experimental.agent_executor.handle_context_length")
+ @patch("crewai.agents.agent_executor.handle_context_length")
def test_recover_from_context_length(
self, mock_handle_context, mock_dependencies
):
@@ -1146,8 +1146,8 @@ class TestFlowErrorHandling:
"tools_handler": Mock(),
}
- @patch("crewai.experimental.agent_executor.get_llm_response")
- @patch("crewai.experimental.agent_executor.enforce_rpm_limit")
+ @patch("crewai.agents.agent_executor.get_llm_response")
+ @patch("crewai.agents.agent_executor.enforce_rpm_limit")
def test_call_llm_parser_error(
self, mock_enforce_rpm, mock_get_llm, mock_dependencies
):
@@ -1163,9 +1163,9 @@ class TestFlowErrorHandling:
assert result == "parser_error"
assert executor._last_parser_error is not None
- @patch("crewai.experimental.agent_executor.get_llm_response")
- @patch("crewai.experimental.agent_executor.enforce_rpm_limit")
- @patch("crewai.experimental.agent_executor.is_context_length_exceeded")
+ @patch("crewai.agents.agent_executor.get_llm_response")
+ @patch("crewai.agents.agent_executor.enforce_rpm_limit")
+ @patch("crewai.agents.agent_executor.is_context_length_exceeded")
def test_call_llm_context_error(
self,
mock_is_context_exceeded,
@@ -1629,7 +1629,7 @@ class TestAgentExecutorPlanning:
"""Test that executor state contains plan after planning phase."""
from crewai import Agent, PlanningConfig
from crewai.llm import LLM
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
llm = LLM("gpt-4o-mini")
@@ -1672,7 +1672,7 @@ class TestAgentExecutorPlanning:
"""
from crewai import Agent, PlanningConfig
from crewai.llm import LLM
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
llm = LLM("gpt-4o-mini")
@@ -1717,7 +1717,7 @@ class TestAgentExecutorPlanning:
"""
from crewai import Agent, PlanningConfig
from crewai.llm import LLM
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
llm = LLM("gpt-4o-mini")
@@ -1873,7 +1873,7 @@ class TestReasoningEffort:
def test_should_observe_steps_respects_config(self):
"""observe_steps and reasoning_effort gate PlannerObserver LLM calls."""
from crewai.agent.planning_config import PlanningConfig
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
executor = Mock(spec=AgentExecutor)
executor._should_observe_steps = (
@@ -1903,7 +1903,7 @@ class TestReasoningEffort:
def test_reasoning_effort_low_skips_planner_observer_llm(self):
"""Low effort must not call PlannerObserver.observe (no per-step LLM)."""
from crewai.agent.planning_config import PlanningConfig
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.utilities.planning_types import TodoItem, TodoList
executor = Mock(spec=AgentExecutor)
@@ -1955,7 +1955,7 @@ class TestReasoningEffort:
"""
from crewai import Agent, PlanningConfig
from crewai.llm import LLM
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
llm = LLM("gpt-4o-mini")
@@ -2018,7 +2018,7 @@ class TestReasoningEffort:
"""
from crewai import Agent, PlanningConfig
from crewai.llm import LLM
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
llm = LLM("gpt-4o-mini")
@@ -2071,7 +2071,7 @@ class TestReasoningEffort:
verifying that medium effort routes to replan_now on failure
but continues on success.
"""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.utilities.planning_types import (
StepObservation,
TodoItem,
@@ -2148,7 +2148,7 @@ class TestReasoningEffort:
Unit test verifying the low handler's behavior directly.
"""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.utilities.planning_types import TodoItem, TodoList
executor = Mock(spec=AgentExecutor)
@@ -2181,7 +2181,7 @@ class TestReasoningEffort:
def test_reasoning_effort_low_marks_failed_steps_failed_without_replan(self):
"""Low effort records failed heuristic observations without replanning."""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.utilities.planning_types import (
StepObservation,
TodoItem,
@@ -2248,7 +2248,7 @@ class TestReasoningEffort:
def test_get_reasoning_effort_reads_from_config(self):
"""Verify _get_reasoning_effort reads from agent.planning_config."""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
executor = Mock(spec=AgentExecutor)
executor._get_reasoning_effort = (
@@ -2411,7 +2411,7 @@ class TestMaxIterationsRouting:
the iteration limit is exceeded, not to a dead-end event."""
def test_exceeded_routes_to_force_final_answer(self):
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
executor = Mock(spec=AgentExecutor)
executor.state = AgentExecutorState(iterations=25)
@@ -2421,7 +2421,7 @@ class TestMaxIterationsRouting:
assert result == "force_final_answer"
def test_under_limit_continues_reasoning(self):
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
executor = Mock(spec=AgentExecutor)
executor.state = AgentExecutorState(iterations=5)
@@ -2431,7 +2431,7 @@ class TestMaxIterationsRouting:
assert result == "continue_reasoning"
def test_under_limit_with_native_tools(self):
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
executor = Mock(spec=AgentExecutor)
executor.state = AgentExecutorState(iterations=5, use_native_tools=True)
@@ -2449,7 +2449,7 @@ class TestNativeToolCallMaxUsage:
even when max_usage_reached=True and original_tool is None."""
def test_max_usage_reached_without_original_tool(self):
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
import inspect
source = inspect.getsource(AgentExecutor._execute_single_native_tool_call)
@@ -2948,7 +2948,7 @@ class TestExecutorStateReset:
def test_finalize_called_reset_in_invoke(self):
import inspect
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
source = inspect.getsource(AgentExecutor.invoke)
finalize_idx = source.index("self._finalize_called = False")
@@ -2959,7 +2959,7 @@ class TestExecutorStateReset:
def test_finalize_called_reset_in_invoke_async(self):
import inspect
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
source = inspect.getsource(AgentExecutor.invoke_async)
finalize_idx = source.index("self._finalize_called = False")
@@ -2978,7 +2978,7 @@ class TestPlanGenerationIsolation:
def test_generate_plan_does_not_mutate_task_description(self):
import inspect
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
source = inspect.getsource(AgentExecutor.generate_plan)
assert "task.description +=" not in source, (
@@ -2998,7 +2998,7 @@ class TestTodoStatusTracking:
def test_medium_effort_marks_failed_step_as_failed(self):
import inspect
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
source = inspect.getsource(AgentExecutor.handle_step_observed_medium)
assert "_mark_todo_failed" in source, (
@@ -3197,3 +3197,53 @@ class TestEnsureForceFinalAnswer:
assert AgentExecutor.ensure_force_final_answer(executor) == "agent_finished"
llm.call.assert_not_called()
+
+
+def test_crew_agent_executor_cannot_be_selected() -> None:
+ import importlib
+
+ from crewai import Agent
+
+ with pytest.raises(ModuleNotFoundError):
+ importlib.import_module("crewai.agents.crew_agent_executor")
+
+ with pytest.raises(ValueError, match="CrewAgentExecutor has been removed"):
+ Agent(
+ role="r",
+ goal="g",
+ backstory="b",
+ executor_class="CrewAgentExecutor",
+ )
+
+
+def test_stable_package_export_is_the_executor_class() -> None:
+ from crewai.agents import AgentExecutor as ExportedExecutor
+ from crewai.agents.agent_executor import AgentExecutor as ModuleExecutor
+
+ assert ExportedExecutor is ModuleExecutor
+
+
+def test_agent_executor_uses_stable_discriminator() -> None:
+ executor = AgentExecutor.model_validate({})
+
+ assert executor.executor_type == "agent"
+ assert executor.model_dump()["executor_type"] == "agent"
+
+
+def test_legacy_experimental_discriminator_is_rejected() -> None:
+ from pydantic import ValidationError
+
+ with pytest.raises(ValidationError):
+ AgentExecutor.model_validate({"executor_type": "experimental"})
+
+
+def test_experimental_executor_import_is_removed() -> None:
+ import importlib
+
+ with pytest.raises(ModuleNotFoundError):
+ importlib.import_module("crewai.experimental.agent_executor")
+
+ experimental = importlib.import_module("crewai.experimental")
+ for name in ("AgentExecutor", "CrewAgentExecutorFlow"):
+ with pytest.raises(AttributeError):
+ getattr(experimental, name)
diff --git a/lib/crewai/tests/agents/test_agent_kickoff_message_history.py b/lib/crewai/tests/agents/test_agent_kickoff_message_history.py
index deb0b3c84..75ae1664c 100644
--- a/lib/crewai/tests/agents/test_agent_kickoff_message_history.py
+++ b/lib/crewai/tests/agents/test_agent_kickoff_message_history.py
@@ -7,7 +7,6 @@ from typing import Any
import pytest
from crewai import Agent
-from crewai.agents.crew_agent_executor import CrewAgentExecutor
from crewai.lite_agent import LiteAgent
from crewai.llms.base_llm import BaseLLM
from crewai.utilities.prompts import StandardPromptResult, SystemPromptResult
@@ -274,57 +273,6 @@ def test_trailing_turns_survive_with_the_system_prompt_disabled() -> None:
]
[email protected]("use_system_prompt", [True, False])
-def test_the_deprecated_executor_places_history_the_same_way(
- use_system_prompt: bool,
-) -> None:
- """`CrewAgentExecutor` carries its own `_setup_messages` twin.
-
- `Agent.kickoff` builds an `AgentExecutor` unconditionally
- (`agent/core.py`), so the deprecated executor is not reachable through
- kickoff and is driven directly here. Both of its branches are covered:
- history must land after any system prompt and before this turn's request.
- """
- agent = Agent(role="Support", goal="help", backstory="b", llm=_Recorder())
- with pytest.warns(DeprecationWarning, match="CrewAgentExecutor is deprecated"):
- executor = CrewAgentExecutor(
- llm=agent.llm,
- agent=agent,
- prompt=SystemPromptResult(system="you are support", user="{input}")
- if use_system_prompt
- else StandardPromptResult(prompt="{input}"),
- max_iter=5,
- tools=[],
- tools_names="",
- stop_words=[],
- tools_description="",
- tools_handler=agent.tools_handler,
- original_tools=[],
- )
-
- executor._setup_messages(
- {
- "input": "where is it?",
- "tool_names": "",
- "tools": "",
- "history": HISTORY[:2],
- "trailing": [{"role": "assistant", "content": "checking now"}],
- }
- )
-
- roles = [message["role"] for message in executor.messages]
- assert roles == (["system"] if use_system_prompt else []) + [
- "user",
- "assistant",
- "user",
- "assistant",
- ]
- assert executor.messages[-4]["content"] == "my order id is 42"
- assert executor.messages[-3]["content"] == "thanks, checking"
- assert "where is it?" in str(executor.messages[-2]["content"])
- assert executor.messages[-1]["content"] == "checking now"
-
-
def test_prior_turn_attachments_are_not_resent_on_this_turn() -> None:
"""History keeps its own files; unioning them all would send them twice."""
llm = _Recorder()
diff --git a/lib/crewai/tests/agents/test_agent_reasoning.py b/lib/crewai/tests/agents/test_agent_reasoning.py
index 6bfc9ade0..1da933dad 100644
--- a/lib/crewai/tests/agents/test_agent_reasoning.py
+++ b/lib/crewai/tests/agents/test_agent_reasoning.py
@@ -269,7 +269,7 @@ def test_agent_kickoff_multi_step_task_with_planning():
@pytest.mark.vcr()
def test_agent_execute_task_with_planning():
- """Test Agent.execute_task() with planning via CrewAgentExecutor."""
+ """Test Agent.execute_task() with planning via AgentExecutor."""
llm = LLM("gpt-4o-mini")
agent = Agent(
diff --git a/lib/crewai/tests/agents/test_async_agent_executor.py b/lib/crewai/tests/agents/test_async_agent_executor.py
deleted file mode 100644
index 517554bbb..000000000
--- a/lib/crewai/tests/agents/test_async_agent_executor.py
+++ /dev/null
@@ -1,543 +0,0 @@
-"""Tests for async agent executor functionality."""
-
-import asyncio
-from typing import Any
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
-
-import pytest
-
-from crewai.agent import Agent
-from crewai.agents.crew_agent_executor import CrewAgentExecutor
-from crewai.agents.parser import AgentAction, AgentFinish
-from crewai.agents.tools_handler import ToolsHandler
-from crewai.llm import LLM
-from crewai.llms.base_llm import BaseLLM
-from crewai.task import Task
-from crewai.tools import tool
-from crewai.tools.tool_types import ToolResult
-from crewai.utilities.i18n import I18N_DEFAULT
-
-
-def mock_llm() -> MagicMock:
- """Create a mock LLM for testing."""
- llm = MagicMock(spec=BaseLLM)
- llm.supports_stop_words.return_value = True
- llm.stop = []
- return llm
-
-
-def test_agent(mock_llm: MagicMock) -> Agent:
- """Create a real Agent for testing."""
- return Agent(
- role="Test Agent",
- goal="Test goal",
- backstory="Test backstory",
- llm=mock_llm,
- verbose=False,
- )
-
-
-def test_task(test_agent: Agent) -> Task:
- """Create a real Task for testing."""
- return Task(
- description="Test task description",
- expected_output="Test output",
- agent=test_agent,
- )
-
-
-def mock_tools_handler() -> MagicMock:
- """Create a mock tools handler."""
- return MagicMock(spec=ToolsHandler)
-
-
-def executor(
- mock_llm: MagicMock,
- test_agent: Agent,
- test_task: Task,
- mock_tools_handler: MagicMock,
-) -> CrewAgentExecutor:
- """Create a CrewAgentExecutor instance for testing."""
- return CrewAgentExecutor(
- llm=mock_llm,
- task=test_task,
- crew=None,
- agent=test_agent,
- prompt={"prompt": "Test prompt {input} {tool_names} {tools}"},
- max_iter=5,
- tools=[],
- tools_names="",
- stop_words=["Observation:"],
- tools_description="",
- tools_handler=mock_tools_handler,
- )
-
-
-class TestAsyncAgentExecutor:
- """Tests for async agent executor methods."""
-
- @pytest.mark.asyncio
- async def test_ainvoke_returns_output(self, executor: CrewAgentExecutor) -> None:
- """Test that ainvoke returns the expected output."""
- expected_output = "Final answer from agent"
-
- with patch.object(
- executor,
- "_ainvoke_loop",
- new_callable=AsyncMock,
- return_value=AgentFinish(
- thought="Done", output=expected_output, text="Final Answer: Done"
- ),
- ):
- with patch.object(executor, "_show_start_logs"):
- with patch.object(executor, "_save_to_memory"):
- result = await executor.ainvoke(
- {
- "input": "test input",
- "tool_names": "",
- "tools": "",
- }
- )
-
- assert result == {"output": expected_output}
-
- @pytest.mark.asyncio
- async def test_ainvoke_loop_calls_aget_llm_response(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that _ainvoke_loop calls aget_llm_response."""
- with patch(
- "crewai.agents.crew_agent_executor.aget_llm_response",
- new_callable=AsyncMock,
- return_value="Thought: I know the answer\nFinal Answer: Test result",
- ) as mock_aget_llm:
- with patch.object(executor, "_show_logs"):
- result = await executor._ainvoke_loop()
-
- mock_aget_llm.assert_called_once()
- assert isinstance(result, AgentFinish)
-
- @pytest.mark.asyncio
- async def test_ainvoke_loop_handles_tool_execution(
- self,
- executor: CrewAgentExecutor,
- ) -> None:
- """Test that _ainvoke_loop handles tool execution asynchronously."""
- call_count = 0
-
- async def mock_llm_response(*args: Any, **kwargs: Any) -> str:
- nonlocal call_count
- call_count += 1
- if call_count == 1:
- return (
- "Thought: I need to use a tool\n"
- "Action: test_tool\n"
- 'Action Input: {"arg": "value"}'
- )
- return "Thought: I have the answer\nFinal Answer: Tool result processed"
-
- with patch(
- "crewai.agents.crew_agent_executor.aget_llm_response",
- new_callable=AsyncMock,
- side_effect=mock_llm_response,
- ):
- with patch(
- "crewai.agents.crew_agent_executor.aexecute_tool_and_check_finality",
- new_callable=AsyncMock,
- return_value=ToolResult(result="Tool executed", result_as_answer=False),
- ) as mock_tool_exec:
- with patch.object(executor, "_show_logs"):
- with patch.object(executor, "_handle_agent_action") as mock_handle:
- mock_handle.return_value = AgentAction(
- text="Tool result",
- tool="test_tool",
- tool_input='{"arg": "value"}',
- thought="Used tool",
- result="Tool executed",
- )
- result = await executor._ainvoke_loop()
-
- assert mock_tool_exec.called
- assert isinstance(result, AgentFinish)
-
- @pytest.mark.asyncio
- async def test_ainvoke_loop_respects_max_iterations(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that _ainvoke_loop respects max iterations."""
- executor.max_iter = 2
-
- async def always_return_action(*args: Any, **kwargs: Any) -> str:
- return (
- "Thought: I need to think more\n"
- "Action: some_tool\n"
- "Action Input: {}"
- )
-
- with patch(
- "crewai.agents.crew_agent_executor.aget_llm_response",
- new_callable=AsyncMock,
- side_effect=always_return_action,
- ):
- with patch(
- "crewai.agents.crew_agent_executor.aexecute_tool_and_check_finality",
- new_callable=AsyncMock,
- return_value=ToolResult(result="Tool result", result_as_answer=False),
- ):
- with patch(
- "crewai.agents.crew_agent_executor.handle_max_iterations_exceeded",
- return_value=AgentFinish(
- thought="Max iterations",
- output="Forced answer",
- text="Max iterations reached",
- ),
- ) as mock_max_iter:
- with patch.object(executor, "_show_logs"):
- with patch.object(executor, "_handle_agent_action") as mock_ha:
- mock_ha.return_value = AgentAction(
- text="Action",
- tool="some_tool",
- tool_input="{}",
- thought="Thinking",
- )
- result = await executor._ainvoke_loop()
-
- mock_max_iter.assert_called_once()
- assert isinstance(result, AgentFinish)
-
- @pytest.mark.asyncio
- async def test_ainvoke_handles_exceptions(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that ainvoke properly propagates exceptions."""
- with patch.object(executor, "_show_start_logs"):
- with patch.object(
- executor,
- "_ainvoke_loop",
- new_callable=AsyncMock,
- side_effect=ValueError("Test error"),
- ):
- with pytest.raises(ValueError, match="Test error"):
- await executor.ainvoke(
- {"input": "test", "tool_names": "", "tools": ""}
- )
-
- @pytest.mark.asyncio
- async def test_concurrent_ainvoke_calls(
- self, mock_llm: MagicMock, test_agent: Agent, test_task: Task,
- mock_tools_handler: MagicMock,
- ) -> None:
- """Test that multiple ainvoke calls can run concurrently."""
- max_concurrent = 0
- current_concurrent = 0
- lock = asyncio.Lock()
-
- async def create_and_run_executor(executor_id: int) -> dict[str, Any]:
- nonlocal max_concurrent, current_concurrent
-
- executor = CrewAgentExecutor(
- llm=mock_llm,
- task=test_task,
- crew=None,
- agent=test_agent,
- prompt={"prompt": "Test {input} {tool_names} {tools}"},
- max_iter=5,
- tools=[],
- tools_names="",
- stop_words=["Observation:"],
- tools_description="",
- tools_handler=mock_tools_handler,
- )
-
- async def delayed_response(*args: Any, **kwargs: Any) -> str:
- nonlocal max_concurrent, current_concurrent
- async with lock:
- current_concurrent += 1
- max_concurrent = max(max_concurrent, current_concurrent)
- await asyncio.sleep(0.01)
- async with lock:
- current_concurrent -= 1
- return f"Thought: Done\nFinal Answer: Result from executor {executor_id}"
-
- with patch(
- "crewai.agents.crew_agent_executor.aget_llm_response",
- new_callable=AsyncMock,
- side_effect=delayed_response,
- ):
- with patch.object(executor, "_show_start_logs"):
- with patch.object(executor, "_show_logs"):
- with patch.object(executor, "_save_to_memory"):
- return await executor.ainvoke(
- {
- "input": f"test {executor_id}",
- "tool_names": "",
- "tools": "",
- }
- )
-
- results = await asyncio.gather(
- create_and_run_executor(1),
- create_and_run_executor(2),
- create_and_run_executor(3),
- )
-
- assert len(results) == 3
- assert all("output" in r for r in results)
- assert max_concurrent > 1, f"Expected concurrent execution, max concurrent was {max_concurrent}"
-
-
-class TestExecutorStateResetBetweenInvocations:
- """Regression tests: executor state must reset across sequential invocations."""
-
- def test_invoke_resets_messages_and_iterations(
- self, executor: CrewAgentExecutor
- ) -> None:
- executor.messages = [{"role": "assistant", "content": "leftover from task 1"}]
- executor.iterations = 7
-
- with patch.object(
- executor,
- "_invoke_loop",
- return_value=AgentFinish(thought="", output="ok", text="ok"),
- ), patch.object(executor, "_show_start_logs"), patch.object(
- executor, "_save_to_memory"
- ):
- executor.invoke({"input": "task 2", "tool_names": "", "tools": ""})
-
- assert executor.iterations == 0
- assert all(
- "leftover from task 1" not in (m.get("content") or "")
- for m in executor.messages
- )
-
- @pytest.mark.asyncio
- async def test_ainvoke_resets_messages_and_iterations(
- self, executor: CrewAgentExecutor
- ) -> None:
- executor.messages = [{"role": "assistant", "content": "leftover from task 1"}]
- executor.iterations = 7
-
- with patch.object(
- executor,
- "_ainvoke_loop",
- new_callable=AsyncMock,
- return_value=AgentFinish(thought="", output="ok", text="ok"),
- ), patch.object(executor, "_show_start_logs"), patch.object(
- executor, "_save_to_memory"
- ):
- await executor.ainvoke({"input": "task 2", "tool_names": "", "tools": ""})
-
- assert executor.iterations == 0
- assert all(
- "leftover from task 1" not in (m.get("content") or "")
- for m in executor.messages
- )
-
- def test_invoke_preserves_state_when_resuming(
- self, executor: CrewAgentExecutor
- ) -> None:
- executor.messages = [{"role": "assistant", "content": "in-flight context"}]
- executor.iterations = 4
- executor._resuming = True
-
- with patch.object(
- executor,
- "_invoke_loop",
- return_value=AgentFinish(thought="", output="ok", text="ok"),
- ), patch.object(executor, "_show_start_logs"), patch.object(
- executor, "_save_to_memory"
- ):
- executor.invoke({"input": "resumed", "tool_names": "", "tools": ""})
-
- assert executor.iterations == 4
- assert any(
- "in-flight context" in (m.get("content") or "") for m in executor.messages
- )
- assert executor._resuming is False
-
-
-class TestInvokeStepCallback:
- """Tests for _invoke_step_callback with sync and async callbacks."""
-
- def test_invoke_step_callback_with_sync_callback(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that a sync step callback is called normally."""
- callback = Mock()
- executor.step_callback = callback
- answer = AgentFinish(thought="thinking", output="test", text="final")
-
- executor._invoke_step_callback(answer)
-
- callback.assert_called_once_with(answer)
-
- def test_invoke_step_callback_with_async_callback(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that an async step callback is awaited via asyncio.run."""
- async_callback = AsyncMock()
- executor.step_callback = async_callback
- answer = AgentFinish(thought="thinking", output="test", text="final")
-
- with patch("crewai.agents.crew_agent_executor.asyncio.run") as mock_run:
- executor._invoke_step_callback(answer)
-
- async_callback.assert_called_once_with(answer)
- mock_run.assert_called_once()
-
- def test_invoke_step_callback_with_none(
- self, executor: CrewAgentExecutor
- ) -> None:
- """Test that no error is raised when step_callback is None."""
- executor.step_callback = None
- answer = AgentFinish(thought="thinking", output="test", text="final")
-
- executor._invoke_step_callback(answer)
-
-
-class TestAsyncLLMResponseHelper:
- """Tests for aget_llm_response helper function."""
-
- @pytest.mark.asyncio
- async def test_aget_llm_response_calls_acall(self) -> None:
- """Test that aget_llm_response calls llm.acall."""
- from crewai.utilities.agent_utils import aget_llm_response
- from crewai_core.printer import Printer
-
- mock_llm = MagicMock()
- mock_llm.acall = AsyncMock(return_value="LLM response")
-
- result = await aget_llm_response(
- llm=mock_llm,
- messages=[{"role": "user", "content": "test"}],
- callbacks=[],
- printer=Printer(),
- )
-
- mock_llm.acall.assert_called_once()
- assert result == "LLM response"
-
- @pytest.mark.asyncio
- async def test_aget_llm_response_raises_on_empty_response(self) -> None:
- """Test that aget_llm_response raises ValueError on empty response."""
- from crewai.utilities.agent_utils import aget_llm_response
- from crewai_core.printer import Printer
-
- mock_llm = MagicMock()
- mock_llm.acall = AsyncMock(return_value="")
-
- with pytest.raises(ValueError, match="Invalid response from LLM call"):
- await aget_llm_response(
- llm=mock_llm,
- messages=[{"role": "user", "content": "test"}],
- callbacks=[],
- printer=Printer(),
- )
-
- @pytest.mark.asyncio
- async def test_aget_llm_response_propagates_exceptions(self) -> None:
- """Test that aget_llm_response propagates LLM exceptions."""
- from crewai.utilities.agent_utils import aget_llm_response
- from crewai_core.printer import Printer
-
- mock_llm = MagicMock()
- mock_llm.acall = AsyncMock(side_effect=RuntimeError("LLM error"))
-
- with pytest.raises(RuntimeError, match="LLM error"):
- await aget_llm_response(
- llm=mock_llm,
- messages=[{"role": "user", "content": "test"}],
- callbacks=[],
- printer=Printer(),
- )
-
-
-class TestAsyncMaxIterationsForcedAnswer:
- """Both async loops request the forced final answer with a trailing user turn."""
-
- @pytest.mark.asyncio
- async def test_react_loop_forces_final_answer_with_user_turn(
- self, executor: CrewAgentExecutor, mock_llm: MagicMock
- ) -> None:
- mock_llm.call.return_value = "Final Answer: forced"
- executor.iterations = executor.max_iter
- executor.messages = [
- {"role": "user", "content": "Collect all the data."},
- {"role": "assistant", "content": "Thought: I need data\nObservation: partial"},
- ]
-
- with patch.object(executor, "_show_logs"):
- result = await executor._ainvoke_loop()
-
- sent = mock_llm.call.call_args.args[0]
- assert sent[-1] == {
- "role": "user",
- "content": I18N_DEFAULT.errors("force_final_answer"),
- }
- assert isinstance(result, AgentFinish)
- assert result.output == "forced"
-
- @pytest.mark.asyncio
- async def test_native_tools_loop_forces_final_answer_with_user_turn(
- self,
- test_agent: Agent,
- test_task: Task,
- mock_tools_handler: MagicMock,
- ) -> None:
- @tool
- def get_data(step: str) -> str:
- """Get data for a step."""
- return f"data for {step}"
-
- # BaseLLM has no supports_function_calling; the native loop needs it.
- llm = MagicMock(spec=LLM)
- llm.stop = []
- llm.supports_function_calling.return_value = True
- llm.call.return_value = "Final Answer: forced"
- executor = CrewAgentExecutor(
- llm=llm,
- task=test_task,
- crew=None,
- agent=test_agent,
- prompt={"prompt": "Test prompt {input} {tool_names} {tools}"},
- max_iter=1,
- tools=[],
- original_tools=[get_data],
- tools_names="get_data",
- stop_words=[],
- tools_description="",
- tools_handler=mock_tools_handler,
- )
- executor.iterations = 1
- executor.messages = [
- {"role": "user", "content": "Collect all the data."},
- {
- "role": "assistant",
- "content": None,
- "tool_calls": [
- {
- "id": "call_1",
- "type": "function",
- "function": {"name": "get_data", "arguments": "{}"},
- }
- ],
- },
- {"role": "tool", "tool_call_id": "call_1", "name": "get_data", "content": "partial"},
- {"role": "user", "content": I18N_DEFAULT.slice("post_tool_reasoning")},
- ]
-
- with patch.object(executor, "_show_logs"):
- result = await executor._ainvoke_loop()
-
- sent = llm.call.call_args.args[0]
- assert sent[-1] == {
- "role": "user",
- "content": I18N_DEFAULT.errors("force_final_answer"),
- }
- assert isinstance(result, AgentFinish)
- assert result.output == "forced"
diff --git a/lib/crewai/tests/agents/test_native_tool_calling.py b/lib/crewai/tests/agents/test_native_tool_calling.py
index 894c0bd45..2908e8ae2 100644
--- a/lib/crewai/tests/agents/test_native_tool_calling.py
+++ b/lib/crewai/tests/agents/test_native_tool_calling.py
@@ -18,7 +18,6 @@ import pytest
from pydantic import BaseModel, Field
from crewai import Agent, Crew, Task
-from crewai.agents.parser import AgentFinish
from crewai.events import crewai_event_bus
from crewai.hooks import register_after_tool_call_hook, register_before_tool_call_hook
from crewai.hooks.tool_hooks import ToolCallHookContext, clear_after_tool_call_hooks
@@ -1117,9 +1116,9 @@ class TestNativeToolCallingJsonParseError:
"""Tests that malformed JSON tool arguments produce clear errors
instead of silently dropping all arguments."""
- def _make_executor(self, tools: list[BaseTool]) -> "CrewAgentExecutor":
- """Create a minimal CrewAgentExecutor with mocked dependencies."""
- from crewai.agents.crew_agent_executor import CrewAgentExecutor
+ def _make_executor(self, tools: list[BaseTool]) -> AgentExecutor:
+ """Create a minimal AgentExecutor with mocked dependencies."""
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.tools.base_tool import to_langchain
structured_tools = to_langchain(tools)
@@ -1135,13 +1134,32 @@ class TestNativeToolCallingJsonParseError:
mock_task.description = "test"
mock_task.id = "test-id"
- executor = CrewAgentExecutor(
+ return AgentExecutor.model_construct(
tools=structured_tools,
original_tools=tools,
+ agent=mock_agent,
+ task=mock_task,
+ crew=None,
+ tools_handler=None,
+ )
+
+ def _execute(
+ self,
+ executor: AgentExecutor,
+ *,
+ call_id: str,
+ func_name: str,
+ func_args: str,
+ available_functions: dict,
+ ) -> dict:
+ executor._available_functions = available_functions
+ return executor._execute_single_native_tool_call(
+ {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": func_name, "arguments": func_args},
+ }
)
- executor.agent = mock_agent
- executor.task = mock_task
- return executor
def test_malformed_json_returns_parse_error(self) -> None:
"""Malformed JSON args must return a descriptive error, not silently become {}."""
@@ -1161,7 +1179,8 @@ class TestNativeToolCallingJsonParseError:
malformed_json = '{"code": "print("hello")"}'
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_123",
func_name="execute_code",
func_args=malformed_json,
@@ -1189,7 +1208,8 @@ class TestNativeToolCallingJsonParseError:
valid_json = '{"code": "print(1)"}'
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_456",
func_name="execute_code",
func_args=valid_json,
@@ -1218,7 +1238,8 @@ class TestNativeToolCallingJsonParseError:
_, available_functions, _ = convert_tools_to_openai_schema([tool])
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_typed",
func_name="typed_search",
func_args='{"query": "crew"}',
@@ -1254,7 +1275,8 @@ class TestNativeToolCallingJsonParseError:
clear_after_tool_call_hooks()
register_after_tool_call_hook(after_hook)
try:
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_typed",
func_name="typed_search",
func_args='{"query": "crew"}',
@@ -1268,50 +1290,6 @@ class TestNativeToolCallingJsonParseError:
('{"query":"crew","score":0.8}', SearchOutput(query="crew", score=0.8))
]
- def test_native_tool_loop_falls_back_when_provider_rejects_tools(self) -> None:
- """Unsupported native tools errors should continue through ReAct."""
-
- class SearchTool(BaseTool):
- name: str = "search"
- description: str = "Search for information"
-
- def _run(self, query: str) -> str:
- return f"result for {query}"
-
- executor = self._make_executor([SearchTool()])
- executor.llm = Mock()
- executor.messages = [{"role": "user", "content": "Search for CrewAI"}]
- executor.callbacks = []
- executor.iterations = 0
- executor.max_iter = 3
- executor.request_within_rpm_limit = None
- executor.respect_context_window = False
-
- fallback_finish = AgentFinish(
- thought="done",
- output="final",
- text="Final Answer: final",
- )
- with (
- patch(
- "crewai.agents.crew_agent_executor.get_llm_response",
- side_effect=RuntimeError(
- "registry.ollama.ai/library/mariner:latest does not support tools"
- ),
- ),
- patch.object(
- executor,
- "_invoke_loop_react",
- return_value=fallback_finish,
- ) as react_loop,
- ):
- result = executor._invoke_loop_native_tools()
-
- assert result is fallback_finish
- react_loop.assert_called_once()
- assert "Native tool calling is unavailable" in executor.messages[-1]["content"]
- assert "Action Input" in executor.messages[-1]["content"]
-
def test_dict_args_bypass_json_parsing(self) -> None:
"""When func_args is already a dict, no JSON parsing occurs."""
@@ -1328,7 +1306,8 @@ class TestNativeToolCallingJsonParseError:
from crewai.utilities.agent_utils import convert_tools_to_openai_schema
_, available_functions, _ = convert_tools_to_openai_schema([tool])
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_789",
func_name="execute_code",
func_args={"code": "x = 42"},
@@ -1354,7 +1333,8 @@ class TestNativeToolCallingJsonParseError:
from crewai.utilities.agent_utils import convert_tools_to_openai_schema
_, available_functions, _ = convert_tools_to_openai_schema([tool])
- result = executor._execute_single_native_tool_call(
+ result = self._execute(
+ executor,
call_id="call_schema",
func_name="strict_tool",
func_args={"code": "print(1)"},
diff --git a/lib/crewai/tests/agents/test_native_tool_from_cache.py b/lib/crewai/tests/agents/test_native_tool_from_cache.py
deleted file mode 100644
index 8b61228b6..000000000
--- a/lib/crewai/tests/agents/test_native_tool_from_cache.py
+++ /dev/null
@@ -1,100 +0,0 @@
-"""A native function-calling tool call served from the cache says so on its event.
-
-`_execute_single_native_tool_call` reads the tools handler's cache and skips
-the tool body on a hit, but its `ToolUsageFinishedEvent` used to be emitted
-without `from_cache`, so every consumer of the bus (tracing included) saw a
-replayed call as a live one. The text-protocol path (`ToolUsage`) already
-carried the flag.
-"""
-
-from __future__ import annotations
-
-import json
-from unittest.mock import Mock
-
-import pytest
-
-from crewai.agents.cache.cache_handler import CacheHandler
-from crewai.agents.crew_agent_executor import CrewAgentExecutor
-from crewai.agents.tools_handler import ToolsHandler
-from crewai.events import crewai_event_bus
-from crewai.events.types.tool_usage_events import ToolUsageFinishedEvent
-from crewai.tools.base_tool import BaseTool, to_langchain
-from crewai.utilities.agent_utils import convert_tools_to_openai_schema
-
-CALLS: list[str] = []
-
-
-class LookupTool(BaseTool):
- name: str = "lookup"
- description: str = "Look a term up."
-
- def _run(self, term: str) -> str:
- CALLS.append(term)
- return f"value:{term}"
-
-
-def _executor(tool: BaseTool, cache: CacheHandler) -> CrewAgentExecutor:
- executor = CrewAgentExecutor(tools=to_langchain([tool]), original_tools=[tool])
- agent = Mock()
- agent.key = "test_agent"
- agent.role = "tester"
- agent.id = "agent-id"
- agent.verbose = False
- agent.fingerprint = None
- agent.tools_results = []
- task = Mock()
- task.name = "test"
- task.description = "test"
- task.id = "task-id"
- executor.agent = agent
- executor.task = task
- executor.tools_handler = ToolsHandler(cache=cache)
- return executor
-
-
-def _call(executor: CrewAgentExecutor, tool: BaseTool, args: dict) -> tuple[dict, list]:
- _, available_functions, _ = convert_tools_to_openai_schema([tool])
- events: list[ToolUsageFinishedEvent] = []
- with crewai_event_bus.scoped_handlers():
-
- @crewai_event_bus.on(ToolUsageFinishedEvent)
- def _capture(_source: object, event: ToolUsageFinishedEvent) -> None:
- events.append(event)
-
- result = executor._execute_single_native_tool_call(
- call_id="call_1",
- func_name="lookup",
- func_args=args,
- available_functions=available_functions,
- original_tool=tool,
- )
- crewai_event_bus.flush()
- return result, events
-
-
[email protected]("ignore::DeprecationWarning")
-def test_a_cached_native_tool_call_reports_from_cache_on_the_finished_event() -> None:
- CALLS.clear()
- tool = LookupTool()
- cache = CacheHandler()
- cache.add(tool="lookup", input=json.dumps({"term": "x"}), output="cached:x")
-
- result, events = _call(_executor(tool, cache), tool, {"term": "x"})
-
- assert result["from_cache"] is True
- assert CALLS == []
- assert [event.from_cache for event in events] == [True]
- assert events[0].output == "cached:x"
-
-
[email protected]("ignore::DeprecationWarning")
-def test_a_live_native_tool_call_reports_from_cache_false() -> None:
- CALLS.clear()
- tool = LookupTool()
-
- result, events = _call(_executor(tool, CacheHandler()), tool, {"term": "y"})
-
- assert result["from_cache"] is False
- assert CALLS == ["y"]
- assert [event.from_cache for event in events] == [False]
diff --git a/lib/crewai/tests/agents/test_native_tool_hook_contract.py b/lib/crewai/tests/agents/test_native_tool_hook_contract.py
index 701a62eb0..75be642d5 100644
--- a/lib/crewai/tests/agents/test_native_tool_hook_contract.py
+++ b/lib/crewai/tests/agents/test_native_tool_hook_contract.py
@@ -12,7 +12,7 @@ from crewai import Agent
from crewai.agents.cache.cache_handler import CacheHandler
from crewai.agents.tools_handler import ToolsHandler
from crewai.events import crewai_event_bus
-from crewai.experimental.agent_executor import AgentExecutor
+from crewai.agents.agent_executor import AgentExecutor
from crewai.hooks.dispatch import HookAborted, InterceptionPoint, clear_all, on
from crewai.llms.base_llm import BaseLLM
from crewai.tools import BaseTool
diff --git a/lib/crewai/tests/hooks/test_deny_reaches_the_caller.py b/lib/crewai/tests/hooks/test_deny_reaches_the_caller.py
index 303b69ee7..bbdcb2852 100644
--- a/lib/crewai/tests/hooks/test_deny_reaches_the_caller.py
+++ b/lib/crewai/tests/hooks/test_deny_reaches_the_caller.py
@@ -15,7 +15,7 @@ from typing import Any
from crewai.agent import Agent
from crewai.agents.step_executor import StepExecutor
from crewai.crew import Crew
-from crewai.experimental.agent_executor import AgentExecutor
+from crewai.agents.agent_executor import AgentExecutor
from crewai.hooks.dispatch import HookAborted, InterceptionPoint, clear_all, on
from crewai.lite_agent import LiteAgent
from crewai.llms.base_llm import BaseLLM
diff --git a/lib/crewai/tests/hooks/test_hook_abort_propagation.py b/lib/crewai/tests/hooks/test_hook_abort_propagation.py
index e498eaa04..84c2be7e3 100644
--- a/lib/crewai/tests/hooks/test_hook_abort_propagation.py
+++ b/lib/crewai/tests/hooks/test_hook_abort_propagation.py
@@ -42,7 +42,7 @@ from crewai.events.types.observation_events import (
StepObservationFailedEvent,
StepObservationStartedEvent,
)
-from crewai.experimental.agent_executor import AgentExecutor
+from crewai.agents.agent_executor import AgentExecutor
from crewai.hooks.dispatch import (
HookAborted,
InterceptionPoint,
diff --git a/lib/crewai/tests/llms/bedrock/test_bedrock.py b/lib/crewai/tests/llms/bedrock/test_bedrock.py
index d7011fcf5..0420fb317 100644
--- a/lib/crewai/tests/llms/bedrock/test_bedrock.py
+++ b/lib/crewai/tests/llms/bedrock/test_bedrock.py
@@ -1000,7 +1000,7 @@ def test_bedrock_stop_sequences_sent_to_api():
"""Test that stop_sequences are properly sent to the Bedrock API."""
llm = LLM(model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0")
- # Set stop sequences via the stop attribute (simulating CrewAgentExecutor)
+ # Set stop sequences via the stop attribute (simulating an executor)
llm.stop = ["\nObservation:", "\nThought:"]
with patch.object(llm._client, 'converse') as mock_converse:
diff --git a/lib/crewai/tests/llms/google/test_google.py b/lib/crewai/tests/llms/google/test_google.py
index 8a747f285..ef6d95b63 100644
--- a/lib/crewai/tests/llms/google/test_google.py
+++ b/lib/crewai/tests/llms/google/test_google.py
@@ -922,7 +922,7 @@ def test_gemini_stop_sequences_sent_to_api():
"""Test that stop_sequences are properly sent to the Gemini API."""
llm = LLM(model="google/gemini-2.0-flash-001")
- # Set stop sequences via the stop attribute (simulating CrewAgentExecutor)
+ # Set stop sequences via the stop attribute (simulating an executor)
llm.stop = ["\nObservation:", "\nThought:"]
with patch.object(llm._client.models, 'generate_content') as mock_generate:
diff --git a/lib/crewai/tests/test_crew.py b/lib/crewai/tests/test_crew.py
index a960a6b09..8cb978239 100644
--- a/lib/crewai/tests/test_crew.py
+++ b/lib/crewai/tests/test_crew.py
@@ -4200,7 +4200,7 @@ def test_multimodal_flag_adds_multimodal_tools():
@pytest.mark.vcr()
def test_multimodal_agent_image_tool_handling():
"""
- Test that multimodal agents properly handle image tools in the CrewAgentExecutor
+ Test that multimodal agents properly handle image tools in the AgentExecutor
"""
multimodal_agent = Agent(
role="Image Analyst",
@@ -5098,7 +5098,7 @@ def test_prepare_kickoff_binds_task_only_agent_to_crew():
Regression for crewAIInc/crewAI#5534: when Crew is built without
agents=[...], multimodal input_files were silently dropped because the
agent's .crew attribute was never assigned, gating file lookup off in
- Task and CrewAgentExecutor.
+ Task and AgentExecutor.
"""
from crewai.crews.utils import prepare_kickoff
diff --git a/lib/crewai/tests/tools/test_tool_failure.py b/lib/crewai/tests/tools/test_tool_failure.py
index 0997c53ae..21eff3abd 100644
--- a/lib/crewai/tests/tools/test_tool_failure.py
+++ b/lib/crewai/tests/tools/test_tool_failure.py
@@ -749,9 +749,8 @@ class TestRaisePolicySurvivesEveryWrapper:
from crewai.agent.core import Agent as AgentCls
from crewai.agents.step_executor import StepExecutor
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
- # CrewAgentExecutor is deprecated and deliberately excluded.
sites = [
(AgentCls._execute_with_timeout, "_passthrough_exceptions"),
(StepExecutor.execute, "ToolExecutionFailedError"),
@@ -1294,23 +1293,6 @@ class TestMalformedArgumentsAreReported:
assert "INVALID_INPUT" in inspect.getsource(agent_utils.parse_tool_call_args)
-class TestDeprecatedExecutorIsNotIntegrated:
- """CrewAgentExecutor is deprecated; the feature must not extend into it."""
-
- def test_no_tool_failure_integration(self) -> None:
- from importlib import import_module
- from pathlib import Path
-
- # Read the file directly: importing this module by name resolves to a
- # different one in this package, so inspect would read the wrong source.
- package = import_module(Agent.__module__.split(".")[0])
- source = (
- Path(package.__file__).parent / "agents" / "crew_agent_executor.py"
- ).read_text()
- assert "tool_failure" not in source
- assert "ToolExecutionFailedError" not in source
-
-
class TestConcurrentExecutionsAreIsolated:
"""A shared agent must not leak failures between concurrent executions.
@@ -1632,7 +1614,7 @@ class TestParallelAbortCancelsPendingSiblings:
"""
import inspect
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
source = inspect.getsource(AgentExecutor.execute_native_tool)
assert "cancel_futures=True" in source
@@ -1900,7 +1882,7 @@ class TestRepeatedToolCallStopsTheRun:
@pytest.mark.asyncio
async def test_parallel_step_loop_stops_the_agent(self) -> None:
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.utilities.planning_types import TodoItem
record = ToolFailureRecord(
diff --git a/lib/crewai/tests/utilities/test_events.py b/lib/crewai/tests/utilities/test_events.py
index e2f99a54c..4de684a0c 100644
--- a/lib/crewai/tests/utilities/test_events.py
+++ b/lib/crewai/tests/utilities/test_events.py
@@ -4,7 +4,6 @@ import os
from unittest.mock import Mock, patch
from crewai.agent import Agent
-from crewai.agents.crew_agent_executor import CrewAgentExecutor
from crewai.crew import Crew
from crewai.events.event_bus import crewai_event_bus
from crewai.events.event_listener import EventListener
@@ -348,7 +347,7 @@ def test_agent_emits_execution_error_event(base_agent, base_task):
received_events.append(event)
event_received.set()
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
error_message = "Error happening while sending prompt to model."
base_agent.max_retry_limit = 0
@@ -395,7 +394,7 @@ def test_agent_retries_close_the_scope_of_every_attempt():
def handle_task_failed(source, event):
task_failed.append(event)
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
agent = Agent(
role="retrying_agent",
@@ -448,7 +447,7 @@ def test_agent_retry_that_succeeds_closes_one_scope_per_attempt():
def handle_task_completed(source, event):
task_completed.append(event)
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
agent = Agent(
role="retrying_agent",
@@ -1284,7 +1283,7 @@ def test_infrastructure_flows_suppress_flow_events_by_default():
``suppress_flow_events=True``; without this guard, removing the flag from
AgentExecutor would silently bring back the verbose per-method trace spans.
"""
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.memory.encoding_flow import EncodingFlow
from crewai.memory.recall_flow import RecallFlow
@@ -1296,7 +1295,7 @@ def test_infrastructure_flows_suppress_flow_events_by_default():
def test_infrastructure_flows_are_marked_internal():
- from crewai.experimental.agent_executor import AgentExecutor
+ from crewai.agents.agent_executor import AgentExecutor
from crewai.memory.encoding_flow import EncodingFlow
from crewai.memory.recall_flow import RecallFlow