# AzurePromptShieldMiddleware

> **Class** in `langchain_azure_ai`

📖 [View in docs](https://reference.langchain.com/python/langchain-azure-ai/agents/middleware/content_safety/_prompt_shield/AzurePromptShieldMiddleware)

AgentMiddleware that detects prompt injection using Azure AI Content Safety.

Prompt shield protects agents from adversarial inputs designed to hijack the
agent's behavior.  Two types of injection are detected:

* **Direct prompt injection** – malicious instructions in the user's own
  prompt (``user_prompt`` in the API).
* **Indirect prompt injection** – malicious instructions embedded in external
  documents fed back to the agent (``documents`` in the API), such as web
  search results, retrieved knowledge-base chunks, or email bodies.

The middleware extracts the last ``HumanMessage`` as the user prompt.  Any
``ToolMessage`` items in the state (tool/function outputs) are forwarded to
the API as ``documents`` so indirect injection via tool results is also caught.

When an injection attack is detected, the middleware takes one of two
actions:

* ``"error"`` – raises :exc:`ContentSafetyViolationError`, halting the graph.
* ``"continue"`` – replaces the offending message with a violation notice
  (either a service-derived description or a custom ``violation_message``)
  and lets execution proceed.

## Signature

```python
AzurePromptShieldMiddleware(
    self,
    endpoint: Optional[str] = None,
    credential: Optional[Any] = None,
    *,
    project_endpoint: Optional[str] = None,
    exit_behavior: Literal['error', 'continue', 'replace'] = 'error',
    violation_message: Optional[str] = None,
    apply_to_input: bool = True,
    apply_to_output: bool = False,
    name: str = 'azure_prompt_shield',
    context_extractor: Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[PromptShieldInput]]] = None,
)
```

## Description

**Note:**

``apply_to_output`` defaults to ``False`` because prompt injection is
an input-side attack.  Set it to ``True`` if you want to screen AI
output as well.

Both synchronous (``before_agent`` / ``after_agent``) and asynchronous
(``abefore_agent`` / ``aafter_agent``) hooks are implemented.

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `endpoint` | `Optional[str]` | No | Azure Content Safety resource endpoint URL.  Falls back to the ``AZURE_CONTENT_SAFETY_ENDPOINT`` environment variable. Mutually exclusive with ``project_endpoint``. (default: `None`) |
| `credential` | `Optional[Any]` | No | Azure credential.  Accepts a :class:`~azure.core.credentials.TokenCredential`, :class:`~azure.core.credentials.AzureKeyCredential`, or a plain API-key string.  Defaults to :class:`~azure.identity.DefaultAzureCredential` when ``None``. (default: `None`) |
| `project_endpoint` | `Optional[str]` | No | Azure AI Foundry project endpoint URL (e.g. ``https://<resource>.services.ai.azure.com/api/projects/<project>``). Falls back to the ``AZURE_AI_PROJECT_ENDPOINT`` environment variable. Mutually exclusive with ``endpoint``. (default: `None`) |
| `exit_behavior` | `Literal['error', 'continue', 'replace']` | No | What to do when an injection is detected.  One of ``"error"`` (default) or ``"continue"``. (default: `'error'`) |
| `violation_message` | `Optional[str]` | No | Custom text used to replace the offending message when ``exit_behavior="continue"``.  Defaults to a message built from the service response. (default: `None`) |
| `apply_to_input` | `bool` | No | Whether to screen the agent's input (last ``HumanMessage``).  Defaults to ``True``. (default: `True`) |
| `apply_to_output` | `bool` | No | Whether to screen the agent's output (last ``AIMessage``).  Defaults to ``False``. (default: `False`) |
| `name` | `str` | No | Node-name prefix used when wiring this middleware into a LangGraph.  Defaults to ``"azure_prompt_shield"``. (default: `'azure_prompt_shield'`) |
| `context_extractor` | `Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[PromptShieldInput]]]` | No | Optional callable with signature ``(state, runtime) -> Optional[PromptShieldInput]`` that receives the current graph state and the LangGraph :class:`~langchain.agents.middleware.Runtime` execution context, and returns the user prompt and documents to screen, or ``None`` to skip evaluation entirely.  When ``None`` (default) the middleware uses its built-in extraction logic. (default: `None`) |

## Extends

- `_AzureContentSafetyBaseMiddleware`

## Constructors

```python
__init__(
    self,
    endpoint: Optional[str] = None,
    credential: Optional[Any] = None,
    *,
    project_endpoint: Optional[str] = None,
    exit_behavior: Literal['error', 'continue', 'replace'] = 'error',
    violation_message: Optional[str] = None,
    apply_to_input: bool = True,
    apply_to_output: bool = False,
    name: str = 'azure_prompt_shield',
    context_extractor: Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[PromptShieldInput]]] = None,
) -> None
```

| Name | Type |
|------|------|
| `endpoint` | `Optional[str]` |
| `credential` | `Optional[Any]` |
| `project_endpoint` | `Optional[str]` |
| `exit_behavior` | `Literal['error', 'continue', 'replace']` |
| `violation_message` | `Optional[str]` |
| `apply_to_input` | `bool` |
| `apply_to_output` | `bool` |
| `name` | `str` |
| `context_extractor` | `Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[PromptShieldInput]]]` |


## Methods

- [`get_annotation_from_evaluations()`](https://reference.langchain.com/python/langchain-azure-ai/agents/middleware/content_safety/_prompt_shield/AzurePromptShieldMiddleware/get_annotation_from_evaluations)
- [`get_evaluation_response()`](https://reference.langchain.com/python/langchain-azure-ai/agents/middleware/content_safety/_prompt_shield/AzurePromptShieldMiddleware/get_evaluation_response)
- [`before_agent()`](https://reference.langchain.com/python/langchain-azure-ai/agents/middleware/content_safety/_prompt_shield/AzurePromptShieldMiddleware/before_agent)
- [`abefore_agent()`](https://reference.langchain.com/python/langchain-azure-ai/agents/middleware/content_safety/_prompt_shield/AzurePromptShieldMiddleware/abefore_agent)

---

[View source on GitHub](https://github.com/langchain-ai/langchain-azure/blob/7a6a664d617264df8dcb12fcfb1bacc09f21d504/libs/azure-ai/langchain_azure_ai/agents/middleware/content_safety/_prompt_shield.py#L51)