LoginSignup
2
2

Azure FunctionsでGPT-4oを叩いてみた。

Posted at

初めに

 この記事では、Azure FunctionsとOpenAIのAPIを使用して、HTTPトリガーを実装する方法について説明します。この実装により、HTTPリクエストを受け取り、そのリクエストに基づいてOpenAIのGPT-4モデルを使用して応答を生成することができます。

開発環境

このプロジェクトを進めるために必要な開発環境は以下の通りです:

Python 3.11
-azure-functions
-openai
-python-dotenv
-os
-requests
-json
Azure Functions Core Tools
Visual Studio Code (推奨)
Azureアカウント
OpenAI APIキー

導入

プロジェクトのセットアップ

まず、Azure Functionsのプロジェクトを作成します。VScodeでAzureにログインします。
左側のメニューのWORKSPACEからCreate Function Projectを選択します。
image.png

プロジェクトフォルダーを選択します。次のパラーメータでFUNCTIONを作成します。
Language: python Model V2
path: python.exeのパス (例)"C:\Users\admin\anaconda3\envs\py311\python.exe"
template: HTTP trigger
auth level: FUNCTION

環境変数の設定

Function AppのEnviorenment variablesのところに次の環境変数を追加します。

AZURE_OPENAI_ENDPOINT=<Your Azure OpenAI Endpoint>
AZURE_OPENAI_API_KEY=<Your Azure OpenAI API Key>

左側のメニューからsettings>>Enviorenment variables選択して。その画面のAddから追加することができます。画像を参考してください。

image.png

コード実装

プロジェクトフォルダーの中に「function_app.py」が作成されています。次のコードに変更して下さい。

.py
import azure.functions as func
import logging
import os
from openai import AzureOpenAI
from dotenv import load_dotenv
import json

load_dotenv()

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

@app.route(route="http_trigger", methods=["POST"])
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        req_body = req.get_json()
        message = req_body.get("message")
    except ValueError:
        return func.HttpResponse(
            "Invalid request body",
            status_code=400
        )

    client = AzureOpenAI(
        azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
        api_key=os.getenv("AZURE_OPENAI_API_KEY"),
        api_version="2024-02-01"
    )

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": message}
        ]
    )

    return func.HttpResponse(
        json.dumps({"result": response.choices[0].message.content}),
        status_code=200,
        headers={
            "Content-Type": "application/json"
        }
    )

コードを書き終わったら下のボタンからデプロイします。

image.png

テスター用コード

ここでFunctionのURLが必要になります。Overviewの下のFunctionのリストからHTTP Triggerを選択して出てくる画面のGet function URLを選択します。出てくる画面からdefault(Function Key)をコピーします。

image.png

そのコードを.envファイルに格納します。

.env
ENDPOINT=<先ほどコピーしたURL>

test.pyを作成します。
次のコードを書き込んでください。

test.py
import os
import requests
import json
from dotenv import load_dotenv

load_dotenv()

url = os.getenv('ENDPOINT')
message = "ここにメッセージを入れてください"

try:
    payload = {
        "message": message
    }
    headers = {
        "Content-Type": "application/json"
    }
    response = requests.post(url, data=json.dumps(payload), headers=headers)
    response.raise_for_status()  # Raise an exception if the request was unsuccessful
    print(response.text)  # Print the text response
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")

結果

image.png

お疲れ様でした。

2
2
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
2
2