Skip to content

microsoft/AzureOpenAI-with-APIM

Repository files navigation

Note

Updated on 2024-12-03,

  • Added Priority routing policy
    • This provides ability to include a Priority value in the HTTP header, which will route the request to your predefined backend. You can combine this with other policies like rate throttling to control throughput while ensuring defined services meet organizational SLAs. Combine with the circuit breaker pool for requests that do not include priority header info.
  • Added more details and reporting on Cost Management
    • Details on implementing the policies and how to generate log analytics reports via App insights
    • Details on creating Power BI reports using log analytics as a data source, this can provide leadership and management access to reporting without needing access to Azure Portal.

Manage Azure OpenAI using APIM

Overview

One-button deploy APIM, Key vault, and Log Analytics. Auto-configure APIM to work with your Azure OpenAI endpoint.

Using Azure's APIM orchestration provides a organizations with a powerful way to scale and manage their Azure OpenAI service without deploying Azure OpenAI endpoints everywhere. Administrators can issue subscription keys via APIM for accessing a single Azure OpenAI service instead of having teams share Azure OpenAI keys. APIM delivers usage metrics along with API monitoring to improve business intelligence. APIM policies control access, throttling, and a mechanism for chargeback cost models.

Gain conceptual details and technical step-by-step knowledge on implementing APIM to support your Azure OpenAI resiliency, scalability, performance, monitoring, and charge back capabilities.

Important

The goal with this repo is to provide more than conceptual knowledge on the services and technology. We want you to walk away from this repo knowing EXACTLY what to do to add these capabilities to YOUR enterprise. If we are missing information or steps or details or visuals or videos or anything that adds friction to you gaining this knowledge effectively and efficiently, please say something - Add your Ideas · Discussions · GitHub.

Solutions

There are two solutions developed to meet the needs of the organization from a sandbox to model a production environment.

Note

With Azure OpenAI's availability in Azure Government, the solutions are consolidated down because they are identical whether deployed into Azure Commercial or Azure Government.

Using it

Once the service is deployed, use the following section to understand how to access your Azure OpenAI service via APIM.

Utilization per subscription (support Charge-back)

Tip

A subscription, in the context of APIM, is the authorization of a user or group to access an API.

Calculate token counts per subscription. This can be helpful to monitor utilization of Azure OpenAI but also provides the foundation for a charge-back model if, internally, your organization provides a shared services model where Azure OpenAI is deployed and provided back to the business with one of the following models:

  • For free and the team managing the service pays for all costs
  • Cost basis so the team managing the service provides access to said service but requires the internal business consumer to pay for its use.

Use the following link to deploy an APIM policy and supporting services to capture token counts by subscription using an Event hub, process them using an Azure Function, and log them to Log Analytics workspace for reporting.

Resiliency (Retry Policy)

Resiliency is the ability of the service to recover from an issue. With regard to Azure OpenAI and APIM, this means using a Retry Policy to attempt the prompt again. Typically the prompt fails because at the time the user submitted their prompt, the Azure OpenAI endpoint was maxed out of either Tokens Per Minute or Requests Per Minute based on the endpoints quota, which triggers a HTTP 429 error.

  • Retry policy to leverage two or more Azure OpenAI endpoints
  • Expands capacity without impact to user experience or requesting increase to existing Azure OpenAI endpoints

Single region Retry policy means APIM will wait for a specific period of time and attempt to submit the prompt to the same Azure OpenAI endpoint. This is ok for development phases of solutions but not ideal for production.

Multi region Retry policy means APIM will immediately submit the prompt to a completely separate Azure OpenAI endpoint that is deployed to a separate Azure region. This effectively doubles your Azure OpenAI quota and provides resiliency. You can tie this together with the APIM Load Balancer capability (as of April 4, 2024, this is Azure Commercial only and in Preview) you can have scale and resiliency. This is discussed in more detail [LINK HERE]

Scalability (Load Balancing)

Scalability provides the ability of your Azure OpenAI service to support higher loads without necessarily increasing regional quotas. This feature (as of April 4, 2024, this is Azure Commercial only and in Preview) uses two or more Azure OpenAI endpoints in a round-robin load balancing configuration. This feature is not built into the One-button deploy but perspective implementation is provided so that organizations can implement.

You can tie this together with the Retry policy (as of April 4, 2024, this is Azure Commercial only and in Preview) you can have scale and resiliency. This is discussed in more detail [LINK HERE]

Performance (Provisioned Throughput Units)

Scale provides ability of an organization to support higher loads by leveraging multiple regions but the TPM cost model is a best effort compute with no SLAs. When using TPM pay as you go model, as long as your Azure OpenAI endpoint has quota - your prompts will be processed but their latency may be higher than anticipated and variability may be more inconsistent than anticipated.

To improve performance, Azure OpenAI has a cost model called Provisioned Throughput Units (PTU). When using PTUs, the organization is procuring an allotted amount of GPU to process their models. No other organization or individual can use that GPU. This has a positive effect of reducing latency and tightening up the variability in latency. It has a secondary effect of improving cost forecasting (discussed in more detail further in this article).

Implementing Priority-based Routing

To effectively manage performance and resource utilization, you can implement priority-based routing in Azure API Management (APIM). This allows you to direct high-priority requests to more performant (and potentially more costly) PTU endpoints, while routing lower-priority requests to standard pay-as-you-go endpoints.

APIM Policy Configuration

Below is an example of an APIM policy that routes requests based on the Priority header value:

<policies>
    <inbound>
        <base />
        <!-- Check if the Priority header exists -->
        <set-variable name="priorityValue" value="@(context.Request.Headers.GetValueOrDefault("Priority", "0"))" />

        <!-- Convert the priorityValue to an integer -->
        <set-variable name="priorityInt" value="@{
            int priority;
            return int.TryParse((string)context.Variables["priorityValue"], out priority) ? priority : 0;
        }" />

        <!-- Conditional routing based on priorityInt -->
        <choose>
            <!-- Route to PTU Endpoint if Priority is between 0 and 100 -->
            <when condition="@(context.Variables.GetValueOrDefault<int>("priorityInt") >= 0 && context.Variables.GetValueOrDefault<int>("priorityInt") <= 100)">
                <set-backend-service backend-id="aoai-ptu-backend" />
            </when>
            <!-- Route to Regional Endpoint if Priority is between 101 and 500 -->
            <when condition="@(context.Variables.GetValueOrDefault<int>("priorityInt") >= 101 && context.Variables.GetValueOrDefault<int>("priorityInt") <= 500)">
                <set-backend-service backend-id="aoai-regional-backend" />
            </when>
            <!-- Route to Data Zone Deployment if Priority is between 501 and 1000 -->
            <when condition="@(context.Variables.GetValueOrDefault<int>("priorityInt") >= 501 && context.Variables.GetValueOrDefault<int>("priorityInt") <= 1000)">
                <set-backend-service backend-id="aoai-data_zone-backend" />
            </when>
            <!-- Default routing using Circuit Breaker pool if Priority header is missing or out of range -->
            <otherwise>
                <set-backend-service backend-id="aoai-circuit_breaker-backend" />
            </otherwise>
        </choose>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Explanation:

  • Set Variable priorityValue: Retrieves the Priority header value from the incoming request. If it's missing, it defaults to "0".
  • Set Variable priorityInt: Converts the priorityValue to an integer for comparison purposes.
  • Conditional Routing with <choose>:
    • First <when> Condition: Routes to the PTU Endpoint if Priority is between 0 and 100.
    • Second <when> Condition: Routes to the Regional Endpoint if Priority is between 101 and 500.
    • Third <when> Condition: Routes to the Data zone Deployment if Priority is between 501 and 1000.
    • <otherwise> Condition: Routes to a default endpoint using a Circuit Breaker pool if the Priority header is missing or doesn't match any of the defined conditions.

Notes:

  • Replace the base-url in <set-backend-service> with your actual endpoint URLs or backend name.
  • Ensure that the priority ranges are correctly defined and non-overlapping.
  • This policy should be added to the inbound section of your APIM policy configuration.

HTTP Header Configuration

To make this routing work, clients need to include the Priority header in their HTTP requests.

  • HTTP Request Header:
    • Header Name: Priority
    • Header Value: An integer between 0 and 1000 depending on the desired priority level.

Example HTTP Request:

POST /apim/url HTTP/1.1
Host: your-apim-instance.azure-api.net
Priority: 50
Content-Type: application/json
Authorization: Bearer your-access-token

{
    "your": "request-body"
}

Cost Management (Rate Limiting)

Cost Forecasting (Provisioned Throughput Units + Rate Limiting)

Access Control

Managed Identity

APIM to Azure OpenAI

Important

The latest update to this repo moves to Managed Identity for the one-button deployments and guides for modifying existing APIM services.

Managed identities is the ideal method for authenticating APIM to Azure OpenAI. This eliminates the need to manage the rotation of keys and for keys to be stored anywhere beyond the Azure OpenAI endpoint.

Client or Application to APIM

Managed identities of the Azure App Service, Virtual Machine, Azure Kubernetes Service, or any other compute service in Azure is the preferred method of authentication. It improves security and eliminates the issuance of keys and tokens. Clients can use an OAuth token if required to validate access when using Azure OpenAI via APIM.

These methods shifts the burden of authentication from the application and onto APIM, which improves performance, scalability, operational management, and identity service selection. Update APIM's identity provider for OAuth and that update flows down to the application without any modification to the application.

The examples provide both methods along with guidance on how to setup the client or application to run the code so that managed identity technique can be used.

Tokens and Keys

APIM to Azure OpenAI SAS Token

Subscription key is like a SAS token provided by the backend service but it is issued by APIM for use by the user or group. These are fine during the development phase. We've retained the policy xml file in the repo as an example but this technique is not used.

Client or Application to APIM

For development and when running test commands from your workstation, using the Subscription key is straightforward but we recommend moving from the Subscription key to Managed Identities beyond development. The examples provide both methods along with guidance on how to setup the client or application to run the code so that managed identity technique can be used.

Prerequisites

Azure

One-Button

Each solution provides a simple one-button deployment. Select the "Deploy to Azure" button which will open the Azure portal and provide a form for details.

Command Line

To use the command line deployment method, fork the library and use Codespaces or clone the forked library to your local computer.

Azure CLI

Azure PowerShell

Architectures

The following architectural solutions support two use-cases in the Azure Commercial and Azure Government environments. Determining which solution to implement requires understanding of your current utilization of Azure.

  • API Management to Azure OpenAI
    • Supports Azure Commercial and Azure Government
    • Developing proof of concept or minimum viable production solution.
    • Isolated from enterprise networking using internal networks, Express Routes, and site-2-site VPN connections from the cloud to on-premises networks.
    • Assigns APIM the
  • API Management to Azure OpenAI with private endpoints
    • Supports Azure Commercial and Azure Government
    • Pilot or production solution.
    • Connected to the enterprise networking using internal networks, Express Routes, and site-2-site VPN connections from the cloud to on-premises networks.

API Management to Azure OpenAI

Use API management deployed to your Azure environment using public IP addresses for accessing APIM and for APIM to access the Azure OpenAI API. Access to the services is secured using keys and Defender for Cloud.

Note

Only API Management Service is deployed, this solution requires the Azure OpenAI service to already exist.

API Management to Azure OpenAI

  1. Users and Groups are used to assign access to an API using subscriptions.
    1. Each User or Group can be assigned their own policies like rate-limiting to control use
  2. The Azure OpenAI API uses policies to assign backends, retry, rate-throttling, and token counts.
  3. The backends are assigned using a policy and can include load balance groups. Retry policies reference additional backends for resiliency.
  4. One or more Azure OpenAI service (endpoint) can be used to manage scale and resiliency.
    1. The endpoints will reside in different regions so that they can utilize the maximum quota available to them.
  5. Policies are used to collect information, perform actions, and manipulate user connections.
  6. App Insights are used to create dashboards to monitor performance and use.

Deploy

! NOTE ! - It can take up to 45 minutes for all services to deploy as API Management has many underlying Azure resources deployed running the service.

One Button

Simple one-button deployment, opens in Azure Portal

Deploy to Azure

Deploy to Azure Government

Azure CLI
# Update the following variables to use the appropriate resource group and subscription.
$resourceGroupName = "RG-APIM-OpenAI"
$location = "East US" # Use MAG region when deploying to MAG
$subscriptionName = "MySubscription"

# az cloud set --name AzureUSGovernment # Uncomment when deploying to MAG
az login
az account set --subscription $subscriptionName
az group create --name $resourceGroupName --location $location
az deployment group create --resource-group $resourceGroupName  --template-file .\public-apim.bicep --mode Incremental
Azure PowerShell
# Update the following variables to use the appropriate resource group and subscription.
$resourceGroupName = "RG-APIM-OpenAI"
$location = "East US" # Use MAG region when deploying to MAG
$subscriptionName = "MySubscription"

Connect-AzAccount #-Environment AzureUSGovernment # Uncomment when deploying to MAG
Set-AzContext -Subscription $subscriptionName
New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile .\public-apim.bicep -Verbose -mode Incremental

Next steps

API Management to Azure OpenAI with private endpoints

Use API management deployed to your Azure environment using private IP addresses for accessing APIM and for APIM to access the Azure OpenAI API. Access to the services is secured using private network connectivity, keys, and Defender for Cloud. Access to the private network is controlled by customer infrastructure and supports internal routing via Express Route or site-2-site VPN for broader enterprise network access like on-premises data centers or site-based users.

API Management to Azure OpenAI with private endpoints

  1. Users and Groups are used to assign access to an API using subscriptions.
    1. Each User or Group can be assigned their own policies like rate-limiting to control use
  2. The Azure OpenAI API uses policies to assign backends, retry, rate-throttling, and token counts.
  3. The backends are assigned using a policy and can include load balance groups. Retry policies reference additional backends for resiliency.
  4. One or more Azure OpenAI service (endpoint) can be used to manage scale and resiliency.
    1. The endpoints will reside in different regions so that they can utilize the maximum quota available to them.
  5. Policies are used to collect information, perform actions, and manipulate user connections.
  6. App Insights are used to create dashboards to monitor performance and use.

Deploy

! NOTE ! - It can take up to 45 minutes for all services to deploy as API Management has many underlying Azure resources deployed running the service.

One Button

Simple one-button deployment, opens in Azure Portal

Deploy to Azure

Deploy to Azure Government

Azure CLI
# Update the following variables to use the appropriate resource group and subscription.
$resourceGroupName = "RG-APIM-OpenAI"
$location = "East US" # Use MAG region when deploying to MAG
$subscriptionName = "MySubscription"

# az cloud set --name AzureUSGovernment # Uncomment when deploying to MAG
az login
az account set --subscription $subscriptionName
az group create --name $resourceGroupName --location $location
az deployment group create --resource-group $resourceGroupName  --template-file .\private-apim.bicep --mode Incremental
Azure PowerShell
# Update the following variables to use the appropriate resource group and subscription.
$resourceGroupName = "RG-APIM-OpenAI"
$location = "East US" # Use MAG region when deploying to MAG
$subscriptionName = "MySubscription"

Connect-AzAccount #-Environment AzureUSGovernment # Uncomment when deploying to MAG
Set-AzContext -Subscription $subscriptionName
New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile .\private-apim.bicep -Verbose -mode Incremental

Next steps

Azure OpenAI token count per subscription

TBD

Policy for collecting tokens and user id

Log Analytics workspace

TBD

Event Hub

TBD

PowerApps Dashboard

TBD

Demo

TBD

Resiliency

Retry Policy

TBD

Azure API Management policy reference - retry | Microsoft Learn

Multi-region

TBD

Ensure reliability of your Azure API Management instance - Azure API Management | Microsoft LearnThrottling

TBD

Advanced request throttling with Azure API Management | Microsoft Learn

Scalability

  • Preview feature for two or more Azure OpenAI endpoints using round-robin load balancing
  • Pair with Resiliency for highly scalable solution

Performance

  • Preview feature for two or more Azure OpenAI endpoints using round-robin load balancing
  • Pair with Resiliency for highly scalable solution

Cost Management

  • Provide cost management per subscription

To effectively manage the costs associated with Azure OpenAI Service usage, you can implement policies in Azure API Management (APIM) that control and monitor the number of tokens consumed by each request. By limiting tokens per subscription and emitting detailed metrics, you can enforce usage quotas, prevent overuse, and enable charge-back models for cost recovery.

Implementing Token Limits and Metrics Emission

The following APIM policy helps you manage costs by:

  • Limiting the number of tokens a subscription can consume per minute.
  • Estimating prompt tokens to include both prompt and completion tokens in the limit.
  • Emitting token usage metrics with dimensions that help you analyze and report on token consumption per deployment and subscription.

APIM Policy Configuration

xmlCopy code<policies>
    <inbound>
        <!-- Set the backend service to your Azure OpenAI endpoint -->
        <set-backend-service id="apim-generated-policy" backend-id="azure-openai-openai-endpoint" />

        <!-- Extract the deployment ID from the URL path after '/deployments/' -->
        <set-variable name="deploymentId" value="@(context.Request.Url.Path.Split('/').ElementAtOrDefault(3))" />

        <!-- Limit tokens per minute per subscription -->
        <azure-openai-token-limit
            tokens-per-minute="10000000"
            counter-key="@(context.Subscription.Id)"
            estimate-prompt-tokens="true"
            tokens-consumed-header-name="consumed-tokens"
            remaining-tokens-header-name="remaining-tokens" />

        <!-- Emit token metrics with custom dimensions -->
        <azure-openai-emit-token-metric>
            <dimension name="API ID" />
            <dimension name="Subscription ID" />
            <dimension name="User ID" />
            <dimension name="Product ID" />
            <!-- Include the deployment ID as a custom dimension -->
            <dimension name="Deployment ID" value="@(context.Variables.GetValueOrDefault<string>("deploymentId", "unknown"))" />
        </azure-openai-emit-token-metric>

        <!-- Authenticate using Managed Identity -->
        <authentication-managed-identity resource="https://cognitiveservices.azure.com/" />
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Explanation

  • Set Backend Service: The <set-backend-service> element directs the request to your Azure OpenAI endpoint.

    xml
    
    
    Copy code
    <set-backend-service id="apim-generated-policy" backend-id="azure-openai-openai-endpoint" />
    
  • Extract Deployment ID: The <set-variable> element extracts the deployment ID from the request URL path. This is useful for tracking usage per model deployment.

    xml
    
    
    Copy code
    <set-variable name="deploymentId" value="@(context.Request.Url.Path.Split('/').ElementAtOrDefault(3))" />
    
  • Token Limit: The <azure-openai-token-limit> policy limits the number of tokens that can be consumed per minute per subscription.

    xmlCopy code<azure-openai-token-limit
        tokens-per-minute="10000000"
        counter-key="@(context.Subscription.Id)"
        estimate-prompt-tokens="true"
        tokens-consumed-header-name="consumed-tokens"
        remaining-tokens-header-name="remaining-tokens" />
    
    • tokens-per-minute: The maximum number of tokens allowed per minute. Adjust this value according to your cost management strategy.
    • counter-key: The key used to track the token count. Using context.Subscription.Id enforces the limit per subscription.
    • estimate-prompt-tokens: When set to true, includes an estimate of the prompt tokens in the token count.
    • tokens-consumed-header-name and remaining-tokens-header-name: Custom header names to include in the response, indicating tokens consumed and remaining.
  • Emit Token Metrics: The <azure-openai-emit-token-metric> policy emits metrics for token usage, which can be used for monitoring and reporting.

    xmlCopy code<azure-openai-emit-token-metric>
        <dimension name="API ID" />
        <dimension name="Subscription ID" />
        <dimension name="User ID" />
        <dimension name="Product ID" />
        <!-- Add the extracted deployment ID as a custom dimension -->
        <dimension name="Deployment ID" value="@(context.Variables.GetValueOrDefault<string>("deploymentId", "unknown"))" />
    </azure-openai-emit-token-metric>
    
    • Each <dimension> element adds a custom dimension to the emitted metric. Including Deployment ID helps in tracking usage per model deployment.
  • Authentication with Managed Identity: The <authentication-managed-identity> policy uses Managed Identity to authenticate with Azure Cognitive Services.

    xml
    
    
    Copy code
    <authentication-managed-identity resource="https://cognitiveservices.azure.com/" />
    

Steps to Implement

  1. Configure the Policy: Add the above policy to your API in APIM under the inbound processing section.
  2. Adjust Token Limits: Modify the tokens-per-minute value to set the desired token limit per subscription.
  3. Monitor Metrics:
    • Use Azure Monitor or Application Insights to collect and analyze the emitted metrics.
    • Set up dashboards and alerts based on token consumption to proactively manage costs.
  4. Communicate Limits to Clients:
    • Inform your API consumers about the token limits.
    • Clients can check the consumed-tokens and remaining-tokens headers in the response to monitor their usage.

Benefits

  • Cost Control: By limiting the number of tokens per subscription, you prevent excessive usage that could lead to unexpectedly high costs.
  • Transparency: Emitting token metrics with custom dimensions allows for detailed usage analysis, enabling charge-back models or internal billing.
  • Scalability: Implementing token limits ensures that resources are fairly distributed among consumers, improving overall system performance.

Example Response Headers

When clients make requests, they can examine the response headers to see their token usage:

yamlCopy codeconsumed-tokens: 1500
remaining-tokens: 9850000

Handling Limit Exceeded Errors

If a client exceeds the token limit, APIM will return a 429 Too Many Requests error. You can customize the error response using APIM policies to provide more context.

xmlCopy code<on-error>
    <base />
    <choose>
        <when condition="@(context.Response.StatusCode == 429)">
            <return-response>
                <set-status code="429" reason="Too Many Requests" />
                <set-header name="Retry-After" exists-action="override">
                    <value>60</value>
                </set-header>
                <set-body>@{
                    return @"{
                        ""error"": {
                            ""code"": ""TooManyTokens"",
                            ""message"": ""Token limit exceeded. Please retry after some time.""
                        }
                    }";
                }</set-body>
            </return-response>
        </when>
    </choose>
</on-error>

Monitoring and Reporting

By emitting token metrics with custom dimensions, you can set up monitoring and reporting to track token consumption per subscription, deployment, and other dimensions. This can be achieved using:

  • Azure Monitor Metrics: Collect and analyze the custom metrics emitted by APIM.
  • Log Analytics: Aggregate logs and perform queries to generate usage reports.
  • Alerts: Configure alerts to notify when token usage approaches limits.
  • Power BI: Configure reports that connect to Log Analytics data sources.
Log Analytics workspace via App Insights

Log Analytics report on use

Power BI

Power BI Report on Use

Implementing Charge-back Models

With detailed metrics, you can implement charge-back models where internal teams or external customers are billed based on their actual usage. By tracking token consumption per subscription, you can allocate costs accurately.

Example: Setting Up a Charge-back Report

Use this KQL Query AzureOpenAI-with-APIM/kql_queries/KQL-Token_Tracking_and_Cost.kql at main · microsoft/AzureOpenAI-with-APIM

  1. Collect Metrics: Ensure that the emitted metrics are being collected in Azure Monitor or Application Insights.

  2. Create a Log Analytics Workspace: If you haven't already, create a Log Analytics workspace to store and query your metrics.

  3. Query Metrics: Use Kusto Query Language (KQL) to query the metrics and aggregate token usage per subscription or deployment.

    customMetrics
    | where name != "_APPRESOURCEPREVIEW_" // Exclude unwanted records
    | where isnotempty(tostring(customDimensions['Deployment ID'])) // Only include records with a Deployment ID
    | extend 
        subscriptionId = tostring(customDimensions['Subscription ID']),
        deploymentId = tostring(customDimensions['Deployment ID']),
        tokens = toreal(value), // Extract the token count
        tokenType = case(
            name == "Prompt Tokens", "Prompt Tokens",
            name == "Completion Tokens", "Completion Tokens", 
            "Other") // Identify token type
    | where tokenType in ("Prompt Tokens", "Completion Tokens") // Filter to relevant token types
    | extend 
        // Calculate costs based on Deployment ID and Token Type, rounded to 2 decimal places
        promptTokenCost = round(case(
            deploymentId == "gpt-4o" and tokenType == "Prompt Tokens", tokens / 1000 * 0.03,
            deploymentId == "gpt-4o-global" and tokenType == "Prompt Tokens", tokens / 1000 * 0.04,
            deploymentId == "gpt-4" and tokenType == "Prompt Tokens", tokens / 1000 * 0.02,
            deploymentId == "gpt-35-turbo" and tokenType == "Prompt Tokens", tokens / 1000 * 0.0015,
            0.0), 3),
        completionTokenCost = round(case(
            deploymentId == "gpt-4o" and tokenType == "Completion Tokens", tokens / 1000 * 0.06,
            deploymentId == "gpt-4o-global" and tokenType == "Completion Tokens", tokens / 1000 * 0.07,
            deploymentId == "gpt-4" and tokenType == "Completion Tokens", tokens / 1000 * 0.05,
            deploymentId == "gpt-35-turbo" and tokenType == "Completion Tokens", tokens / 1000 * 0.002,
            0.0), 3)
    | summarize 
        totalPromptTokens = sumif(tokens, tokenType == "Prompt Tokens"), 
        totalCompletionTokens = sumif(tokens, tokenType == "Completion Tokens"),
        totalPromptTokenCost = round(sumif(promptTokenCost, tokenType == "Prompt Tokens"), 2), 
        totalCompletionTokenCost = round(sumif(completionTokenCost, tokenType == "Completion Tokens"), 2)
        by subscriptionId, deploymentId // Group by Subscription ID and Deployment ID
    | extend 
        totalCost = round(totalPromptTokenCost + totalCompletionTokenCost, 2) // Add total cost, rounded to 2 decimal places
    | order by totalCost desc // Sort by total cost
    
  4. Generate Reports: Use Azure Dashboards or Power BI to visualize the data and create reports for charge-back.

  5. Automate Billing: Export the reports or integrate with billing systems to automate the charge-back process.

Cost Forecasting

  • Provide cost management per subscription

Access Control

TBD

Managed Identity

APIM to Azure OpenAI

TBD

Application to APIM

TBD

Client to APIM

TBD

Tokens and Keys

APIM to Azure OpenAI (SAS Token)

TBD

Application to APIM (Subscription Key)

TBD

Client to APIM (Subscription Key)

TBD

Tying it All together

Read through the following steps to setup interacting with APIM and how to use consoles or .net to programatically interact with Azure OpenAI via APIM.

Get your Azure OpenAI Model Name

To determine if you have one or more models deployed, visit the AI Studio. Here you can determine if you need to create a model or use an existing model. You will use the model name when quering the Azure OpenAI API via your APIM.

Get your Azure OpenAI Model Name

  1. Navigate to your Azure OpenAI resource in Azure

  2. Select Model deployments

  3. Select Manage Deployments

  4. Review your models and copy the Deployment name of the model you want to use

Get your APIM Subscription Key

The subscription key for APIM is collected at the Subscription section of the APIM resource, regardless if you are in Azure Commercial or Government.

You can use this key for testing or as an example on how to create subscriptions to provide access to you Azure OpenAI service. Instead of sharing your Azure OpenAI Key, you create subscriptions in APIM and share this key, then you can analyze and monitor usage, provide guardrails for usage, and manage access.

Get your APIM Subscription Key

  1. Navigate to your new APIM
  2. Select Subscriptions from the menu
  3. Select ...
  4. Select Show/Hide keys
  5. Select copy icon

Get your APIM Azure OpenAI URL

The URL for APIM is collected at the Overview section of the APIM resource, regardless if you are in Azure Commercial or Government.

Get your APIM Azure OpenAI URL

Query Examples

Using your Azure OpenAI model, API version, APIM URL, and APIM subscription key you can now execute Azure OpenAI queries against your APIM URL instead of your Azure OpenAI URL. This means you can create new subscription keys for anyone or any team who needs access to Azure OpenAI instead of deploying new Azure OpenAI services.

curl

PowerShell 7

Copy and paste this script into a text editor or Visual Studio code (VSC).

Modify by including your values, then copy and paste all of it into PowerShell 7 terminal or run from VSC.

Note

Modify the "CONTENT" line for the system role and the user role to support your development and testing.

# Update these values to match your environment
$apimUrl = 'THE_HTTPS_URL_OF_YOUR_APIM_INSTANCE'
$deploymentName = 'DEPLOYMENT_NAME'
$apiVersion = '2024-02-15-preview'
$subscriptionKey = 'YOUR_APIM_SUBSCRIPTION_KEY'

# Construct the URL
$url = "$apimUrl/deployments/$deploymentName/chat/completions?api-version=$apiVersion"

# Headers
$headers = @{
    "Content-Type" = "application/json"
    "Ocp-Apim-Subscription-Key" = $subscriptionKey
}

# JSON Body
$body = @{
    messages = @(
        @{
            role = "system"
            content = "You are an AI assistant that helps people find information."
        },
        @{
            role = "user"
            content = "What are the differences between Azure Machine Learning and Azure AI services?"
        }
    )
    temperature = 0.7
    top_p = 0.95
    max_tokens = 800
} | ConvertTo-Json

# Invoke the API
$response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $body

# Output the response
$response.choices.message.content
Bash

Copy and paste this script into a text editor or Visual Studio code.

Modify by including your values, then copy and paste all of it into bash terminal, run from VSC, or create a ".sh" file to run.

Note

Modify the "CONTENT" line for the system role and the user role to support your development and testing.

#!/bin/bash
apimUrl="THE_HTTPS_URL_OF_YOUR_APIM_INSTANCE"
deploymentName="DEPLOYHMENT_NAME" # Probaby what you named your model, but change if necessary
apiVersion="2024-02-15-preview" # Change to use the latest version
subscriptionKey="YOUR_APIM_SUBSCRIPTION_KEY"

url="${apimUrl}/deployments/${deploymentName}/chat/completions?api-version=${apiVersion}"
key="Ocp-Apim-Subscription-Key: ${subscriptionKey}"

# JSON payload
jsonPayload='{
    "messages": [
        {
            "role": "system",
            "content": "You are an AI assistant that helps people find information."
        },
        {
            "role": "user",
            "content": "What are the differences between Azure Machine Learning and Azure AI services?"
        }
    ],
    "temperature": 0.7,
    "top_p": 0.95,
    "max_tokens": 800
}'

curl "${url}" -H "Content-Type: application/json" -H "${key}" -d "${jsonPayload}"

.net

You will most likely be using Visual Studio 202x to run this and you know what you are doing.

Note

Modify the "ChatMessage" lines for the system role and the user role to support your development and testing.

// Note: The Azure OpenAI client library for .NET is in preview.
// Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5 
using Azure;
using Azure.AI.OpenAI;

OpenAIClient client = new OpenAIClient(
	new Uri("https://INSERT_APIM_URL_HERE/deployments/INSERT_DEPLOYMENT_NAME_HERE/chat/completions?api-version=INSERT_API_VERSION_HERE"),
	new AzureKeyCredential("INSERT_APIM_SUBSCRIPTION_KEY_HERE"));

// ### If streaming is not selected
Response<ChatCompletions> responseWithoutStream = await client.GetChatCompletionsAsync(
	"INSERT_MODEL_NAME_HERE",
	new ChatCompletionsOptions()
	{
		Messages =
		{
			new ChatMessage(ChatRole.System, @"You are an AI assistant that helps people find information."),
			new ChatMessage(ChatRole.User, @"What are the differences between Azure Machine Learning and Azure AI services?"),
		},
		Temperature = (float)0,
		MaxTokens = 800,
		NucleusSamplingFactor = (float)1,
		FrequencyPenalty = 0,
		PresencePenalty = 0,
	});

// The following code shows how to get to the content from Azure OpenAI's response
ChatCompletions completions = responseWithoutStream.Value; 
ChatChoice choice = completions.Choices[0];
Console.WriteLine(choice.Message.Content);

Python

Copy and paste this script into a text editor or Visual Studio code.

Modify by including your values, then copy and paste all of it into bash terminal, run from VSC, or create a ".py" file to run.

Note

If you are running Juypter notebooks, this provides an example on using Azure OpenAI via APIM

# This code is an example of how to use the OpenAI API with Azure API Management (APIM) in a Jupyter Notebook.
import requests
import json

# Set the parameters
apim_url = "apim_url"
deployment_name = "deployment_name"
api_version = "2024-02-15-preview"
subscription_key = "subscription_key"

# Construct the URL and headers
url = f"{apim_url}/deployments/{deployment_name}/chat/completions?api-version={api_version}"
headers = {
    "Content-Type": "application/json",
    "Ocp-Apim-Subscription-Key": subscription_key
}

# Define the JSON payload
json_payload = {
    "messages": [
        {
            "role": "system",
            "content": "You are an AI assistant that helps people find information."
        },
        {
            "role": "user",
            "content": "What are the differences between Azure Machine Learning and Azure AI services?"
        }
    ],
    "temperature": 0.7,
    "top_p": 0.95,
    "max_tokens": 800
}

# Make the POST request
response = requests.post(url, headers=headers, json=json_payload)

# Print the response text (or you can process it further as needed)
print(response.text)

References