Skip to content

Commit 8dc99a1

Browse files
committed
Token provider improvement
1 parent d1ea20c commit 8dc99a1

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

src/quartapp/chat.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import json
22
import os
33

4+
import httpx
45
from azure.identity.aio import AzureDeveloperCliCredential, ManagedIdentityCredential, get_bearer_token_provider
5-
from openai import AsyncOpenAI
6+
from openai import AsyncOpenAI, DefaultAsyncHttpxClient
67
from 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

Comments
 (0)