Skip to main content
Use the langchain-azure-ai package to add Azure Content Safety in Foundry Tools capabilities to your LangChain agents. You learn how to apply content moderation, prompt shielding, groundedness detection, and protected material scanning as middleware in your agent graphs.

Prerequisites

  • An Azure subscription. Create one for free.
  • A Foundry project.
  • A deployed chat model (for example, gpt-4.1) in your project.
  • Python 3.10 or later.
  • Azure CLI signed in (az login) so DefaultAzureCredential can authenticate.
Install the required packages:

Configure your environment

Set one of the following connection patterns:
  • Project endpoint with Microsoft Entra ID (recommended).
  • Direct endpoint with an API key.
Set your environment variable:
Import the common classes and initialize the model used throughout this article:

Connect to content safety

Use classes in the namespace langchain_azure_ai.agents.middleware.* to add Content Safety capabilities to your agents. The package automatically detects the project connection when you set the FOUNDRY_PROJECT_ENDPOINT environment variable. Microsoft Entra ID is the default authentication method, but key-based authentication is also available.
Or:
In the following sections we demonstrate multiple capabilities of the namespace.

Content moderation

Azure Content Safety in Foundry Tools flags objectionable content with AI algorithms. Attach AzureContentModerationMiddleware to your agent to enable content moderation.

Raise an error on violations

Set exit_behavior="error" to raise a ContentSafetyViolationError exception when a violation is detected:
What this snippet does: Creates an agent with content moderation middleware that monitors for hate, violence, and self-harm categories. When content exceeds the severity threshold of 4, the middleware raises an exception instead of returning a response. The following diagram shows how the middleware integrates into the agent graph:
Diagram of the agent graph with content moderation middleware.
Invoke the agent with content that might violate policies:

Replace offending content

Set exit_behavior="replace" to remove offending content instead of raising an exception. Use violation_message to customize the replacement text.
What this snippet does: Creates an agent that replaces flagged content instead of raising an error. Content that exceeds the severity threshold is removed from the message. Invoke the agent:
The agent doesn’t raise an exception because exit_behavior="replace" removes offending content automatically. Inspect the content safety annotations on the message:

Prompt shielding

Prompt Shields in Azure Content Safety in Foundry Tools detects and blocks adversarial prompt injection attacks on large language models (LLMs). The middleware analyzes prompts and documents before the model generates content.

Continue on detection

Set exit_behavior="continue" to annotate the message without blocking execution:
What this snippet does: Creates an agent with prompt shield middleware. AzurePromptShieldMiddleware hooks before model execution and analyzes inbound messages for injection attempts. With exit_behavior="continue", the request proceeds but an annotation is added to the message. The following diagram shows how the prompt shield hooks into the agent graph:
Diagram of the agent graph with prompt shield middleware.
Invoke the agent with a prompt injection attempt:
Content Safety flags the prompt injection attempt. Since exit_behavior="continue" is set, the request proceeds and an annotation is added to the message.

Raise an error on detection

Set exit_behavior="error" to raise an exception when a prompt injection is detected:

Groundedness detection

Groundedness detection identifies when a model generates content beyond what the source data supports. This capability is useful in retrieval-augmented generation (RAG) patterns to ensure the model’s response stays faithful to retrieved documents. Use langchain_azure_ai.agents.middleware.AzureGroundednessMiddleware to evaluate AI generated content against grounding sources. The following example:
  1. Creates an in-memory vector store with sample documents.
  2. Defines a tool that retrieves relevant content from the store.
  3. Creates an agent with AzureGroundednessMiddleware to evaluate responses.

Set up the vector store and retriever tool

What this snippet does: Creates a simple in-memory vector store with three documents about LangChain and RAG, then wraps the retriever as a LangChain tool so agents can query it during execution.

Create the agent with groundedness middleware

By default, AzureGroundednessMiddleware automatically gathers the answer from the last AIMessage, the question from the last HumanMessage, and the grounding sources from SystemMessage / ToolMessage content and AIMessage citation annotations in the conversation history. See configure grounding. The following diagram shows how groundedness middleware integrates into the agent graph:
Diagram of the agent graph with groundedness middleware.
Invoke the agent and inspect the groundedness annotations:
The grounding evaluation flags the response because the model uses its internal knowledge to fill in details beyond the retrieved documents. Because exit_behavior="continue" is set, execution proceeds and only the annotation is added.

Improve grounding with a stricter prompt

Adjust the system prompt to instruct the model to rely exclusively on retrieved information:
Invoke the agent again and verify the grounding annotations improve:

Configure grounding

You can change how context, questions, and answers are collected by the middleware. This is useful when:
  • Your application stores retrieved documents in a custom state key.
  • You want to restrict grounding sources to a specific subset of messages (e.g. only tool results, excluding the system prompt).
  • You need access to the run-scoped execution context (e.g. runtime.context or runtime.store) to build the inputs.
The following example uses an LLM (gpt-5-nano) to extract the most relevant question from the chat history, and only grounds with ToolMessage messages:

Protected material detection

Protected material detection identifies AI-generated content that matches known copyrighted sources. Use AzureProtectedMaterialMiddleware with type="text" for text content or type="code" for code that matches existing GitHub repositories.
What this snippet does: Creates an agent with protected material middleware that scans both input and output for code that matches known GitHub repositories. With exit_behavior="continue", flagged content is annotated but execution proceeds. The following diagram shows how protected material middleware integrates into the agent graph:
Diagram of the agent graph with protected material middleware.
Invoke the agent with code that might match a known repository:

Next step

Use Foundry Agent Service with LangGraph