LoginSignup
15
16

More than 5 years have passed since last update.

Dialogflow(旧:API.AI) Python SDKを使ってみる #dialogflow

Last updated at Posted at 2017-02-23

API.AI Python SDKを使ってみる

API.AIをPythonのコードから触ってみたいと思います。API.AIが何か知らない方はこちらをご参照ください。
今回のサンプルはこちらで作成したプロジェクトをベースに進めていきたいと思います。

API.AI Python SDKをインストール

Git hubにSDKのプロジェクトが公開されています。簡単なサンプルも入っているのでオススメです。

pipでもインストール可能です。

pip install apiai

CLIENT ACCESS TOKEN を取得する

コンソール上で任意のプロジェクトを選択し歯車マークをクリックするとTokenを確認することができる。Tokenをコピーしておきましょう。

Screen Shot 0029-02-23 at 16.31.50.png

試してみる

こちらで作成したラーメンを注文するIntentに対して「味噌ラーメンをお願いします。」と送信してみます。

CLIENT ACCESS TOKEN に先ほど取得したTokenを入れましょう。

Pythonコード

send_text_example.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os.path
import sys

try:
    import apiai
except ImportError:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
    )
    import apiai

CLIENT_ACCESS_TOKEN = 'CLIENT ACCESS TOKEN'

def main():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'ja'  # optional, default value equal 'en'

    request.session_id = '<SESSION ID, UNIQUE FOR EACH USER>'

    request.query = u'味噌ラーメンをお願いします。'

    response = request.getresponse()

    print (response.read())


if __name__ == '__main__':
    main()

実行

python send_text_example.py

レスポンス

response
{
  "id": "",
  "timestamp": "2017-02-23T07:37:13.582Z",
  "lang": "ja",
  "result": {
    "source": "agent",
    "resolvedQuery": "味噌ラーメンをお願いします。",
    "action": "order",
    "actionIncomplete": false,
    "parameters": {
      "RamenMenu": "miso_ramen"
    },
    "contexts": [],
    "metadata": {
      "intentId": "",
      "webhookUsed": "false",
      "webhookForSlotFillingUsed": "false",
      "intentName": "Order"
    },
    "fulfillment": {
      "speech": "かしこまりました。",
      "messages": [
        {
          "type": 0,
          "speech": "かしこまりました。"
        }
      ]
    },
    "score": 1.0
  },
  "status": {
    "code": 200,
    "errorType": "success"
  },
  "sessionId": "<SESSION_ID,_UNIQUE_FOR_EACH_USER>"
}

参考リンク

API.AI Docs

15
16
1

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
15
16