1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

App ServiceでAzure Open AIをキーなしで実行する方法

Posted at

概要

ユーザー割り当てマネージドIDを使用して、認証トークンを取得し、App Serviceで利用する方法

App Serviceの設定

  1. 新規にユーザー割り当てマネージドID作成
  2. ポータルでOpenAIのリソースへ移動し、1.のIDに「Cognitive Services OpenAI User」を付与
  3. ポータルでApp Serviceのリソースへ移動し、「設定」>「ID」>「ユーザー割り当て済み」タブから1.のIDを設定
  4. App Serviceの「設定」>「環境変数」にて、あらかじめコードで設定しておいたCLIENT_ID=[1.のID]のとして設定
  5. 他環境変数についても設定する

コード側の設定

from openai import AzureOpenAI
from azure.identity import ManagedIdentityCredential, get_bearer_token_provider 

# Azure OpenAI設定
endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
api_version = os.getenv("AZURE_OPENAI_API_VERSION")

# デプロイ名 ※モデル名ではない​
deployment_name = os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"

# ユーザー割り当てマネージドIDのクライアントID​
client_id=os.getenv("CLIENT_ID")

def send_openai_request(system_prompt, chat_prompt, temperature):
    token_provider = get_bearer_token_provider(
        ManagedIdentityCredential(client_id=client_id),
        "https://cognitiveservices.azure.com/.default"
    )
    client = AzureOpenAI(
        azure_ad_token_provider=token_provider,
        azure_endpoint=endpoint,
        api_version=api_version,
    )
    
    try:
        response = client.chat.completions.create(
            model=deployment_name,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": chat_prompt}
            ],
            max_tokens=5000,
            temperature=temperature
        )
        
        return response.choices[0].message.content
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return None
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?