11import json
22import os
33
4+ import httpx
45from azure .identity .aio import AzureDeveloperCliCredential , ManagedIdentityCredential , get_bearer_token_provider
5- from openai import AsyncOpenAI
6+ from openai import AsyncOpenAI , DefaultAsyncHttpxClient
67from quart import (
78 Blueprint ,
89 Response ,
@@ -27,15 +28,25 @@ async def configure_openai():
2728 bp .azure_credential = AzureDeveloperCliCredential (tenant_id = tenant_id )
2829
2930 # Get the token provider for Azure OpenAI based on the selected Azure credential
30- bp . openai_token_provider = get_bearer_token_provider (
31+ openai_token_provider = get_bearer_token_provider (
3132 bp .azure_credential , "https://cognitiveservices.azure.com/.default"
3233 )
3334
35+ class TokenBasedAuth (httpx .Auth ):
36+ async def async_auth_flow (self , request ):
37+ token = await openai_token_provider ()
38+ request .headers ["Authorization" ] = f"Bearer { token } "
39+ yield request
40+
41+ def sync_auth_flow (self , request ):
42+ raise RuntimeError ("Cannot use a sync authentication class with httpx.AsyncClient" )
43+
3444 # Create the Asynchronous Azure OpenAI client
3545 bp .openai_client = AsyncOpenAI (
3646 base_url = os .environ ["AZURE_INFERENCE_ENDPOINT" ],
37- api_key = await bp . openai_token_provider () ,
47+ api_key = "placeholder" ,
3848 default_query = {"api-version" : "2024-05-01-preview" },
49+ http_client = DefaultAsyncHttpxClient (auth = TokenBasedAuth ()),
3950 )
4051
4152 # Set the model name to the Azure OpenAI model deployment name
@@ -63,7 +74,6 @@ async def response_stream():
6374 {"role" : "system" , "content" : "You are a helpful assistant." },
6475 ] + request_messages
6576
66- bp .openai_client .api_key = await bp .openai_token_provider ()
6777 chat_coroutine = bp .openai_client .chat .completions .create (
6878 # Azure Open AI takes the deployment name as the model name
6979 model = bp .openai_model ,
0 commit comments