crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

before_llm_call hooks never run on async acall(), so a blocking hook fails to block the request

Open LHMQ878 opened this issue 4 months ago • 10 comments

Description

before_llm_call hooks are the only interception point that can abort an LLM call: returning False (or raising HookAborted via the reducer) is supposed to stop the request from ever reaching the provider. That works on the synchronous call() path of every native provider, but none of the five native providers invoke the hook on their async acall() path.

The consequence is not "the hook didn't get a chance to observe the messages" — it is that the request is actually issued. A guardrail hook written to block a call (PII gate, spend cap, policy check, prompt-injection filter) silently permits it whenever the caller uses acall()/kickoff_async.

Coverage of _invoke_before_llm_call_hooks in main (ebe0082):

provider sync call() async acall()
llms/providers/openai/completion.py ✅ :465 ❌ missing
llms/providers/anthropic/completion.py ✅ :377 ❌ missing
llms/providers/bedrock/completion.py ✅ :380 ❌ missing
llms/providers/gemini/completion.py ✅ :316 ❌ missing
llms/providers/azure/completion.py ✅ :524 ❌ missing

llms/base_llm.py (the LiteLLM fallback) has the guard on both paths, so the bug is specific to the native providers.

Steps to Reproduce

No network needed — swap the provider client for a stub that records whether a request was issued, so the observable is "did the HTTP call happen", not merely "did the response change".

import asyncio
from types import SimpleNamespace

from crewai.hooks import register_before_llm_call_hook
from crewai.llms.providers.openai.completion import OpenAICompletion

ISSUED: list[str] = []


def blocking_hook(context) -> bool:
    return False  # must abort the call


register_before_llm_call_hook(blocking_hook)

llm = OpenAICompletion(model="gpt-4o", api_key="stub", stream=False)


def _response():
    msg = SimpleNamespace(content="LEAKED", tool_calls=None, refusal=None)
    return SimpleNamespace(
        choices=[SimpleNamespace(message=msg, finish_reason="stop")],
        usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1, total_tokens=2),
    )


def create(**_kwargs):
    ISSUED.append("sync")
    return _response()


async def acreate(**_kwargs):
    ISSUED.append("async")
    return _response()


llm._client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=create)))
llm._async_client = SimpleNamespace(chat=SimpleNamespace(completions=SimpleNamespace(create=acreate)))

msgs = [{"role": "user", "content": "hi"}]

try:
    llm.call(msgs)
except ValueError as exc:
    print("sync  ->", exc)
print("sync  request issued:", ISSUED or "no")

ISSUED.clear()
print("async ->", asyncio.run(llm.acall(msgs)))
print("async request issued:", ISSUED or "no")

Expected Behavior

Both paths refuse to issue the request:

sync  -> LLM call blocked by before_llm_call hook
sync  request issued: no
async -> LLM call blocked by before_llm_call hook
async request issued: no

Actual Behavior

sync  -> LLM call blocked by before_llm_call hook
sync  request issued: no
async -> LEAKED
async request issued: ['async']

Same result on AnthropicCompletion (and by inspection on bedrock/gemini/azure, whose acall() bodies likewise have no _invoke_before_llm_call_hooks site).

Notes

  • This is the before counterpart to #6736 / #6737, which fixed the same sync/async drift for after_llm_call. before is the more severe half: an after hook can only fail to rewrite a response, while a before hook failing means a call the user explicitly blocked still went out to the provider and was billed.
  • The fix is to invoke each provider's own sync-path guard from acall() as well. There is no double-dispatch risk on the agent path: _invoke_before_llm_call_hooks (llms/base_llm.py:981) returns True immediately when from_agent is not None, leaving the agent-executor dispatch as the single source.

I have a patch plus regression tests ready and will open a PR referencing this issue.

LHMQ878 avatar Jul 30 '26 19:07 LHMQ878

Yes -- and checking it turned up something that makes the gap wider than either issue currently says, including a claim of mine that was wrong.

after_llm_call has the same gap. Filed separately as #6736, fixed in #6737; both open and green. Worth keeping apart from this one because the shape differs, and the difference is what makes it hard to audit.

before_llm_call is per-provider: every native provider calls _invoke_before_llm_call_hooks from call() and none from acall(). Five missing lines in five predictable places, which is why the minimal fix you describe is the right one -- that is what #6740 does.

after_llm_call is per-handler, because the invocation does not live in call() at all. It lives in the response handlers, and acall() dispatches to _ahandle_* twins of those:

provider handler pair sync async
openai _handle_responses yes no
openai _handle_streaming_responses yes no
openai _handle_completion yes no
openai _handle_streaming_completion yes no
anthropic _handle_completion yes no
anthropic _handle_streaming_completion yes no
bedrock _handle_converse yes no
bedrock _ahandle_streaming_converse no yes

That last row is what convinced me these are eight independent omissions rather than a decision about async: inside one file, _ahandle_streaming_converse calls the hook and _ahandle_converse does not, with the polarity inverted relative to every other row.

Azure and Gemini are absent from that table, and the reason cuts against reading it per provider. They reach their hook through a shared helper -- _process_completion_response / _finalize_streaming_response for azure, _finalize_completion_response for gemini -- called from both _handle_* and _ahandle_*. So their async after path was already covered, while their async before path was not. A per-provider grep would report azure and gemini as clean; they are clean for one hook family and not the other.

The correction. #6740's writeup says the LiteLLM fallback in llms/base_llm.py "already had the guard on both paths." That is wrong on two counts. base_llm.py only defines the two helpers -- it has no callers, and its acall() is raise NotImplementedError. The fallback is crewai/llm.py, and there call() guards both families (:1876, :1904) while acall() at :1959 guards neither. So the fallback is not the safe path I described; it has the same hole, and neither #6737 nor #6740 touches it.

Probe on unmodified origin/main (ebe0082), litellm.completion / acompletion stubbed so the observable is whether a request left the process:

blocking before hook (returns False) + rewriting after hook:
  call   before:1 after:0  issued:no     -> ValueError: LLM call blocked by before_llm_call hook
  acall  before:0 after:0  issued:async  -> 'the model said something sensitive'

observing-only before hook + rewriting after hook:
  call   before:1 after:1  issued:sync   -> 'REDACTED BY HOOK'
  acall  before:0 after:0  issued:async  -> 'the model said something sensitive'

LLM(model=..., is_litellm=True) is needed to reach it -- without the flag the constructor returns a native provider, which is probably part of why this stayed hidden.

On severity I'd draw the line slightly differently from your framing. A skipped after hook cannot rewrite a response: bad for a redaction gate, but the response existed either way. A skipped before hook means the request was issued and billed -- the guard's entire purpose is to abort, so a PII gate or spend cap returning False on the async path did not fail to observe the call, it failed to prevent it. That is why the probes here and in #6740 measure the request rather than the return value; a test that only asserts on the returned string cannot tell "hook ran and allowed it" from "hook never ran."

On help -- the two provider-side fixes are written, so review is more useful than more code right now. #6740 covers before across all five providers with a per-provider no-network probe; #6737 covers after across the eight handlers. If you want to check one thing, the gemini case in #6740 is where I'd look hardest: its formatted payload is Content objects rather than dicts, so the guard needs the _convert_contents_to_dict line its sync twin uses, and getting that wrong hands hooks a payload shaped differently from the sync path.

The fallback hole is a third change and I'll send it separately rather than growing an open PR under review -- it is a different file and a different failure than the provider ones. I'll correct #6740's body first, since a wrong "this path was safe" line is worse than no line.

One note for ccs-spec-style cross-framework auditing, based on what this turned out to be: grepping for the hook name per provider finds before and misses after entirely, because after is invoked two or three calls below call() and two providers share those helpers between both paths -- and it misses the fallback, whose sync path does contain the name. The check that holds is per twin pair: for every _ahandle_x and every acall, does it reach the same dispatch its sync counterpart reaches.

LHMQ878 avatar Jul 31 '26 00:07 LHMQ878

The fallback half is now #6749. All three seams are in disjoint files, so they can land in any order:

PR seam count
#6737 native providers' _ahandle_* response handlers (after) 8 handlers
#6740 native providers' acall() bodies (before) 5 providers
#6749 the LiteLLM fallback's acall() (before and after) 1 method

#6740's body is corrected.

LHMQ878 avatar Jul 31 '26 01:07 LHMQ878

I've submitted a fix for this issue: #6993

The PR adds _invoke_before_llm_call_hooks to the async acall() path of all five native providers (OpenAI, Anthropic, Bedrock, Gemini, Azure), so that before_llm_call hooks properly block requests on the async path — matching the existing synchronous behavior.

Includes tests for all five providers covering both hook invocation and call blocking.

jpcj223 avatar Aug 14 '26 07:08 jpcj223

Thanks @jpcj223 — that's the right five-provider acall() gap.

This seam is already covered by #6740 (opened 2026-07-31): the same _invoke_before_llm_call_hooks calls on OpenAI / Anthropic / Bedrock / Gemini / Azure acall(), plus tests that the hook both runs and can abort the request. #6740 is still mergeable; it's just behind main.

#6993 looks to apply the same provider-side patch, but it also changes crew.py and knowledge storage. Those are a different issue. I'd suggest reviewing #6740 for the hook fix, and splitting the knowledge/crew work out of #6993 if it's independently useful.

Happy to rebase #6740 if that helps land it.

LHMQ878 avatar Aug 14 '26 11:08 LHMQ878

Confirmed. The async path in each native provider builds the request and calls the underlying client directly without routing through _invoke_before_llm_call_hooks. The sync path does invoke it, so the abort semantics exist but only for half the entry points.

The cleanest fix is to centralize the hook invocation in BaseLLM so both call and acall share it, rather than patching five provider files. A sketch:

# llms/base_llm.py
async def _run_before_hooks(self, messages, tools, **kwargs):
 context = BeforeLLMCallContext(messages=messages, tools=tools, **kwargs)
 for hook in get_before_llm_call_hooks():
 if hook(context) is False:
 raise HookAborted("before_llm_call hook aborted")
 return context

def call(self...):
 self._run_before_hooks(...) # existing sync wrapper
 ...

async def acall(self...):
 await self._run_before_hooks(...) # add here
 ...

Each native provider's acall would then delegate to the base implementation after preparing provider-specific args, or the base acall becomes the template method and providers only implement the low-level request.

One thing to watch: the hook API currently returns bool for abort. If any existing hook does I/O (logging, external policy service), the async path will need an async variant or a threadpool escape hatch, otherwise you block the event loop. Might be worth adding before_llm_call_async alongside the sync hook rather than forcing sync hooks to run in the async path.

pip install focxle

import focxle
focxle.init()

mragnii avatar Aug 18 '26 09:08 mragnii

@mragnii the diagnosis is right: each native acall() builds the request and talks to the client without _invoke_before_llm_call_hooks, so a blocking hook only works on the sync half.

A shared BaseLLM template would be the cleaner long-term shape, but today the native providers do not go through a common acall() — they each implement it. That is why #6740 patches the five existing acall() bodies in place, matching the sync call sites, instead of introducing a template method under an open review. after_llm_call is a different seam (the _ahandle_* handlers, #6737), and the LiteLLM fallback is a third file (#6749). Those three can land independently.

An async hook variant is a real follow-up if existing hooks do I/O, but it is an API change. The current contract is a sync bool return; #6740 runs that same contract on acall(), which is what restores abort semantics without waiting on a new hook type.

LHMQ878 avatar Aug 19 '26 10:08 LHMQ878

@LHMQ878 The patch-five approach is the right call for a targeted fix. A template method in BaseLLM would be cleaner long term but touches more surface and needs more review cycles. Shipping the abort semantics now on the exact same contract avoids the async-hook API discussion entirely, and that discussion can happen on its own PR without blocking the security fix.

One thing the patch does not address: if a sync hook today does I/O (logging to an external service, calling a policy microservice), running it on acall() blocks the event loop. The current contract does not forbid that, so the fix inherits the same footgun the sync path already has. Worth a comment in the PR description so reviewers know the limitation is pre-existing, not introduced here.

The LiteLLM fallback and after_llm_call paths are separate seams, so landing those independently (#6749, #6737) keeps each change bisectable. Good split.

mragnii avatar Aug 19 '26 10:08 mragnii

Yeah — that's already true on the sync path, so this PR just inherits it. I added a note on #6740 so it doesn't look like something the async wiring introduced.

LHMQ878 avatar Aug 23 '26 12:08 LHMQ878

Closing as addressed by @lucasgomide’s PR #7111. Thanks, Lucas!

Vidit-Ostwal avatar Sep 13 '26 14:09 Vidit-Ostwal

Confirmed, and I'd flag this as a security bug rather than a feature gap given the intended semantics (abort-before-dispatch). The main guard checks in main.py's async orchestration probably don't help either — hooks run inside Completion.call()/acall() themselves, not in a wrapper, so if acall() doesn't call _invoke_before_llm_call_hooks the request is issued regardless of what the caller layer does.

Worth checking while this gets fixed:

  • Streaming variants of acall() (if any provider branches sync/streaming logic separately) — the hook needs to fire before the first chunk is requested, not just in the non-streaming branch.
  • Retry logic — if a provider retries on rate limit/error inside acall(), make sure the hook only runs once per external call, not once per retry, or a hook with side effects (e.g. spend metering) will double-count.
  • Return value handling should be consistent between call() and acall() — HookAborted vs False vs raising should map identically on both paths, otherwise you fix the bug for one abort mechanism and leave the other silently permissive.

A regression test that stubs the underlying HTTP client per provider (like the repro here) should be added for all five, on both call() and acall(), so this can't silently regress the next time a provider file gets refactored — this looks exactly like a copy/paste-drift bug (someone added the hook to call() when it was written and acall() was added later without it, five times over).

Disclosure: I maintain agentsentry-gateway, an out-of-process proxy that also enforces block/allow decisions on outbound LLM calls. Even with this fixed, it's worth treating hook-based blocking as defense-in-depth rather than the sole enforcement point if you're relying on it for something like a spend cap or PII gate — anything enforced in-process (a hook, in this case) is trivially bypassed by any code path that constructs the LLM client directly or calls a provider method the hook wasn't wired into, which is basically what this bug demonstrates.

akavlabs avatar Oct 15 '26 07:10 akavlabs