Prerequisites
- Python 3.9 or later.
- The
openai>=1.75.0andpython-dotenvpackages. Install them by runningpip install "openai>=1.75.0" python-dotenv. - A model router deployment that you can access through an Azure OpenAI endpoint.
- The endpoint and API key for your Azure OpenAI resource. The complete sample reads them from the
AZURE_OPENAI_ENDPOINTandAZURE_OPENAI_API_KEYenvironment variables. - Azure OpenAI API version
2024-10-21.
Enable per-request routing metadata
After your application reads the endpoint and API key intoendpoint and api_key, create the client with the preview feature header:
Foundry-Features: ModelRouterControls=V1Preview header requests per-request routing metadata. Because this feature is in preview, the metadata presence and response schema can vary by request and service version.
Send a Chat Completions request
Use the model router deployment name to send a request. The response includes the completion and, when available, the per-request routing metadata:Understand routing metadata
The followingmodel_selection_details fragment illustrates a request with two ordered model attempts:
modeis the routing mode returned for the request.routing_tracecontains the routing entries returned for the request.latency_msis the latency reported for a routing-trace entry.attemptslists model attempts in order.- Each attempt contains a model and an HTTP status in
result.status. - A failed attempt can include an optional
errorwith a code and message.
Extract routing and fallback information
After the Chat Completions request returnsresponse, inspect the serving model and model selection details:
Interpret session affinity metadata
When you enable the Chat Completions session affinity preview,model_router_details can include a session_affinity object. The following response fragment shows a request that retained its associated model:
When
decision is switch, inspect routing_trace and the top-level model field together. The following fragment shows an associated model that returned a retryable response before fallback selected another model:
session_affinity object. Don’t infer an affinity decision when the object or decision field is absent.
Interpret the results
The following output shows the response and routing metadata for an example request:- If
model_selection_detailsis absent, the sample reports that no model selection details were returned. Don’t infer routing details that aren’t present. - If
routing_traceis empty, the sample reports that no routing trace was returned. - An attempt can omit
error. The extraction code prints an error only when the response includes one. - Model names, HTTP statuses, attempt counts, and reported latency can vary by request and service version.
response.modelidentifies the serving model for the demonstrated request.