Skip to content
Merged
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ unless you opt in with the new options below.

### Known limitation

- LangChain answers a bare (non-chat) LLM call that is fully served from its
LLM cache without firing `on_llm_start` or `on_llm_end`, so neither the
prompt nor the cached output is scanned and no block can stop that call.
The 0.4.0 bare-LLM prompt scanning applies only to calls that reach the
model. Set `cache=False` on LLMs whose calls must be scanned (the default,
`cache=None`, uses any cache set with `set_llm_cache`), or scan outside the
model call. Chat models fire their start callback before the cache lookup,
so cached chat calls still have their input scanned. Regression tests pin
this behaviour.
- With the async handler, a sync-only tool (no coroutine) called through
`ainvoke` runs in a worker thread where LangChain logs and swallows every
exception the handler raises. Neither BLOCK verdicts nor `fail_closed`
Expand Down
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,9 @@ except MemoryBlockedError as e:
## LangChain Integration

The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs,
LLM outputs, and tool outputs. Use the async handler for `ainvoke` and
`astream`, or the sync handler for `invoke`:
LLM outputs, and tool outputs, whenever LangChain fires the matching callback
(see **LLM cache** below for a case where it does not). Use the async handler
for `ainvoke` and `astream`, or the sync handler for `invoke`:

```python
from langchain_openai import ChatOpenAI # or any LangChain chat model / LLM
Expand Down Expand Up @@ -161,6 +162,15 @@ from `invoke`.
a string `text` (for example `{"payload": "..."}`), are dropped rather than
JSON-encoded, so their contents are not scanned. `None` and non-string outputs that reduce
to empty text are not scanned.
- **LLM cache:** a bare (non-chat) LLM call answered entirely from a
LangChain LLM cache fires no callbacks: LangChain checks the cache before
`on_llm_start` and returns the cached text without `on_llm_end`. Neither
the prompt nor the cached output is scanned, and no block or `fail_closed`
error can stop that call. Set `cache=False` on LLMs whose calls must be
scanned (the default, `cache=None`, uses any cache set with
`set_llm_cache`), or scan outside the model call. Chat models fire
`on_chat_model_start` before their cache lookup, so a cached chat call
still has its input scanned.
- **Sync-only tools under `ainvoke`:** LangChain runs a tool that has no
coroutine in a worker thread and logs and swallows every exception the
async handler raises there. Neither a `BLOCK` verdict nor a `fail_closed`
Expand Down
9 changes: 9 additions & 0 deletions src/shieldcortex/integrations/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@
errors, are not caught: with ``raise_on_block=True`` they stop the run,
otherwise LangChain logs them.

LLM cache: LangChain answers a bare (non-chat) LLM call that is served
entirely from its LLM cache without firing ``on_llm_start`` or
``on_llm_end``, so neither the prompt nor the cached output is scanned and no
block can stop that call. Set ``cache=False`` on LLMs whose calls must be
scanned (the default, ``cache=None``, uses any cache set with
``set_llm_cache``), or scan outside the model call. Chat models fire
``on_chat_model_start`` before their cache lookup, so a cached chat call still
has its input scanned.

Exception: with the async handler, a tool without a coroutine (a sync-only
tool) called through ``ainvoke`` runs in a worker thread, and LangChain logs
and swallows every exception the async handler raises there. Neither a block
Expand Down
85 changes: 85 additions & 0 deletions tests/integrations/test_langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,3 +626,88 @@ async def test_connection_error_propagates_unwrapped(is_sync: bool, hook: str) -
is_sync, make_runnable(), value, raise_on_block=True, fail_closed=True, **options
)
assert len(route.calls) == 1


# --- LLM cache hits (documented limitation) ---


async def invoke_twice(
is_sync: bool, runnable: Any, route: respx.Route, first_scans: list[str]
) -> Any:
"""Invoke ``runnable`` twice with one handler; the second call sees BLOCK.

The first call's scan identifiers are appended to ``first_scans`` and the
route's call log is then cleared, so ``route.calls`` holds only the second
call's scans.
"""
if is_sync:
with ShieldCortex(api_key="sc_test_abc") as client:
handler = integration.ShieldCortexSyncCallbackHandler(client, raise_on_block=True)
runnable.invoke("prompt", config={"callbacks": [handler]})
first_scans.extend(item["source"]["identifier"] for item in scan_requests(route))
route.mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE))
route.reset()
return runnable.invoke("prompt", config={"callbacks": [handler]})
async with AsyncShieldCortex(api_key="sc_test_abc") as aclient:
ahandler = ShieldCortexCallbackHandler(aclient, raise_on_block=True)
await runnable.ainvoke("prompt", config={"callbacks": [ahandler]})
first_scans.extend(item["source"]["identifier"] for item in scan_requests(route))
route.mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE))
route.reset()
return await runnable.ainvoke("prompt", config={"callbacks": [ahandler]})


@pytest.mark.asyncio
@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"])
@respx.mock
async def test_bare_llm_cache_hit_is_not_scanned(is_sync: bool) -> None:
# LangChain answers a full LLM cache hit without firing on_llm_start or
# on_llm_end, so neither the prompt nor the cached output is scanned. If
# this starts failing, LangChain now fires callbacks on cache hits: update
# the docs.
from langchain_core.caches import InMemoryCache

route = respx.post(f"{BASE}/v1/scan").mock(
return_value=httpx.Response(200, json=ALLOWED_RESPONSE)
)
llm = FakeListLLM(responses=["cached reply"], cache=InMemoryCache())
first_scans: list[str] = []
result = await invoke_twice(is_sync, llm, route, first_scans)
assert first_scans == ["langchain:llm_input", "langchain:llm_output"]
assert result == "cached reply"
assert len(route.calls) == 0


@pytest.mark.asyncio
@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"])
@respx.mock
async def test_bare_llm_without_cache_rescans_and_blocks(is_sync: bool) -> None:
route = respx.post(f"{BASE}/v1/scan").mock(
return_value=httpx.Response(200, json=ALLOWED_RESPONSE)
)
llm = FakeListLLM(responses=["reply", "reply"], cache=False)
first_scans: list[str] = []
with pytest.raises(integration.ContentBlockedError) as exc_info:
await invoke_twice(is_sync, llm, route, first_scans)
assert first_scans == ["langchain:llm_input", "langchain:llm_output"]
assert exc_info.value.source_identifier == "langchain:llm_input"
assert len(route.calls) == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"])
@respx.mock
async def test_chat_model_cache_hit_still_scans_input(is_sync: bool) -> None:
# Chat models fire on_chat_model_start before the cache lookup.
from langchain_core.caches import InMemoryCache

route = respx.post(f"{BASE}/v1/scan").mock(
return_value=httpx.Response(200, json=ALLOWED_RESPONSE)
)
chat = FakeListChatModel(responses=["cached reply"], cache=InMemoryCache())
first_scans: list[str] = []
with pytest.raises(integration.ContentBlockedError) as exc_info:
await invoke_twice(is_sync, chat, route, first_scans)
assert first_scans == ["langchain:chat_input", "langchain:llm_output"]
assert exc_info.value.source_identifier == "langchain:chat_input"
assert len(route.calls) == 1
Loading