在本教學課程中,您將整合 Azure OpenAI 與 Python Web 應用程式,並將其部署至 Azure App Service,以建置智慧型手機 AI 應用程式。 您將建立 Flask 應用程式,以將聊天完成要求傳送至 Azure OpenAI 中的模型。
在本教學課程中,您將瞭解如何:
- 建立 Azure OpenAI 資源並部署語言模型。
- 建置連線至 Azure OpenAI 的 Flask 應用程式。
- 將應用程式部署至 Azure App Service。
- 在開發環境和 Azure 中實作無密碼安全驗證。
Prerequisites
1.建立 Azure OpenAI 資源
在本節中,您將使用 GitHub Codespaces 搭配 Azure CLI 建立 Azure OpenAI 資源。
移至 GitHub Codespaces 並使用您的 GitHub 帳戶登入。
在 GitHub 上尋找 空白 範本,然後選取 使用此範本 來建立新的空白 Codespace。
在 Codespace 終端機中,安裝 Azure CLI:
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash登入您的 Azure 帳戶:
az login請遵循終端機中的指示進行驗證。
設定資源群組名稱、Azure OpenAI 服務名稱和位置的環境變數:
export RESOURCE_GROUP="<group-name>" export OPENAI_SERVICE_NAME="<azure-openai-name>" export APPSERVICE_NAME="<app-name>" export LOCATION="eastus2"Important
區域很重要,因為它與所選模型的區域可用性相關。 模型可用性和 部署類型可用性 會因區域而異。 此教學課程會使用
gpt-4o-mini,其可在標準部署類型下的eastus2中取得。 如果您部署到不同的區域,此模型可能無法使用,或可能需要不同的階層。 變更區域之前,請參閱 模型摘要數據表和區域可用性 ,以確認您慣用區域中的模型支援。使用自定義網域建立資源群組和 Azure OpenAI 資源,然後新增 gpt-4o-mini 模型:
# Resource group az group create --name $RESOURCE_GROUP --location $LOCATION # Azure OpenAI resource az cognitiveservices account create \ --name $OPENAI_SERVICE_NAME \ --resource-group $RESOURCE_GROUP \ --location $LOCATION \ --custom-domain $OPENAI_SERVICE_NAME \ --kind OpenAI \ --sku s0 # gpt-4o-mini model az cognitiveservices account deployment create \ --name $OPENAI_SERVICE_NAME \ --resource-group $RESOURCE_GROUP \ --deployment-name gpt-4o-mini \ --model-name gpt-4o-mini \ --model-version 2024-07-18 \ --model-format OpenAI \ --sku-name Standard \ --sku-capacity 1 # Cognitive Services OpenAI User role that lets the signed in Azure user to read models from Azure OpenAI az role assignment create \ --assignee $(az ad signed-in-user show --query id -o tsv) \ --role "Cognitive Services OpenAI User" \ --scope /subscriptions/$(az account show --query id -o tsv)/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.CognitiveServices/accounts/$OPENAI_SERVICE_NAME
現在您已擁有 Azure OpenAI 資源,您將建立 Web 應用程式來與其互動。
2.建立及設定 Flask 應用程式
在您的 Codespace 終端機中,建立虛擬環境並安裝您需要的 PIP 套件。
python3 -m venv .venv source .venv/bin/activate pip install flask openai azure.identity dotenv pip freeze > requirements.txt在工作區根目錄中,建立 app.py ,並將下列程式代碼複製到其中,以使用 Azure OpenAI 進行簡單的聊天完成呼叫。
import os from flask import Flask, render_template, request from azure.identity import DefaultAzureCredential, get_bearer_token_provider from openai import AzureOpenAI app = Flask(__name__) # Initialize the Azure OpenAI client with Microsoft Entra authentication token_provider = get_bearer_token_provider( DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default" ) client = AzureOpenAI( api_version="2024-10-21", azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), azure_ad_token_provider=token_provider, ) @app.route('/', methods=['GET', 'POST']) def index(): response = None if request.method == 'POST': # Handle form submission user_message = request.form.get('message') if user_message: try: # Call the Azure OpenAI API with the user's message completion = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": user_message}] ) ai_message = completion.choices[0].message.content response = ai_message except Exception as e: response = f"Error: {e}" return render_template('index.html', response=response) if __name__ == '__main__': app.run()建立 範本 目錄和其中 index.html 檔案。 將下列程式代碼複製到其中以取得簡單的聊天介面:
<!doctype html> <html> <head> <title>Azure OpenAI Chat</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <main class="container py-4"> <h1 class="mb-4 text-primary">Azure OpenAI Chat</h1> <form method="post" action="/" class="mb-3"> <div class="input-group"> <input type="text" name="message" class="form-control" placeholder="Type your message..." required> <button type="submit" class="btn btn-primary">Send</button> </div> </form> <div class="card p-3"> {% if response %} <div class="alert alert-info mt-3">{{ response }}</div> {% endif %} </div> </main> </body> </html>在終端機中,擷取您的 OpenAI 端點:
az cognitiveservices account show \ --name $OPENAI_SERVICE_NAME \ --resource-group $RESOURCE_GROUP \ --query properties.endpoint \ --output tsv執行應用程式時,使用從 CLI 輸出中獲取的值來新增
AZURE_OPENAI_ENDPOINT:AZURE_OPENAI_ENDPOINT=<output-from-previous-cli-command> flask run選取 [在瀏覽器中開啟 ] 以在新瀏覽器索引標籤中啟動應用程式。提交問題,並查看您是否收到回應消息。
3.部署至 Azure App Service 並設定 OpenAI 連線
既然您的應用程式在本機運作,讓我們將其部署至 Azure App Service,並使用受控識別設定 Azure OpenAI 的服務連線。
首先,使用 Azure CLI 命令
az webapp up將您的應用程式部署至 Azure App Service。 這個指令會建立新的 Web 應用程式,並將程式代碼部署到其中:az webapp up \ --resource-group $RESOURCE_GROUP \ --location $LOCATION \ --name $APPSERVICE_NAME \ --plan $APPSERVICE_NAME \ --sku B1 \ --os-type Linux \ --track-status false此命令可能需要幾分鐘才能完成。 它會在與 OpenAI 資源相同的資源群組中建立新的 Web 應用程式。
部署應用程式之後,請使用受控識別,在 Web 應用程式與 Azure OpenAI 資源之間建立服務連線:
az webapp connection create cognitiveservices \ --resource-group $RESOURCE_GROUP \ --name $APPSERVICE_NAME \ --target-resource-group $RESOURCE_GROUP \ --account $OPENAI_SERVICE_NAME \ --connection azure-openai \ --system-identity此命令會建立 Web 應用程式與 Azure OpenAI 資源之間的連線,方法是:
- 為 Web 應用程式產生系統指派的受控識別。
- 將認知服務 OpenAI 參與者角色新增至 Azure OpenAI 資源的受控識別。
- 將
AZURE_OPENAI_ENDPOINT應用程式設定新增至 Web 應用程式。
在瀏覽器中開啟已部署的 Web 應用程式。 在終端機輸出中尋找已部署 Web 應用程式的 URL。 開啟網頁瀏覽器並瀏覽至其中。
az webapp browse在文字框輸入訊息並選擇 發送,給應用程式幾秒鐘回覆 Azure OpenAI 的訊息。
您的應用程式現在已部署並連線至具有受控識別的 Azure OpenAI。
常見問題
- 如果我想要連線到 OpenAI 而不是 Azure OpenAI,該怎麼辦?
- 我可以改為使用 API 金鑰連線到 Azure OpenAI 嗎?
- DefaultAzureCredential 如何在本教學課程中運作?
如果我想要連線到 OpenAI 而不是 Azure OpenAI,該怎麼辦?
若要改為連線到 OpenAI,請使用下列程式代碼:
from openai import OpenAI
client = OpenAI(
api_key="<openai-api-key>"
)
如需詳細資訊,請參閱 如何使用 Python 在 OpenAI 與 Azure OpenAI 端點之間切換。
在 App Service 中使用連線密碼時,您應該使用 Key Vault 參考 ,而不是將秘密直接儲存在程式碼基底中。 這可確保敏感性資訊保持安全且集中管理。
我可以改為使用 API 金鑰連線到 Azure OpenAI 嗎?
是,您可以使用 API 金鑰來連線到 Azure OpenAI,而不是受控識別。 Azure OpenAI SDK 和語意核心支援此方法。
- 如需搭配語意核心使用 API 金鑰的詳細資料:語意核心 C# 快速入門。
- 如需搭配 Azure OpenAI 用戶端程式庫使用 API 金鑰的詳細資訊,請參閱快速入門:使用 Azure OpenAI 服務的聊天功能開始。
在 App Service 中使用連線密碼時,您應該使用 Key Vault 參考 ,而不是將秘密直接儲存在程式碼基底中。 這可確保敏感性資訊保持安全且集中管理。
DefaultAzureCredential 如何在本教學課程中運作?
藉 DefaultAzureCredential 由自動選取最佳的可用驗證方法,簡化驗證:
-
在本機開發期間:執行
az login之後,它會使用本機 Azure CLI 認證。 - 部署至 Azure App Service 時:它會使用應用程式的受控識別進行安全、無密碼的驗證。
這種方法可讓您的程式代碼在本機和雲端環境中安全地順暢地執行,而不需要修改。