1. はじめに
- dialogflow CXのwebhookで、pythonを使ったCloudFunctionの書き方を覚えた。
2. 経緯
- dialogflow CXのチュートリアルをやっていると、webhookでレスポンスを作れるとのこと。
- チュートリアルでは、webhookの先のCloudFunctionsではGoで書かれていたので、そのままコピペしてたけれど、自分で書くならpythonになるだろうなと思い、サンプルを調べる。
まず、Goのサンプルはここに記載のとおり
⇓このへんがメインのところと思われます。
// confirm handles webhook calls using the "confirm" tag.
func confirm(request webhookRequest) (webhookResponse, error) {
// Create a text message that utilizes the "size" and "color"
// parameters provided by the end-user.
// This text message is used in the response below.
t := fmt.Sprintf("You can pick up your order for a %s %s shirt in 5 days.",
request.SessionInfo.Parameters["size"],
request.SessionInfo.Parameters["color"])
// Create session parameters that are populated in the response.
// The "cancel-period" parameter is referenced by the agent.
// This example hard codes the value 2, but a real system
// might look up this value in a database.
p := map[string]interface{}{"cancel-period": "2"}
// Build and return the response.
response := webhookResponse{
FulfillmentResponse: fulfillmentResponse{
Messages: []responseMessage{
{
Text: text{
Text: []string{t},
},
},
},
},
SessionInfo: sessionInfo{
Parameters: p,
},
}
return response, nil
}
- これをpythonに書き直そうということで、bingのchatgptに問い合わせたところいい回答をもらえなかったので、Goのソースからpythonに書き直すならこんな感じかと作成。
- 苦労した点としては、dialogflowから受け取る際の値の取り出し方と、戻す際のFulfillmentResponseとSessionInfoの設定の仕方。
- 下記の2サイトの情報を頼りに、それぞれ解決した。
https://stackoverflow.com/questions/64493735/dialogflow-cx-using-webhook-fulfilment-to-reply-user
https://cloud.google.com/dialogflow/cx/docs/reference/rpc/google.cloud.dialogflow.cx.v3beta1#webhookresponse - 2021年に変数の大文字などが変更になったらしく、そこも混乱した一因だった。。。
3. こんな感じに書けばよい
import functions_framework
@functions_framework.http
def hello_http(request):
"""Handles a Dialogflow CX webhook request."""
request_dict = request.get_json()
size = request_dict["sessionInfo"]['parameters']["size"]
color = request_dict["sessionInfo"]['parameters']["color"]
return json.dumps(
{
"fulfillment_response": {
"messages": [
{
"text": {
"text": ["You can pick up your order for a {} {} shirt in 5 days.".format(size,color)],
"allow_playback_interruption": False,
}
}
]
},
"session_info": {
"parameters": {"cancel-period": "500"}
}
}
)
良く見たらここにもちょっと書き方があった。
20230707追加;
rich messageにして返したい場合のレスポンスの書き方:
fulfillment_response = {
'messages': [{
までは上と同様。
response_json = jsonify(
fulfillment_response = {
'messages': [{
"payload": {
"richContent": [[{
"actionLink": "https://assistant.google.com/",
"subtitle": "This is the body text of a card. You can even use line\n breaks and emoji! 💁",
"title": "Title: this is a card title",
"type": "info"
}]]
}
}]
}
)
return response_json