Skip to main content

HiddenLayer Guardrails for 🦜🔗 LangChain & LangGraph (Beta)

This package provides a LangChain agent middleware that integrates with the HiddenLayer Python SDK to scan, redact, and/or block content before and after the agent executes.

It follows the official LangChain custom guardrails middleware pattern using wrap-style hooks to intercept model and tool request and responses.

Installation

pip install hiddenlayer-langchain-guardrails

Configuration

Set your credentials in your environment variables to authenticate with HiddenLayer via the SDK:

  • HIDDENLAYER_CLIENT_ID
  • HIDDENLAYER_CLIENT_SECRET

Usage

from langchain.agents import create_agent
from langchain.tools import tool
from hiddenlayer_langchain_guardrails import HiddenLayerGuardrail, HiddenLayerParams

@tool
def get_weather(city: str) -> str:
    """Return simple weather info for the specified city."""
    return f"The weather in {city} is sunny."

agent = create_agent(
    model="gpt-4o-mini",
    tools=[get_weather],
    middleware=[HiddenLayerGuardrail(
        params=HiddenLayerParams(
            model="gpt-4o-mini",
            project_id=None,          # or your HL project id
            requester_id="example",   # optional but recommended
        )
    )],
)

result = agent.invoke(
    {
        "messages": [
            {"role": "system", "content": "Always respond in haiku form."},
            {"role": "user", "content": "What's the weather in Austin? Use the get_weather tool."},
        ]
    }
)

print(result["messages"][-1].content)

LangGraph Agent with Memory

Use InMemorySaver as a checkpointer to give your agent persistent conversation history across turns:

from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import InMemorySaver

from hiddenlayer_langchain_guardrails import HiddenLayerGuardrail, HiddenLayerParams

@tool
def calculator(expression: str) -> str:
    """Evaluate a basic math expression. Example: '(3 + 5) * 2'."""
    try:
        result = eval(expression, {"__builtins__": {}}, {})  # noqa: S307
        return str(result)
    except Exception as exc:
        return f"Error evaluating expression: {exc}"

agent = create_agent(
    model="gpt-4o-mini",
    tools=[calculator],
    middleware=[HiddenLayerGuardrail(
        params=HiddenLayerParams(requester_id="calculator-agent")
    )],
    checkpointer=InMemorySaver(),
    system_prompt="You are a helpful calculator assistant.",
)

config: RunnableConfig = {"configurable": {"thread_id": "session-1"}}

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What is (12 * 34) + 1348? Use the calculator tool."}]},
    config=config,
)
print(result["messages"][-1].content)

Async Usage

from hiddenlayer_langchain_guardrails import (
    AsyncHiddenLayerGuardrail,
    HiddenLayerParams,
)

@tool
def get_weather(city: str) -> str:
    """Return simple weather info for the specified city."""
    return f"The weather in {city} is sunny."

guardrail = AsyncHiddenLayerGuardrail(
    params=HiddenLayerParams(
        model="gpt-4o-mini",
        project_id=None,          # or your HL project id
        requester_id="example",   # optional but recommended
    )
)

agent = create_agent(
    model="gpt-4o-mini",
    tools=[get_weather],
    middleware=[guardrail],
)

async def main() -> None:
    result = await agent.ainvoke(
        {
            "messages": [
                {"role": "system", "content": "Always respond in haiku form."},
                {
                    "role": "user",
                    "content": "What's the weather in Austin? Use the get_weather tool.",
                },
            ]
        }
    )

    print(result["messages"][-1].content)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Capability Matrix

Alert Block Redact
Input Guardrails :white_check_mark: :white_check_mark: :white_check_mark:
Output Guardrails :white_check_mark: :white_check_mark: :white_check_mark:
Streaming Output Guardrails :white_check_mark: :x: :x:

Known Limitations

Streaming not supported

Due to a bug in LangChain, middleware guardrails do not run before tokens are streamed to the caller. This means that when using agent.stream() or agent.astream(), output guardrails cannot intercept content before it reaches the user, defeating their purpose for streaming workflows.

Workaround: Use agent.invoke() or agent.ainvoke() instead of the streaming variants to ensure guardrails are applied correctly.

Development

Run tests after installing dev deps (pytest and pytest-asyncio): pytest tests Code lives in src/hiddenlayer_langchain_guardrails/middleware.py; tests are under the tests directory.

Metadata

Release files for hiddenlayer-langchain-guardrails 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hiddenlayer-langchain-guardrails 0.2.0
File Size Uploaded
hiddenlayer_langchain_guardrails-0.2.0.tar.gz 6.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for hiddenlayer-langchain-guardrails 0.2.0
File Interpreter ABI Platform
hiddenlayer_langchain_guardrails-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 13.3 kB

Release files / hiddenlayer_langchain_guardrails-0.2.0.tar.gz

Download URL hiddenlayer_langchain_guardrails-0.2.0.tar.gz
Size 6.1 kB
Tags Source
SHA-256 checksum
How to use checksums
2588154bcd48bc2266a27db7a61e3a5c9e6b6aa2463b18c76f5860d1f2012d17
BLAKE2b-256 checksum
How to use checksums
84aed6d0e5a82f6f3d5e3841e406cd9390e7f6a22117102d19b4d71a25d17b10
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 7, 2026.

Transparency log

Release files / hiddenlayer_langchain_guardrails-0.2.0-py3-none-any.whl

Download URL hiddenlayer_langchain_guardrails-0.2.0-py3-none-any.whl
Size 7.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0fdd8684eec27268f8d100a14c6d8e19a3fad0477e1039eef4dadd83911dd82e
BLAKE2b-256 checksum
How to use checksums
438521aeae12bbc25c3808b23011eb6ec1ea86e6f9cf82cb22e7c4e33472b94b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 7, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page