Skip to content

Commit

Permalink
Merge branch 'master' into abstract_forms
Browse files Browse the repository at this point in the history
  • Loading branch information
tmbo authored Feb 27, 2019
2 parents 1cb8bac + fc12d54 commit b4c32de
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 55 deletions.
29 changes: 21 additions & 8 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,48 @@ This project adheres to `Semantic Versioning`_ starting with version 0.11.0.

.. _master-release:

[Unreleased 0.12.0.aX] - `master`_
[Unreleased 0.13.0.aX] - `master`_
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. note:: This version is not yet released and is under active development.

Added
-----
- add optional `validate_{slot}` methods to `FormAction`
- forms can now be deactivated during the validation function by returning
`self.deactivate()`
- Abstract Actions can now be subclassed
- add warning in case of mismatched version of rasa_core and rasa_core_sdk

Changed
-------

Fixed
-----

Removed
-------

[0.12.2] - 2019-02-17
^^^^^^^^^^^^^^^^^^^^^

Added
-----
- add optional `validate_{slot}` methods to `FormAction`
- forms can now be deactivated during the validation function by returning
`self.deactivate()`
- Function to get latest input channel from the tracker with
``tracker.get_latest_input_channel()``

Changed
-------
- ``self._deactivate()`` method from the ``FormAction`` class has been
renamed to ``self.deactivate()``

Fixed
-----
- changed endpoint function so that it is now accessible with Python as well

[0.12.1] - 2018-11-11
^^^^^^^^^^^^^^^^^^^^^

Fixed
-----
- doc formatting preventing successfull rasa core travis build
- doc formatting preventing successful rasa core travis build

[0.12.0] - 2018-11-11
^^^^^^^^^^^^^^^^^^^^^
Expand Down
10 changes: 10 additions & 0 deletions rasa_core_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Dict, Text, Any, Optional, Iterator, List

import rasa_core_sdk.version
import rasa_core_sdk.cli

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -76,6 +77,7 @@ def current_state(self):
"latest_event_time": latest_event_time,
"paused": self.is_paused(),
"events": self.events,
"latest_input_channel": self.get_latest_input_channel(),
"active_form": self.active_form,
"latest_action_name": self.latest_action_name
}
Expand Down Expand Up @@ -108,6 +110,14 @@ def get_latest_entity_values(self, entity_type):
for x in entities
if x.get("entity") == entity_type)

def get_latest_input_channel(self):
# type: () -> Optional[Text]
"""Get the name of the input_channel of the latest UserUttered event"""

for e in reversed(self.events):
if e.get("event") == "user":
return e.get("input_channel")

def is_paused(self):
# type: () -> bool
"""State whether the tracker is currently paused."""
Expand Down
Empty file added rasa_core_sdk/cli/__init__.py
Empty file.
32 changes: 32 additions & 0 deletions rasa_core_sdk/cli/arguments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import argparse

from rasa_core_sdk.constants import DEFAULT_SERVER_PORT


def action_arg(action):
if "/" in action:
raise argparse.ArgumentTypeError(
'Invalid actions format. Actions file should be a python module '
'and passed with module notation (e.g. directory.actions).')
else:
return action


def add_endpoint_arguments(parser):
parser.add_argument(
'-p', '--port',
default=DEFAULT_SERVER_PORT,
type=int,
help="port to run the server at")
parser.add_argument(
'--cors',
nargs='*',
type=str,
help="enable CORS for the passed origin. "
"Use * to whitelist all origins")
parser.add_argument(
'--actions',
type=action_arg,
default=None,
help="name of action package to be loaded"
)
1 change: 1 addition & 0 deletions rasa_core_sdk/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DEFAULT_SERVER_PORT = 5055
66 changes: 25 additions & 41 deletions rasa_core_sdk/endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,48 +11,24 @@
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
from gevent.pywsgi import WSGIServer

from rasa_core_sdk.cli.arguments import add_endpoint_arguments
from rasa_core_sdk.constants import DEFAULT_SERVER_PORT
from rasa_core_sdk.executor import ActionExecutor
from rasa_core_sdk import ActionExecutionRejection
import rasa_core_sdk

from rasa_core_sdk import utils

DEFAULT_SERVER_PORT = 5055

logger = logging.getLogger(__name__)


def action_arg(action):
if "/" in action:
raise argparse.ArgumentTypeError(
'Invalid actions format. Actions file should be a python module '
'and passed with module notation (e.g. directory.actions).')
else:
return action


def create_argument_parser():
"""Parse all the command line arguments for the run script."""

parser = argparse.ArgumentParser(
description='starts the action endpoint')
parser.add_argument(
'-p', '--port',
default=DEFAULT_SERVER_PORT,
type=int,
help="port to run the server at")
parser.add_argument(
'--cors',
nargs='*',
type=str,
help="enable CORS for the passed origin. "
"Use * to whitelist all origins")
parser.add_argument(
'--actions',
type=action_arg,
default=None,
help="name of action package to be loaded"
)
add_endpoint_arguments(parser)
utils.add_logging_option_arguments(parser)
return parser

Expand Down Expand Up @@ -135,24 +111,32 @@ def check_version_compatibility(core_version):
"".format(core_version, rasa_core_sdk.__version__))


if __name__ == '__main__':
# Running as standalone python application
arg_parser = create_argument_parser()
cmdline_args = arg_parser.parse_args()

logging.basicConfig(level=logging.DEBUG)
logging.getLogger('matplotlib').setLevel(logging.WARN)

utils.configure_colored_logging(cmdline_args.loglevel)

def run(actions, port=DEFAULT_SERVER_PORT, cors='*'):
logger.info("Starting action endpoint server...")
edp_app = endpoint_app(cors_origins=cmdline_args.cors,
action_package_name=cmdline_args.actions)
edp_app = endpoint_app(cors_origins=cors,
action_package_name=actions)

http_server = WSGIServer(('0.0.0.0', cmdline_args.port), edp_app)
http_server = WSGIServer(('0.0.0.0', port), edp_app)

http_server.start()
logger.info("Action endpoint is up and running. on {}"
"".format(http_server.address))

http_server.serve_forever()


def main(args):
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('matplotlib').setLevel(logging.WARN)

utils.configure_colored_logging(args.loglevel)

run(args.actions, args.port, args.cors)


if __name__ == '__main__':
# Running as standalone python application
arg_parser = create_argument_parser()
cmdline_args = arg_parser.parse_args()

main(cmdline_args)
14 changes: 13 additions & 1 deletion rasa_core_sdk/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@
# noinspection PyPep8Naming
def UserUttered(text,
parse_data=None,
timestamp=None):
timestamp=None,
input_channel=None):
return {
"event": "user",
"timestamp": timestamp,
"text": text,
"parse_data": parse_data,
"input_channel": input_channel
}


Expand Down Expand Up @@ -80,6 +82,16 @@ def ReminderScheduled(action_name, trigger_date_time, name=None,
}


# noinspection PyPep8Naming
def ReminderCancelled(action_name, name=None, timestamp=None):
return {
"event": "cancel_reminder",
"timestamp": timestamp,
"action": action_name,
"name": name
}


# noinspection PyPep8Naming
def ActionReverted(timestamp=None):
return {
Expand Down
6 changes: 1 addition & 5 deletions tests/test_endpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@
import rasa_core_sdk.endpoint as ep


def test_endpoint():
pass


def test_arg_parser_actions_params_folder_style():
parser = ep.create_argument_parser()
args = ['--actions', 'actions/act']

with pytest.raises(BaseException) as e:
cmdline_args = parser.parse_args(args)
parser.parse_args(args)
if e is not None:
assert True
else:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_tracker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from rasa_core_sdk import Tracker
from rasa_core_sdk.events import ActionExecuted, UserUttered


def test_latest_input_channel():
tracker = Tracker('default', {},
{'intent': {'name': 'some_intent', 'confidence': 1.0}},
[UserUttered("my message text",
input_channel="superchat"),
ActionExecuted("action_listen")],
False, None, {}, 'action_listen')

assert tracker.get_latest_input_channel() == "superchat"

0 comments on commit b4c32de

Please sign in to comment.