Skip to main content

Middleware for inspecting and filtering unsafe content using LlamaGuard

Project description

Swarmauri Logo

PyPI - Downloads Hits PyPI - Python Version PyPI - License PyPI - swarmauri_middleware_llamaguard


Swarmauri Middleware LlamaGuard

A FastAPI middleware that wraps Groq's llama-guard-3-8b model to provide end-to-end content inspection for both inbound requests and outbound responses. The middleware is designed to slot into any FastAPI application and enforce safety policies before your handlers are invoked.

Features

  • Real-time scanning of incoming request bodies and outgoing responses (including streaming responses).
  • Configurable language model injection – provide your own :class:~swarmauri_standard.llms.GroqModel or let the middleware create one for you.
  • Graceful degradation when no model is configured (traffic is allowed but logged).

Middleware behavior

LlamaGuardMiddleware inspects content by default with Groq's llama-guard-3-8b model. Provide an API key via the api_key argument or the GROQ_API_KEY environment variable to enable enforcement. When no model is available the middleware logs a warning and treats all content as safe so that applications can continue to function while you configure credentials.

Both JSON responses and streaming responses are inspected. Unsafe content results in an HTTP 400 response with a descriptive error payload.

Installation

Choose the workflow that matches your project tooling:

  • pip

    pip install swarmauri_middleware_llamaguard
    
  • poetry

    poetry add swarmauri_middleware_llamaguard
    
  • uv

    uv add swarmauri_middleware_llamaguard
    

Quickstart

  1. Configure your Groq API key (either export GROQ_API_KEY or pass api_key when constructing the middleware).
  2. Attach the middleware to your FastAPI application:
from fastapi import FastAPI, Request

from swarmauri_middleware_llamaguard import LlamaGuardMiddleware

app = FastAPI()
middleware = LlamaGuardMiddleware()  # Uses GROQ_API_KEY from the environment


@app.middleware("http")
async def llama_guard(request: Request, call_next):
    return await middleware.dispatch(request, call_next)


@app.get("/health")
async def health_check():
    return {"status": "ok"}

The middleware will block requests or responses when llama-guard-3-8b labels the payload as unsafe.

Example: Local safety checks without Groq

The middleware also accepts a custom language model implementation. The following self-contained example demonstrates how to supply a stub model for local development or tests while still benefiting from end-to-end request inspection.

# README Example: Basic request filtering
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient

from swarmauri_middleware_llamaguard import LlamaGuardMiddleware
from swarmauri_standard.messages.AgentMessage import AgentMessage


class StubGuardModel:
    def predict(self, conversation, *args, **kwargs):
        latest = str(conversation.get_last().content).lower()
        verdict = "unsafe" if "malicious" in latest else "safe"
        conversation.add_message(AgentMessage(content=verdict))


app = FastAPI()
middleware = LlamaGuardMiddleware(llm=StubGuardModel())


@app.middleware("http")
async def llama_guard(request: Request, call_next):
    return await middleware.dispatch(request, call_next)


@app.post("/echo")
def echo(payload: dict) -> dict:
    return payload


with TestClient(app) as client:
    assert client.post("/echo", json={"message": "hello"}).status_code == 200
    assert (
        client.post("/echo", json={"message": "malicious content"}).status_code
        == 400
    )

Want to help?

If you want to contribute to swarmauri-sdk, read up on our guidelines for contributing that will help you get started.

Want to help?

If you want to contribute to swarmauri-sdk, read up on our guidelines for contributing that will help you get started.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file swarmauri_middleware_llamaguard-0.7.0.dev42.tar.gz.

File metadata

  • Download URL: swarmauri_middleware_llamaguard-0.7.0.dev42.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_middleware_llamaguard-0.7.0.dev42.tar.gz
Algorithm Hash digest
SHA256 0d54f2f9a9a318fb4db1c6a2ec308d30ed0a775643c20e1e1428009d69d30a0a
MD5 7ad676293c335304b92a23b0ced2a0d6
BLAKE2b-256 8739f0b9c7eccbdddd85076a5adbc6f405b9401bb2b7934b3e7687344f9338e1

See more details on using hashes here.

File details

Details for the file swarmauri_middleware_llamaguard-0.7.0.dev42-py3-none-any.whl.

File metadata

  • Download URL: swarmauri_middleware_llamaguard-0.7.0.dev42-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_middleware_llamaguard-0.7.0.dev42-py3-none-any.whl
Algorithm Hash digest
SHA256 4bcdb717e25a2aaade41682bc19f5d55c8eff00dca0931025bdbbeebb20357f6
MD5 2d7c3d0af3d1c6898d30b1dec7057020
BLAKE2b-256 7ba61e8c708d643d4db12fd0d0ca33002a49d89327ae1592cccdc04c5f88fe14

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page