def default_agent(default_domain): agent = Agent(default_domain, policies=[MemoizationPolicy()], interpreter=RegexInterpreter(), tracker_store=InMemoryTrackerStore(default_domain)) training_data = agent.load_data(DEFAULT_STORIES_FILE) agent.train(training_data) return agent
def test_agent_wrong_use_of_load(tmpdir, default_domain): training_data_file = 'examples/moodbot/data/stories.md' agent = Agent("examples/moodbot/domain.yml", policies=[AugmentedMemoizationPolicy()]) with pytest.raises(ValueError): # try to load a model file from a data path, which is nonsense and # should fail properly agent.load(training_data_file)
def default_processor(default_domain, default_nlg): agent = Agent(default_domain, SimplePolicyEnsemble([AugmentedMemoizationPolicy()]), interpreter=RegexInterpreter()) training_data = agent.load_data(DEFAULT_STORIES_FILE) agent.train(training_data) tracker_store = InMemoryTrackerStore(default_domain) return MessageProcessor(agent.interpreter, agent.policy_ensemble, default_domain, tracker_store, default_nlg)
def run_concertbot_online(input_channel, interpreter, domain_file="concert_domain.yml", training_data_file='data/stories.md'): agent = Agent(domain_file, policies=[MemoizationPolicy(max_history=2), KerasPolicy()], interpreter=interpreter) training_data = agent.load_data(training_data_file) agent.train_online(training_data, input_channel=input_channel, batch_size=50, epochs=200, max_training_samples=300) return agent
def test_slack_channel(): from rasa_core.channels.slack import SlackInput 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 = SlackInput( slack_token="YOUR_SLACK_TOKEN", # this is the `bot_user_o_auth_access_token` slack_channel="YOUR_SLACK_CHANNEL" # the name of your channel to which the bot posts (optional) ) # set serve_forever=False 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/slack/").startswith( 'slack_webhook.health') assert routes_list.get("/webhooks/slack/webhook").startswith( 'slack_webhook.webhook') finally: s.stop()
def run_concerts(serve_forever=True): agent = Agent.load("models/dialogue", interpreter=RegexInterpreter()) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
def run(serve_forever=True): interpreter = RasaNLUInterpreter("models/nlu/default/current") agent = Agent.load("models/current/dialogue", interpreter=interpreter) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
def test_botframework_channel(): from rasa_core.channels.botframework import BotFrameworkInput 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 = BotFrameworkInput( # you get this from your Bot Framework account app_id="MICROSOFT_APP_ID", # also from your Bot Framework account app_password="******" ) # set serve_forever=False 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/botframework/").startswith( 'botframework_webhook.health') assert routes_list.get("/webhooks/botframework/webhook").startswith( 'botframework_webhook.webhook') finally: s.stop()
def test_mattermost_channel(): from rasa_core.channels.mattermost import MattermostInput 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 = MattermostInput( # this is the url of the api for your mattermost instance url="http://chat.example.com/api/v4", # the name of your team for mattermost team="community", # the username of your bot user that will post user="******", # messages pw="password" # the password of your bot user that will post messages ) # set serve_forever=False 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/mattermost/").startswith( 'mattermost_webhook.health') assert routes_list.get("/webhooks/mattermost/webhook").startswith( 'mattermost_webhook.webhook') finally: s.stop()
def test_rocketchat_channel(): from rasa_core.channels.rocketchat import RocketChatInput 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 = RocketChatInput( # your bots rocket chat user name user="******", # the password for your rocket chat bots account password="******", # url where your rocket chat instance is running server_url="https://demo.rocket.chat" ) # set serve_forever=False 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/rocketchat/").startswith( 'rocketchat_webhook.health') assert routes_list.get("/webhooks/rocketchat/webhook").startswith( 'rocketchat_webhook.webhook') finally: s.stop()
def run(serve_forever=True): agent = Agent.load("projects/dialogue", interpreter=RasaNLUInterpreter("projects/ivr_nlu/demo")) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
def run_ivrbot_online(input_channel=ConsoleInputChannel(), interpreter=RasaNLUInterpreter("projects/ivr_nlu/demo"), domain_file="mobile_domain.yml", training_data_file="data/mobile_story.md"): agent = Agent(domain_file, policies=[MemoizationPolicy(), KerasPolicy()], interpreter=interpreter) training_data = agent.load_data(training_data_file) agent.train_online(training_data, input_channel=input_channel, batch_size=16, epochs=200, max_training_samples=300) return agent
def test_facebook_channel(): from rasa_core.channels.facebook import FacebookInput 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 = FacebookInput( fb_verify="YOUR_FB_VERIFY", # you need tell facebook this token, to confirm your URL fb_secret="YOUR_FB_SECRET", # your app secret fb_access_token="YOUR_FB_PAGE_ACCESS_TOKEN" # token for the page you subscribed to ) # set serve_forever=False 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/facebook/").startswith( 'fb_webhook.health') assert routes_list.get("/webhooks/facebook/webhook").startswith( 'fb_webhook.webhook') finally: s.stop()
def test_twilio_channel(): from rasa_core.channels.twilio import TwilioInput 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 = TwilioInput( # you get this from your twilio account account_sid="YOUR_ACCOUNT_SID", # also from your twilio account auth_token="YOUR_AUTH_TOKEN", # a number associated with your twilio account twilio_number="YOUR_TWILIO_NUMBER" ) # set serve_forever=False 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/twilio/").startswith( 'twilio_webhook.health') assert routes_list.get("/webhooks/twilio/webhook").startswith( 'twilio_webhook.message') finally: s.stop()
def train_dialogue(domain_file="mobile_domain.yml", model_path="models/dialogue", training_data_file="data/mobile_story.md"): agent = Agent(domain_file, policies=[MemoizationPolicy(), MobilePolicy()]) agent.train( training_data_file, max_history=2, epochs=200, batch_size=16, augmentation_factor=50, validation_split=0.2 ) agent.persist(model_path) return agent
def _create_agent( model_directory, interpreter, action_factory=None, tracker_store=None ): return Agent.load(model_directory, interpreter, action_factory=action_factory, tracker_store=tracker_store)
def run_online_training(self, domain, # type: Domain interpreter, # type: NaturalLanguageInterpreter input_channel=None # type: Optional[InputChannel] ): # type: (...) -> None from rasa_core.agent import Agent if interpreter is None: interpreter = RegexInterpreter() bot = Agent(domain, self, interpreter=interpreter) bot.toggle_memoization(False) try: bot.handle_channel( input_channel if input_channel else ConsoleInputChannel()) except TrainingFinishedException: pass # training has finished
def test_moodbot_example(trained_moodbot_path): agent = Agent.load(trained_moodbot_path) responses = agent.handle_text("/greet") assert responses[0]['text'] == 'Hey! How are you?' responses.extend(agent.handle_text("/mood_unhappy")) assert responses[-1]['text'] in {"Did that help you?"} # (there is a 'I am on it' message in the middle we are not checking) assert len(responses) == 4
def test_training_script_with_max_history_set(tmpdir): max_history = 3 train_dialogue_model(DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, tmpdir.strpath, nlu_model_path=None, max_history=max_history, kwargs={}) agent = Agent.load(tmpdir.strpath) for policy in agent.policy_ensemble.policies: if hasattr(policy.featurizer, 'max_history'): assert policy.featurizer.max_history == max_history
def test_training_script_without_max_history_set(tmpdir): train_dialogue_model(DEFAULT_DOMAIN_PATH, DEFAULT_STORIES_FILE, tmpdir.strpath, use_online_learning=False, nlu_model_path=None, max_history=None, kwargs={}) agent = Agent.load(tmpdir.strpath) for policy in agent.policy_ensemble.policies: if hasattr(policy.featurizer, 'max_history'): assert policy.featurizer.max_history == \ policy.featurizer.MAX_HISTORY_DEFAULT
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 test_remote_training(tmpdir): train_dialogue_model("examples/remotebot/concert_domain_remote.yml", "examples/remotebot/data/stories.md", tmpdir.strpath, use_online_learning=False, nlu_model_path=None, kwargs={}) agent = Agent.load(tmpdir.strpath) assert agent.domain._factory_name == "remote" action_types = [type(a) for a in agent.domain.actions] assert action_types[:4] == [ActionListen, ActionRestart, ActionDefaultFallback, RemoteAction]
def train_dialogue(domain_file, model_path, training_folder): agent = Agent(domain_file, policies=[ MemoizationPolicy(max_history=6), KerasPolicy(MaxHistoryTrackerFeaturizer(BinarySingleStateFeaturizer(), max_history=6)), FallbackPolicy(nlu_threshold=0.8, core_threshold=0.3)]) training_data = agent.load_data(training_folder) agent.train(training_data, epochs=100) agent.persist(model_path)
def load_agent(core_model, interpreter, endpoints, tracker_store=None, wait_time_between_pulls=100): if endpoints.model: return agent.load_from_server( interpreter=interpreter, generator=endpoints.nlg, action_endpoint=endpoints.action, model_server=endpoints.model, tracker_store=tracker_store, wait_time_between_pulls=wait_time_between_pulls ) else: return Agent.load(core_model, interpreter=interpreter, generator=endpoints.nlg, tracker_store=tracker_store, action_endpoint=endpoints.action)
def main(model_directory, nlu_model=None, channel=None, port=None, credentials_file=None, nlg_endpoint=None, nlu_endpoint=None): """Run the agent.""" log = logging.getLogger('werkzeug') log.setLevel(logging.WARN) logger.info("Rasa process starting") interpreter = interpreter_from_args(nlu_model, nlu_endpoint) agent = Agent.load(model_directory, interpreter, generator=nlg_endpoint) logger.info("Finished loading agent, starting input channel & server.") if channel: input_channel = create_input_channel(channel, port, credentials_file) agent.handle_channel(input_channel) return agent
def _create_agent( model_directory, # type: Text interpreter, # type: Union[Text,NLI,None] action_factory=None, # type: Optional[Text] tracker_store=None, # type: Optional[TrackerStore] generator=None ): # type: (...) -> Optional[Agent] try: return Agent.load(model_directory, interpreter, tracker_store=tracker_store, action_factory=action_factory, generator=generator) except Exception as e: logger.warn("Failed to load any agent model. Running " "Rasa Core server with out loaded model now. {}" "".format(e)) return None
def recreate_agent(model_directory, # type: Text nlu_model=None, # type: Optional[Text] tracker_dump=None, # type: Optional[Text] endpoints=None ): # type: (...) -> Tuple[Agent, DialogueStateTracker] """Recreate an agent instance.""" nlg_endpoint = utils.read_endpoint_config(endpoints, "nlg") logger.debug("Loading Rasa Core Agent") agent = Agent.load(model_directory, nlu_model, generator=nlg_endpoint) logger.debug("Finished loading agent. Loading stories now.") tracker = load_tracker_from_json(tracker_dump, agent.domain) replay_events(tracker, agent) return agent, tracker
def test_telegram_channel(): # telegram channel will try to set a webhook, so we need to mock the api httpretty.register_uri( httpretty.POST, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook', body='{"ok": true, "result": {}}') httpretty.enable() from rasa_core.channels.telegram import TelegramInput 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 = TelegramInput( # you get this when setting up a bot access_token="123:YOUR_ACCESS_TOKEN", # this is your bots username verify="YOUR_TELEGRAM_BOT", # the url your bot should listen for messages webhook_url="YOUR_WEBHOOK_URL" ) # set serve_forever=False 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/telegram/").startswith( 'telegram_webhook.health') assert routes_list.get("/webhooks/telegram/webhook").startswith( 'telegram_webhook.message') finally: s.stop() httpretty.disable()
def test_restoring_tracker(trained_moodbot_path, recwarn): tracker_dump = "data/test_trackers/tracker_moodbot.json" agent = Agent.load(trained_moodbot_path) tracker = restore.load_tracker_from_json(tracker_dump, agent.domain) restore.replay_events(tracker, agent) # makes sure there are no warnings. warnings are raised, if the models # predictions differ from the tracker when the dumped tracker is replayed assert [e for e in recwarn if e._category_name == "UserWarning"] == [] assert len(tracker.events) == 7 assert tracker.latest_action_name == "action_listen" assert not tracker.is_paused() assert tracker.sender_id == "mysender" assert tracker.events[-1].timestamp == 1517821726.211042
def train_dialogue_model(domain_file, stories_file, output_path, nlu_model_path=None, endpoints=None, max_history=None, dump_flattened_stories=False, kwargs=None): if not kwargs: kwargs = {} action_endpoint = utils.read_endpoint_config(endpoints, "action_endpoint") fallback_args, kwargs = utils.extract_args(kwargs, {"nlu_threshold", "core_threshold", "fallback_action_name"}) policies = [ FallbackPolicy( fallback_args.get("nlu_threshold", DEFAULT_NLU_FALLBACK_THRESHOLD), fallback_args.get("core_threshold", DEFAULT_CORE_FALLBACK_THRESHOLD), fallback_args.get("fallback_action_name", DEFAULT_FALLBACK_ACTION)), MemoizationPolicy( max_history=max_history), KerasPolicy( MaxHistoryTrackerFeaturizer(BinarySingleStateFeaturizer(), max_history=max_history))] agent = Agent(domain_file, action_endpoint=action_endpoint, interpreter=nlu_model_path, policies=policies) data_load_args, kwargs = utils.extract_args(kwargs, {"use_story_concatenation", "unique_last_num_states", "augmentation_factor", "remove_duplicates", "debug_plots"}) training_data = agent.load_data(stories_file, **data_load_args) agent.train(training_data, **kwargs) agent.persist(output_path, dump_flattened_stories) return agent
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy if __name__ == '__main__': agent = Agent("domain.yml", policies=[MemoizationPolicy(), KerasPolicy()]) agent.visualize("data/stories.md", output_file="graph.html", max_history=2)
# trainer to create the pipeline trainer = Trainer(config.load("NLU_model_Config.yml")) # training the model interpreter = trainer.train(training_data) # storeing it for future model_directory = trainer.persist("./models/nlu", fixed_model_name="current") print("Done") print("STEP 2: Training the CORE model") fallback = FallbackPolicy(fallback_action_name="utter_default", core_threshold=0.2, nlu_threshold=0.1) agent = Agent(domain='restaurant_domain.yml', policies=[ MemoizationPolicy(), KerasPolicy(validation_split=0.0, epochs=200), fallback ]) training_data = agent.load_data('Core_Stories.md') agent.train(training_data) agent.persist('models/dialogue') print("Done") print("STEP 3: Starting the Bot") from rasa_core.agent import Agent agent = Agent.load('models/dialogue', interpreter=model_directory) print("Your bot is ready to talk! Type your messages here or send 'stop'") while True: a = input("You:") if a == 'stop': break
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019-05-11 19:07 # @Author : zhangzhen # @Site : # @File : run_app.py.py # @Software: PyCharm from rasa_core.channels.slack import SlackInput from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter import yaml from rasa_core.utils import EndpointConfig nlu_interpreter = RasaNLUInterpreter('./models/current/nlu') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('./models/current/dialogue', interpreter=nlu_interpreter, action_endpoint=action_endpoint) input_channel = SlackInput( 'xoxb-236655948598-a0Zsqx1VI3idWm0LHEANxWGy' # your bot user authentication token ) agent.handle_channels([input_channel], 5004, serve_forever=True)
# In[36]: get_ipython().system( 'python -m rasa_core.train interactive -s stories.md --nlu models/nlu/ResBot -d domain.yml -o models/dialogue --verbose --endpoints endpoints.yml' ) # In[71]: from rasa_core.policies import KerasPolicy, MemoizationPolicy, FormPolicy from rasa_core.agent import Agent agent = Agent('domain.yml', policies=[ MemoizationPolicy(), KerasPolicy(batch_size=100, epochs=500, validation_split=0.2), FormPolicy() ]) # loading our neatly defined training dialogues training_data = agent.load_data('stories.md') agent.train(training_data) agent.persist('models/dialogue') # In[ ]: # In[ ]:
def load_agent(): action_endpoint=EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('models/dialogue', interpreter='models/nlu/current',action_endpoint=action_endpoint) return agent
from rasa_core.agent import Agent from rasa_core.channels.socketio import SocketIOInput from rasa_core.agent import Agent # load your trained agent agent = Agent.load('models/dialogue-2', interpreter='models/nlu/default/model_20190503-154719/') #14h29-15h16 input_channel = SocketIOInput( # event name for messages sent from the user user_message_evt="user_uttered", # event name for messages sent from the bot bot_message_evt="bot_uttered", # socket.io namespace to use for the messages namespace=None) # set serve_forever=False if you want to keep the server running s = agent.handle_channels([input_channel], 5500, serve_forever=True)
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import logging from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy from rasa_core.featurizers import (MaxHistoryTrackerFeaturizer, BinarySingleStateFeaturizer) if __name__ == '__main__': logging.basicConfig(level='INFO') training_data_file = './data/stories.md' model_path = './models/dialogue' featurizer = MaxHistoryTrackerFeaturizer(BinarySingleStateFeaturizer(), max_history=5) agent = Agent('weather_domain.yml', policies=[ MemoizationPolicy(max_history=5), KerasPolicy(featurizer, epochs=500, batch_size=10) ]) data = agent.load_data(training_data_file) agent.train(data, augmentation_factor=50, validation_split=0.2) agent.persist(model_path)
from rasa_core.agent import Agent from rasa_core.interpreter import NaturalLanguageInterpreter, RasaNLUInterpreter from rasa_core.utils import EndpointConfig interpreter = RasaNLUInterpreter('./models/nlu/default/chat') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint) print("Bot đã sẵn sàng để trò chuyện, nhập 'stop' để kết thúc") while True: print('user: '******'') a = input() if a == 'stop': break for response in responses: print('bot:', response["text"])
# print(response) # response = agent.handle_message("餐馆") # print(response) # response = agent.handle_message("万达") # print(response) # response = agent.handle_message("日本料理") # print(response) import IPython from IPython.display import clear_output,display from rasa_core.agent import Agent import time messages = ["Hi! you can chat in this window. Type 'stop' to end the conversation."] agent = Agent.load("./models/dialogue", interpreter="./models/current/nlu/default/model_20180911-134739") def chatlogs_html(messages): messages_html = "".join(["<p>{}</p>".format(m) for m in messages]) chatbot_html = """<div class="chat-window" {}</div>""".format(messages_html) return chatbot_html while True: clear_output() display(IPython.display.HTML(chatlogs_html(messages))) print(messages) time.sleep(0.3) a = input() messages.append(a) if a == 'stop': break
import requests import json from flask import Flask from flask import request from flask import Response from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from rasa_core.utils import EndpointConfig # load trained models interpreter = RasaNLUInterpreter('./models/current/nlu') agent = Agent.load( './models/current/dialogue', interpreter=interpreter, action_endpoint=EndpointConfig(url="http://*****:*****@app.route('/', methods=['POST', 'GET']) def index(): if (request.method == 'POST'): msg = request.get_json() chat_id, message = parse_msg(msg) response_messages = applyAi(message) send_message(chat_id, response_messages)
from rasa_core.channels.slack import SlackInput from rasa_core.agent import Agent from rasa_core.interpreter import RegexInterpreter from rasa_core.interpreter import RasaNLUInterpreter nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/restaurantnlu') agent = Agent.load('./models/dialogue', interpreter = nlu_interpreter) input_channel = SlackInput( slack_token="xoxp-610890028624-610814375781-614177227505-1a7c5856ca5fa2acd993de02e3cf663e" # this is the `bot_user_o_auth_access_token` #slack_channel="YOUR_SLACK_CHANNEL" # the name of your channel to which the bot posts (optional) ) # set serve_forever=True if you want to keep the server running s = agent.handle_channels([input_channel], 5004, serve_forever=True)
def test_handling_of_telegram_user_id(): # telegram channel will try to set a webhook, so we need to mock the api httpretty.register_uri( httpretty.POST, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook', body='{"ok": true, "result": {}}') # telegram will try to verify the user, so we need to mock the api httpretty.register_uri( httpretty.GET, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/getMe', body='{"result": {"id": 0, "first_name": "Test", "is_bot": true, ' '"username": "******"}}') # The channel will try to send a message back to telegram, so mock it. httpretty.register_uri( httpretty.POST, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/sendMessage', body='{"ok": true, "result": {}}') httpretty.enable() from rasa_core.channels.telegram import TelegramInput 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 = TelegramInput( # you get this when setting up a bot access_token="123:YOUR_ACCESS_TOKEN", # this is your bots username verify="YOUR_TELEGRAM_BOT", # the url your bot should listen for messages webhook_url="YOUR_WEBHOOK_URL") from flask import Flask import rasa_core app = Flask(__name__) rasa_core.channels.channel.register([input_channel], app, agent.handle_message, route="/webhooks/") data = { "message": { "chat": { "id": 1234, "type": "private" }, "text": "Hello", "message_id": 0, "date": 0 }, "update_id": 0 } test_client = app.test_client() test_client.post("http://localhost:5004/webhooks/telegram/webhook", data=json.dumps(data), content_type='application/json') assert agent.tracker_store.retrieve("1234") is not None httpretty.disable()
from rasa_core.interpreter import RasaNLUInterpreter from rasa_core.agent import Agent from rasa_core.trackers import DialogueStateTracker from rasa_core.slots import TextSlot from rasa_core.events import SlotSet from rasa_core.tracker_store import * agent = Agent.load("models/dialogue", interpreter=RasaNLUInterpreter("models/default/current")) if __name__ == '__main__': while True: msg = raw_input('>> ') print('You said', msg) print(agent.handle_message(unicode(msg)))
def run_online_dialogue(serve_forever=True): interpreter = RasaNLUInterpreter('./models/nlu/default/chat') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('./models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint) interactive.run_interactive_learning(agent)#, channel='cmdline') return agent
def load_agent(): interpreter = RasaNLUInterpreter("train_model/models/current/nlu") agent = Agent.load("train_model/models/dialogue", interpreter=interpreter) return agent
def run_dialogue(serve_forever=True): interpreter = RasaNLUInterpreter('./models/nlu/default/chat') 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/weathernlu') agent = Agent.load('./models/dialogue', interpreter=interpreter) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
from __future__ import absolute_import from __future__ import division #from __future__ import unicode_laterals import logging, warnings warnings.simplefilter('ignore') from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy if __name__ == '__main__': warnings.filterwarnings(action='ignore', category=DeprecationWarning) logging.basicConfig(level='INFO') model_path = './models/dialogue' agent = Agent('weather_domain.yml', policies=[MemoizationPolicy(max_history=2), KerasPolicy()]) training_data_file = agent.load_data('./data/stories.md') agent.train(training_data_file, epochs=500, batch_size=10, validation_split=0.2) agent.persist(model_path)
from rasa_core.channels import HttpInputChannel from rasa_core.channels.facebook import FacebookInput from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter # load your trained agent agent = Agent.load( "models/dialogue", interpreter=RasaNLUInterpreter( model_directory= "C:/Users/Administrator/Desktop/BotV3.0/models/nlu/current", config_file="nlu_model_config.json")) YOUR_FB_VERIFY = "rasa-bot" YOUR_FB_SECRET = "a9f5370c907e14a983051bd4d266c47b" YOUR_FB_PAGE_ID = "158943344706542" YOUR_FB_PAGE_TOKEN = "EAACZAVkjEPR8BANiwfuKaSVz8yxtLsytuOPvaUzUTlCMAmvuX9TdqGR5P4F1EepBfZCQoKhSR49zM5C9pYX9hmmv3qqiUnRCMDE0eJ1lWRjeqNYTLLA5nbXelSMw0p7neZBSyyIcNHS3e1lbbf2raWPY8IUosJZBMlDLLA7ZBJgTxZAZCvhbO84" input_channel = FacebookInput( fb_verify= YOUR_FB_VERIFY, # you need tell facebook this token, to confirm your URL fb_secret=YOUR_FB_SECRET, # your app secret fb_tokens={YOUR_FB_PAGE_ID: YOUR_FB_PAGE_TOKEN}, # page ids + tokens you subscribed to debug_mode=True # enable debug mode for underlying fb library ) agent.handle_channel(HttpInputChannel(8080, "", input_channel))
args1 = {"pipeline": "tensorflow_embedding"} conf1 = RasaNLUModelConfig(args1) trainer1 = Trainer(conf1) #nlu for agent 1 training_data1 = load_data("./data2/nlu.md") Interpreter1 = trainer1.train(training_data1) model_directory1 = trainer1.persist('./models', fixed_model_name="ner_a2") #core for agent1 domain_file = "domain2.yml" training_data_file = './data2/stories.md' model_path = './models/dialogue_agent_2' agent = Agent(domain_file, policies=[ MemoizationPolicy(max_history=3), KerasPolicy(max_history=3, epochs=500, batch_size=10), FormPolicy() ]) data = agent.load_data(training_data_file) agent.train(data) agent.persist(model_path) agent = Agent(domain_file, policies=[ MemoizationPolicy(), KerasPolicy(max_history=3, epochs=500, batch_size=50) ]) data = agent.load_data(training_data_file) agent.train(data) agent.persist(model_path)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy if __name__ == '__main__': agent = Agent("../domain.yml", policies=[MemoizationPolicy(), KerasPolicy()]) agent.visualize("generated_tree.md", output_file="graph.html", max_history=2)
from rasa_core.featurizers import (MaxHistoryTrackerFeaturizer, BinarySingleStateFeaturizer) if __name__ == '__main__': logging.basicConfig(level='INFO') training_data_file = './data/stories.md' model_path = './models/dialogue' fallback = FallbackPolicy(fallback_action_name="action_default_fallback", core_threshold=0.4, nlu_threshold=0.4) featurizer = MaxHistoryTrackerFeaturizer(BinarySingleStateFeaturizer(), max_history=5) agent = Agent('restaurant_domain.yml', policies=[ MemoizationPolicy(max_history=4), KerasPolicy(featurizer), fallback ]) agent.train( training_data_file, augmentation_factor=50, #max_history = 4, epochs=500, batch_size=30, validation_split=0.2) agent.persist(model_path)
logging.basicConfig(level=cmdline_arguments.loglevel) _endpoints = AvailableEndpoints.read_endpoints(cmdline_arguments.endpoints) if cmdline_arguments.output: nlu_utils.create_dir(cmdline_arguments.output) if not cmdline_arguments.core: raise ValueError("you must provide a core model directory to evaluate " "using -d / --core") if cmdline_arguments.mode == 'default': _interpreter = NaturalLanguageInterpreter.create( cmdline_arguments.nlu, _endpoints.nlu) _agent = Agent.load(cmdline_arguments.core, interpreter=_interpreter) stories = cli.stories_from_cli_args(cmdline_arguments) run_story_evaluation(stories, _agent, cmdline_arguments.max_stories, cmdline_arguments.output, cmdline_arguments.fail_on_prediction_errors, cmdline_arguments.e2e) elif cmdline_arguments.mode == 'compare': run_comparison_evaluation(cmdline_arguments.core, cmdline_arguments.stories, cmdline_arguments.output) story_n_path = os.path.join(cmdline_arguments.core, 'num_stories.json')
#agent.visualize("stories.md", "story_graph.png", max_history=2) #Image(filename="story_graph.png") from rasa_core.policies import FallbackPolicy, KerasPolicy, MemoizationPolicy from rasa_core.agent import Agent # this will catch predictions the model isn't very certain about # there is a threshold for the NLU predictions as well as the action predictions fallback = FallbackPolicy(fallback_action_name="utter_unclear", core_threshold=0.2, nlu_threshold=0.6) agent = Agent('domain.yml', policies=[MemoizationPolicy(), KerasPolicy()]) # loading our neatly defined training dialogues training_data = agent.load_data('stories.md') agent.train( training_data, validation_split=0.2, epochs=400 ) agent.persist('models/dialogue') agent = Agent.load('models/dialogue', interpreter=model_directory) print("Your bot is ready to talk! Type your messages here or send 'stop'")
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from rasa_core import utils from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy if __name__ == '__main__': utils.configure_colored_logging(loglevel="INFO") training_data_file = 'data/stories.md' model_path = 'models/dialogue' agent = Agent("restoclima_domain.yml", policies=[MemoizationPolicy(), KerasPolicy()]) training_data = agent.load_data(training_data_file) agent.train(training_data, augmentation_factor=50, max_history=2, epochs=500, batch_size=10, validation_split=0.2) agent.persist(model_path)
def __init__( self, disable_nlu=os.environ.get('rasa_disable_nlu', 'no'), disable_core=os.environ.get('rasa_disable_core', 'no'), mqtt_hostname=os.environ.get('mqtt_hostname', 'mosquitto'), mqtt_port=os.environ.get('mqtt_port', 1883), nlu_model_path=os.environ.get('rasa_nlu_model_path', 'rasa_config/models/default/current'), snips_assistant_path=os.environ.get('rasa_snips_assistant_path', 'models/snips'), snips_user_id=os.environ.get('rasa_snips_user_id', 'user_Kr5A7b4OD'), core_model_path=os.environ.get('rasa_core_model_path', 'rasa_config/models/dialogue'), config_file=os.environ.get('rasa_config_file', 'rasa_config/config.json'), domain_file=os.environ.get('rasa_domain_file', 'rasa_config/domain.yml'), nlu_training_file=os.environ.get('rasa_nlu_training_file', 'rasa_config/nlu.md'), core_training_file=os.environ.get('rasa_core_training_file', 'rasa_config/stories.md'), lang=os.environ.get('rasa_lang', 'en-GB')): """ Initialisation. :param config: a YAML configuration. :param assistant: the client assistant class, holding the intent handler and intents registry. """ self.thread_handler = ThreadHandler() self.client = mqtt.Client() self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_message = self.on_message self.mqtt_hostname = mqtt_hostname self.mqtt_port = mqtt_port self.lang = lang # RASA config self.disable_nlu = disable_nlu self.disable_core = disable_core self.interpreter = None self.nlu_model_path = nlu_model_path self.core_model_path = core_model_path # to generate stub assistant self.snips_assistant_path = snips_assistant_path self.snips_user_id = snips_user_id self.config_file = config_file # RASA training config self.domain_file = domain_file self.nlu_training_file = nlu_training_file self.core_training_file = core_training_file self.isNluTraining = False self.isCoreTraining = False # save modified times on source files self.nlu_modified = self.getNluModified() self.core_modified = self.getCoreModified() self.core_domain_modified = self.getCoreDomainModified() self.nlu_model_modified = self.getNluModelModified() self.core_model_modified = self.getCoreModelModified() self.agent = agent = Agent( self.domain_file, policies=[MemoizationPolicy(), KerasPolicy()]) self.agentLoaded = None self.loadModels(True)
def run_bot(serve_forever=True, model_path='./models/dialogue', nlu_model_path='./models/nlu/default/current'): nlu_interpreter = RasaNLUInterpreter(nlu_model_path) action_endpoint = EndpointConfig(url="http://localhost:5055/webhook", serve_forever=serve_forever) return Agent.load(model_path, interpreter=nlu_interpreter, action_endpoint=action_endpoint)
import os, tempfile, zipfile, tarfile, time from rasa_nlu.model import Metadata, Interpreter from rasa_nlu import config from rasa_nlu.model import Trainer from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter ##run durectly ''' python -m rasa_core.run -d nlu_dialogue/models/restaurant -u nlu_model/restaurant/default/model_20180620-224333 ''' model_directory = 'nlu_model/jarvis_nlu/default/current' # interpreter = Interpreter.load(model_directory) agent = Agent.load('nlu_dialogue/models/jarvis_nlu', interpreter=RasaNLUInterpreter(model_directory)) # Create your views here. def home(requests): return render(requests, 'jarvis/home.html', {}) def task(requests): req = requests.GET['query'] context = {} ### using NLU intent prediction # intent = interpreter.parse(req) # print(intent) # context['message'] = intent
from rasa_core.channels import HttpInputChannel from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from rasa_slack_connector import SlackInput from config import getData nlu_interpreter = RasaNLUInterpreter(getData()["model_directory"] + '/default/' + getData()["model_name"]) agent = Agent.load(getData()["dialogue"],interpreter= nlu_interpreter) input_channel = SlackInput(getData()["slack"]["oauth_access_token"], getData()["slack"]["user_oauth_access_token"], getData()["slack"]["verification_token"],True) agent.handle_channel(HttpInputChannel(5004,'/',input_channel))