AzureGroundednessMiddleware(
self,
endpoint: Optional[str] = None,
credential: Optional[Any] = None,
*,
project_endpoint: Optional[str] = None,
domain: Literal['Generic', 'Medical'] = 'Generic',
task: Literal['Summarization', 'QnA'] = 'Summarization',
exit_behavior: Literal['error', 'continue'] = 'error',
name: str = 'azure_groundedness',
context_extractor: Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[GroundednessInput]]] = None
)_AzureContentSafetyBaseMiddlewareAgentMiddleware that evaluates groundedness of model outputs.
Groundedness detection analyses language model outputs to determine whether they are factually aligned with user-provided information or contain fictional/hallucinated content.
The middleware runs as an after_model hook — it evaluates every model
response immediately after generation. The behaviour when ungrounded
content is detected depends on exit_behavior:
"error" (default) – raises :exc:ContentSafetyViolationError,
halting the graph. The exception carries the evaluation details."continue" – annotates the state with a groundedness_evaluation
key containing the evaluation results and lets execution proceed.In both modes the state is annotated with the evaluation result so callers can inspect it.
Grounding sources are collected automatically from the chat history by default:
SystemMessage content – the system prompt often contains the
authoritative context the model should stay grounded in.ToolMessage content – tool / function-call results such as RAG
retrieval chunks, web-search snippets, or database lookups.AIMessage annotation titles – citation metadata attached to model
responses (e.g. url_citation annotations from web-search grounding).You can override the extraction logic by supplying a context_extractor
callable. It receives the current graph state and the LangGraph
:class:~langchain.agents.middleware.Runtime execution context, and must
return a :class:GroundednessInput (or None to skip evaluation
entirely) containing the answer to evaluate, the grounding sources, and
(for task="QnA") the question::
from langchain_azure_ai.agents.middleware import (
AzureGroundednessMiddleware,
GroundednessInput,
)
def my_extractor(state, runtime):
# ``runtime`` is the LangGraph Runtime object — use it to access
# the user-defined context, memory store, stream writer, etc.
return GroundednessInput(
answer=state["custom_answer"],
sources=state["retrieved_chunks"],
question=state.get("user_question"),
)
middleware = AzureGroundednessMiddleware(
context_extractor=my_extractor,
task="QnA",
)
After the model runs (in continue mode), the state will contain a
groundedness_evaluation key with the evaluation results::
{
"is_grounded": True,
"ungrounded_percentage": 0.0,
"details": []
}Default: None |
domain | Literal['Generic', 'Medical'] | Default: 'Generic' |
task | Literal['Summarization', 'QnA'] | Default: 'Summarization' |
exit_behavior | Literal['error', 'continue'] | Default: 'error' |
name | str | Default: 'azure_groundedness' |
context_extractor | Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[GroundednessInput]]] | Default: None |
| Literal['Generic', 'Medical'] |
| task | Literal['Summarization', 'QnA'] |
| exit_behavior | Literal['error', 'continue'] |
| name | str |
| context_extractor | Optional[Callable[[AgentState[Any], Runtime[Any]], Optional[GroundednessInput]]] |
Azure Content Safety resource endpoint URL. Falls back to
the AZURE_CONTENT_SAFETY_ENDPOINT environment variable.
Mutually exclusive with project_endpoint.
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.
Build a NonStandardAnnotation for groundedness violations.
Build an annotation dict from a detectGroundedness API response.
Evaluate groundedness of the last model response.
Extracts the answer, grounding sources, and (for task="QnA") the
question from the state — either via the context_extractor callable
supplied at construction time or using the built-in heuristics — then
sends the result to the groundedness detection API.
The middleware annotates the state with the evaluation result and
either raises :exc:ContentSafetyViolationError (exit_behavior="error")
or lets execution proceed (exit_behavior="continue").
Async version of :meth:after_model.
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.
The domain of the text for analysis. "Generic" (default) or
"Medical".
The task type for the analysis. "Summarization" (default) or
"QnA".
What to do when ungrounded content is detected. One of
"error" (default) or "continue".
Node-name prefix used when wiring this middleware into a
LangGraph. Defaults to "azure_groundedness".
Optional callable with signature
(state, runtime) -> Optional[GroundednessInput]
that receives the current graph state and the LangGraph
:class:~langchain.agents.middleware.Runtime execution context,
and returns the answer, grounding sources, and optional question to
evaluate, or None to skip evaluation entirely. When None
(default) the middleware uses its built-in extraction logic.