Skip to content

Commit

Permalink
Merge pull request #7 from Azure-Samples/hookfixes
Browse files Browse the repository at this point in the history
Fix up hooks
  • Loading branch information
pamelafox authored May 22, 2024
2 parents b5762b4 + e009ec1 commit a681930
Show file tree
Hide file tree
Showing 12 changed files with 99 additions and 35 deletions.
19 changes: 14 additions & 5 deletions infra/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,16 @@ param deployAzureOpenAi bool = true

param openAiResourceName string = ''
param openAiResourceGroupName string = ''
param openAiResourceGroupLocation string = ''

// https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models#standard-deployment-model-availability
@description('Location for the OpenAI resource')
@allowed([ 'canadaeast', 'northcentralus', 'southcentralus' ])
@metadata({
azd: {
type: 'location'
}
})
param openAiResourceLocation string
param openAiDeploymentName string = 'chatgpt'
param openAiSkuName string = ''
param openAiDeploymentCapacity int = 30
Expand All @@ -37,12 +46,12 @@ var openAiConfig = {
param openAiComAPIKey string = ''
param openAiComAPIKeySecretName string = 'openai-com-api-key'

param authClientId string
param authClientId string = ''
@secure()
param authClientSecret string
param authClientSecret string = ''
param authClientSecretName string = 'AZURE-AUTH-CLIENT-SECRET'
param authTenantId string
param loginEndpoint string
param loginEndpoint string = ''
param tenantId string = tenant().tenantId
var tenantIdForAuth = !empty(authTenantId) ? authTenantId : tenantId

Expand All @@ -66,7 +75,7 @@ module openAi 'core/ai/cognitiveservices.bicep' = if (deployAzureOpenAi) {
scope: openAiResourceGroup
params: {
name: !empty(openAiResourceName) ? openAiResourceName : '${resourceToken}-cog'
location: !empty(openAiResourceGroupLocation) ? openAiResourceGroupLocation : location
location: !empty(openAiResourceLocation) ? openAiResourceLocation : location
tags: tags
sku: {
name: !empty(openAiSkuName) ? openAiSkuName : 'S0'
Expand Down
2 changes: 2 additions & 0 deletions scripts/auth_init.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ if (Test-Path -Path "/usr") {
}

Start-Process -FilePath $venvPythonPath -ArgumentList "./scripts/auth_init.py" -Wait -NoNewWindow

. ./scripts/unload_azd_env.ps1
12 changes: 9 additions & 3 deletions scripts/auth_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import datetime
import os
import random
import sys

import aiohttp
from auth_common import (
Expand Down Expand Up @@ -222,9 +223,12 @@ def get_credential(tenantId: str) -> AsyncTokenCredential:
async def main():
tenant_id = os.getenv("AZURE_AUTH_TENANT_ID", None)
print("Setting up authentication for tenant %s" % tenant_id)
credential = get_credential(tenant_id)
scopes = ["https://graph.microsoft.com/.default"]
graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
try:
credential = get_credential(tenant_id)
scopes = ["https://graph.microsoft.com/.default"]
graph_client = GraphServiceClient(credentials=credential, scopes=scopes)
except Exception:
sys.exit(1)
try:
(tenant_type, _) = await get_tenant_details(AzureDeveloperCliCredential(tenant_id=tenant_id), tenant_id)
print(f"Detected a tenant of type: {tenant_type}")
Expand Down Expand Up @@ -264,6 +268,8 @@ async def main():

print(f"Adding user flow to application {app_id}")
await add_app_to_userflow(auth_headers, userflow_id, app_id)
except Exception:
sys.exit(1)
finally:
await credential.close()
print("Pre-provisioning script complete.")
Expand Down
2 changes: 2 additions & 0 deletions scripts/auth_init.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
. ./scripts/load_python_env.sh

.venv/bin/python ./scripts/auth_init.py

. ./scripts/unload_azd_env.sh
2 changes: 2 additions & 0 deletions scripts/auth_update.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ if (Test-Path -Path "/usr") {
Start-Process -FilePath $venvPythonPath -ArgumentList "./scripts/auth_update.py" -Wait -NoNewWindow

azd env set OPENAICOM_API_KEY ""

. ./scripts/unload_azd_env.ps1
2 changes: 2 additions & 0 deletions scripts/auth_update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
. ./scripts/load_python_env.sh

.venv/bin/python ./scripts/auth_update.py

. ./scripts/unload_azd_env.sh
1 change: 1 addition & 0 deletions scripts/requirements.in
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
azure-identity
aiohttp
msgraph-sdk
msgraph-beta-sdk
32 changes: 25 additions & 7 deletions scripts/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ azure-core==1.30.1
azure-identity==1.16.0
# via
# -r requirements.in
# msgraph-beta-sdk
# msgraph-sdk
certifi==2024.2.2
# via
Expand Down Expand Up @@ -72,32 +73,47 @@ microsoft-kiota-abstractions==1.3.2
# microsoft-kiota-serialization-json
# microsoft-kiota-serialization-multipart
# microsoft-kiota-serialization-text
# msgraph-beta-sdk
# msgraph-core
# msgraph-sdk
microsoft-kiota-authentication-azure==1.0.0
# via
# msgraph-beta-sdk
# msgraph-core
# msgraph-sdk
microsoft-kiota-http==1.3.1
# via
# msgraph-beta-sdk
# msgraph-core
# msgraph-sdk
microsoft-kiota-serialization-form==0.1.0
# via msgraph-sdk
# via
# msgraph-beta-sdk
# msgraph-sdk
microsoft-kiota-serialization-json==1.2.0
# via msgraph-sdk
# via
# msgraph-beta-sdk
# msgraph-sdk
microsoft-kiota-serialization-multipart==0.1.0
# via msgraph-sdk
# via
# msgraph-beta-sdk
# msgraph-sdk
microsoft-kiota-serialization-text==1.0.0
# via msgraph-sdk
# via
# msgraph-beta-sdk
# msgraph-sdk
msal==1.28.0
# via
# azure-identity
# msal-extensions
msal-extensions==1.1.0
# via azure-identity
msgraph-beta-sdk==1.4.0
# via -r requirements.in
msgraph-core==1.0.0
# via msgraph-sdk
# via
# msgraph-beta-sdk
# msgraph-sdk
msgraph-sdk==1.4.0
# via -r requirements.in
multidict==6.0.5
Expand Down Expand Up @@ -128,13 +144,15 @@ portalocker==2.8.2
pycparser==2.22
# via cffi
pyjwt[crypto]==2.8.0
# via msal
# via
# msal
# pyjwt
python-dateutil==2.9.0.post0
# via
# microsoft-kiota-serialization-text
# pendulum
# time-machine
requests==2.31.0
requests==2.32.2
# via
# azure-core
# msal
Expand Down
9 changes: 9 additions & 0 deletions scripts/unload_azd_env.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
$envValues = azd env get-values
$envValues.Split("`n") | ForEach-Object {
$keyValue = $_.Split('=')
$key = $keyValue[0]
$value = $keyValue[1] -replace '^"|"$', ''
Remove-Item Env:$key
}

Write-Host "Unloaded azd env variables from current environment."
10 changes: 10 additions & 0 deletions scripts/unload_azd_env.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/sh

while IFS='=' read -r key value; do
value=$(echo "$value" | sed 's/^"//' | sed 's/"$//')
unset "$key"
done <<EOF
$(azd env get-values)
EOF

echo "Unloaded azd env variables from current environment."
35 changes: 18 additions & 17 deletions src/quartapp/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,7 @@ async def configure_openai():
bp.openai_client = openai.AsyncOpenAI(
**client_args,
)
elif os.getenv("OPENAICOM_API_KEY_SECRET_NAME") or os.getenv("OPENAICOM_API_KEY"):
current_app.logger.info("Using OpenAI.com OpenAI with key")
if os.getenv("OPENAICOM_API_KEY"):
client_args["api_key"] = os.getenv("OPENAICOM_API_KEY")
else:
OPENAICOM_API_KEY_SECRET_NAME = os.getenv("OPENAICOM_API_KEY_SECRET_NAME")
AZURE_KEY_VAULT_NAME = os.getenv("AZURE_KEY_VAULT_NAME")
async with SecretClient(
vault_url=f"https://{AZURE_KEY_VAULT_NAME}.vault.azure.net", credential=get_azure_credential()
) as key_vault_client:
openai_api_key = (await key_vault_client.get_secret(OPENAICOM_API_KEY_SECRET_NAME)).value
client_args["api_key"] = openai_api_key
bp.openai_client = openai.AsyncOpenAI(
**client_args,
)
bp.openai_model_arg = os.getenv("OPENAI_MODEL_NAME") or "gpt-3.5-turbo"
else:
elif os.getenv("AZURE_OPENAI_ENDPOINT"):
# Use an Azure OpenAI endpoint instead,
# either with a key or with keyless authentication
if os.getenv("AZURE_OPENAI_KEY"):
Expand All @@ -75,6 +59,22 @@ async def configure_openai():
)
# Note: Azure OpenAI takes the deployment name as the model name
bp.openai_model_arg = os.getenv("AZURE_OPENAI_CHATGPT_DEPLOYMENT")
elif os.getenv("OPENAICOM_API_KEY_SECRET_NAME") or os.getenv("OPENAICOM_API_KEY"):
current_app.logger.info("Using OpenAI.com OpenAI with key")
if os.getenv("OPENAICOM_API_KEY"):
client_args["api_key"] = os.getenv("OPENAICOM_API_KEY")
else:
OPENAICOM_API_KEY_SECRET_NAME = os.getenv("OPENAICOM_API_KEY_SECRET_NAME")
AZURE_KEY_VAULT_NAME = os.getenv("AZURE_KEY_VAULT_NAME")
async with SecretClient(
vault_url=f"https://{AZURE_KEY_VAULT_NAME}.vault.azure.net", credential=get_azure_credential()
) as key_vault_client:
openai_api_key = (await key_vault_client.get_secret(OPENAICOM_API_KEY_SECRET_NAME)).value
client_args["api_key"] = openai_api_key
bp.openai_client = openai.AsyncOpenAI(
**client_args,
)
bp.openai_model_arg = os.getenv("OPENAI_MODEL_NAME") or "gpt-3.5-turbo"


@bp.after_app_serving
Expand All @@ -92,6 +92,7 @@ def extract_username(headers, default_username="You"):

token = json.loads(base64.b64decode(headers.get("X-MS-CLIENT-PRINCIPAL")))
claims = {claim["typ"]: claim["val"] for claim in token["claims"]}
current_app.logger.info(f"Claims: {claims}")
return claims.get("name", default_username)


Expand Down
8 changes: 5 additions & 3 deletions src/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ aiohttp==3.9.5
# via quartapp (pyproject.toml)
aiosignal==1.3.1
# via aiohttp
annotated-types==0.6.0
annotated-types==0.7.0
# via pydantic
anyio==4.3.0
# via
Expand Down Expand Up @@ -128,7 +128,9 @@ pydantic==2.7.1
pydantic-core==2.18.2
# via pydantic
pyjwt[crypto]==2.8.0
# via msal
# via
# msal
# pyjwt
python-dotenv==1.0.1
# via
# quartapp (pyproject.toml)
Expand All @@ -139,7 +141,7 @@ pyyaml==6.0.1
# uvicorn
quart==0.19.6
# via quartapp (pyproject.toml)
requests==2.31.0
requests==2.32.2
# via
# azure-core
# msal
Expand Down

0 comments on commit a681930

Please sign in to comment.