Skip to main content
Middleware specifically designed for Microsoft Foundry and Azure AI Content Safety. Learn more about middleware. These middleware classes live in the langchain-azure-ai package and are exported from langchain_azure_ai.agents.middleware.
Azure AI Content Safety middleware is currently marked experimental upstream. Expect the API surface to evolve as Azure AI Content Safety and LangChain middleware support continue to mature.

Overview

Features

  • Unified guardrail policy enforcement with AzureContentSafetyPolicyMiddleware across agent, model, and tool hooks.
  • Text moderation for harmful content and custom blocklists.
  • Image moderation for data URLs and public HTTP(S) image inputs.
  • Prompt injection detection with Prompt Shield.
  • Protected material detection for text and code.
  • Groundedness evaluation for generated answers against retrieved context.
  • Custom context_extractor hooks to adapt screening and evaluation to your agent state.

Setup

To use the Azure AI Content Safety middleware, install the integration package, configure either an Azure AI Foundry project endpoint or an Azure Content Safety endpoint, and provide a credential.

Installation

Install the package:

Credentials

For authentication, pass either DefaultAzureCredential() or an API-key string through the credential argument. Using a Foundry Project requires the use of Microsoft Entra ID for authentication.
Initialize credential

Instantiation

The middleware supports two endpoint styles:
  • An Azure Content Safety resource endpoint via AZURE_CONTENT_SAFETY_ENDPOINT
  • An Azure AI Foundry project endpoint via AZURE_AI_PROJECT_ENDPOINT
If both are available, prefer project_endpoint because it gives better defaults for Azure AI Foundry-based workflows. In most setups, you can set the environment variable once and omit endpoint or project_endpoint from each middleware instantiation.
Configure endpoint
Import and configure your middleware from langchain_azure_ai.agents.middleware.
Initialize middleware

Use with an agent

Pass middleware to create_agent in order. You can combine Azure AI middleware with built-in middleware.
Agent with middleware
If AZURE_AI_PROJECT_ENDPOINT is already set, you can usually omit project_endpoint during instantiation.

Azure AI Content Safety

Guardrail policy

AzureContentSafetyPolicyMiddleware is in preview and requires azure-ai-contentsafety>=1.1.0b1.
Use AzureContentSafetyPolicyMiddleware to enforce an Azure AI Content Safety guardrail policy across agent, model, and tool input and output hooks in create_agent or create_deep_agent. The guardrail policy controls each intervention point; the same text may be evaluated at both agent and model boundaries. Unlike the sibling Content Safety middleware classes, this middleware has no exit_behavior, apply_to_input, or apply_to_output settings: a blocked verdict always raises ContentSafetyViolationError. Allowed verdicts apply service-provided transforms, and non-blocking findings are attached as annotations readable via get_content_safety_annotations from langchain_azure_ai.agents.middleware. Agent and model hooks screen text; tool hooks screen JSON-encoded arguments and results.
string
required
Guardrail policy ID configured on your Content Safety resource.
string
Content Safety resource URL. Falls back to AZURE_CONTENT_SAFETY_ENDPOINT. Mutually exclusive with project_endpoint.
string
Microsoft Foundry project endpoint. Falls back to AZURE_AI_PROJECT_ENDPOINT when endpoint is not set.
TokenCredential | AzureKeyCredential | str | None
Azure credential or API key. Defaults to DefaultAzureCredential().
UnifiedModerateContext | None
Optional SDK context carrying agent, session, or correlation metadata for each moderation request.
string
Middleware name. Defaults to azure_unified_moderation.

Text moderation

Use AzureContentModerationMiddleware to screen the last HumanMessage before the agent runs and the last AIMessage after the agent runs. This middleware uses Azure AI Content Safety harm detection and can also check custom blocklists configured in your resource. Text moderation is useful for the following:
  • Blocking harmful user input before a model call
  • Screening model output before it reaches end users
  • Enforcing custom blocklists in regulated or enterprise deployments
  • Composing multiple moderation passes with different category and direction settings
list[str] | None
Harm categories to analyze. Valid values are 'Hate', 'SelfHarm', 'Sexual', and 'Violence'. Defaults to all four categories.
int
default:"4"
Minimum severity score from 0 to 6 that triggers the configured behavior.
string
default:"error"
One of 'error', 'continue', or 'replace'.
bool
default:"True"
Whether to screen the last HumanMessage before the agent runs.
bool
default:"True"
Whether to screen the last AIMessage after the agent runs.
list[str] | None
Names of custom blocklists configured in your Azure Content Safety resource.
Callable | None
Optional callable that extracts the text to screen from agent state and runtime.

Image moderation

Use AzureContentModerationForImagesMiddleware when your agent handles visual content. It extracts images from the latest input or output message and screens them with the Azure AI Content Safety image analysis API. This middleware supports:
  • Base64 data URLs such as data:image/png;base64,...
  • Public HTTP(S) image URLs
list[str] | None
Image harm categories to analyze. Defaults to all four supported categories.
int
default:"4"
Minimum severity score from 0 to 6 that triggers the configured behavior.
string
default:"error"
One of 'error' or 'continue'.
bool
default:"True"
Whether to screen images in the latest HumanMessage.
bool
default:"False"
Whether to screen images in the latest AIMessage.
Callable | None
Optional callable that extracts images from agent state and runtime.

Prompt shield

Use AzurePromptShieldMiddleware to detect prompt injection in user prompts and optional supporting documents. By default it screens input only, because prompt injection is usually an input-side attack, but you can also enable output screening.
string
default:"error"
One of 'error', 'continue', or 'replace'.
bool
default:"True"
Whether to screen the latest HumanMessage before the agent runs.
bool
default:"False"
Whether to screen the latest AIMessage after the agent runs.
Callable | None
Optional callable that extracts the user prompt and grounding documents from agent state and runtime.

Protected material

Use AzureProtectedMaterialMiddleware to detect protected content such as copyrighted text or code. This middleware can screen both the latest user input and the latest model output.
string
default:"text"
The content type to screen: 'text' or 'code'.
string
default:"error"
One of 'error', 'continue', or 'replace'.
bool
default:"True"
Whether to screen the latest HumanMessage.
bool
default:"True"
Whether to screen the latest AIMessage.
Callable | None
Optional callable that extracts text from agent state and runtime.

Groundedness

Use AzureGroundednessMiddleware to evaluate whether a model response is grounded in the context available to the agent. Unlike the other middleware classes on this page, groundedness runs after model generation and inspects the generated answer against supporting sources. By default, groundedness collects sources from the current conversation, including system content, tool outputs, and relevant annotations attached to model responses.
string
default:"Generic"
The analysis domain. Supported values are 'Generic' and 'Medical'.
string
default:"Summarization"
The task type for the analysis. Supported values are 'Summarization' and 'QnA'.
string
default:"error"
One of 'error' or 'continue'.
Callable | None
Optional callable that extracts the answer, grounding sources, and optional question from agent state and runtime.

Microsoft Foundry memory

AzureAIMemoryMiddleware is marked experimental. Create the target memory store in your Microsoft Foundry project before using this middleware.
Use AzureAIMemoryMiddleware to persist long-term user and conversation memories into a Microsoft Foundry Memory store after agent turns and expose a retrieval tool via get_retriever_tool().
memory_middleware.get_retriever_tool() does not forward a custom credential from AzureAIMemoryMiddleware. When not using DefaultAzureCredential, pass memory_middleware.get_retriever_tool(credential=...).
string
required
Name of an existing Microsoft Foundry Memory store in your project.
string
required
Memory partition key (for example, a stable user ID) used to isolate stored memories.
int
default:"1"
Number of agent turns to buffer before flushing memories to the store.
Sequence[Literal['user', 'assistant']]
default:"('user',)"
Message roles to extract into long-term memory. Pass ['user', 'assistant'] to remember both turns.

API reference

For the full public API, see the middleware exports in langchain_azure_ai.agents.middleware and the underlying Content Safety middleware package in langchain_azure_ai.agents.middleware.content_safety.