はじめに
Azure API Management でAzure OpenAI のChatGPTを取り扱う方法を紹介します。
REST APIへの通信を簡略化したかったり、VNETから処理をしたい、認証したいということがあると思います。そんな場合にLogic AppsやAzure API Management でクエリを受け付ける方法になってくると思います。そこでLogic Apps に引き続きAzure API Management での利用方法を紹介します。
前提
下記のような前提で行っています。
- すでにAzure API Management が作成されていること
- APIが作成されていること
Operation
Operationの作成を行います。
名前を付けます。
URLの設定ではPOSTを設定し「/」を設定します。

作成後にHeadersを追加します。
NAMEに「Content-Type」 を指定します。VALUESに「text/plain」を指定します。
入力値は質問のみの文章を想定しています。

以上でOperationの設定は終わりです。
Backend
Backendの指定を行います。Azure OpenAIのエンドポイントを入力します。
Overrideで指定します。
https://{YOUR_DOMAIN}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/chat/completions?api-version=2023-03-15-preview

Inbound processing
inbound policy を追加します。。
最初にHeadersを追加します。

2つ追加します。
「api-key」これは対象のOpenAIのキーを入力します。overrideで追加します。
「Content-Type」に「application/json」を追加します。overrideで追加します。

以下のようにset-bodyを追記します。これは、受け取ったAPI Managementで受け取った文章をOpenAI用に整形しています。パラメータなどもクエリに変更することもできます。
<set-body>@{
// POSTリクエストボディからテキストを取得
string content = context.Request.Body.As<string>();
// 新しいJSONオブジェクトを作成
JObject requestBody = new JObject(
new JProperty("frequency_penalty", 0),
new JProperty("max_tokens", 800),
new JProperty("messages", new JArray(
new JObject(
new JProperty("content", content),
new JProperty("role", "user")
)
)),
new JProperty("presence_penalty", 0),
new JProperty("stop", null),
new JProperty("temperature", 0.7),
new JProperty("top_p", 0.95)
);
a// JSONデータを文字列に変換して返す
return requestBody.ToString();
}</set-body>
下記のようなJSONを生成します。
{
"frequency_penalty": 0,
"max_tokens": 800,
"messages": [
{
"content": "POSTした値",
"role": "user"
}
],
"presence_penalty": 0,
"stop": null,
"temperature": 0.7,
"top_p": 0.95
}
Policy Code 全文
<policies>
<inbound>
<base />
<set-backend-service base-url="https://{YOUR_DOMAIN}.openai.azure.com/openai/deployments/{DEPLOYMENT_NAME}/chat/completions?api-version=2023-03-15-preview" />
<set-header name="api-key" exists-action="override">
<value>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</value>
</set-header>
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
// POSTリクエストボディからテキストを取得
string content = context.Request.Body.As<string>();
// 新しいJSONオブジェクトを作成
JObject requestBody = new JObject(
new JProperty("frequency_penalty", 0),
new JProperty("max_tokens", 800),
new JProperty("messages", new JArray(
new JObject(
new JProperty("content", content),
new JProperty("role", "user")
)
)),
new JProperty("presence_penalty", 0),
new JProperty("stop", null),
new JProperty("temperature", 0.7),
new JProperty("top_p", 0.95)
);
// JSONデータを文字列に変換して返す
return requestBody.ToString();
}</set-body>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
いじょうで設定は完了です。
試験
Testを行ってみます。
bodyに質問したい文章を入力します。

送信すると返答があることがわかります。

以上で完了です。
まとめ
API Managementでも簡単に利用できます。API Managementを通して利用することも可能になることが開発側でも利点は多いのでしょうないでしょうか。