はじめに
カロリーはだいたいの数値が出れば OK → GPT モデルの出番ということでこんなのを作ります。
コンポーネント
- Azure Open AI : GPT-4o モデルのAPIを提供
- カメラアプリ: Power Apps で作成。写真の解析を AOAI にリクエスト→ Fabric に送信まで行う
- Microsoft Fabric
- Real-time Intelligence : 送信されたデータをリアルタイム分析用データベース(KQL データベース)に格納
- Power BI : データベースへのクエリの発行、可視化の提供
- リアルタイムダッシュボード で可視化を作成すれば Real-time Intelligence で完結します。これだと Power BI ライセンスは不要。
参考にしたもの
手順
- Fabric の準備
- Power Apps カスタムコネクタ(AOAI)の作成
- Power Apps カスタムコネクタ(Fabricデータ送信)の作成
- Power Apps カメラアプリの作成
- データ変換とPower BI による可視化
前提条件
- GPT-4o デプロイが利用可能な Azure Open AI Service が必要です
- プレミアムコネクタが利用可能なPower Apps ライセンス(開発者ライセンスなど)
- Microsoft Fabric 容量(試用版など)
- (共有する場合)Power BI Pro
Fabric の準備
1 . チュートリアルのワークスペース作成手順 などを参考にワークスペースを作成
2 . チュートリアルのイベントハウス作成手順を参考にKQL データベースを作成します。
7 . 以下のコードにより、tokenなどを取得します
#%%
import time
import urllib.parse
import hmac
import hashlib
import base64
sb_name='<記録した情報(サービスバス名)に置き換え>'
eh_name='<記録した情報(Event hub name)に置き換え>'
sas_name='<記録した情報(Shared access key Name)に置き換え>'
sas_key='<記録した情報(primary key)に置き換え>'
def get_auth_token(sb_name, eh_name, sas_name, sas_key):
"""
Returns an authorization token dictionary
for making calls to Event Hubs REST API.
"""
uri_str = f"https://{sb_name}.servicebus.windows.net/{eh_name}/"
uri = urllib.parse.quote_plus(uri_str)
sas = sas_key.encode('utf-8')
expiryNum = 60*60*24*365*3
expiry = str(int(time.time() + expiryNum))
string_to_sign = (uri + '\n' + expiry).encode('utf-8')
signed_hmac_sha256 = hmac.HMAC(sas, string_to_sign, hashlib.sha256)
signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest()))
return {
"uri": uri_str,
"sb_name": sb_name,
"eh_name": eh_name,
"token":'SharedAccessSignature sr={}&sig={}&se={}&skn={}' \
.format(uri, signature, expiry, sas_name)
}
# %%
result = get_auth_token(sb_name,eh_name,sas_name,sas_key)
print (f"result: {result}")
Power Apps カスタムコネクタ(AOAI)の作成
3 . https://make.powerapps.com/ にアクセスして、すべて見るに移動
6 . ホスト名など入力。ベースURLは/openai/ 固定
7 . セキュリティ
補足:chat completion API docs 参考箇所:
補足:chat completion API docs 参考箇所:
10 . 全般はこのように入力。※説明はdocsから適宜もってきました
11 . サンプルからのインポートを選択してインポート
補足:chat completion API docs 参考箇所:
12 . 応答も入れます※docs そのままだとjsonと認識してくれないので改良
{
"id": "chatcmpl-6v7mkQj980V1yBec6ETrKPRqFjNw9",
"object": "chat.completion",
"created": 1679072642,
"model": "gpt-35-turbo",
"usage": {
"prompt_tokens": 58,
"completion_tokens": 68,
"total_tokens": 126
},
"choices": [
{
"message": {
"role": "assistant",
"content": "Yes, other Azure AI services also support customer managed keys.\r\n Azure AI services offer multiple options for customers to manage keys, such as\r\n using Azure Key Vault, customer-managed keys in Azure Key Vault or\r\n customer-managed keys through Azure Storage service. This helps customers ensure\r\n that their data is secure and access to their services is controlled."
},
"finish_reason": "stop",
"index": 0
}
]
}
補足:chat completion API docs 参考箇所:
14 . テストのために新しい接続を作成します。ポップアップでは、冒頭でメモした、AOAI リソースのAPIキーを入力します。なお、画面遷移してしまうので、URLもメモっておくとよいです
15 . テスト用の情報を入力。未加工の本文にして、サンプルからのインポートで使った本文を入れるとよいです。
16 . テストを実行すると、解析結果が返ってきます。AOAI用のカスタムアプリはこれでOK
参考のswaggerはこちら
swagger: '2.0'
info:
title: 置き換えてください
description: ''
version: '1.0'
host: 置換えてください.openai.azure.com
basePath: /openai/
schemes:
- https
consumes: []
produces: []
paths:
/deployments/{deployment-id}/chat/completions:
post:
responses:
default:
description: default
schema:
type: object
properties:
id:
type: string
description: id
object:
type: string
description: object
created:
type: integer
format: int32
description: created
model:
type: string
description: model
usage:
type: object
properties:
prompt_tokens:
type: integer
format: int32
description: prompt_tokens
completion_tokens:
type: integer
format: int32
description: completion_tokens
total_tokens:
type: integer
format: int32
description: total_tokens
description: usage
choices:
type: array
items:
type: object
properties:
message:
type: object
properties:
role:
type: string
description: role
content:
type: string
description: content
description: message
finish_reason:
type: string
description: finish_reason
index:
type: integer
format: int32
description: index
description: choices
summary: Chat-completions
operationId: Chat-completions
description: GPT-35-Turbo と GPT-4 モデルを使用して、チャット メッセージの入力候補を作成します。
parameters:
- name: deployment-id
in: path
required: true
type: string
- name: api-version
in: query
required: false
type: string
- name: body
in: body
required: false
schema:
type: object
properties:
messages:
type: array
items:
type: object
properties:
role:
type: string
description: role
content:
type: array
items:
type: object
properties:
type:
type: string
description: type
text:
type: string
description: text
image_url:
type: object
properties:
url:
type: string
description: url
detail:
type: string
description: detail
description: image_url
description: content
description: messages
definitions: {}
parameters: {}
responses: {}
securityDefinitions:
API KEY:
type: apiKey
in: header
name: api-key
security:
- API KEY: []
tags: []
Power Apps カスタムコネクタ(Fabricデータ送信)の作成
1 . 同様にFabric 用のカスタムコネクタも作ります。ホストやベースURLを入力※メモで記録したURIから値をもってきます
<メモしたURI部>messages?timeout=60&api-version=2014-01
{
"image": "test2",
"result": ""
}
5 . 作成後、テスト画面に移動します。キーにはメモしたtoken部を利用ください。うまくいかない場合はアクションを削除して再度作成してください。
{
"image": "test2",
"result": "[]"
}
6 . 成功すると、Fabric のイベントストリームでデータが表示されます
参考のswaggerはこちら
swagger: '2.0'
info:
title: 置き換えてください
description: ''
version: '1.0'
host: 置き換えてください
basePath: 置き換えてください
schemes:
- https
consumes: []
produces: []
paths:
/messages:
post:
responses:
default:
description: default
schema: {}
summary: send-message
description: send-message
operationId: Send-message
parameters:
- name: timeout
in: query
required: false
type: integer
- name: api-version
in: query
required: false
type: string
- name: body
in: body
required: false
schema:
type: object
properties:
image:
type: string
description: image
result:
type: string
description: result
definitions: {}
parameters: {}
responses: {}
securityDefinitions:
SAS:
type: apiKey
in: header
name: Authorization
security:
- SAS: []
tags: []
Power Apps カメラアプリの作成
5 . ALTキー押しながらクリックして画像を読み込ませておくとよいでしょう。
6 . ボタンを追加して、OnSelect に以下コマンドをコネクタ名だけ変更して追加。いわゆるシステムプロンプトなどは適宜調整してください。私はテキスト入力コントロールを追加してカロリーをn倍するなどの調整ができるように使っています
Set( ImageJSON, JSON( UploadedImage1.Image, JSONFormat.IncludeBinaryData ) );
ClearCollect(aoaiCollection,
'<コネクタ名に置き換えてください>'.Chatcompletions("<デプロイ名に置換えてください>",
{
'api-version':"2024-02-01",
max_tokens:800,
messages:[
{role:"system",content:[{type:"text",text:"あなたは画像からjson形式のデータを生成するAIです。json形式のデータのみを応答します。コードスニペットやデータ以外の情報を応答に含めてはいけません"}]},
{role:"user",
content:[
{type:"text",text:"画像の中の料理のそれぞれの日本語料理名と日本語での説明、摂取カロリーを推定して。回答はシステムに取り込むため、以下のjson形式にしてください。
[{food:"",kcal:0.0,description:""}]
"},
{type: "image_url",image_url:
{url:Substitute(ImageJSON,"""",""),detail: "auto"}
}
]
}
]
}).choices);
Set(resultText,Substitute(Substitute(First(aoaiCollection).message.content,"```",""),"json",""));
8 . ALTキーを押しながら解析ボタンを押すとラベルに結果が表示されます。
9 . ボタンを追加して、OnSelect にFabricに送信する以下コマンドをコネクタ名だけ変更して追加。
<コネクタ名に置き換えてください>.Send-messages(
{
'api-version':"2014-01",
image:Substitute(ImageJSON,"""",""),
result: resultText,
timeout:60}
);
Notify(
"Fabric にデータ送信しました",
NotificationType.Success
);
10 . ALTキーを押しながら送信ボタンを押して、Fabric 側でも確認ができます。
これでアプリが完成しました
データ変換とPower BI による可視化
1 . Fabric イベントストリームで、あて先をKQLデータベースで選択
6 . イベントハウスに移動してテーブルを見つけたら、右クリックから100行選択をクリック
7 . 自動でクエリ結果が表示されるのでKQL クエリセットとして保存
8 . KQLを置き換えます。テーブル名は適宜変更してください。クエリ結果が表示されたらPower BI レポートを構築を選択
['input-food']
| extend ingest_datetime = ingestion_time()
| mv-expand result
| project
ingest_datetime_JST = datetime_add('hour',9,ingest_datetime),
image,
food = tostring(result.food),
decription=tostring(result.description),
kcal = todecimal(result.kcal)
9 . 簡単に折れ線だけ作成してみます。が、作りにくいので、一旦保存して移動
10 . ワークスペース設定を変えておきます。(画像表示のためなので必須ではありません。)
12 . image 列はカテゴリを画像のURLに変えておきます
13 . レポートを開き、テーブルを追加して微調整したら完成です。
参考
- https://learn.microsoft.com/ja-jp/connectors/custom-connectors/define-blank
- https://learn.microsoft.com/ja-jp/connectors/custom-connectors/use-custom-connector-powerapps
- https://learn.microsoft.com/ja-jp/rest/api/servicebus/send-message-to-queue
- https://zenn.dev/microsoft/articles/azure-openai-latest-api-schema