openai/openai-python
Publicexamples/azure_ad.py
67lines · modecode
| 1 | import asyncio |
| 2 | |
| 3 | from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI, AzureADTokenProvider, AsyncAzureADTokenProvider |
| 4 | |
| 5 | scopes = "https://cognitiveservices.azure.com/.default" |
| 6 | |
| 7 | # May change in the future |
| 8 | # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning |
| 9 | api_version = "2023-07-01-preview" |
| 10 | |
| 11 | # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource |
| 12 | endpoint = "https://my-resource.openai.azure.com" |
| 13 | |
| 14 | deployment_name = "deployment-name" # e.g. gpt-35-instant |
| 15 | |
| 16 | |
| 17 | def sync_main() -> None: |
| 18 | from azure.identity import DefaultAzureCredential, get_bearer_token_provider |
| 19 | |
| 20 | token_provider: AzureADTokenProvider = get_bearer_token_provider(DefaultAzureCredential(), scopes) |
| 21 | |
| 22 | client = AzureOpenAI( |
| 23 | api_version=api_version, |
| 24 | azure_endpoint=endpoint, |
| 25 | azure_ad_token_provider=token_provider, |
| 26 | ) |
| 27 | |
| 28 | completion = client.chat.completions.create( |
| 29 | model=deployment_name, |
| 30 | messages=[ |
| 31 | { |
| 32 | "role": "user", |
| 33 | "content": "How do I output all files in a directory using Python?", |
| 34 | } |
| 35 | ], |
| 36 | ) |
| 37 | |
| 38 | print(completion.to_json()) |
| 39 | |
| 40 | |
| 41 | async def async_main() -> None: |
| 42 | from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider |
| 43 | |
| 44 | token_provider: AsyncAzureADTokenProvider = get_bearer_token_provider(DefaultAzureCredential(), scopes) |
| 45 | |
| 46 | client = AsyncAzureOpenAI( |
| 47 | api_version=api_version, |
| 48 | azure_endpoint=endpoint, |
| 49 | azure_ad_token_provider=token_provider, |
| 50 | ) |
| 51 | |
| 52 | completion = await client.chat.completions.create( |
| 53 | model=deployment_name, |
| 54 | messages=[ |
| 55 | { |
| 56 | "role": "user", |
| 57 | "content": "How do I output all files in a directory using Python?", |
| 58 | } |
| 59 | ], |
| 60 | ) |
| 61 | |
| 62 | print(completion.to_json()) |
| 63 | |
| 64 | |
| 65 | sync_main() |
| 66 | |
| 67 | asyncio.run(async_main()) |
| 68 | |