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 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_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_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): 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_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 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 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_concerts(serve_forever=True): agent = Agent.load("models/dialogue", interpreter=RegexInterpreter()) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
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 _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 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 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 test_agent_train(tmpdir, default_domain): training_data_file = 'examples/moodbot/data/stories.md' agent = Agent("examples/moodbot/domain.yml", policies=[AugmentedMemoizationPolicy()]) training_data = agent.load_data(training_data_file) agent.train(training_data) agent.persist(tmpdir.strpath) loaded = Agent.load(tmpdir.strpath) # test domain assert loaded.domain.action_names == agent.domain.action_names assert loaded.domain.intents == agent.domain.intents assert loaded.domain.entities == agent.domain.entities assert loaded.domain.templates == agent.domain.templates assert [s.name for s in loaded.domain.slots] == \ [s.name for s in agent.domain.slots] # test policies assert type(loaded.policy_ensemble) is type( agent.policy_ensemble) # nopep8 assert [type(p) for p in loaded.policy_ensemble.policies] == \ [type(p) for p in agent.policy_ensemble.policies]
def collect_story_predictions(story_file, policy_model_path, nlu_model_path, max_stories=None, shuffle_stories=True): """Test the stories from a file, running them through the stored model.""" def actions_since_last_utterance(tracker): actions = [] for e in reversed(tracker.events): if isinstance(e, UserUttered): break elif isinstance(e, ActionExecuted): actions.append(e.action_name) actions.reverse() return actions if nlu_model_path is not None: interpreter = RasaNLUInterpreter(model_directory=nlu_model_path) else: interpreter = RegexInterpreter() agent = Agent.load(policy_model_path, interpreter=interpreter) stories = _get_stories(story_file, agent.domain, max_stories=max_stories, shuffle_stories=shuffle_stories) preds = [] actual = [] logger.info("Evaluating {} stories\nProgress:".format(len(stories))) for s in tqdm(stories): sender = "default-" + uuid.uuid4().hex dialogue = s.as_dialogue(sender, agent.domain) actions_between_utterances = [] last_prediction = [] for i, event in enumerate(dialogue.events[1:]): if isinstance(event, UserUttered): p, a = _min_list_distance(last_prediction, actions_between_utterances) preds.extend(p) actual.extend(a) actions_between_utterances = [] agent.handle_message(event.text, sender=sender) tracker = agent.tracker_store.retrieve(sender) last_prediction = actions_since_last_utterance(tracker) elif isinstance(event, ActionExecuted): actions_between_utterances.append(event.action_name) if last_prediction: preds.extend(last_prediction) preds_padding = len(actions_between_utterances) - \ len(last_prediction) preds.extend(["None"] * preds_padding) actual.extend(actions_between_utterances) actual_padding = len(last_prediction) - \ len(actions_between_utterances) actual.extend(["None"] * actual_padding) return actual, preds
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.agent import Agent agent = Agent.load('models/dialogue', interpreter='./models/nlu/default/current') print("Your bot is ready to talk! Type your messages here or send 'stop'") while True: a = input() if a == 'stop': break responses = agent.handle_message(a) for response in responses: print(response["text"])
def __init__(self): self.intrepreter = RasaNLUInterpreter('models/current/nlu') self.nluModel = Interpreter.load('./models/current/nlu') self.dialogue = Agent.load('./models/current/dialogue', interpreter=self.intrepreter) self.unknown_command = "я вас не понял, попробуйте ещё раз"
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_model(project='Lambton'): interpreter = RasaNLUInterpreter("../Chatbots/projects/" + project + "/models/nlu/default/current") agent = Agent.load("../Chatbots/projects/" + project + "/models/dialogue", interpreter=interpreter) return agent
def run_concerts(serve_forever=True): agent = Agent.load("models/policy/init", interpreter=RegexInterpreter()) if serve_forever: agent.handle_channel(ConsoleInputChannel()) return agent
from rasa_core.channels import HttpInputChannel from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from rasa_slack_connector import SlackInput nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/foodpandanlu') agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter) input_channel = SlackInput( 'xoxp-700516438022-686960774642-728450041478-9278249d32e05544b5d7636175135a4b', #app verification token 'xoxb-700516438022-714824344163-oQoLIooYosorGHSEvbm5Ruao', # bot verification token 'rmjDPRE7I9yTXnpWdSgVZcZl', # slack verification token True) agent.handle_channel(HttpInputChannel(5004, '/', input_channel))
from rasa_core.channels import HttpInputChannel from rasa_core.channels.slack import SlackInput from rasa_core.agent import Agent from rasa_core.interpreter import RegexInterpreter import const # load your trained agent agent = Agent.load("dialogue", interpreter=RegexInterpreter()) input_channel = SlackInput( slack_token="xoxb-351036068130-363820053621-RJbTEl4ekYSaPBZQNWFahyHX", # this is the `bot_user_o_auth_access_token` slack_channel="botchan" # the name of your channel to which the bot posts ) agent.handle_channel(HttpInputChannel(5000, "/parse", input_channel))
from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from google_connecter import GoogleConnector from rasa_core.utils import EndpointConfig action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") nlu_interpreter = RasaNLUInterpreter( '/home/saradindu/dev/Work-II/Happsales/models/nlu/default/happsales') agent = Agent.load('/home/saradindu/dev/Work-II/Happsales/models/dialogue', interpreter=nlu_interpreter, action_endpoint=action_endpoint) input_channel = GoogleConnector() agent.handle_channels([input_channel], 5005, serve_forever=True)
def collect_story_predictions(resource_name, policy_model_path, nlu_model_path, max_stories=None, shuffle_stories=True): """Test the stories from a file, running them through the stored model.""" if nlu_model_path is not None: interpreter = RasaNLUInterpreter(model_directory=nlu_model_path) else: interpreter = RegexInterpreter() agent = Agent.load(policy_model_path, interpreter=interpreter) story_graph = training.extract_story_graph(resource_name, agent.domain, interpreter) preds = [] actual = [] max_history = agent.policy_ensemble.policies[0].max_history g = TrainingsDataGenerator(story_graph, agent.domain, agent.featurizer, max_history=max_history, use_story_concatenation=False, tracker_limit=100) data = g.generate() completed_trackers = data.metadata["trackers"] logger.info("Evaluating {} stories\nProgress:".format( len(completed_trackers))) for tracker in tqdm(completed_trackers): sender_id = "default-" + uuid.uuid4().hex events = list(tracker.events) actions_between_utterances = [] last_prediction = [] for i, event in enumerate(events[1:]): if isinstance(event, UserUttered): p, a = align_lists(last_prediction, actions_between_utterances) preds.extend(p) actual.extend(a) actions_between_utterances = [] agent.handle_message(event.text, sender_id=sender_id) tracker = agent.tracker_store.retrieve(sender_id) last_prediction = actions_since_last_utterance(tracker) elif isinstance(event, ActionExecuted): actions_between_utterances.append(event.action_name) if last_prediction: preds.extend(last_prediction) preds_padding = len(actions_between_utterances) - \ len(last_prediction) preds.extend(["None"] * preds_padding) actual.extend(actions_between_utterances) actual_padding = len(last_prediction) - \ len(actions_between_utterances) actual.extend(["None"] * actual_padding) return actual, preds
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
from rasa_core.agent import Agent from rasa_core.channels.socketio import SocketIOInput from rasa_core.agent import Agent from rasa_core.utils import EndpointConfig # load action server endpoint action_endpoint = EndpointConfig(url="http://127.0.0.1:5055/webhook") # load your trained agent agent = Agent.load('models/dialogue', interpreter='models/default/bimnlu', action_endpoint=action_endpoint) 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], 5005, serve_forever=True)
from rasa_core.channels.socketio import SocketIOInput from rasa_core.agent import Agent from rasa_core.interpreter import RegexInterpreter # load your trained agent agent = Agent.load( "/data/xingyang/Documents/Hangzhou Dianzi University - Chatbot/capstone-master/models/20190717-114901.tar.gz", interpreter=RegexInterpreter()) 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=True if you want to keep the server running #s = agent.handle_channels([input_channel], 5004, serve_forever=False) s = agent.handle_channels([input_channel], http_port=5005, route="/webhooks/", cors="*")
from rasa_core.interpreter import RasaNLUInterpreter # from wxpy import get_wechat_logger import sys # parent = os.path.dirname(os.path.realpath(__file__)) sys.path.append( r'C:\Users\Zack\AppData\Roaming\Python\Python36\site-packages\mitie') # 之前训练好的NLU模型 config_dir = "config.yml" nlu_model_dir = "models/nlu/nlu" dia_model_dir = 'models/dialogue' domain_file = "domain.yml" nlu_model_path = nlu_model_dir # agent = Agent.load("../models/policy/mom", interpreter=RasaNLUInterpreter(nlu_model_path)) agent = Agent.load(dia_model_dir, interpreter=RasaNLUInterpreter(nlu_model_dir)) # 初始化机器人,扫码登陆 bot = Bot(console_qr=False, cache_path=True) # bot = Bot(console_qr=False, cache_path=True) # bot.self.add() # bot.self.accept() # bot.self.send('哈咯~') # bot.file_helper.send('哈咯~') # logger = get_wechat_logger() # 自动接受新的好友请求 @bot.register(msg_types=FRIENDS) def auto_accept_friends(msg):
log_evaluation_table(test_y, predictions, "ACTION", include_report=True) cnf_matrix = confusion_matrix(test_y, predictions) plot_confusion_matrix(cnf_matrix, classes=unique_labels(test_y, predictions), title='Action Confusion matrix') fig = plt.gcf() fig.set_size_inches(int(20), int(20)) fig.savefig(out_file, bbox_inches='tight') if __name__ == '__main__': # Running as standalone python application arg_parser = create_argument_parser() cmdline_args = arg_parser.parse_args() logging.basicConfig(level=cmdline_args.loglevel) _endpoints = AvailableEndpoints.read_endpoints(cmdline_args.endpoints) _interpreter = NaturalLanguageInterpreter.create(cmdline_args.nlu, _endpoints.nlu) _agent = Agent.load(cmdline_args.core, interpreter=_interpreter) run_story_evaluation(cmdline_args.stories, _agent, cmdline_args.max_stories, cmdline_args.failed, cmdline_args.output, cmdline_args.fail_on_prediction_errors) logger.info("Finished evaluation")
def setUp(self): interpreter = RasaNLUInterpreter(INTERPRETER_PATH) self.agent = Agent.load(MODEL_PATH, interpreter)
def rasa_core_run(request): agent = Agent.load('rasa/models/dialogue' , interpreter = '/rasa/models/nlu/default/current') bot_response = agent.handle_message('hello') print("bot_response" + bot_response[0])
def run_rst_bot(server_forever=True): agent = Agent.load(policy_model_path, RasaNLUInterpreter(nlu_model_path)) if server_forever: agent.handle_channel(ConsoleInputChannel()) return agent
# hello.py # -*- coding: utf-8 -*- from sanic import Sanic, Blueprint from sanic.views import HTTPMethodView from sanic.response import text from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter import sys sys.path.append('../MITIE/mitielib') # from momo.helper import get_momo_answer # 导入获取机器人回答获取函数 nlu_model_path = '../models/nlu/model_20171109-164837' agent = Agent.load("../models/policy/mom", interpreter=RasaNLUInterpreter(nlu_model_path)) blueprint = Blueprint('index', url_prefix='/') class ChatBot(HTTPMethodView): # 聊天机器人 http 请求处理逻辑 async def get(self, request): ask = request.args.get('ask') # 先获取url 参数值 如果没有值,返回 '你说啥' if ask: answer = get_momo_answer(ask) return text(answer) return text('你说啥?')
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/nlu/default/current') action_endpoint = EndpointConfig(url="http://localhost:5055/webhook") agent = Agent.load('./models/dialogue', interpreter = nlu_interpreter, action_endpoint = action_endpoint) input_channel = SlackInput('xoxb-514185865477-514638817877-ZlAUhYSuoydYHkl0oCrUU7MC' #your bot user authentication token ) agent.handle_channels([input_channel], 5004, serve_forever=True)
from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter from rasa_core.utils import EndpointConfig core_endpoint_config = EndpointConfig(url='http://localhost:5055/webhook') interpreter = RasaNLUInterpreter('models/current/nlu') agent = Agent.load('models/current/dialogue', interpreter=interpreter, action_endpoint=core_endpoint_config) messages = [] while True: a = input("Eu: ") messages.append(a) if a == 'stop': break responses = agent.handle_message(a) for r in responses: answer = r.get("text") messages.append(answer) print("Bot: " + answer)
import os from django.http import HttpResponse, JsonResponse from django.shortcuts import render from .forms import ChatForm from moodbot.settings import BASE_DIR from rasa_nlu.converters import load_data from rasa_nlu.config import RasaNLUConfig from rasa_nlu.model import Trainer from rasa_nlu.model import Metadata, Interpreter from rasa_core.agent import Agent agent = Agent.load(os.path.join(BASE_DIR, 'rasa/models/dialogue') , interpreter = os.path.join(BASE_DIR, 'rasa/models/nlu/default/current')) def index(request): return render(request, 'bot_ui/index.html') def get_input(request): if request.method == 'POST': form = ChatForm(request.POST) print("##### inside post") #if form.is_valid(): print("##### inside form valid") user_input = request.POST.get('user_input') bot_response = agent.handle_message(user_input) print("bot_response:" + bot_response[0]) return JsonResponse({'user_input':user_input,'bot_response':bot_response}) #return render(request, 'bot_ui/index.html', {'user_input':user_input,'bot_response':bot_response[0]})
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import IPython from IPython.display import clear_output, HTML, display from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter import time interpreter = RasaNLUInterpreter('models/current/nlu') messages = [ "Hi! you can chat in this window. Type 'stop' to end the conversation." ] agent = Agent.load('models/current/dialogue', interpreter=interpreter) def run(self, dispatcher, tracker, domain): # what your action should do dispatcher.utter_message(messages) # send the message back to the user return [] while True: clear_output() display(run(messages)) time.sleep(0.3) a = input() messages.append(a) if a == 'stop':
import os from rasa_addons.webchat import WebChatInput, SocketInputChannel from rasa_core.agent import Agent current_path = os.path.dirname(os.path.realpath(__file__)) agent = Agent.load("models/dialogue", "models/default/current") input_channel = WebChatInput( static_assets_path=os.path.join(current_path, 'static')) agent.handle_channel(SocketInputChannel(5002, "/", input_channel))
def collect_story_predictions(resource_name, policy_model_path, nlu_model_path, max_stories=None, shuffle_stories=True, message_preprocessor=None, interpreter_class=None): """Test the stories from a file, running them through the stored model.""" if nlu_model_path is not None and interpreter_class is None: interpreter = RasaNLUInterpreter(model_directory=nlu_model_path) elif nlu_model_path is None: interpreter = RegexInterpreter() else: interpreter = interpreter_class(nlu_model_path) interpreter = RegexInterpreter() agent = Agent.load(policy_model_path, interpreter=interpreter) story_graph = training.extract_story_graph_evaluate( resource_name, agent.domain, interpreter) max_history = agent.policy_ensemble.policies[0].max_history g = TrainingsDataGenerator(story_graph, agent.domain, agent.featurizer, max_history=max_history, use_story_concatenation=False, tracker_limit=1500, remove_duplicates=False, augmentation_factor=0) data = g.generate() completed_trackers = data.metadata["trackers"] logger.info("Evaluating {} stories\nProgress:".format( len(completed_trackers))) turn_level_preds = [] turn_level_actual = [] dialogue_predictions = [] dialogue_actual = [] preds = [] actual = [] for j, tracker in enumerate(tqdm(completed_trackers)): simulate_dialogue_execution_and_compare(agent, tracker, j, message_preprocessor, turn_level_preds, turn_level_actual, dialogue_predictions, dialogue_actual, preds, actual) if logger.getEffectiveLevel() == 10: # logger is in debug mode logger.debug("Number of actual turns in the dialogue : {}".format( len(turn_level_actual))) logger.debug(" ---------------- actuals ----------------") for i, turn in enumerate(turn_level_actual): logger.debug("Turn {} -> {}".format(i, turn)) logger.debug("Number of predicted turns in the dialogue : {}".format( len(turn_level_preds))) logger.debug(" ---------------- predicted ----------------") for i, turn in enumerate(turn_level_preds): logger.debug("Turn {} -> {}".format(i, turn)) turn_index = 0 for turn_predictions, turn_actuals in zip(turn_level_preds, turn_level_actual): if turn_predictions != turn_actuals: logger.debug( "At turn {} : predicted_actions = {} and real_actions = {}" .format(turn_index, turn_predictions, turn_actuals)) turn_index += 1 # Compute dialogue success rate compute_dialogue_success_rate(dialogue_predictions, dialogue_actual) return actual, preds
def complex(): agent = Agent.load("../models/policy/mom", interpreter=HelloInterpreter()) return agent
warnings.simplefilter('ignore', yaml.error.UnsafeLoaderWarning) logger = logging.getLogger(__name__) # mongo_url = "PLEASE ENTER THE HOST URL OF MONGO DB EXAMPLE-mongodb://localhost:27017" mongo_url = "mongodb://localhost:27017" # loading the agent1 domain_file1 = "domain1.yml" interpreter1 = RasaNLUInterpreter('./models/ner_a1') action_endpoint1 = EndpointConfig(url="http://localhost:5055/webhook", serve_forever=True) mongo_tracker1 = MongoTrackerStore(domain=domain_file1, host=mongo_url, db="agent_1") agent_1 = Agent.load("./models/dialogue_agent_1", interpreter=interpreter1, tracker_store=mongo_tracker1, action_endpoint=action_endpoint1) # loading the agent2 domain_file2 = "domain2.yml" interpreter2 = RasaNLUInterpreter('./models/ner_a2') action_endpoint2 = EndpointConfig(url="http://localhost:5055/webhook", serve_forever=True) mongo_tracker2 = MongoTrackerStore(domain=domain_file2, host=mongo_url, db="agent_2") agent_2 = Agent.load("./models/dialogue_agent_2", interpreter=interpreter2, tracker_store=mongo_tracker2, action_endpoint=action_endpoint2)
#RASA CORE from rasa_core.actions import Action from rasa_core.agent import Agent from rasa_core.channels.console import ConsoleInputChannel from rasa_core.interpreter import RasaNLUInterpreter from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy def generate_random_password(): ''' from https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python''' return ''.join( choice(string.ascii_uppercase) for i in range(randint(6, 12))) agent = Agent.load("models/dialogue", interpreter=interpreter) print(agent.handle_message("hi")) print(agent.handle_message("My name is Giannis Atentekoumpo")) #RASA CORE import random ask_name = [ "Hello there! What is your name? ", "Hey there, what is your name?", "What is your name?", "Name please? " ] #global var firstname = '' email = ''
from rasa_core.channels.console import ConsoleInputChannel from rasa_core.interpreter import RegexInterpreter from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import MemoizationPolicy def train(): logging.basicConfig(level='INFO') dialog_training_data_file = './stories.md' path_to_model = './models/dialogue' agent = Agent('domain.yml', policies=[MemoizationPolicy(), KerasPolicy()]) agent.train( dialog_training_data_file, augmentation_factor=50, epochs=100, batch_size=10, ) agent.persist(path_to_model) if __name__ == '__main__': train() agent = Agent.load( './models/dialogue', interpreter="./models/nlu/default/model_20180808-121641") agent.handle_channel(ConsoleInputChannel())
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory #from prompt_toolkit.contrib.completers import WordCompleter from rasa_core.agent import Agent from rasa_core.interpreter import RasaNLUInterpreter import time interpreter = RasaNLUInterpreter('models/current/nlu') agent = Agent.load('models/dialogue', interpreter=interpreter) print("Hi! you can chat in this REPL. Type 'stop' to end the conversation.\n") while True: user_input = prompt('_ ', history=FileHistory('/tmp/bot-history'), auto_suggest=AutoSuggestFromHistory()) if user_input == 'stop': break responses = agent.handle_message(user_input) for r in responses: print(r.get('text'))
def collect_story_predictions(resource_name, policy_model_path, nlu_model_path, max_stories): """Test the stories from a file, running them through the stored model.""" if nlu_model_path is not None: interpreter = RasaNLUInterpreter(model_directory=nlu_model_path) else: interpreter = RegexInterpreter() agent = Agent.load(policy_model_path, interpreter=interpreter) story_graph = training.extract_story_graph(resource_name, agent.domain, interpreter) preds = [] actual = [] g = TrainingDataGenerator(story_graph, agent.domain, use_story_concatenation=False, tracker_limit=max_stories) completed_trackers = g.generate() failed_stories = [] logger.info("Evaluating {} stories\nProgress:" "".format(len(completed_trackers))) for tracker in tqdm(completed_trackers): sender_id = "default-" + uuid.uuid4().hex story = {"predicted": [], "actual": []} events = list(tracker.events) actions_between_utterances = [] last_prediction = [] for i, event in enumerate(events[1:]): if isinstance(event, UserUttered): p, a = align_lists(last_prediction, actions_between_utterances) story["predicted"].extend(p) story["actual"].extend(a) actions_between_utterances = [] agent.handle_message(event.text, sender_id=sender_id) tracker = agent.tracker_store.retrieve(sender_id) last_prediction = actions_since_last_utterance(tracker) elif isinstance(event, ActionExecuted): actions_between_utterances.append(event.action_name) if last_prediction: preds.extend(last_prediction) preds_padding = (len(actions_between_utterances) - len(last_prediction)) story["predicted"].extend(["None"] * preds_padding) preds.extend(story["predicted"]) actual.extend(actions_between_utterances) actual_padding = (len(last_prediction) - len(actions_between_utterances)) story["actual"].extend(["None"] * actual_padding) actual.extend(story["actual"]) if story["predicted"] != story["actual"]: failed_stories.append(story) return actual, preds, failed_stories