[BUG] result_as_answer discards after-tool hook replacement
Description
When result_as_answer=True, the final task output contains the original tool result instead of the value returned by the after-tool hook. Reproduced with both Agent.execute_task and Agent.aexecute_task on the unchanged 1.15.27 release, ReAct path.
Steps to Reproduce
Save the exact test below as test_hook_result.py. With Python 3.12 and uv:
git clone --depth 1 --branch 1.15.27 https://github.com/crewAIInc/crewAI.git source
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python -e source/lib/crewai-core -e source/lib/cli -e source/lib/crewai pytest==9.1.1
.venv/bin/python -m pytest -p no:cacheprovider -s -v test_hook_result.py
The two final-hook cases fail; four controls pass.
Expected behavior
Return Amount: 100 USD without another model call. Is preserving the hook replacement intended here? Docs permit replacement strings: https://docs.crewai.com/v1.15.27/en/learn/tool-hooks ; result_as_answer avoids agent rewriting: https://docs.crewai.com/en/learn/force-tool-output-as-result
Screenshots/Code snippets
Exact test used for both final verification runs:
import asyncio
import json
import os
import socket
from typing import Any
os.environ['OTEL_SDK_DISABLED'] = 'true'
os.environ['CREWAI_TRACING_ENABLED'] = 'false'
os.environ['CREWAI_TELEMETRY_ENABLED'] = 'false'
# A test-only guard ensures import and execution cannot use any network service.
def no_network(*args: Any, **kwargs: Any) -> None:
raise AssertionError('Unexpected network operation in offline reproduction')
socket.socket.connect = no_network
socket.socket.connect_ex = no_network
socket.create_connection = no_network
import pytest
from crewai import Agent, Task
from crewai.llms.base_llm import BaseLLM
from crewai.tools import BaseTool
from crewai.hooks.tool_hooks import (
clear_all_tool_call_hooks, register_after_tool_call_hook,
)
from pydantic import PrivateAttr
ORIGINAL = 'amount: 100'
FORMATTED = 'Amount: 100 USD'
class LocalReport(BaseTool):
name: str = 'local_report'
description: str = 'Return a fixed local report.'
def _run(self) -> str:
return ORIGINAL
async def _arun(self) -> str:
return ORIGINAL
class ScriptedLLM(BaseLLM):
_calls: int = PrivateAttr(default=0)
_observations: list[str] = PrivateAttr(default_factory=list)
def call(self, messages: Any, **kwargs: Any) -> str:
self._calls += 1
if self._calls == 1:
return 'Thought: Read the local report.\nAction: local_report\nAction Input: {}'
if self._calls == 2:
last_message = next(m['content'] for m in reversed(messages) if isinstance(m.get('content'), str) and 'Observation: ' in m['content'])
self._observations.append(last_message)
# Echo the actual tool observation; do not hardcode replacement text.
observation = last_message.rsplit('Observation: ', 1)[-1].strip()
return f'Thought: I have the report.\nFinal Answer: {observation}'
raise AssertionError('Unexpected extra model call')
async def acall(self, messages: Any, **kwargs: Any) -> str:
return self.call(messages, **kwargs)
def supports_function_calling(self) -> bool:
return False
def supports_stop_words(self) -> bool:
return False
@pytest.mark.parametrize('asynchronous', [False, True], ids=['sync', 'async'])
@pytest.mark.parametrize('final_tool,with_hook', [(True, True), (True, False), (False, True)], ids=['final-hook', 'final-no-hook', 'nonfinal-hook'])
def test_after_tool_output(asynchronous: bool, final_tool: bool, with_hook: bool) -> None:
clear_all_tool_call_hooks()
hook_inputs: list[str] = []
def format_report(context: Any) -> str:
hook_inputs.append(context.tool_result)
return FORMATTED
if with_hook:
register_after_tool_call_hook(format_report)
llm = ScriptedLLM(model='offline-scripted')
agent = Agent(role='Reporter', goal='Read the local report', backstory='Local test reporter',
llm=llm, tools=[LocalReport(result_as_answer=final_tool)],
verbose=False, max_retry_limit=0, max_iter=3, cache=False)
task = Task(description='Read and return the local report.', expected_output='The report text.', agent=agent)
try:
output = asyncio.run(agent.aexecute_task(task)) if asynchronous else agent.execute_task(task)
evidence = dict(asynchronous=asynchronous, final_tool=final_tool, with_hook=with_hook,
hook_inputs=hook_inputs, output=output, stored_tool_results=agent.tools_results,
model_calls=llm._calls, model_observations=llm._observations)
print('\nEVIDENCE ' + json.dumps(evidence, default=str))
assert hook_inputs == ([ORIGINAL] if with_hook else [])
assert llm._calls == (1 if final_tool else 2)
assert output == (FORMATTED if with_hook else ORIGINAL)
finally:
clear_all_tool_call_hooks()
Operating System
Other (specify in additional context)
Python Version
3.12
crewAI Version
1.15.27
crewAI Tools Version
Not installed; local crewai.tools.BaseTool only
Virtual Environment
Venv
Evidence
Two final runs: 2 failed, 4 passed each. Sync/async final+hook returned amount: 100 (expected Amount: 100 USD); hook ran and model called once. Final without hook passed. Nonfinal+hook passed with the model echoing the actual modified Observation. The test uses the unchanged framework, a local scripted model, and no network services.
A separate offline quote test on the same release also produced 2 failed, 4 passed: the hook parsed Subtotal: USD 100.00 with Decimal and added a known USD 12.50 shipping fixture, returning Total: USD 112.50 (includes USD 12.50 shipping). Both final-tool task APIs instead returned Subtotal: USD 100.00. The same four controls passed.
Possible Solution
ToolUsage stores the pre-hook result in agent.tools_results. tool_utils returns the replacement, but process_tool_results restores the stored original. Keep the stored final result consistent with post-hook output? I can submit a focused fix PR if maintainers confirm the expected behavior.
Additional context
Debian 13, Python 3.12.14, pytest 9.1.1, uv venv. Release 1.15.27, commit 6b93fa0e25a926215ca7bb52a95d4db7d9d7262d. Only ReAct public sync/async APIs tested; not native calling/all providers/full suite. Dependencies resolved during installation.
AI disclosure: report and reproduction prepared with an AI assistant. Please apply the required llm-generated label; this form does not let me set it.
Opened #8160 as a comprehensive resolution for this issue.
In addition to ensuring after-tool hook replacements are preserved when result_as_answer=True, it introduces execution-scoped ContextVar isolation to prevent tool-result leaks across concurrent tasks and threads sharing an agent, and preserves hook replacements across warm-cache hits.
Verified across remote Ruff lint/format, the full tool usage test suite (44/44 passed), and workspace package builds.
This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
Keeping this open — PR #8160 has a fix ready for maintainer review (CodeRabbit feedback addressed and branch is mergeable).