Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
feat(flow): run an integration app action directly with call: tool (#8367)
Gabe Milani5c154cd701fb
diff --git a/lib/crewai/src/crewai/flow/flow_definition.py b/lib/crewai/src/crewai/flow/flow_definition.pyindex 0a65fd7ef..13250e6b7 100644--- a/lib/crewai/src/crewai/flow/flow_definition.py+++ b/lib/crewai/src/crewai/flow/flow_definition.py@@ -377,7 +377,7 @@ class FlowCodeActionDefinition(BaseModel):class FlowToolActionDefinition(BaseModel):- """A Flow method action that invokes a CrewAI tool."""+ """A Flow method action that runs a CrewAI tool or one integration app action."""model_config = ConfigDict(populate_by_name=True,@@ -385,12 +385,18 @@ class FlowToolActionDefinition(BaseModel):)call: Literal["tool"] = Field(- description="Action discriminator. Use tool to instantiate and run a CrewAI tool.",+ description=(+ "Action discriminator. Use tool to run a CrewAI tool or one "+ "integration app action."+ ),examples=["tool"],)ref: str = Field(- description="Reference to the CrewAI tool to run.",- examples=["my_project.tools:SearchTool"],+ description=(+ "What to run: module:ToolClass for a CrewAI tool, or "+ "<app>/<action>[@<connection>] for one integration app action."+ ),+ examples=["my_project.tools:SearchTool", "google_gmail/send_email"],)with_: dict[str, ExpressionData] | None = Field(default=None,diff --git a/lib/crewai/src/crewai/flow/runtime/_actions.py b/lib/crewai/src/crewai/flow/runtime/_actions.pyindex 5714239f7..afa25de3c 100644--- a/lib/crewai/src/crewai/flow/runtime/_actions.py+++ b/lib/crewai/src/crewai/flow/runtime/_actions.py@@ -100,16 +100,32 @@ class ToolAction:self.kwargs = definition.with_ or {}def run(self, *_args: Any, **kwargs: Any) -> Any:- local_context = _pop_local_context(kwargs)- return self.tool.run(- **Expression.from_flow(- self.kwargs, self.flow, local_context=local_context- ).render_template()+ from crewai.tools.tool_failure import (+ ToolExecutionFailedError,+ ToolFailureRecord,+ detect_tool_failure,)+ local_context = _pop_local_context(kwargs)+ rendered = Expression.from_flow(+ self.kwargs, self.flow, local_context=local_context+ ).render_template()+ result = self.tool.run(**rendered)+ if failure := detect_tool_failure(result):+ raise ToolExecutionFailedError(+ ToolFailureRecord(+ tool_name=self.tool.name, failure=failure, tool_args=rendered+ )+ )+ return result+def _build_tool(self) -> Any:from crewai.tools import BaseTool+ # A class ref always has a colon; an app selector never does.+ if ":" not in self.definition.ref:+ return _build_platform_tool(self.definition.ref)+tool_cls = cast(Callable[[], BaseTool],resolve_class_ref(@@ -127,6 +143,24 @@ class ToolAction:) from e+def _build_platform_tool(ref: str) -> Any:+ """Build the one integration app action named by ``<app>/<action>[@<connection>]``."""+ from crewai.project.json_loader import _resolve_platform_tools++ if "/" not in ref.partition("@")[0]:+ raise InvalidRefError(+ f"invalid tool ref {ref!r}; expected 'module:qualname' for a tool "+ "class or '<app>/<action>[@<connection>]' for one integration app action"+ )+ tools = _resolve_platform_tools(ref)+ if len(tools) != 1:+ raise InvalidRefError(+ f"tool ref {ref!r} resolved to {len(tools)} tools; the action "+ "does not exist or the app is not connected"+ )+ return tools[0]++class CrewAction:definition_type = FlowCrewActionDefinitiondiff --git a/lib/crewai/src/crewai/flow/templates/flow_definition_skill.md.j2 b/lib/crewai/src/crewai/flow/templates/flow_definition_skill.md.j2index ed9c014ce..2d8d09d05 100644--- a/lib/crewai/src/crewai/flow/templates/flow_definition_skill.md.j2+++ b/lib/crewai/src/crewai/flow/templates/flow_definition_skill.md.j2@@ -44,6 +44,7 @@ Pick the simplest action that does the job.{% endif %}{% if include_tool_action %}- Use `call: tool` for packaged deterministic work: API calls, searches, lookups, scoring, file work, or custom CrewAI tools.+- An integration app action can run as `call: tool` with `ref: <app>/<action>[@<connection>]`, the same selector an agent lists in `apps`. Use it when the inputs are flat values from state. Use an agent when the input must be built or decided.{% endif %}- Use `call: agent` for one AI worker that classifies, decides, summarizes, writes, or drafts. Put `role`, `goal`, `backstory`, and `input` under `with`. Do not add an action-level `inputs` map to an agent.- Repository-backed agents may set `from_repository` and omit inline `role`, `goal`, and `backstory`. Explicitly provided fields override repository values.diff --git a/lib/crewai/tests/test_flow_from_definition.py b/lib/crewai/tests/test_flow_from_definition.pyindex 1eea8fa7d..4e3c7fdc3 100644--- a/lib/crewai/tests/test_flow_from_definition.py+++ b/lib/crewai/tests/test_flow_from_definition.py@@ -30,7 +30,8 @@ from crewai.flow.persistence.base import FlowPersistencefrom crewai.flow.runtime._actions import FlowScriptExecutionDisabledErrorfrom crewai.project.crew_definition import AgentDefinitionfrom crewai.state.checkpoint_config import CheckpointConfig-from crewai.tools import BaseTool+from crewai.tools import BaseTool, ToolFailure+from crewai.tools.tool_failure import ToolExecutionFailedErrorfrom crewai.types.streaming import StreamSession@@ -3228,6 +3229,85 @@ def test_tool_action_requires_module_qualname_ref():Flow.from_declaration(contents=definition)+class FailingTool(BaseTool):+ name: str = "FailingTool"+ description: str = "Always reports failure."++ def _run(self, to: str) -> ToolFailure:+ return ToolFailure(message=f"cannot send to {to}", code="bad_recipient")+++def _tool_flow_definition(ref: str, with_: dict[str, Any]) -> FlowDefinition:+ return FlowDefinition.from_declaration(contents=+ {+ "schema": "crewai.flow/v1",+ "name": "ToolFlow",+ "methods": {+ "send": {+ "start": True,+ "do": {"call": "tool", "ref": ref, "with": with_},+ }+ },+ }+ )+++ "selector",+ [+ "google_gmail/send_email",+ "google_gmail/send_email@0b3c9f8e-1d2a-4c5b-9e6f-7a8b9c0d1e2f",+ ],+)+def test_tool_action_runs_platform_action(selector: str):+ definition = _tool_flow_definition(+ selector,+ {"search_query": "${state.topic}", "prefix": "mail"},+ )++ with patch(+ "crewai.project.json_loader._resolve_platform_tools",+ return_value=[StaticSearchTool()],+ ) as resolve:+ flow = Flow.from_declaration(contents=definition)++ resolve.assert_called_once_with(selector)+ assert flow.kickoff(inputs={"topic": "digest"}) == "mail:digest"+++def test_tool_action_platform_ref_requires_action():+ definition = _tool_flow_definition("google_gmail", {})++ with patch("crewai.project.json_loader._resolve_platform_tools") as resolve:+ with pytest.raises(ValueError, match="<app>/<action>"):+ Flow.from_declaration(contents=definition)++ resolve.assert_not_called()+++def test_tool_action_platform_ref_with_no_tools_names_ref():+ definition = _tool_flow_definition("google_gmail/send_email", {})++ with patch(+ "crewai.project.json_loader._resolve_platform_tools", return_value=[]+ ):+ with pytest.raises(ValueError, match="'google_gmail/send_email'"):+ Flow.from_declaration(contents=definition)+++def test_tool_action_raises_when_tool_reports_failure():+ definition = _tool_flow_definition(+ f"{__name__}:FailingTool", {"to": "${state.email}"}+ )+ flow = Flow.from_declaration(contents=definition)++ with pytest.raises(ToolExecutionFailedError, match="cannot send to [email protected]") as exc:+ flow.kickoff(inputs={"email": "[email protected]"})++ assert exc.value.record.tool_name == "FailingTool"+ assert exc.value.record.tool_args == {"to": "[email protected]"}++def test_pydantic_state_from_ref_parity():flow, result = assert_parity(PydanticStateFlow, PYDANTIC_STATE_YAML)assert result == "count=1"