Ejemplo n.º 1
0
def test_endpoint_config():
    endpoint = EndpointConfig(
            "https://abc.defg/",
            params={"A": "B"},
            headers={"X-Powered-By": "Rasa"},
            basic_auth={"username": "******",
                        "password": "******"},
            token="mytoken",
            token_name="letoken"
    )

    httpretty.register_uri(
            httpretty.POST,
            'https://abc.defg/test',
            status=500,
            body='')

    httpretty.enable()
    endpoint.request("post", subpath="test",
                     content_type="application/text",
                     json={"c": "d"},
                     params={"P": "1"})
    httpretty.disable()

    r = httpretty.latest_requests[-1]

    assert json.loads(str(r.body.decode("utf-8"))) == {"c": "d"}
    assert r.headers.get("X-Powered-By") == "Rasa"
    assert r.headers.get("Authorization") == "Basic dXNlcjpwYXNz"
    assert r.querystring.get("A") == ["B"]
    assert r.querystring.get("P") == ["1"]
    assert r.querystring.get("letoken") == ["mytoken"]
Ejemplo n.º 2
0
def load_rasa_agent():
      ## path should be changed
    interpreter = RasaNLUInterpreter("./rasa/models/nlu/default/chatbot")
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    app.rasa_agent = Agent.load("./rasa/models/dialogue",
        interpreter=interpreter,action_endpoint=action_endpoint)
    
    # lemma used to preprocess the input
    app.lemma = nltk.wordnet.WordNetLemmatizer()
Ejemplo n.º 3
0
def test_remote_clients(http_app):
    client = RasaCoreClient(EndpointConfig(http_app))

    cid = str(uuid.uuid1())
    client.respond("/greet", cid)

    clients = client.clients()

    assert cid in clients
Ejemplo n.º 4
0
def rasa_config():
    # Set the actions endpoint
    action_endpoint = EndpointConfig(url='http://localhost:5055/webhook')

    # Load the trained RASA models
    interpreter = RasaNLUInterpreter('./models/current/nlu')
    return Agent.load('./models/current/dialogue',
                      interpreter=interpreter,
                      action_endpoint=action_endpoint)
Ejemplo n.º 5
0
def replace_events(endpoint: EndpointConfig, sender_id: Text,
                   evts: List[Dict[Text, Any]]) -> Dict[Text, Any]:
    """Replace all the events of a conversation with the provided ones."""

    subpath = "/conversations/{}/tracker/events".format(sender_id)

    r = endpoint.request(json=evts, method="put", subpath=subpath)

    return _response_as_json(r)
Ejemplo n.º 6
0
def test_nlg(http_nlg, default_agent_path):
    sender = str(uuid.uuid1())

    nlg_endpoint = EndpointConfig.from_dict({"url": http_nlg})
    agent = Agent.load(default_agent_path, None, generator=nlg_endpoint)

    response = agent.handle_message("/greet", sender_id=sender)
    assert len(response) == 1
    assert response[0] == {"text": "Hey there!", "recipient_id": sender}
def run_test_bot(serve_forever=True):
    interpreter = RasaNLUInterpreter('./models/nlu/default/testbotnlu')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook/")
    agent = Agent.load('./models/dialogue',
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)
    rasa_core.run.serve_application(agent, channel='cmdline')

    return agent
Ejemplo n.º 8
0
def send_event(endpoint: EndpointConfig, sender_id: Text,
               evt: Dict[Text, Any]) -> Dict[Text, Any]:
    """Log an event to a conversation."""

    subpath = "/conversations/{}/tracker/events".format(sender_id)

    r = endpoint.request(json=evt, method="post", subpath=subpath)

    return _response_as_json(r)
Ejemplo n.º 9
0
def test_formbot_example():
    sys.path.append("examples/formbot/")

    p = "examples/formbot/"
    stories = os.path.join(p, "data", "stories.md")
    endpoint = EndpointConfig("https://abc.defg/webhooks/actions")
    endpoints = AvailableEndpoints(action=endpoint)
    agent = train_dialogue_model(os.path.join(p, "domain.yml"),
                                 stories,
                                 os.path.join(p, "models", "dialogue"),
                                 endpoints=endpoints,
                                 policy_config="rasa_core/default_config.yml")
    response = {
        'events': [{
            'event': 'form',
            'name': 'restaurant_form',
            'timestamp': None
        }, {
            'event': 'slot',
            'timestamp': None,
            'name': 'requested_slot',
            'value': 'cuisine'
        }],
        'responses': [{
            'template': 'utter_ask_cuisine'
        }]
    }

    httpretty.register_uri(httpretty.POST,
                           'https://abc.defg/webhooks/actions',
                           body=json.dumps(response))

    httpretty.enable()

    responses = agent.handle_text("/request_restaurant")

    httpretty.disable()

    assert responses[0]['text'] == 'what cuisine?'

    response = {
        "error": "Failed to validate slot cuisine with action restaurant_form",
        "action_name": "restaurant_form"
    }

    httpretty.register_uri(httpretty.POST,
                           'https://abc.defg/webhooks/actions',
                           status=400,
                           body=json.dumps(response))

    httpretty.enable()

    responses = agent.handle_text("/chitchat")

    httpretty.disable()

    assert responses[0]['text'] == 'chitchat'
Ejemplo n.º 10
0
async def test_endpoint_config():
    with aioresponses() as mocked:
        endpoint = EndpointConfig("https://example.com/",
                                  params={"A": "B"},
                                  headers={"X-Powered-By": "Rasa"},
                                  basic_auth={
                                      "username": "******",
                                      "password": "******"
                                  },
                                  token="mytoken",
                                  token_name="letoken",
                                  type="redis",
                                  port=6379,
                                  db=0,
                                  password="******",
                                  timeout=30000)

        mocked.post('https://example.com/test?A=B&P=1&letoken=mytoken',
                    payload={"ok": True},
                    repeat=True,
                    status=200)

        await endpoint.request("post",
                               subpath="test",
                               content_type="application/text",
                               json={"c": "d"},
                               params={"P": "1"})

        r = latest_request(mocked, 'post',
                           "https://example.com/test?A=B&P=1&letoken=mytoken")

        assert r

        assert json_of_latest_request(r) == {"c": "d"}
        assert r[-1].kwargs.get("params", {}).get("A") == "B"
        assert r[-1].kwargs.get("params", {}).get("P") == "1"
        assert r[-1].kwargs.get("params", {}).get("letoken") == "mytoken"

        # unfortunately, the mock library won't report any headers stored on
        # the session object, so we need to verify them separately
        async with endpoint.session() as s:
            assert s._default_headers.get("X-Powered-By") == "Rasa"
            assert s._default_auth.login == "user"
            assert s._default_auth.password == "pass"
Ejemplo n.º 11
0
def load_agent():
    action_endpoint = EndpointConfig(url="http://localhost:8000/webhook")
    interpreter = RasaNLUInterpreter("./models/default/nlu")

    agent = Agent.load(
        "./models/dialogue",
        interpreter=interpreter,
        action_endpoint=action_endpoint,
    )
    return agent
Ejemplo n.º 12
0
    def __init__(self, model_name=None, endpoint=None, project_name='default'):
        # type: (Text, EndpointConfig, Text) -> None

        self.model_name = model_name
        self.project_name = project_name

        if endpoint:
            self.endpoint = endpoint
        else:
            self.endpoint = EndpointConfig(constants.DEFAULT_SERVER_URL)
Ejemplo n.º 13
0
def run_happsales_bot(serve_forever=True):
    interpreter = RasaNLUInterpreter(
        '/home/saradindu/dev/Work-II/Happsales/models/nlu/default/happsales')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('/home/saradindu/dev/Work-II/Happsales/models/dialogue',
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)
    rasa_core.run.serve_application(agent, channel='cmdline')

    return agent
Ejemplo n.º 14
0
def test_sorted_predict(http_app, app):
    client = RasaCoreClient(EndpointConfig(http_app))
    cid = str(uuid.uuid1())
    for event in test_events[:3]:
        client.append_event_to_tracker(cid, event)
    response = app.post("http://dummy/conversations/{}/predict".format(cid))
    content = response.get_json()
    scores = content["scores"]
    sorted_scores = sorted(scores, key=lambda k: (-k['score'], k['action']))
    assert scores == sorted_scores
Ejemplo n.º 15
0
def run_malu_bot(serve_forever=True):
    interpreter = RasaNLUInterpreter(
        './models/nlu/default/malu')  #carrega o modelo de nlu
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('./models/dialogue',
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)  #carregar um agente
    serve_application(agent, channel='cmdline')

    return agent
Ejemplo n.º 16
0
def request_prediction(
    endpoint: EndpointConfig,
    sender_id: Text
) -> Dict[Text, Any]:
    """Request the next action prediction from core."""

    r = endpoint.request(method="post",
                         subpath="/conversations/{}/predict".format(sender_id))

    return _response_as_json(r)
Ejemplo n.º 17
0
def test_tracker_store_endpoint_config_loading():
    cfg = utils.read_endpoint_config(DEFAULT_ENDPOINTS_FILE, "tracker_store")

    assert cfg == EndpointConfig.from_dict({
        "type": "redis",
        "url": "localhost",
        "port": 6379,
        "db": 0,
        "password": "******",
        "timeout": 30000
    })
Ejemplo n.º 18
0
def run_core(core_model_path, nlu_model_path, action_endpoint_url,
             slack_token):
    nlu_interpreter = RasaNLUInterpreter(nlu_model_path)
    action_endpoint = EndpointConfig(url=action_endpoint_url)
    agent = Agent.load(core_model_path,
                       interpreter=nlu_interpreter,
                       action_endpoint=action_endpoint)
    input_channel = SlackInput(slack_token)
    agent.handle_channels([input_channel], 5002, serve_forever=True)

    return agent
Ejemplo n.º 19
0
def send_finetune(
    endpoint: EndpointConfig,
    evts: List[Dict[Text, Any]]
) -> Dict[Text, Any]:
    """Finetune a core model on the provided additional training samples."""

    r = endpoint.request(json=evts,
                         method="post",
                         subpath="/finetune")

    return _response_as_json(r)
Ejemplo n.º 20
0
def test_remote_action_endpoint_not_running(default_dispatcher_collecting,
                                            default_domain):
    tracker = DialogueStateTracker("default", default_domain.slots)

    endpoint = EndpointConfig("https://abc.defg/webhooks/actions")
    remote_action = action.RemoteAction("my_action", endpoint)

    with pytest.raises(Exception) as execinfo:
        remote_action.run(default_dispatcher_collecting, tracker,
                          default_domain)
    assert "Failed to execute custom action." in str(execinfo.value)
Ejemplo n.º 21
0
def test_predict(http_app, app):
    client = RasaCoreClient(EndpointConfig(http_app))
    cid = str(uuid.uuid1())
    for event in test_events[:2]:
        client.append_event_to_tracker(cid, event)
    out = app.get('/domain', headers={'Accept': 'yml'})
    domain = TemplateDomain.from_yaml(out.get_data())
    tracker = client.tracker(cid, domain)
    event_dicts = [ev.as_dict() for ev in tracker.applied_events()]
    response = app.post('/predict', json=event_dicts)
    assert response.status_code == 200
Ejemplo n.º 22
0
def run_weather_online(interpreter, domain_file="weather_domain.yml", training_data_file = './data/stories.md'):
	action_endpoint = EndpointConfig(url = "http://localhost:5005/webhook")
	
	agent = Agent(domain_file, policies = [MemoizationPolicy(max_history = 2), KerasPolicy(max_history = 3, epochs = 3, batch_size = 50)], interpreter = interpreter, 
				  action_endpoint = action_endpoint)
	
	training_data = agent.load_data(training_data_file)
	
	agent.train(training_data)
	interactive.run_interactive_learning(agent, training_data_file)
	
	return agent
def run_restaurant_bot(serve_forever=True):
    interpreter = RasaNLUInterpreter('./models/nlu/default/restaurantnlu')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('./models/dialogue',
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)

    rasa_core.run.serve_application(agent, channel='cmdline')
    #if serve_forever:
    #	agent.handle_channel(ConsoleInputChannel())

    return agent
Ejemplo n.º 24
0
async def test_formbot_example():
    sys.path.append("examples/formbot/")

    p = "examples/formbot/"
    stories = os.path.join(p, "data", "stories.md")
    endpoint = EndpointConfig("https://example.com/webhooks/actions")
    endpoints = AvailableEndpoints(action=endpoint)
    agent = await train(os.path.join(p, "domain.yml"),
                        stories,
                        os.path.join(p, "models", "dialogue"),
                        endpoints=endpoints,
                        policy_config="rasa_core/default_config.yml")
    response = {
        'events': [{
            'event': 'form',
            'name': 'restaurant_form',
            'timestamp': None
        }, {
            'event': 'slot',
            'timestamp': None,
            'name': 'requested_slot',
            'value': 'cuisine'
        }],
        'responses': [{
            'template': 'utter_ask_cuisine'
        }]
    }

    with aioresponses() as mocked:
        mocked.post('https://example.com/webhooks/actions',
                    payload=response,
                    repeat=True)

        responses = await agent.handle_text("/request_restaurant")

        assert responses[0]['text'] == 'what cuisine?'

    response = {
        "error": "Failed to validate slot cuisine with action "
        "restaurant_form",
        "action_name": "restaurant_form"
    }

    with aioresponses() as mocked:
        # noinspection PyTypeChecker
        mocked.post('https://example.com/webhooks/actions',
                    repeat=True,
                    exception=ClientResponseError(400, "",
                                                  json.dumps(response)))

        responses = await agent.handle_text("/chitchat")

        assert responses[0]['text'] == 'chitchat'
Ejemplo n.º 25
0
def run(serve_forever=True):
    interpreter = RasaNLUInterpreter("models/nlu/default/current")
    action_endpoint = EndpointConfig(url="http://0.0.0.0:5055/webhook")
    agent = Agent.load("models/dialogue",
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)
    print("Your bot is ready to talk! Type your messages here or send 'stop'")
    while True:
        responses = agent.handle_text(input())
        for response in responses:
            print(response["text"])
    return agent
Ejemplo n.º 26
0
def test_nlg(http_nlg, default_agent_path):
    sender = str(uuid.uuid1())

    nlg_endpoint = EndpointConfig.from_dict({
        "url": http_nlg
    })
    agent = Agent.load(default_agent_path, None,
                       generator=nlg_endpoint)

    response = agent.handle_message("/greet", sender_id=sender)
    assert len(response) == 1
    assert response[0] == {"text": "Hey there!", "recipient_id": sender}
Ejemplo n.º 27
0
def agnt(st):
    nlu_interpreter = RasaNLUInterpreter('/app/models/rasa_nlu/current/nlu')

    core='/app/models/rasa_core'

    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")


    agent = Agent.load(path=core, interpreter = nlu_interpreter, action_endpoint = action_endpoint)

    input_channel = SlackInput(st)
    agent.handle_channels([input_channel], 5005, serve_forever=True)
Ejemplo n.º 28
0
def test_remote_append_events(http_app):
    client = RasaCoreClient(EndpointConfig(http_app))

    cid = str(uuid.uuid1())

    client.append_events_to_tracker(cid, test_events[:2])

    tracker = client.tracker_json(cid)

    evts = tracker.get("events")
    expected = [ActionExecuted(ACTION_LISTEN_NAME)] + test_events[:2]
    assert events.deserialise_events(evts) == expected
def run_recruitment_bot():
    '''
    Initialize bot for chat.
    :return: agent
    '''
    interpreter = RasaNLUInterpreter('./models/nlu/default/current')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('./models/dialogue',
                       interpreter=interpreter,
                       action_endpoint=action_endpoint)
    rasa_core.run.serve_application(agent, channel='cmdline')

    return agent
Ejemplo n.º 30
0
def train_interactive():
    current_directory = os.path.dirname(os.path.realpath(__file__))
    domain_file = 'domain.yml'
    interpreter = RasaNLUInterpreter(current_directory + '/agent-data/models/nlu/default/current')
    action_endpoint = EndpointConfig(url=actionIP)
    stories_file = current_directory + '/agent-data/data/stories.md'
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(max_history=5), KerasPolicy()],
                  interpreter=interpreter, action_endpoint=action_endpoint)
    data = agent.load_data(stories_file)
    agent.train(data)
    interactive.run_interactive_learning(agent, stories_file)
    return agent
Ejemplo n.º 31
0
def load_agent():
    p = "examples/formbot/"
    strpath = os.path.join(p, "models", "dialogue")
    endpoint = EndpointConfig("http://localhost:5055/webhook")
    endpoints = AvailableEndpoints(action=endpoint)
    loaded = Agent.load(strpath,
                        interpreter=RegexInterpreter(),
                        action_endpoint=endpoints.action)
    # loaded = Agent.load(strpath, interpreter=RegexInterpreter())
    responses = loaded.handle_text("/request_restaurant")
    print(responses[0])
    responses = loaded.handle_text("/chitchat")
    print(responses)
Ejemplo n.º 32
0
def retrieve_tracker(
        endpoint: EndpointConfig,
        sender_id: Text,
        verbosity: EventVerbosity = EventVerbosity.ALL) -> Dict[Text, Any]:
    """Retrieve a tracker from core."""

    path = "/conversations/{}/tracker?include_events={}".format(
        sender_id, verbosity.name)
    r = endpoint.request(method="get",
                         subpath=path,
                         headers={"Accept": "application/json"})

    return _response_as_json(r)
Ejemplo n.º 33
0
def test_agent_with_model_server(tmpdir, zipped_moodbot_model):
    fingerprint = 'somehash'
    model_endpoint_config = EndpointConfig.from_dict(
        {"url": 'http://server.com/model/default_core@latest'}
    )

    # mock a response that returns a zipped model
    with io.open(zipped_moodbot_model, 'rb') as f:
        responses.add(responses.GET,
                      model_endpoint_config.url,
                      headers={"ETag": fingerprint},
                      body=f.read(),
                      content_type='application/zip',
                      stream=True)
    agent = rasa_core.agent.load_from_server(model_server=model_endpoint_config)
    assert agent.fingerprint == fingerprint
Ejemplo n.º 34
0
def test_nlg_endpoint_config_loading():
    cfg = utils.read_endpoint_config(DEFAULT_ENDPOINTS_FILE, "nlg")

    assert cfg == EndpointConfig.from_dict({
        "url": "http://localhost:5055/nlg"
    })