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
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 21 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
46 changes: 39 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
50 changes: 29 additions & 21 deletions examples/langchain_callback.py
Original file line number Diff line number Diff line change
@@ -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__":
Expand Down
Loading
Loading