Exemplo 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"]
Exemplo n.º 2
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"]
Exemplo n.º 3
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)
Exemplo n.º 4
0
def send_action(endpoint: EndpointConfig,
                sender_id: Text,
                action_name: Text,
                policy: Optional[Text] = None,
                confidence: Optional[float] = None,
                is_new_action: bool = False) -> Dict[Text, Any]:
    """Log an action to a conversation."""

    payload = ActionExecuted(action_name, policy, confidence).as_dict()

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

    try:
        r = endpoint.request(json=payload, method="post", subpath=subpath)
        return _response_as_json(r)
    except requests.exceptions.HTTPError:
        if is_new_action:
            warning_questions = questionary.confirm(
                "WARNING: You have created a new action: '{}', "
                "which was not successfully executed. "
                "If this action does not return any events, "
                "you do not need to do anything. "
                "If this is a custom action which returns events, "
                "you are recommended to implement this action "
                "in your action server and try again."
                "".format(action_name))
            _ask_or_abort(warning_questions, sender_id, endpoint)

            payload = ActionExecuted(action_name).as_dict()

            return send_event(endpoint, sender_id, payload)
        else:
            logger.error("failed to execute action!")
            raise
Exemplo n.º 5
0
def retrieve_domain(endpoint: EndpointConfig) -> Dict[Text, Any]:
    """Retrieve the domain from core."""

    r = endpoint.request(method="get",
                         subpath="/domain",
                         headers={"Accept": "application/json"})

    return _response_as_json(r)
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo 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)
Exemplo n.º 9
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)
Exemplo n.º 10
0
def _pull_model_and_fingerprint(model_server: EndpointConfig,
                                model_directory: Text,
                                fingerprint: Optional[Text]
                                ) -> Optional[Text]:
    """Queries the model server and returns the value of the response's

    <ETag> header which contains the model hash."""
    header = {"If-None-Match": fingerprint}
    try:
        logger.debug("Requesting model from server {}..."
                     "".format(model_server.url))
        response = model_server.request(method="GET",
                                        headers=header,
                                        timeout=DEFAULT_REQUEST_TIMEOUT)
    except RequestException as e:
        logger.warning("Tried to fetch model from server, but couldn't reach "
                       "server. We'll retry later... Error: {}."
                       "".format(e))
        return None

    if response.status_code in [204, 304]:
        logger.debug("Model server returned {} status code, indicating "
                     "that no new model is available. "
                     "Current fingerprint: {}"
                     "".format(response.status_code, fingerprint))
        return response.headers.get("ETag")
    elif response.status_code == 404:
        logger.debug("Model server didn't find a model for our request. "
                     "Probably no one did train a model for the project "
                     "and tag combination yet.")
        return None
    elif response.status_code != 200:
        logger.warning("Tried to fetch model from server, but server response "
                       "status code is {}. We'll retry later..."
                       "".format(response.status_code))
        return None

    zip_ref = zipfile.ZipFile(IOReader(response.content))
    zip_ref.extractall(model_directory)
    logger.debug("Unzipped model to {}"
                 "".format(os.path.abspath(model_directory)))

    # get the new fingerprint
    return response.headers.get("ETag")
Exemplo n.º 11
0
def send_message(
        endpoint: EndpointConfig,
        sender_id: Text,
        message: Text,
        parse_data: Optional[Dict[Text, Any]] = None) -> Dict[Text, Any]:
    """Send a user message to a conversation."""

    payload = {
        "sender": UserUttered.type_name,
        "message": message,
        "parse_data": parse_data
    }

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

    return _response_as_json(r)