Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions lib/crewai/src/crewai/agents/agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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,
Expand Down
63 changes: 59 additions & 4 deletions lib/crewai/tests/agents/test_native_tool_hook_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,28 @@
import json
from typing import Any

import pytest

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
from crewai.tools import BaseTool
from crewai.tools.base_tool import to_langchain
from crewai.utilities.agent_utils import (
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)
Expand Down Expand Up @@ -102,6 +103,55 @@ 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] = Field(default_factory=list)

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])
Expand Down Expand Up @@ -132,6 +182,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"]
Expand Down