# AI Gateway Policies Complete reference for Azure API Management AI governance policies. --- ## Policy Placement Order Recommended order in `` section: ``` 1. Authentication (managed identity) 2. Semantic Cache Lookup 3. Token Rate Limiting 4. Content Safety 5. Backend Selection / Load Balancing 6. Token Metrics ``` --- ## Model Policies ### Token Rate Limiting Control costs by limiting token consumption per minute. ```xml ``` | Attribute | Purpose | Default | |-----------|---------|---------| | `tokens-per-minute` | Max tokens per counter window | Required | | `counter-key` | Grouping key (subscription, IP, custom) | Required | | `estimate-prompt-tokens` | Count prompt tokens toward limit | `true` | | `tokens-consumed-header-name` | Response header with consumed count | — | | `remaining-tokens-header-name` | Response header with remaining count | — | **Usage tiers example:** ```xml ``` --- ### Semantic Caching Cache AI responses for semantically similar prompts. Saves 60-80% on repeated queries. **Lookup** (in ``): ```xml ``` **Store** (in ``): ```xml ``` | Attribute | Purpose | Recommended | |-----------|---------|-------------| | `score-threshold` | Similarity threshold (0-1) | 0.8 (lower = more cache hits) | | `embeddings-backend-id` | Backend for embedding generation | Required | | `embeddings-backend-auth` | Auth to embeddings backend | `system-assigned` | | `duration` | Cache TTL in seconds | 3600 (1 hour) | **Prerequisites:** - An embeddings model deployed (e.g., `text-embedding-ada-002`) - A separate backend pointing to the embeddings endpoint - Azure Cache for Redis Enterprise with RediSearch module (for vector storage) ```bash # Create embeddings backend az apim backend create --service-name --resource-group \ --backend-id embeddings-backend --protocol http \ --url "https://.openai.azure.com/openai" ``` > **Note**: Semantic caching is NOT compatible with streaming responses (`"stream": true`). --- ### Token Metrics Emit token usage metrics for monitoring and chargeback. ```xml ``` Emits to Azure Monitor with these metrics: - `Total Tokens` — prompt + completion combined - `Prompt Tokens` — input tokens - `Completion Tokens` — output tokens **Query token usage (KQL):** ```kql customMetrics | where name == "Total Tokens" | extend Subscription = tostring(customDimensions["Subscription"]) | summarize TotalTokens = sum(value) by Subscription, bin(timestamp, 1h) | order by TotalTokens desc ``` --- ## Agent Policies ### Content Safety Filter harmful, violent, or inappropriate content from AI inputs and outputs. ```xml ``` | Category | Description | Threshold Range | |----------|-------------|-----------------| | Hate | Discrimination, slurs | 0 (block all) - 6 (allow most) | | Sexual | Explicit content | 0-6 | | SelfHarm | Self-injury content | 0-6 | | Violence | Violent content | 0-6 | **Prerequisites:** - Azure AI Content Safety resource deployed - Backend configured for the Content Safety endpoint: ```bash az apim backend create --service-name --resource-group \ --backend-id contentsafety-backend --protocol http \ --url "https://.cognitiveservices.azure.com" ``` --- ### Jailbreak Detection Block prompt injection attacks that attempt to bypass AI safety guardrails. ```xml ``` Custom response for blocked content: ```xml {"error": "Request blocked by content safety policy"} ``` --- ## Tool Policies ### Request Rate Limiting Protect MCP tools and API endpoints from excessive requests. ```xml ``` ```xml ``` --- ## Combining Policies Complete inbound policy example with all governance layers: ```xml 60 {"error": "Token rate limit exceeded. Try again later."} ``` --- ## Policy Quick-Decision Table | Need | Policy | Section | |------|--------|---------| | Control token spend | `azure-openai-token-limit` | `` | | Cache similar prompts | `azure-openai-semantic-cache-lookup/store` | `` / `` | | Track token usage | `azure-openai-emit-token-metric` | `` | | Block harmful content | `llm-content-safety` | `` | | Rate limit API calls | `rate-limit-by-key` | `` | | Authenticate to backend | `authentication-managed-identity` | `` | | Load balance backends | `set-backend-service` + retry | `` | --- ## References - [GenAI Gateway Capabilities](https://learn.microsoft.com/azure/api-management/genai-gateway-capabilities) - [APIM Policy Reference](https://learn.microsoft.com/azure/api-management/api-management-policies) - [AI-Gateway Samples](https://github.com/Azure-Samples/AI-Gateway)