← Back to Pull requests

[DOCS-16431] Move AI Guard middleware to its own page #41933

Merged
melamos merged 5 files (392 lines) on Nov 19, 2026 10:34 UTC
View on GitHub
melamos melamos commented on Nov 18, 2026 18:59 UTC
Author

<!-- Note: Please remember to review the Datadog Documentation Contribution Guidelines if you have not yet done so. -->

What does this PR do? What is the motivation?

Fixes DOCS-16431

Editorial and IA pass on #41417. Middleware works with every Python integration method, not only automatic integrations, so this PR moves the middleware content from the SDK page to its own page, Control Evaluations with Middleware, with rewrites to bring the content in line with tech writing best practice. Custom tags for SDK calls stay on the SDK page.

Also adds middleware mentions on the main AI Guard landing page for discoverability.

Merge readiness

  • Ready for merge
  • AI assistance

    Restructured and edited with Claude Code. Technical claims were checked against the dd-trace-py 4.17.0 source.

    For Datadog employees:

  • ⚠️ Your branch name MUST follow the <name>/<description> convention and include the forward slash (/). If you've already created your PR with an incorrect branch name, please rename your branch and open a fresh PR.

  • 🤖 New: Comment with /review to run an automated check that catches common issues before a Documentation team member reviews your PR.
  • Additional notes

  • The middleware page has two TODO comments for the author: where to register middleware for LiteLLM Proxy, and whether skipped SDK calls return unredacted messages.

  • The middleware page also corrects the context table: request.source is "auto" for manual integrations too, and request.integration includes "litellm".

  • The landing page (security/ai_guard/_index.md) is a file that #41417 doesn't otherwise touch.
  • Diff: 392 lines (+236 / -156) across 5 files Reviewer: avara1986 Review duration: 934m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.50) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 392 lines diff across 5 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.84 · 5 substantive comment(s)
    0.84
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.357
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    7 items
    melamos melamos commented on code on Nov 18, 2026 19:22 UTC
    Code Review
    hugo/content/en/security/ai_guard/middleware.md:1
    @@ -0,0 +1,181 @@
    +---
    +title: Control Evaluations with Middleware
    +description: Skip, tag, or log AI Guard evaluations in Python applications with middleware.
    +---
    +
    +{{< site-region region="gov,gov2" >}}
    +<div class="alert alert-danger">AI Guard isn't available in the {{< region-param key="dd_site_name" >}} site.</div>
    +{{< /site-region >}}
    +
    +AI Guard middleware lets you decide in Python code which requests AI Guard evaluates and run your own logic around each evaluation. Use middleware to skip evaluations for traffic you trust, add custom tags to evaluations, or log evaluation outcomes. The AI Guard policy for the service still decides what's unsafe and whether AI Guard blocks unsafe requests.
    +
    +## Supported SDK versions
    +
    +Middleware is supported for Python applications instrumented with automatic or manual integrations, or the SDK. Middleware requires `dd-trace-py` 4.17.0 or later.
    +
    +The Datadog SDKs for Node.js, Java, and Ruby don't support middleware.
    +
    +## Register middleware
    +
    +Register middleware at application startup, so the middleware runs around every AI Guard evaluation that follows.
    +
    +Middleware classes run in registration order.
    +
    +Middleware errors don't break your application. If a hook raises an exception, the SDK ignores the exception and logs the exception at debug level. If `should_evaluate` raises an exception, AI Guard evaluates the request.
    +
    +**Before you begin**: [Set up AI Guard][1] for the application.
    +
    +1. Create a subclass of `AIGuardMiddleware` and override one or more of its hooks:
    +
    +   | Hook | When it runs | Use the hook to |
    +   | --- | --- | --- |
    +   | `should_evaluate(context)` | Before the evaluation starts, before AI Guard creates the span. | Skip the evaluation by returning `False`. Any other return value, including `None`, lets the evaluation run. |
    +   | `pre_evaluate(context)` | Inside the AI Guard span, right before the request to AI Guard. | Add tags to the AI Guard span, or store values for `post_evaluate`. |
    +   | `post_evaluate(context)` | One time, after the evaluation finishes, whether AI Guard allows, denies, or blocks the request, or the request fails. | Log, count, or tag the outcome. |
    +
    +   For the values each hook can read from `context`, see the [Hook attributes](#hook-attributes) section.
    +
    +1. At application startup, register an instance of the middleware class with `register_middleware`:
    +
    +   ```python
    +   from ddtrace.aiguard.middleware import AIGuardMiddleware, EvaluationDirection, register_middleware
    +
    +
    +   class InputOnly(AIGuardMiddleware):
    +       """Evaluate the messages sent to the model, not the model responses."""
    +
    +       def should_evaluate(self, context):
    +           return context.request.direction is EvaluationDirection.INPUT
    +
    +
    +   register_middleware(InputOnly())
    +   ```
    +
    +   <!-- TODO: For LiteLLM Proxy, middleware runs in the proxy process, not in the agents behind the proxy. Where do users call register_middleware for the proxy? For example, in the guardrails.py file that imports the AI Guard guardrail? -->

    @avara1986 Technical question here.

    melamos melamos commented on code on Nov 18, 2026 19:22 UTC
    Code Review
    hugo/content/en/security/ai_guard/middleware.md:1
    @@ -0,0 +1,181 @@
    +---
    +title: Control Evaluations with Middleware
    +description: Skip, tag, or log AI Guard evaluations in Python applications with middleware.
    +---
    +
    +{{< site-region region="gov,gov2" >}}
    +<div class="alert alert-danger">AI Guard isn't available in the {{< region-param key="dd_site_name" >}} site.</div>
    +{{< /site-region >}}
    +
    +AI Guard middleware lets you decide in Python code which requests AI Guard evaluates and run your own logic around each evaluation. Use middleware to skip evaluations for traffic you trust, add custom tags to evaluations, or log evaluation outcomes. The AI Guard policy for the service still decides what's unsafe and whether AI Guard blocks unsafe requests.
    +
    +## Supported SDK versions
    +
    +Middleware is supported for Python applications instrumented with automatic or manual integrations, or the SDK. Middleware requires `dd-trace-py` 4.17.0 or later.
    +
    +The Datadog SDKs for Node.js, Java, and Ruby don't support middleware.
    +
    +## Register middleware
    +
    +Register middleware at application startup, so the middleware runs around every AI Guard evaluation that follows.
    +
    +Middleware classes run in registration order.
    +
    +Middleware errors don't break your application. If a hook raises an exception, the SDK ignores the exception and logs the exception at debug level. If `should_evaluate` raises an exception, AI Guard evaluates the request.
    +
    +**Before you begin**: [Set up AI Guard][1] for the application.
    +
    +1. Create a subclass of `AIGuardMiddleware` and override one or more of its hooks:
    +
    +   | Hook | When it runs | Use the hook to |
    +   | --- | --- | --- |
    +   | `should_evaluate(context)` | Before the evaluation starts, before AI Guard creates the span. | Skip the evaluation by returning `False`. Any other return value, including `None`, lets the evaluation run. |
    +   | `pre_evaluate(context)` | Inside the AI Guard span, right before the request to AI Guard. | Add tags to the AI Guard span, or store values for `post_evaluate`. |
    +   | `post_evaluate(context)` | One time, after the evaluation finishes, whether AI Guard allows, denies, or blocks the request, or the request fails. | Log, count, or tag the outcome. |
    +
    +   For the values each hook can read from `context`, see the [Hook attributes](#hook-attributes) section.
    +
    +1. At application startup, register an instance of the middleware class with `register_middleware`:
    +
    +   ```python
    +   from ddtrace.aiguard.middleware import AIGuardMiddleware, EvaluationDirection, register_middleware
    +
    +
    +   class InputOnly(AIGuardMiddleware):
    +       """Evaluate the messages sent to the model, not the model responses."""
    +
    +       def should_evaluate(self, context):
    +           return context.request.direction is EvaluationDirection.INPUT
    +
    +
    +   register_middleware(InputOnly())
    +   ```
    +
    +   <!-- TODO: For LiteLLM Proxy, middleware runs in the proxy process, not in the agents behind the proxy. Where do users call register_middleware for the proxy? For example, in the guardrails.py file that imports the AI Guard guardrail? -->
    +
    +Registered middleware can't be unregistered. To remove middleware, remove the `register_middleware` calls from your code.
    +
    +## Skip evaluations for trusted traffic
    +
    +Skip evaluations for traffic you trust, such as calls through one integration or requests to an internal route.
    +
    +<div class="alert alert-warning">Skipped requests go to the model without an evaluation, and no AI Guard span records the skipped requests. Skip only requests that you trust.</div>
    +
    +**Before you begin**: [Register middleware](#register-middleware) in a Python application with `dd-trace-py` 4.17.0 or later.
    +
    +1. To skip requests, override `should_evaluate` in a middleware class so that the method returns `False` for each request to skip and `True` for all other requests.
    +
    +   The values in the [Hook attributes](#hook-attributes) section identify each request, such as `context.request.integration` for the integration or the HTTP route on `context.local_root_span`.
    +
    +After a middleware class skips a request:
    +
    +- SDK calls return an `ALLOW` action with the reason `skipped by middleware`, and the original messages without redaction. <!-- TODO: Please confirm. A skipped request never reaches AI Guard, so Sensitive Data Scanner redaction doesn't apply, and result.messages holds the original, unredacted messages. Is that right? This matters for SDK users who forward result.messages to the model, as the Redact Sensitive Data page instructs. -->

    @avara1986 Technical question here.

    avara1986 avara1986 commented on code on Nov 19, 2026 09:02 UTC
    Code Review
    hugo/content/en/security/ai_guard/middleware.md:1
    @@ -0,0 +1,181 @@
    +---
    +title: Control Evaluations with Middleware
    +description: Skip, tag, or log AI Guard evaluations in Python applications with middleware.
    +---
    +
    +{{< site-region region="gov,gov2" >}}
    +<div class="alert alert-danger">AI Guard isn't available in the {{< region-param key="dd_site_name" >}} site.</div>
    +{{< /site-region >}}
    +
    +AI Guard middleware lets you decide in Python code which requests AI Guard evaluates and run your own logic around each evaluation. Use middleware to skip evaluations for traffic you trust, add custom tags to evaluations, or log evaluation outcomes. The AI Guard policy for the service still decides what's unsafe and whether AI Guard blocks unsafe requests.
    +
    +## Supported SDK versions
    +
    +Middleware is supported for Python applications instrumented with automatic or manual integrations, or the SDK. Middleware requires `dd-trace-py` 4.17.0 or later.
    +
    +The Datadog SDKs for Node.js, Java, and Ruby don't support middleware.
    +
    +## Register middleware
    +
    +Register middleware at application startup, so the middleware runs around every AI Guard evaluation that follows.
    +
    +Middleware classes run in registration order.
    +
    +Middleware errors don't break your application. If a hook raises an exception, the SDK ignores the exception and logs the exception at debug level. If `should_evaluate` raises an exception, AI Guard evaluates the request.
    +
    +**Before you begin**: [Set up AI Guard][1] for the application.
    +
    +1. Create a subclass of `AIGuardMiddleware` and override one or more of its hooks:
    +
    +   | Hook | When it runs | Use the hook to |
    +   | --- | --- | --- |
    +   | `should_evaluate(context)` | Before the evaluation starts, before AI Guard creates the span. | Skip the evaluation by returning `False`. Any other return value, including `None`, lets the evaluation run. |
    +   | `pre_evaluate(context)` | Inside the AI Guard span, right before the request to AI Guard. | Add tags to the AI Guard span, or store values for `post_evaluate`. |
    +   | `post_evaluate(context)` | One time, after the evaluation finishes, whether AI Guard allows, denies, or blocks the request, or the request fails. | Log, count, or tag the outcome. |
    +
    +   For the values each hook can read from `context`, see the [Hook attributes](#hook-attributes) section.
    +
    +1. At application startup, register an instance of the middleware class with `register_middleware`:
    +
    +   ```python
    +   from ddtrace.aiguard.middleware import AIGuardMiddleware, EvaluationDirection, register_middleware
    +
    +
    +   class InputOnly(AIGuardMiddleware):
    +       """Evaluate the messages sent to the model, not the model responses."""
    +
    +       def should_evaluate(self, context):
    +           return context.request.direction is EvaluationDirection.INPUT
    +
    +
    +   register_middleware(InputOnly())
    +   ```
    +
    +   <!-- TODO: For LiteLLM Proxy, middleware runs in the proxy process, not in the agents behind the proxy. Where do users call register_middleware for the proxy? For example, in the guardrails.py file that imports the AI Guard guardrail? -->

       For LiteLLM Proxy, register middleware in the proxy process, not in the agents behind the proxy. Define the middleware in its own Python module that the proxy can import, such as a module on the proxy's `PYTHONPATH`, and import that module from the `guardrails.py` file that imports the AI Guard guardrail. LiteLLM Proxy can load `guardrails.py` more than once, but Python imports your module only one time, so the middleware is registered one time:
    
       
    python
    # aiguard_middleware.py, on the proxy's PYTHONPATH
    from ddtrace.aiguard.middleware import AIGuardMiddleware, register_middleware

    class InputOnly(AIGuardMiddleware):
    ...

    register_middleware(InputOnly())

    
       
    python
    # guardrails.py
    import aiguard_middleware # noqa: F401
    from ddtrace.aiguard.integrations.litellm import DatadogAIGuardGuardrail

    __all__ = ["DatadogAIGuardGuardrail"]

    avara1986 avara1986 commented on code on Nov 19, 2026 09:02 UTC
    Code Review
    hugo/content/en/security/ai_guard/middleware.md:1
    @@ -0,0 +1,181 @@
    +---
    +title: Control Evaluations with Middleware
    +description: Skip, tag, or log AI Guard evaluations in Python applications with middleware.
    +---
    +
    +{{< site-region region="gov,gov2" >}}
    +<div class="alert alert-danger">AI Guard isn't available in the {{< region-param key="dd_site_name" >}} site.</div>
    +{{< /site-region >}}
    +
    +AI Guard middleware lets you decide in Python code which requests AI Guard evaluates and run your own logic around each evaluation. Use middleware to skip evaluations for traffic you trust, add custom tags to evaluations, or log evaluation outcomes. The AI Guard policy for the service still decides what's unsafe and whether AI Guard blocks unsafe requests.
    +
    +## Supported SDK versions
    +
    +Middleware is supported for Python applications instrumented with automatic or manual integrations, or the SDK. Middleware requires `dd-trace-py` 4.17.0 or later.
    +
    +The Datadog SDKs for Node.js, Java, and Ruby don't support middleware.
    +
    +## Register middleware
    +
    +Register middleware at application startup, so the middleware runs around every AI Guard evaluation that follows.
    +
    +Middleware classes run in registration order.
    +
    +Middleware errors don't break your application. If a hook raises an exception, the SDK ignores the exception and logs the exception at debug level. If `should_evaluate` raises an exception, AI Guard evaluates the request.
    +
    +**Before you begin**: [Set up AI Guard][1] for the application.
    +
    +1. Create a subclass of `AIGuardMiddleware` and override one or more of its hooks:
    +
    +   | Hook | When it runs | Use the hook to |
    +   | --- | --- | --- |
    +   | `should_evaluate(context)` | Before the evaluation starts, before AI Guard creates the span. | Skip the evaluation by returning `False`. Any other return value, including `None`, lets the evaluation run. |
    +   | `pre_evaluate(context)` | Inside the AI Guard span, right before the request to AI Guard. | Add tags to the AI Guard span, or store values for `post_evaluate`. |
    +   | `post_evaluate(context)` | One time, after the evaluation finishes, whether AI Guard allows, denies, or blocks the request, or the request fails. | Log, count, or tag the outcome. |
    +
    +   For the values each hook can read from `context`, see the [Hook attributes](#hook-attributes) section.
    +
    +1. At application startup, register an instance of the middleware class with `register_middleware`:
    +
    +   ```python
    +   from ddtrace.aiguard.middleware import AIGuardMiddleware, EvaluationDirection, register_middleware
    +
    +
    +   class InputOnly(AIGuardMiddleware):
    +       """Evaluate the messages sent to the model, not the model responses."""
    +
    +       def should_evaluate(self, context):
    +           return context.request.direction is EvaluationDirection.INPUT
    +
    +
    +   register_middleware(InputOnly())
    +   ```
    +
    +   <!-- TODO: For LiteLLM Proxy, middleware runs in the proxy process, not in the agents behind the proxy. Where do users call register_middleware for the proxy? For example, in the guardrails.py file that imports the AI Guard guardrail? -->
    +
    +Registered middleware can't be unregistered. To remove middleware, remove the `register_middleware` calls from your code.
    +
    +## Skip evaluations for trusted traffic
    +
    +Skip evaluations for traffic you trust, such as calls through one integration or requests to an internal route.
    +
    +<div class="alert alert-warning">Skipped requests go to the model without an evaluation, and no AI Guard span records the skipped requests. Skip only requests that you trust.</div>
    +
    +**Before you begin**: [Register middleware](#register-middleware) in a Python application with `dd-trace-py` 4.17.0 or later.
    +
    +1. To skip requests, override `should_evaluate` in a middleware class so that the method returns `False` for each request to skip and `True` for all other requests.
    +
    +   The values in the [Hook attributes](#hook-attributes) section identify each request, such as `context.request.integration` for the integration or the HTTP route on `context.local_root_span`.
    +
    +After a middleware class skips a request:
    +
    +- SDK calls return an `ALLOW` action with the reason `skipped by middleware`, and the original messages without redaction. <!-- TODO: Please confirm. A skipped request never reaches AI Guard, so Sensitive Data Scanner redaction doesn't apply, and result.messages holds the original, unredacted messages. Is that right? This matters for SDK users who forward result.messages to the model, as the Redact Sensitive Data page instructs. -->

    Redaction never runs, so result.messages holds the original, unredacted messages. Automatic integrations don't use the returned evaluation, so this only affects SDK callers that forward result.messages.

    - SDK calls return an `ALLOW` action with the reason `skipped by middleware`, no attack tags or Sensitive Data Scanner findings, and the original messages. A skipped request never reaches AI Guard, so sensitive data redaction doesn't apply: if you forward `result.messages` to the model, the model receives the unredacted messages.
    

    avara1986 avara1986 approved these changes on Nov 19, 2026 10:06 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    melamos melamos
    Labels
    risk: low confidence: 87.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 49.6% (MEDIUM) · Higher = larger blast radius
    49.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.5% · Lower = rushed or shallow review
    87.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.2% · Safe to merge
    6.2%