How do you configure Azure OpenAI content filters and managed identity authentication in Python SDK? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you configure Azure OpenAI content filters and managed identity authentication in Python SDK?

message-square
0

How Azure OpenAI Managed Identity Auth and Content Filters Work Together

In Azure OpenAI (via the openai Python SDK’s AzureOpenAI client), Microsoft Entra ID / Managed Identity authentication replaces static API keys with short-lived bearer tokens acquired via azure-identity, while content filters are configured on the Azure OpenAI / Microsoft Foundry resource and attached to model deployments (covering input prompts, output completions, Prompt Shields, and protected material).

  • Keyless Entra ID token acquisition (get_bearer_token_provider): Instead of passing api_key, you pass azure_ad_token_provider backed by DefaultAzureCredential (or a specific ManagedIdentityCredential / ClientSecretCredential) scoped to https://cognitiveservices.azure.com/.default, and the SDK automatically refreshes tokens before expiry.
  • Resource/deployment-level filter policies vs. SDK runtime handling: Content filter thresholds (hate, sexual, violence, self-harm, Prompt Shields, protected material, and streaming mode) are defined in the Foundry / Azure portal and bound to a deployment. Your Python SDK code enforces resilience by catching 400 content-filter errors on prompts and inspecting finish_reason == "content_filter" (plus content_filter_results annotations) on completions.
  • RBAC requirement: The managed identity running your Python service must have an appropriate RBAC role—such as Cognitive Services OpenAI User—assigned on the Azure OpenAI resource.

Steps to Configure Managed Identity Auth and Content Filter Handling in Python

  1. Assign RBAC and create/attach a content filter policy: Grant Cognitive Services OpenAI User to the service’s managed identity on the Azure OpenAI resource, and create or assign your content filter configuration (severity thresholds, Prompt Shields, or streaming filter mode) to the target deployment in Microsoft Foundry / Azure portal.
  2. Install openai and azure-identity: Install both packages in your Python environment so AzureOpenAI can request Entra ID tokens against https://cognitiveservices.azure.com/.default.
  3. Initialize AzureOpenAI with azure_ad_token_provider: Supply azure_endpoint, api_version, and azure_ad_token_provider (passing managed_identity_client_id when using a user-assigned managed identity).
  4. Handle input blocks, output content_filter stops, and annotations: Catch BadRequestError / APIStatusError when input prompts are blocked (400 with content_filter code) and inspect choice.finish_reason and prompt_filter_results / content_filter_results for safe fallback handling.

Python Example: Managed Identity Client and Content Filter Handling

import os
from typing import Any

from azure.identity import DefaultAzureCredential, ManagedIdentityCredential, get_bearer_token_provider
from openai import APIStatusError, AzureOpenAI, BadRequestError


def build_azure_openai_client() -> AzureOpenAI:
    endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
    api_version = os.environ.get("AZURE_OPENAI_API_VERSION", "2024-10-21")
    user_assigned_client_id = os.environ.get("AZURE_CLIENT_ID")

    credential = (
        ManagedIdentityCredential(client_id=user_assigned_client_id)
        if user_assigned_client_id
        else DefaultAzureCredential()
    )

    token_provider = get_bearer_token_provider(
        credential,
        "[https://cognitiveservices.azure.com/.default](https://cognitiveservices.azure.com/.default)",
    )

    return AzureOpenAI(
        azure_endpoint=endpoint,
        api_version=api_version,
        azure_ad_token_provider=token_provider,
    )


def generate_with_filter_handling(
    client: AzureOpenAI,
    deployment: str,
    user_prompt: str,
    system_prompt: str = "You are a helpful assistant.",
) -> dict[str, Any]:
    try:
        response = client.chat.completions.create(
            model=deployment,
            temperature=0.2,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt},
            ],
        )
    except BadRequestError as exc:
        body = getattr(exc, "body", None)
        is_filtered = isinstance(body, dict) and (
            body.get("code") == "content_filter"
            or (body.get("innererror") or {}).get("code") == "ResponsibleAIPolicyViolation"
        )
        return {
            "status": "blocked_input" if is_filtered else "bad_request",
            "content": None,
            "error": str(exc),
        }
    except APIStatusError as exc:
        return {
            "status": f"http_{exc.status_code}",
            "content": None,
            "error": str(exc),
        }

    choice = response.choices[0]
    if choice.finish_reason == "content_filter":
        return {
            "status": "filtered_output",
            "content": choice.message.content,
            "finish_reason": choice.finish_reason,
            "prompt_filter_results": getattr(response, "prompt_filter_results", None),
        }

    return {
        "status": "ok",
        "content": choice.message.content,
        "finish_reason": choice.finish_reason,
    }


if __name__ == "__main__":
    aoai_client = build_azure_openai_client()
    result = generate_with_filter_handling(
        client=aoai_client,
        deployment=os.environ["AZURE_OPENAI_DEPLOYMENT"],
        user_prompt="Summarize the benefits of zero-trust authentication in cloud APIs.",
    )
    print(result)

Helpful Tips for Production Azure OpenAI Security and Filtering

  • Use explicit ManagedIdentityCredential(client_id=...) in production workloads: While DefaultAzureCredential is convenient across local dev and Azure hosts, explicitly specifying the user-assigned managed identity client ID in production avoids ambiguity when multiple identities or local auth caches exist.
  • Do not retry content_filter rejections blindly: Unlike transient 429 or 5xx errors, a 400 content-filter block or finish_reason == "content_filter" indicates a policy trigger—log the incident, return a safe user-facing message, and avoid retrying the exact same blocked prompt.
  • Account for asynchronous streaming filter behavior if enabled: If your deployment uses asynchronous content filtering during streaming, policy annotations may arrive slightly behind streamed tokens within a short character window—design your stream consumer to handle late filter signals or redaction cleanly.