From 1d59980c54bc613c19a273e10ffd173395d91a38 Mon Sep 17 00:00:00 2001 From: sll00 <1275142234@qq.com> Date: Wed, 25 Nov 2026 16:48:34 +0800 Subject: [PATCH 1/2] fix(agent): record hook-adjusted native tool arguments --- .../src/crewai/agents/agent_executor.py | 43 ++++++++++++--- .../agents/test_native_tool_hook_contract.py | 54 +++++++++++++++++++ 2 files changed, 90 insertions(+), 7 deletions(-) diff --git a/lib/crewai/src/crewai/agents/agent_executor.py b/lib/crewai/src/crewai/agents/agent_executor.py index 8c7a5253284..29df1f81d05 100644 --- a/lib/crewai/src/crewai/agents/agent_executor.py +++ b/lib/crewai/src/crewai/agents/agent_executor.py @@ -2027,12 +2027,14 @@ def execute_native_tool( # Group all tool calls into a single assistant message tool_calls_to_report = [] + runnable_tool_calls = [] for tool_call in pending_tool_calls: info = extract_tool_call_info(tool_call) if not info: continue call_id, func_name, func_args = info + runnable_tool_calls.append(tool_call) tool_calls_to_report.append( { "id": call_id, @@ -2056,11 +2058,6 @@ def execute_native_tool( assistant_message["raw_tool_call_parts"] = list(pending_tool_calls) self.state.messages.append(assistant_message) - runnable_tool_calls = [ - tool_call - for tool_call in pending_tool_calls - if extract_tool_call_info(tool_call) is not None - ] should_parallelize = self._should_parallelize_native_tool_calls( runnable_tool_calls ) @@ -2111,8 +2108,11 @@ def execute_native_tool( else: # Execute sequentially so result_as_answer tools can short-circuit # immediately without running remaining calls. - for tool_call in runnable_tool_calls: + for tool_call, report in zip( + runnable_tool_calls, tool_calls_to_report, strict=True + ): execution_result = self._execute_single_native_tool_call(tool_call) + self._record_effective_tool_arguments(report, execution_result) call_id = cast(str, execution_result["call_id"]) func_name = cast(str, execution_result["func_name"]) result = self._prepare_tool_result_for_context(execution_result) @@ -2152,7 +2152,10 @@ def execute_native_tool( return "native_tool_completed" - for execution_result in execution_results: + for execution_result, report in zip( + execution_results, tool_calls_to_report, strict=True + ): + self._record_effective_tool_arguments(report, execution_result) call_id = cast(str, execution_result["call_id"]) func_name = cast(str, execution_result["func_name"]) result = self._prepare_tool_result_for_context(execution_result) @@ -2195,6 +2198,13 @@ def execute_native_tool( return "native_tool_completed" + @staticmethod + def _record_effective_tool_arguments( + report: dict[str, Any], execution_result: dict[str, Any] + ) -> None: + if (arguments := execution_result.get("history_arguments")) is not None: + report["function"]["arguments"] = arguments + def _should_parallelize_native_tool_calls(self, tool_calls: list[Any]) -> bool: """Determine if native tool calls are safe to run in parallel.""" if len(tool_calls) <= 1: @@ -2260,6 +2270,8 @@ def _execute_single_native_tool_call(self, tool_call: Any) -> dict[str, Any]: ) return parse_error args_dict: dict[str, Any] = parsed_args or {} + model_argument_names = tuple(args_dict) if isinstance(args_dict, dict) else () + model_arguments = json.dumps(args_dict) if model_argument_names else "" # Get agent_key for event tracking agent_key = getattr(self.agent, "key", "unknown") if self.agent else "unknown" @@ -2331,6 +2343,18 @@ def _execute_single_native_tool_call(self, tool_call: Any) -> dict[str, Any]: hook_blocked = run_before_tool_call_hooks(before_hook_context) input_str = json.dumps(args_dict) if args_dict else "" + history_arguments = None + if model_argument_names and input_str != model_arguments: + # Keep newly injected top-level arguments out of model history. + visible_arguments = json.dumps( + { + name: args_dict[name] + for name in model_argument_names + if name in args_dict + } + ) + if visible_arguments != model_arguments: + history_arguments = visible_arguments if ( not hook_blocked and self.tools_handler @@ -2346,6 +2370,7 @@ def _execute_single_native_tool_call(self, tool_call: Any) -> dict[str, Any]: tool_failure = detect_tool_failure(cached_result) from_cache = True + tool_called = False if hook_blocked: result = f"Tool execution blocked by hook. Tool: {func_name}" raw_tool_result = result @@ -2354,6 +2379,7 @@ def _execute_single_native_tool_call(self, tool_call: Any) -> dict[str, Any]: if func_name in self._available_functions: try: tool_func = self._available_functions[func_name] + tool_called = True raw_result = tool_func(**args_dict) raw_tool_result = raw_result @@ -2463,6 +2489,9 @@ def _execute_single_native_tool_call(self, tool_call: Any) -> dict[str, Any]: "func_name": func_name, "result": result, "tool_args": args_dict, + "history_arguments": history_arguments + if tool_called or from_cache + else None, "from_cache": from_cache, "original_tool": original_tool, "tool_failure": tool_failure, 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 c69616c459f..c145bcb93ba 100644 --- a/lib/crewai/tests/agents/test_native_tool_hook_contract.py +++ b/lib/crewai/tests/agents/test_native_tool_hook_contract.py @@ -7,6 +7,7 @@ from typing import Any import pytest +from pydantic import ValidationError from crewai import Agent from crewai.agents.cache.cache_handler import CacheHandler @@ -14,6 +15,7 @@ from crewai.events import crewai_event_bus from crewai.agents.agent_executor import AgentExecutor from crewai.hooks.dispatch import HookAborted, InterceptionPoint, clear_all, on +from crewai.hooks.tool_hooks import ToolCallHookContext from crewai.llms.base_llm import BaseLLM from crewai.tools import BaseTool from crewai.tools.base_tool import to_langchain @@ -102,6 +104,53 @@ def deny(_context): assert llm.calls == 1 +@pytest.mark.parametrize("batch_size", [1, 2], ids=["serial", "parallel"]) +@pytest.mark.parametrize("async_entry", [False, True], ids=["sync", "async"]) +def test_kickoff_history_records_input_applied_by_pre_tool_hooks( + batch_size: int, async_entry: bool +) -> None: + class LookupWithExecutionNote(LookupTool): + execution_notes: list[str] = [] + + def _run(self, term: str = "default", execution_note: str = "") -> str: + self.execution_notes.append(execution_note) + return super()._run(term) + + @on(InterceptionPoint.PRE_TOOL_CALL) + def rewrite(context: ToolCallHookContext) -> None: + context.tool_input["term"] = f"effective-{context.tool_input['term']}" + context.tool_input["execution_note"] = "for the tool only" + + @on(InterceptionPoint.POST_TOOL_CALL) + def edit_context_after_execution(context: ToolCallHookContext) -> None: + context.tool_input["term"] = "after-execution" + + tool = LookupWithExecutionNote() + agent = Agent( + role="Tester", + goal="Look up values", + backstory="Test hooks", + llm=ScriptedLLM(batch_size), + tools=[tool], + verbose=False, + ) + + output = ( + asyncio.run(agent.kickoff_async("Look up values")) + if async_entry + else agent.kickoff("Look up values") + ) + + expected = [f"effective-{i}" for i in range(batch_size)] + assert sorted(tool.calls) == expected + assert tool.execution_notes == ["for the tool only"] * batch_size + calls = [call for message in output.messages for call in message.get("tool_calls", [])] + assert [call["id"] for call in calls] == [f"call_{i}" for i in range(batch_size)] + assert [json.loads(call["function"]["arguments"]) for call in calls] == [ + {"term": term} for term in expected + ] + + def native_call(backend, tool, cache, args): structured = to_langchain([tool]) _, functions, _ = convert_tools_to_openai_schema([tool]) @@ -132,6 +181,11 @@ def native_call(backend, tool, cache, args): return result["result"], result["from_cache"] +def test_non_object_tool_arguments_still_fail_event_validation() -> None: + with pytest.raises(ValidationError, match="ToolUsageStartedEvent"): + native_call("agent", LookupTool(), CacheHandler(), 5) + + @pytest.mark.parametrize("backend", ["agent", "shared"]) @pytest.mark.parametrize( "input_args", [{"term": "original"}, {}], ids=["original", "empty"] From 9f78fc3d609f4e5213fb8170de979fc0d1663a59 Mon Sep 17 00:00:00 2001 From: sll00 <1275142234@qq.com> Date: Wed, 25 Nov 2026 16:59:45 +0800 Subject: [PATCH 2/2] test(agent): isolate native hook test fixtures --- .../agents/test_native_tool_hook_contract.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) 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 c145bcb93ba..8287598f448 100644 --- a/lib/crewai/tests/agents/test_native_tool_hook_contract.py +++ b/lib/crewai/tests/agents/test_native_tool_hook_contract.py @@ -6,14 +6,11 @@ import json from typing import Any -import pytest -from pydantic import ValidationError - from crewai import Agent +from crewai.agents.agent_executor import AgentExecutor from crewai.agents.cache.cache_handler import CacheHandler from crewai.agents.tools_handler import ToolsHandler from crewai.events import crewai_event_bus -from crewai.agents.agent_executor import AgentExecutor from crewai.hooks.dispatch import HookAborted, InterceptionPoint, clear_all, on from crewai.hooks.tool_hooks import ToolCallHookContext from crewai.llms.base_llm import BaseLLM @@ -23,12 +20,14 @@ convert_tools_to_openai_schema, execute_single_native_tool_call, ) +from pydantic import Field, ValidationError +import pytest class LookupTool(BaseTool): name: str = "lookup" description: str = "Look up a value." - calls: list[str] = [] + calls: list[str] = Field(default_factory=list) def _run(self, term: str = "default") -> str: self.calls.append(term) @@ -110,7 +109,7 @@ def test_kickoff_history_records_input_applied_by_pre_tool_hooks( batch_size: int, async_entry: bool ) -> None: class LookupWithExecutionNote(LookupTool): - execution_notes: list[str] = [] + execution_notes: list[str] = Field(default_factory=list) def _run(self, term: str = "default", execution_note: str = "") -> str: self.execution_notes.append(execution_note) @@ -144,7 +143,9 @@ def edit_context_after_execution(context: ToolCallHookContext) -> None: expected = [f"effective-{i}" for i in range(batch_size)] assert sorted(tool.calls) == expected assert tool.execution_notes == ["for the tool only"] * batch_size - calls = [call for message in output.messages for call in message.get("tool_calls", [])] + calls = [ + call for message in output.messages for call in message.get("tool_calls", []) + ] assert [call["id"] for call in calls] == [f"call_{i}" for i in range(batch_size)] assert [json.loads(call["function"]["arguments"]) for call in calls] == [ {"term": term} for term in expected