Rasa调用外部API不会抛出异常

时间:2019-10-08 09:36:34

标签: nlp rasa-core rasa nlua

我使用rasa构建了一个小型聊天机器人。我希望我的机器人通过调用一个外部api来开个玩笑,但我得到的响应为None。

我在这里附加API调用方法。

class Question(models.Model):

    class Meta:
        db_table = 'name_of_question_table'

在我的domain.yml中,我有个玩笑响应插槽

class ApiAction(Action):
    def name(self):
        return "action_get_jokes"

    def run(self, dispatcher, tracker, domain):
        r = requests.get('https://api.chucknorris.io/jokes/random')
        response = r.text
        json_data= json.loads(response)
        for k,v in json_data.items():
            if k == 'value':
                return [SlotSet("jokes_response",v)]
            else:
                return [SlotSet("jokes_response","404 not found")]
slots:
  jokes_response:
    type: unfeaturized
    auto_fill: false

在我尝试同时使用 main 和直接指定'-action_get_jokes'的操作下,但没有一个起作用。

utter_jokes:
  - text: "Here you go : {jokes_response} "
  - text: "There you go: {jokes_response} "

1 个答案:

答案 0 :(得分:0)

我没有使用插槽,但是我尝试了您的用例并以另一种方式成功。而且我也不认为您需要在“操作”部分的域文件中提供 ApiAction

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher    
import requests
import json
class ApiAction(Action):

def name(self) -> Text:
    return "action_get_jokes"

def run(self, dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
    r = requests.get('https://api.chucknorris.io/jokes/random')
    response = r.text
    json_data= json.loads(response)

    reply = 'Here you go '
    if (json_data["value"]):
        reply = reply + json_data["value"]
    else:
        reply = reply + "404 not found"

    dispatcher.utter_message(reply)

    return []