diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3ddda90..f623005 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install dependencies - run: pip install -e ".[dev]" + run: pip install -e ".[dev,langchain]" - name: Lint run: ruff check src/ - name: Type check diff --git a/CHANGELOG.md b/CHANGELOG.md index e52ae32..6671141 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,29 @@ # Changelog -## Unreleased +## [Unreleased] +### Fixed + +- LangChain async blocks now propagate when `raise_on_block=True`. +- Bare LLM and chat model inputs are scanned by their start callbacks. + Chat message text covers string content, string blocks, and dict blocks + whose `text` is a string and whose `type` is `"text"` or absent. Empty + prompts and empty chat text are skipped; chain and tool scans are unchanged. + +### Added + +- `ShieldCortexSyncCallbackHandler` for synchronous LangChain calls and + `ContentBlockedError` for catching blocked content with its scan result. - Ship a PEP 561 `py.typed` marker so type checkers treat the installed package as typed (the `Typing :: Typed` classifier was already declared). + +### Documentation + +- LangChain: output is scanned when the model finishes, so with `stream` / + `astream` a BLOCK on output stops the run only after the chunks were + delivered. Only `ShieldCortexError` from the scan call is logged and + skipped; other exceptions (for example connection errors) stop the run + when `raise_on_block=True`. - README: describe `ShieldCortexMemoryGuard` as a framework-agnostic pre-write guard (it does not import or hook into CrewAI; the `[crewai]` extra only installs CrewAI itself). diff --git a/README.md b/README.md index 574f3bf..d76b550 100644 --- a/README.md +++ b/README.md @@ -113,19 +113,51 @@ except MemoryBlockedError as e: ## LangChain Integration -Automatically scan all LLM inputs and outputs as they flow through your chain — no changes to your existing code: +The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs, +LLM outputs, and string tool outputs. Use the async handler for `ainvoke` and +`astream`, or the sync handler for `invoke`: ```python -from shieldcortex import AsyncShieldCortex -from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler +from langchain_openai import ChatOpenAI # or any LangChain chat model / LLM +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations.langchain import ( + ContentBlockedError, + ShieldCortexCallbackHandler, + ShieldCortexSyncCallbackHandler, +) + +model = ChatOpenAI() -client = AsyncShieldCortex(api_key="sc_live_...") -handler = ShieldCortexCallbackHandler(client, raise_on_block=True) +async with AsyncShieldCortex(api_key="sc_live_...") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + try: + reply = await model.ainvoke("Hello", config={"callbacks": [handler]}) + except ContentBlockedError as error: # also a ValueError + print(error.result.firewall.reason, error.source_identifier) -# Scans inputs on chain start, outputs on LLM end, and tool I/O -llm = ChatOpenAI(callbacks=[handler]) +with ShieldCortex(api_key="sc_live_...") as client: + handler = ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + reply = model.invoke("Hello", config={"callbacks": [handler]}) ``` +Only `BLOCK` verdicts act today. With `raise_on_block=True`, a block stops the +run with `ContentBlockedError`; otherwise it logs a warning. Use the matching +handler for the call mode: LangChain cannot propagate an async handler's block +from `invoke`. + +- **Chat message text** means string content, string blocks, and dict blocks + whose `text` is a string and whose `type` is `"text"` or absent. Images and + other block types are not scanned. Empty prompts are skipped. +- **Streaming:** LLM output is scanned when the model finishes. With `stream` + or `astream`, every chunk has already reached your code by then, so an + output block stops the run after delivery and cannot prevent exposure. + Buffer the stream yourself if blocked output must never be shown. Input + scans still run before the model starts. +- **Scan errors:** a `ShieldCortexError` from the scan call (HTTP error, + timeout) is logged and that scan is skipped. Other exceptions, such as + connection errors, are not caught: with `raise_on_block=True` they stop the + run, otherwise LangChain logs them. + ## Audit Logs Every scan is logged. Query your history, export for compliance, or auto-paginate through all entries: diff --git a/examples/langchain_callback.py b/examples/langchain_callback.py index d3669e6..3b4d8bb 100644 --- a/examples/langchain_callback.py +++ b/examples/langchain_callback.py @@ -1,33 +1,41 @@ -"""LangChain callback handler example. +"""Scan LangChain inputs and outputs with the matching callback handler. -Scans LLM inputs and outputs through ShieldCortex. - - pip install shieldcortex[langchain] +Install with ``pip install shieldcortex[langchain]``. The handlers scan chain +inputs, LLM prompts, text in chat messages, tool inputs, LLM outputs, and +string tool outputs. Only BLOCK verdicts act. Streamed output is scanned +after the chunks are delivered, so an output block cannot hide them. """ import asyncio -from shieldcortex import AsyncShieldCortex -from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler +from langchain_core.language_models.fake_chat_models import FakeListChatModel + +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations.langchain import ( + ContentBlockedError, + ShieldCortexCallbackHandler, + ShieldCortexSyncCallbackHandler, +) async def main() -> None: + model = FakeListChatModel(responses=["Hello!"]) + async with AsyncShieldCortex(api_key="sc_live_YOUR_KEY_HERE") as client: - handler = ShieldCortexCallbackHandler( - client, - mode="balanced", - scan_inputs=True, - scan_outputs=True, - raise_on_block=False, # Log warnings instead of raising - ) - - # Use with any LangChain component: - # - # from langchain_openai import ChatOpenAI - # llm = ChatOpenAI(callbacks=[handler]) - # response = await llm.ainvoke("Hello!") - - print(f"Handler ready. Audit IDs so far: {handler.audit_ids}") + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + try: + print(await model.ainvoke("Hello", config={"callbacks": [handler]})) + except ContentBlockedError as error: # also a ValueError + print(f"Blocked {error.source_identifier}: {error.result.firewall.reason}") + + # For invoke(), use the sync client and handler. The async handler's block + # cannot propagate from a sync call. + with ShieldCortex(api_key="sc_live_YOUR_KEY_HERE") as client: + handler = ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + try: + print(model.invoke("Hello", config={"callbacks": [handler]})) + except ContentBlockedError as error: + print(f"Blocked {error.source_identifier}: {error.result.firewall.reason}") if __name__ == "__main__": diff --git a/src/shieldcortex/integrations/langchain.py b/src/shieldcortex/integrations/langchain.py index 2390282..d71eb79 100644 --- a/src/shieldcortex/integrations/langchain.py +++ b/src/shieldcortex/integrations/langchain.py @@ -1,22 +1,22 @@ -"""LangChain integration for ShieldCortex memory security scanning. +"""LangChain callbacks for ShieldCortex scanning. -Provides a callback handler that scans LLM inputs and outputs through -the ShieldCortex defence pipeline. +The async handler is for ``ainvoke``/``astream``; the sync handler is for +``invoke``. They scan chain inputs, LLM prompts, chat message text, tool inputs, +LLM outputs, and string tool outputs. Chat message text means string content, +string blocks, and dict blocks whose ``text`` is a string and whose ``type`` is +``"text"`` or absent. Only ``BLOCK`` verdicts act today. With +``raise_on_block=True``, a block raises :class:`ContentBlockedError`. -Install with:: +LLM output is scanned in ``on_llm_end``, after the model finishes. With +``stream``/``astream`` every chunk has already reached the caller by then, so +an output block stops the run after delivery and cannot prevent exposure. - pip install shieldcortex[langchain] +A :class:`~shieldcortex.errors.ShieldCortexError` from the scan call (HTTP +error, timeout) is logged and that scan is skipped. Other exceptions, such as +connection errors, are not caught: with ``raise_on_block=True`` they stop the +run, otherwise LangChain logs them. -Usage:: - - from shieldcortex import AsyncShieldCortex - from shieldcortex.integrations.langchain import ShieldCortexCallbackHandler - - client = AsyncShieldCortex(api_key="sc_live_...") - handler = ShieldCortexCallbackHandler(client) - - # Pass to any LangChain component - llm = ChatOpenAI(callbacks=[handler]) +Install with ``pip install shieldcortex[langchain]``. """ from __future__ import annotations @@ -24,118 +24,217 @@ import logging from typing import Any, Literal +from shieldcortex.async_client import AsyncShieldCortex +from shieldcortex.client import ShieldCortex from shieldcortex.errors import ShieldCortexError -from shieldcortex.types import ScanConfig, ScanSource +from shieldcortex.types import ScanConfig, ScanResult, ScanSource try: - from langchain_core.callbacks import AsyncCallbackHandler + from langchain_core.callbacks import AsyncCallbackHandler, BaseCallbackHandler + from langchain_core.messages import BaseMessage from langchain_core.outputs import LLMResult except ImportError: raise ImportError( "LangChain is not installed. Install with: pip install shieldcortex[langchain]" ) -from shieldcortex.async_client import AsyncShieldCortex - logger = logging.getLogger("shieldcortex.langchain") - - -class ShieldCortexCallbackHandler(AsyncCallbackHandler): # type: ignore[misc] - """LangChain async callback handler that scans content through ShieldCortex. - - Scans user inputs (chain start) and LLM outputs (LLM end) through - the defence pipeline. Optionally raises on blocked content. - - Args: - client: An :class:`~shieldcortex.AsyncShieldCortex` instance. - mode: Defence mode — ``"strict"``, ``"balanced"``, or ``"permissive"``. - scan_inputs: Scan user inputs at chain start. - scan_outputs: Scan LLM outputs. - raise_on_block: Raise ``ValueError`` when content is blocked - (default: log a warning). +Mode = Literal["strict", "balanced", "permissive"] + + +class ContentBlockedError(ValueError): + """A ``BLOCK`` verdict, with the scan result and source identifier.""" + + def __init__(self, result: ScanResult, source_identifier: str) -> None: + self.result = result + self.source_identifier = f"langchain:{source_identifier}" + super().__init__(f"ShieldCortex blocked {source_identifier}: {result.firewall.reason}") + + +def _chat_texts(messages: list[list[BaseMessage]]) -> list[str]: + texts: list[str] = [] + for batch in messages: + for message in batch: + content = message.content + if isinstance(content, str): + texts.append(content) + elif isinstance(content, list): + for block in content: + if isinstance(block, str): + texts.append(block) + elif isinstance(block, dict) and block.get("type", "text") == "text": + # Typed text blocks and legacy untyped ``{"text": ...}`` + # blocks (extra keys allowed). Other block types are + # not text, even when they carry a ``text`` key. + value = block.get("text") + if isinstance(value, str): + texts.append(value) + return texts + + +def _output_texts(response: LLMResult) -> list[str]: + return [ + generation.text for group in response.generations for generation in group if generation.text + ] + + +class _ScanLogic: + """Shared source construction and verdict handling for both callback types.""" + + mode: Mode + scan_inputs: bool + scan_outputs: bool + raise_on_block: bool + audit_ids: list[int] + + def _configure( + self, mode: Mode, scan_inputs: bool, scan_outputs: bool, raise_on_block: bool + ) -> None: + self.mode = mode + self.scan_inputs = scan_inputs + self.scan_outputs = scan_outputs + self.raise_on_block = raise_on_block + self.audit_ids = [] + + def _scan_options(self, source_identifier: str) -> dict[str, Any]: + return { + "source": ScanSource(type="agent", identifier=f"langchain:{source_identifier}"), + "config": ScanConfig(mode=self.mode), + } + + def _handle_result(self, result: ScanResult, source_identifier: str) -> None: + self.audit_ids.append(result.audit_id) + if result.firewall.result == "BLOCK": + error = ContentBlockedError(result, source_identifier) + if self.raise_on_block: + raise error + logger.warning("%s", error) + + +class ShieldCortexCallbackHandler(_ScanLogic, AsyncCallbackHandler): + """Async LangChain handler for ``ainvoke`` and ``astream``. + + Scans chain inputs, LLM prompts, chat message text, tool inputs, LLM + outputs, and string tool outputs. ``raise_on_block=True`` propagates + :class:`ContentBlockedError` (a ``ValueError``). Only ``BLOCK`` acts. + Streamed output is scanned after delivery; see the module docstring for + that and for which scan errors are logged. """ def __init__( self, client: AsyncShieldCortex, *, - mode: Literal["strict", "balanced", "permissive"] = "balanced", + mode: Mode = "balanced", scan_inputs: bool = True, scan_outputs: bool = True, raise_on_block: bool = False, ) -> None: self.client = client - self.mode = mode - self.scan_inputs = scan_inputs - self.scan_outputs = scan_outputs - self.raise_on_block = raise_on_block - self.audit_ids: list[int] = [] + self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self.raise_error = raise_on_block async def on_chain_start( - self, - serialized: dict[str, Any], - inputs: dict[str, Any], - **kwargs: Any, + self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any ) -> None: - """Scan user inputs at chain start.""" - if not self.scan_inputs: - return - input_text = str(inputs) - await self._scan(input_text, "chain_input") + if self.scan_inputs: + await self._scan(str(inputs), "chain_input") - async def on_llm_end( - self, - response: LLMResult, - **kwargs: Any, + async def on_llm_start( + self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any ) -> None: - """Scan LLM outputs.""" - if not self.scan_outputs: - return - for generation_list in response.generations: - for generation in generation_list: - if hasattr(generation, "text") and generation.text: - await self._scan(generation.text, "llm_output") + if self.scan_inputs: + for prompt in dict.fromkeys(p for p in prompts if p): + await self._scan(prompt, "llm_input") + + async def on_chat_model_start( + self, serialized: dict[str, Any], messages: list[list[BaseMessage]], **kwargs: Any + ) -> None: + if self.scan_inputs: + for content in dict.fromkeys(t for t in _chat_texts(messages) if t): + await self._scan(content, "chat_input") + + async def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: + if self.scan_outputs: + for content in _output_texts(response): + await self._scan(content, "llm_output") async def on_tool_start( - self, - serialized: dict[str, Any], - input_str: str, - **kwargs: Any, + self, serialized: dict[str, Any], input_str: str, **kwargs: Any ) -> None: - """Scan tool inputs.""" if self.scan_inputs: await self._scan(input_str, "tool_input") - async def on_tool_end( - self, - output: Any, - **kwargs: Any, - ) -> None: - """Scan tool outputs.""" + async def on_tool_end(self, output: Any, **kwargs: Any) -> None: if self.scan_outputs and isinstance(output, str): await self._scan(output, "tool_output") async def _scan(self, content: str, source_identifier: str) -> None: - """Internal: scan content and handle the result.""" try: - result = await self.client.scan( - content, - source=ScanSource( - type="agent", identifier=f"langchain:{source_identifier}" - ), - config=ScanConfig(mode=self.mode), - ) - self.audit_ids.append(result.audit_id) - - if result.firewall.result == "BLOCK": - msg = ( - f"ShieldCortex blocked {source_identifier}: " - f"{result.firewall.reason}" - ) - if self.raise_on_block: - raise ValueError(msg) - logger.warning(msg) - - except ShieldCortexError as e: - # Don't break the LangChain pipeline on scanning errors - logger.warning("ShieldCortex scan error: %s", e) + result = await self.client.scan(content, **self._scan_options(source_identifier)) + except ShieldCortexError as exc: + logger.warning("ShieldCortex scan error: %s", exc) + return + self._handle_result(result, source_identifier) + + +class ShieldCortexSyncCallbackHandler(_ScanLogic, BaseCallbackHandler): + """Sync LangChain handler for ``invoke`` with the same scanning options. + + ``raise_on_block=True`` propagates :class:`ContentBlockedError` (a + ``ValueError``). Only ``BLOCK`` acts. Streamed output is scanned after + delivery; see the module docstring for that and for which scan errors + are logged. + """ + + def __init__( + self, + client: ShieldCortex, + *, + mode: Mode = "balanced", + scan_inputs: bool = True, + scan_outputs: bool = True, + raise_on_block: bool = False, + ) -> None: + self.client = client + self._configure(mode, scan_inputs, scan_outputs, raise_on_block) + self.raise_error = raise_on_block + + def on_chain_start( + self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any + ) -> None: + if self.scan_inputs: + self._scan(str(inputs), "chain_input") + + def on_llm_start(self, serialized: dict[str, Any], prompts: list[str], **kwargs: Any) -> None: + if self.scan_inputs: + for prompt in dict.fromkeys(p for p in prompts if p): + self._scan(prompt, "llm_input") + + def on_chat_model_start( + self, serialized: dict[str, Any], messages: list[list[BaseMessage]], **kwargs: Any + ) -> None: + if self.scan_inputs: + for content in dict.fromkeys(t for t in _chat_texts(messages) if t): + self._scan(content, "chat_input") + + def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: + if self.scan_outputs: + for content in _output_texts(response): + self._scan(content, "llm_output") + + def on_tool_start(self, serialized: dict[str, Any], input_str: str, **kwargs: Any) -> None: + if self.scan_inputs: + self._scan(input_str, "tool_input") + + def on_tool_end(self, output: Any, **kwargs: Any) -> None: + if self.scan_outputs and isinstance(output, str): + self._scan(output, "tool_output") + + def _scan(self, content: str, source_identifier: str) -> None: + try: + result = self.client.scan(content, **self._scan_options(source_identifier)) + except ShieldCortexError as exc: + logger.warning("ShieldCortex scan error: %s", exc) + return + self._handle_result(result, source_identifier) diff --git a/tests/integrations/test_langchain.py b/tests/integrations/test_langchain.py new file mode 100644 index 0000000..9a79708 --- /dev/null +++ b/tests/integrations/test_langchain.py @@ -0,0 +1,240 @@ +"""Regression tests using real LangChain runnables and mocked scan HTTP calls.""" + +from __future__ import annotations + +import json +import logging + +import httpx +import pytest +import respx +from langchain_core.language_models.fake import FakeListLLM +from langchain_core.language_models.fake_chat_models import FakeListChatModel +from langchain_core.messages import HumanMessage +from langchain_core.runnables import RunnableLambda + +from shieldcortex import AsyncShieldCortex, ShieldCortex +from shieldcortex.integrations import langchain as integration + +ShieldCortexCallbackHandler = integration.ShieldCortexCallbackHandler + + +BASE = "https://api.shieldcortex.ai" +ALLOWED_RESPONSE = { + "allowed": True, + "firewall": { + "result": "ALLOW", + "reason": "OK", + "threatIndicators": [], + "anomalyScore": 0.01, + "blockedPatterns": [], + }, + "sensitivity": {"level": "PUBLIC", "redactionRequired": False}, + "trust": {"score": 0.95}, + "auditId": 1, +} +BLOCKED_RESPONSE = { + "allowed": False, + "firewall": { + "result": "BLOCK", + "reason": "Credential leak detected", + "threatIndicators": ["credential_leak"], + "anomalyScore": 0.95, + "blockedPatterns": ["AWS_KEY"], + }, + "sensitivity": {"level": "RESTRICTED", "redactionRequired": True}, + "trust": {"score": 0.1}, + "auditId": 2, +} + + +def scan_requests(route: respx.Route) -> list[dict[str, object]]: + return [json.loads(call.request.read()) for call in route.calls] + + +@pytest.mark.asyncio +@respx.mock +async def test_async_block_stops_chat_model() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=BLOCKED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert isinstance(exc_info.value, ValueError) + assert exc_info.value.result.firewall.result == "BLOCK" + assert exc_info.value.source_identifier == "langchain:chat_input" + assert len(route.calls) == 1 + + +@pytest.mark.asyncio +@respx.mock +async def test_async_block_warns_and_returns(caplog: pytest.LogCaptureFixture) -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=False) + with caplog.at_level(logging.WARNING, logger="shieldcortex.langchain"): + result = await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert result.content == "hi" + assert "ShieldCortex blocked chat_input" in caplog.text + + +@pytest.mark.asyncio +@respx.mock +async def test_bare_chat_scans_prompt_once() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert [(item["content"], item["source"]["identifier"]) for item in scan_requests(route)] == [ + ("prompt", "langchain:chat_input") + ] + + +@pytest.mark.asyncio +@respx.mock +async def test_bare_llm_scans_prompt() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListLLM(responses=["hi"]).ainvoke("prompt", config={"callbacks": [handler]}) + assert [(item["content"], item["source"]["identifier"]) for item in scan_requests(route)] == [ + ("prompt", "langchain:llm_input") + ] + + +@pytest.mark.asyncio +@respx.mock +async def test_chat_content_blocks_scan_text_only() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + [ + HumanMessage( + content=[ + {"type": "text", "text": "visible"}, + {"type": "image_url", "image_url": "hidden"}, + "plain", + "", + ] + ) + ], + config={"callbacks": [handler]}, + ) + assert [item["content"] for item in scan_requests(route)] == ["visible", "plain"] + + +@pytest.mark.asyncio +@respx.mock +async def test_scan_inputs_false() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_inputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert [item["source"]["identifier"] for item in scan_requests(route)] == [ + "langchain:llm_output" + ] + + +@respx.mock +def test_sync_block_stops_model() -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError): + FakeListChatModel(responses=["hi"]).invoke("prompt", config={"callbacks": [handler]}) + + +@pytest.mark.asyncio +@respx.mock +async def test_chain_start_blocks() -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError) as exc_info: + await RunnableLambda(lambda value: value).ainvoke( + "prompt", config={"callbacks": [handler]} + ) + assert exc_info.value.source_identifier == "langchain:chain_input" + + +@pytest.mark.asyncio +@respx.mock +async def test_chat_untyped_text_block_with_extra_keys_is_scanned() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListChatModel(responses=["hi"]).ainvoke( + [ + HumanMessage( + content=[ + {"text": "legacy", "metadata": {"k": "v"}}, + {"type": "image_url", "text": "not text", "image_url": "x"}, + ] + ) + ], + config={"callbacks": [handler]}, + ) + assert [item["content"] for item in scan_requests(route)] == ["legacy"] + + +@respx.mock +def test_sync_chat_untyped_text_block_with_extra_keys_blocks() -> None: + respx.post(f"{BASE}/v1/scan").mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + with pytest.raises(integration.ContentBlockedError) as exc_info: + FakeListChatModel(responses=["hi"]).invoke( + [HumanMessage(content=[{"text": "secret", "metadata": {}}])], + config={"callbacks": [handler]}, + ) + assert exc_info.value.source_identifier == "langchain:chat_input" + + +@pytest.mark.asyncio +@respx.mock +async def test_empty_tool_input_and_output_are_still_scanned() -> None: + from langchain_core.tools import Tool + + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + tool = Tool(name="echo", description="echo", func=lambda value: "", coroutine=None) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client) + await tool.ainvoke("", config={"callbacks": [handler]}) + identifiers = [item["source"]["identifier"] for item in scan_requests(route)] + assert "langchain:tool_input" in identifiers + assert "langchain:tool_output" in identifiers + + +@pytest.mark.asyncio +@respx.mock +async def test_empty_llm_prompt_is_skipped() -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + async with AsyncShieldCortex(api_key="sc_test_abc") as client: + handler = ShieldCortexCallbackHandler(client, scan_outputs=False) + await FakeListLLM(responses=["hi"]).ainvoke("", config={"callbacks": [handler]}) + assert scan_requests(route) == []