def run_remote(): from rasa_core.remote import RemoteAgent from rasa_core.utils import EndpointConfig logging.basicConfig(level="DEBUG") from rasa_core.channels.rasa_chat import RasaChatInput from rasa_addons.webchat import WebChatInput, SocketInputChannel # definte the input channels for the platform and the chat widget rasa_in = RasaChatInput(config.platform_api) widget_in = WebChatInput(static_assets_path=os.path.join( os.path.dirname(os.path.realpath(__file__)), 'static')) input_channel = SocketInputChannel(config.self_port, "/", rasa_in, widget_in) # define the core endpoint core_endpoint_config = EndpointConfig(url=config.remote_core_endpoint, token=config.rasa_core_token) # define the nlg endpoint nlg_endpoint_config = EndpointConfig(url=config.rasa_nlg_endpoint, token=config.rasa_platform_token) # start the remote agent agent = RemoteAgent.load(config.core_model_dir, core_endpoint=core_endpoint_config, nlg_endpoint=nlg_endpoint_config) agent.handle_channel(input_channel)
def run_recipe_bot(): interpreter = RasaNLUInterpreter('./models/nlu/default/grandmarecipes') 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
def run_bot_online(interpreter, domain_file="domain.yml", training_data_file='data/stories.md'): ''' This function trains the bot in an interactive manner :param interpreter: NLU Interpreter :param domain_file: Domain file :param training_data_file: Chat story board file :return: Agent ''' action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent(domain_file, policies=[ MemoizationPolicy(max_history=3), KerasPolicy(max_history=5, epochs=300, batch_size=50) ], interpreter=interpreter, action_endpoint=action_endpoint) data = agent.load_data(training_data_file) agent.train(data) interactive.run_interactive_learning(agent, training_data_file) return agent
def __init__(self, log): self.logger = log directorioNLU = 'model/default/Jarvis' directorioDialogo = 'model/dialogue' if (os.path.isdir(directorioNLU)): self.interpreter = RasaNLUInterpreter( model_directory=directorioNLU) if (os.path.isdir(directorioDialogo)): with open("config/endpoint.yml", 'r') as stream: try: config = yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) action_endopoint = EndpointConfig( url=config["action_endpoint"]["url"]) tracker_store = MongoTrackerStore( domain=Domain.load('model/dialogue/domain.yml'), host=config["tracker_store"]["url"], db=config["tracker_store"]["db"], username=config["tracker_store"]["username"], password=config["tracker_store"]["password"]) self.agent = Agent.load(directorioDialogo, interpreter=self.interpreter, action_endpoint=action_endopoint, tracker_store=tracker_store) self._slots = {}
def run_tracker_bot(serve_forever=True): interpreter = RasaNLUInterpreter('./models/tracker/default/trackermodel') 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
def run_weather_bot(serve_forever=True): interpreter = RasaNLUInterpreter('./models/nlu/default/nlu') action_endpoint = EndpointConfig(url="http://localhost:4040") agent = Agent.load('./models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint) rasa_core.run.serve_application(agent ,channel='cmdline') return agent
def run_bot(interpreter, domain_file="domain.yml", training_data_file='./data/stories.md'): action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent(domain_file, policies=[MemoizationPolicy(max_history=2), KerasPolicy()], interpreter=interpreter, action_endpoint=action_endpoint) data = agent.load_data(training_data_file) """ agent.train(data, batch_size=50, epochs=200, max_training_samples=300) online.serve_agent(agent) online.ser """ agent.persist('./models/dialogue') return agent
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"]
def run(serve_forever=True): AvailableEndpoints = namedtuple('AvailableEndpoints', 'nlg ' 'nlu ' 'action ' 'model') _endpoints = EndpointConfig(url="http://localhost:5055/webhook") try: endpoints = AvailableEndpoints(action=_endpoints, nlg=None, nlu=None, model=None) _interpreter = RasaNLUInterpreter("models/current/nlu/") _agent = load_agent("models/current/dialogue", interpreter=_interpreter, endpoints=endpoints) serve_application( _agent, "cmdline", constants.DEFAULT_SERVER_PORT, ) except: raise Exception("Failed to run")
def _serve_application(app, stories, finetune=False, serve_forever=True, skip_visualization=False): # type: (Flask, Text, bool, bool, bool) -> WSGIServer """Start a core server and attach the interactive learning IO.""" if not skip_visualization: _add_visualization_routes(app, "story_graph.dot") http_server = WSGIServer(('0.0.0.0', DEFAULT_SERVER_PORT), app, log=None) logger.info("Rasa Core server is up and running on " "{}".format(DEFAULT_SERVER_URL)) http_server.start() endpoint = EndpointConfig(url=DEFAULT_SERVER_URL) _start_interactive_learning_io(endpoint, stories, http_server.stop, finetune=finetune, skip_visualization=skip_visualization) if serve_forever: try: http_server.serve_forever() except Exception as exc: logger.exception(exc) return http_server
def test_callback_channel(): from rasa_core.channels.callback import CallbackInput from rasa_core.agent import Agent from rasa_core.interpreter import RegexInterpreter # load your trained agent agent = Agent.load(MODEL_PATH, interpreter=RegexInterpreter()) input_channel = CallbackInput( # URL Core will call to send the bot responses endpoint=EndpointConfig("http://localhost:5004")) # set serve_forever=True if you want to keep the server running s = agent.handle_channels([input_channel], 5004, serve_forever=False) # END DOC INCLUDE # the above marker marks the end of the code snipped included # in the docs try: assert s.started routes_list = utils.list_routes(s.application) assert routes_list.get("/webhooks/callback/").startswith( 'callback_webhook.health') assert routes_list.get("/webhooks/callback/webhook").startswith( 'callback_webhook.webhook') finally: s.stop()
def run_laliga_bot(serve_forever=True): interpreter = RasaNLUInterpreter(r'.\LaLiga_bot\models\laligamodelnlu\nlumodel') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load(r'.\LaLiga_bot\models\dialogue', interpreter=interpreter, action_endpoint=action_endpoint) rasa_core.run.serve_application(agent ,channel='cmdline') return agent
def run_weather_online(interpreter, domain_file='weather_domain.yml', training_data_file='data/stories.md'): action_endpoint = EndpointConfig(url="http://localhost:5000/webhook") fallback = FallbackPolicy(fallback_action_name="action_default_fallback", core_threshold=0.8, nlu_threshold=0.8) agent = Agent('./weather_domain.yml', policies=[ MemoizationPolicy(max_history=2, ), KerasPolicy(epochs=500, batch_size=50, validation_split=0.2), fallback ], interpreter=interpreter, action_endpoint=action_endpoint) data_ = agent.load_data(training_data_file, augmentation_factor=50) agent.train(data_) interactive.run_interactive_learning(agent, training_data_file, skip_visualization=True) # agent.handle_channels(input_channel) return agent
def test_remote_client(http_app, default_agent, tmpdir): model_path = tmpdir.join("persisted_model").strpath default_agent.persist(model_path) remote_agent = RemoteAgent.load(model_path, EndpointConfig(http_app)) message = UserMessage("""/greet{"name":"Rasa"}""", output_channel=CollectingOutputChannel()) remote_agent.process_message(message) tracker = remote_agent.core_client.tracker_json("default") assert len(tracker.get("events")) == 6 # listen assert tracker["events"][0]["name"] == "action_listen" # this should be the utterance assert tracker["events"][1]["text"] == """/greet{"name":"Rasa"}""" # set slot event assert tracker["events"][2]["value"] == "Rasa" # utter action assert tracker["events"][3]["name"] == "utter_greet" # this should be the bot utterance assert tracker["events"][4]["text"] == "hey there Rasa!" # listen assert tracker["events"][5]["name"] == "action_listen"
def load_agent(): nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/restaurantbot/') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter, action_endpoint=action_endpoint) return agent
def train_dialog(dialog_training_data_file, domain_file, path_to_model='models/dialogue'): logging.basicConfig(level='INFO') logging.info(dialog_training_data_file) # Action to be called if the confidence of intent / action is below the threshold fallback = FallbackPolicy( fallback_action_name="action_default_fallback", core_threshold=0.3, # Define the threshold that you need to capture nlu_threshold=0.3) # Configuring the endpoint webhook core_endpoint_config = EndpointConfig(url='http://localhost:5055/webhook') # Configuring the agent agent = Agent(domain_file, policies=[MemoizationPolicy(max_history=2), fallback], interpreter=RasaNLUInterpreter('models/nlu/default/chat'), action_endpoint=core_endpoint_config) # Load the stories for training the dialog training_data = agent.load_data(dialog_training_data_file) # Start training the dialog agent.train(training_data) # Save the training data agent.persist(path_to_model) # Run interactive learning # interactive.run_interactive_learning(agent, dialog_training_data_file, skip_visualization=True) return agent
def test_remote_action_logs_events(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) response = { "events": [ {"event": "slot", "value": "rasa", "name": "name"}], "responses": [{"text": "test text", "buttons": [{"title": "cheap", "payload": "cheap"}]}, {"template": "utter_greet"}]} httpretty.register_uri( httpretty.POST, 'https://abc.defg/webhooks/actions', body=json.dumps(response)) httpretty.enable() events = remote_action.run(default_dispatcher_collecting, tracker, default_domain) httpretty.disable() assert (httpretty.latest_requests[-1].path == "/webhooks/actions") b = httpretty.latest_requests[-1].body.decode("utf-8") assert json.loads(b) == { 'domain': default_domain.as_dict(), 'next_action': 'my_action', 'sender_id': 'default', 'tracker': { 'latest_message': { 'entities': [], 'intent': {}, 'text': None }, 'sender_id': 'default', 'paused': False, 'followup_action': 'action_listen', 'latest_event_time': None, 'slots': {'name': None}, 'events': [], 'latest_input_channel': None } } assert events == [SlotSet("name", "rasa")] channel = default_dispatcher_collecting.output_channel assert channel.messages == [ {"text": "test text", "recipient_id": "my-sender", "buttons": [{"title": "cheap", "payload": "cheap"}]}, {"text": "hey there None!", "recipient_id": "my-sender"}]
def load_agent(): interpreter = RasaNLUInterpreter('./models/current/healthbot') #agent = Agent() action_endpoint = EndpointConfig(url='http://localhost:5055/webhook') return Agent.load('./models/current/dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
def create_agent(): interpreter = NaturalLanguageInterpreter.create("models/nlu/current") from rasa_core.utils import EndpointConfig action_endpoint = EndpointConfig(url="http://localhost:5056/webhook") agent = Agent.load("models/dialog", interpreter=interpreter, action_endpoint=action_endpoint) return agent
def run_provider_bot(): interpreter = RasaNLUInterpreter( './models/prior_auth_nlu/default/model_20190425-074151') 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')
def run_online_dialogue(serve_forever=True): interpreter = RasaNLUInterpreter('./models/nlu/default/chat') action_endpoint = EndpointConfig(url="http://localhost:5004/webhook") agent = Agent.load('./models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint) interactive.run_interactive_learning(agent) #, channel='cmdline') return agent
def run_job_bot(serve_forever=True): interpreter = RasaNLUInterpreter("./models/current/default/nlu") 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
def loadChatbot(self): nlu_model_path = "models/nlu/default/iCubbot" core_model_path = "models/dialogue" nlu_interpreter = RasaNLUInterpreter(nlu_model_path) action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") return Chatbot.load(core_model_path, interpreter=nlu_interpreter, action_endpoint=action_endpoint)
def test_remote_clients(http_app): client = RasaCoreClient(EndpointConfig(http_app)) cid = str(uuid.uuid1()) client.parse("/greet", cid) clients = client.clients() assert cid in clients
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(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'
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") return agent
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)
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()
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
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)