Ejemplo n.º 1
0
def run(serve_forever=True):
    agent = Agent.load("models/core",
                       interpreter=RasaNLUInterpreter("models/nlu"))

    if serve_forever:
        agent.handle_channel(CmdlineInput())
    return agent
Ejemplo n.º 2
0
def _load_and_set_updated_model(agent: 'Agent',
                                model_directory: Text,
                                fingerprint: Text):
    """Load the persisted model into memory and set the model on the agent."""

    logger.debug("Found new model with fingerprint {}. Loading..."
                 "".format(fingerprint))

    stack_model_directory = _get_stack_model_directory(model_directory)
    if stack_model_directory:
        from rasa.core.interpreter import RasaNLUInterpreter
        nlu_model = os.path.join(stack_model_directory, "nlu")
        core_model = os.path.join(stack_model_directory, "core")
        interpreter = RasaNLUInterpreter(model_directory=nlu_model)
    else:
        interpreter = agent.interpreter
        core_model = model_directory

    domain_path = os.path.join(os.path.abspath(core_model), "domain.yml")
    domain = Domain.load(domain_path)

    # noinspection PyBroadException
    try:
        policy_ensemble = PolicyEnsemble.load(core_model)
        agent.update_model(domain, policy_ensemble, fingerprint, interpreter)
        logger.debug("Finished updating agent to new model.")
    except Exception:
        logger.exception("Failed to load policy and update agent. "
                         "The previous model will stay loaded instead.")
Ejemplo n.º 3
0
def create_agent(model: Text, endpoints: Text = None) -> 'Agent':
    from rasa.core.interpreter import RasaNLUInterpreter
    from rasa.core.tracker_store import TrackerStore
    from rasa.core import broker
    from rasa.core.utils import AvailableEndpoints

    core_path, nlu_path = get_model_subdirectories(model)
    _endpoints = AvailableEndpoints.read_endpoints(endpoints)

    _interpreter = None
    if os.path.exists(nlu_path):
        _interpreter = RasaNLUInterpreter(model_directory=nlu_path)
    else:
        _interpreter = None
        logging.info("No NLU model found. Running without NLU.")

    _broker = broker.from_endpoint_config(_endpoints.event_broker)

    _tracker_store = TrackerStore.find_tracker_store(None,
                                                     _endpoints.tracker_store,
                                                     _broker)

    return Agent.load(core_path,
                      generator=_endpoints.nlg,
                      tracker_store=_tracker_store,
                      action_endpoint=_endpoints.action)
Ejemplo n.º 4
0
def _load_and_set_updated_model(agent: "Agent", model_directory: Text,
                                fingerprint: Text):
    """Load the persisted model into memory and set the model on the agent."""

    logger.debug(f"Found new model with fingerprint {fingerprint}. Loading...")

    core_path, nlu_path = get_model_subdirectories(model_directory)

    if nlu_path:
        from rasa.core.interpreter import RasaNLUInterpreter

        interpreter = RasaNLUInterpreter(model_directory=nlu_path)
    else:
        interpreter = (agent.interpreter if agent.interpreter is not None else
                       RegexInterpreter())

    domain = None
    if core_path:
        domain_path = os.path.join(os.path.abspath(core_path),
                                   DEFAULT_DOMAIN_PATH)
        domain = Domain.load(domain_path)

    try:
        policy_ensemble = None
        if core_path:
            policy_ensemble = PolicyEnsemble.load(core_path)
        agent.update_model(domain, policy_ensemble, fingerprint, interpreter,
                           model_directory)
        logger.debug("Finished updating agent to new model.")
    except Exception:
        logger.exception("Failed to load policy and update agent. "
                         "The previous model will stay loaded instead.")
Ejemplo n.º 5
0
def run(serve_forever=True):
    interpreter = RasaNLUInterpreter("models/nlu")
    agent = Agent.load("models/dialogue", interpreter=interpreter)
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")

    if serve_forever:
        agent.handle_channels([CmdlineInput()])
    return agent
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
def run_dialogue(serve_forever=True):
    interpreter = RasaNLUInterpreter('./models/nlu/chatter')
    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
Ejemplo n.º 8
0
def chat(
    model_path: Optional[Text] = None,
    endpoints: Optional[Text] = None,
    agent: Optional["Agent"] = None,
    interpreter: Optional[NaturalLanguageInterpreter] = None,
) -> None:
    """Chat to the bot within a Jupyter notebook.

    Args:
        model_path: Path to a combined Rasa model.
        endpoints: Path to a yaml with the action server is custom actions are defined.
        agent: Rasa Core agent (used if no Rasa model given).
        interpreter: Rasa NLU interpreter (used with Rasa Core agent if no
                     Rasa model is given).
    """

    if model_path:
        from rasa.run import create_agent

        agent = create_agent(model_path, endpoints)

    elif agent is not None and interpreter is not None:
        # HACK: this skips loading the interpreter and directly
        # sets it afterwards
        nlu_interpreter = RasaNLUInterpreter(
            "skip this and use given interpreter", lazy_init=True
        )
        nlu_interpreter.interpreter = interpreter
        agent.interpreter = interpreter
    else:
        print_error(
            "You either have to define a model path or an agent and an interpreter."
        )
        return

    print("Your bot is ready to talk! Type your messages here or send '/stop'.")
    loop = asyncio.get_event_loop()
    while True:
        message = input()
        if message == "/stop":
            break

        responses = loop.run_until_complete(agent.handle_text(message))
        for response in responses:
            _display_bot_response(response)
Ejemplo n.º 9
0
def chat(
    model_path: Text = None,
    agent: "Agent" = None,
    interpreter: NaturalLanguageInterpreter = None,
) -> None:
    """Chat to the bot within a Jupyter notebook.

    Args:
        model_path: Path to a Rasa Stack model.
        agent: Rasa Core agent (used if no Rasa Stack model given).
        interpreter: Rasa NLU interpreter (used with Rasa Core agent if no
                     Rasa Stack model is given).
    """

    if model_path:
        from rasa.run import create_agent

        unpacked = model.get_model(model_path)
        agent = create_agent(unpacked)

    elif agent and interpreter:
        # HACK: this skips loading the interpreter and directly
        # sets it afterwards
        nlu_interpreter = RasaNLUInterpreter(
            "skip this and use given interpreter", lazy_init=True)
        nlu_interpreter.interpreter = interpreter
        agent.interpreter = interpreter
    else:
        print_error(
            "You either have to define a model path or an agent and an interpreter."
        )

    print(
        "Your bot is ready to talk! Type your messages here or send '/stop'.")
    loop = asyncio.get_event_loop()
    while True:
        message = input()
        if message == "/stop":
            break

        responses = loop.run_until_complete(agent.handle_text(message))
        for response in responses:
            _display_bot_response(response)
Ejemplo n.º 10
0
    def __init__(self, *args, **kwargs):
        # 创建路径上下文对象
        path_context = PathContext()
        # nlu 模块
        interpreter = RasaNLUInterpreter(
            model_directory=path_context.model_directory,
            config_file=path_context.config_file_path)

        super(LSTMAgent).__init__(domain=path_context.domain_path,
                                  interpreter=interpreter,
                                  model_directory=path_context.model_directory)
Ejemplo n.º 11
0
def _load_interpreter(agent: "Agent",
                      nlu_path: Optional[Text]) -> NaturalLanguageInterpreter:
    """Load the NLU interpreter at `nlu_path`.

    Args:
        agent: Instance of `Agent` to inspect for an interpreter if `nlu_path` is
            `None`.
        nlu_path: NLU model path.

    Returns:
        The NLU interpreter.
    """
    if nlu_path:
        from rasa.core.interpreter import RasaNLUInterpreter

        return RasaNLUInterpreter(model_directory=nlu_path)

    return agent.interpreter or RegexInterpreter()
Ejemplo n.º 12
0
def suggestedMessage(model_save, dialogue_save, text):
    '''
    Function to return suggested message from Bot
    '''
    asyncio.set_event_loop(asyncio.new_event_loop())
    loop = asyncio.get_event_loop()  # call asyncio
    #asyncio.set_event_loop(loop)

    #train_dialogue()
    interpreter = RasaNLUInterpreter(
        model_save)  # interpreter is the intent classifier
    agent = Agent.load(dialogue_save,
                       interpreter=interpreter)  # load dialogue agent
    botMessage = loop.run_until_complete(agent.handle_text(
        text))  # test agent response agent.handle_text(text)#
    #print(botMessage) # print response
    loop.close()  # close loop
    return botMessage
Ejemplo n.º 13
0
async def parse(
    text: Text, core_model_path: Text, nlu_model_path: Optional[Text] = None
):
    if nlu_model_path:
        interpreter = RasaNLUInterpreter(nlu_model_path)
    else:
        logger.warning("No NLU model passed, parsing messages using RegexInterpreter.")
        interpreter = RegexInterpreter()

    agent = Agent.load(core_model_path, interpreter=interpreter)

    response = await agent.handle_text(text)

    logger.info("Text: '{}'".format(text))
    logger.info("Response:")
    logger.info(response)

    return response
Ejemplo n.º 14
0
 def __init__(self, config, loop):
     """constructor"""
     super(RasaServiceLocal, self).__init__(config, loop)
     self.config = config
     self.subscribe_to = 'hermod/+/rasa/get_domain,hermod/+/rasa/set_slots' \
     + ',hermod/+/dialog/ended,hermod/+/dialog/init,hermod/+/nlu/externalparse,' \
     + 'hermod/+/nlu/parse,hermod/+/intent,hermod/+/intent,hermod/+/dialog/started'
     model_path = get_model(
         config['services']['RasaServiceLocal'].get('model_path'))
     endpoint = EndpointConfig(
         config['services']['RasaServiceLocal'].get('rasa_actions_url'))
     domain = 'domain.yml'
     self.tracker_store = InMemoryTrackerStore(domain)
     regex_interpreter = RegexInterpreter()
     self.text_interpreter = RasaNLUInterpreter(model_path + '/nlu')
     self.agent = Agent.load(model_path,
                             action_endpoint=endpoint,
                             tracker_store=self.tracker_store,
                             interpreter=regex_interpreter)
Ejemplo n.º 15
0
def load_interpreter(model_path):
    model_path = pathlib.Path(model_path)
    model_path_val = get_validated_path(str(model_path), "model")
    model_path = get_model(model_path_val)
    _, nlu_model = get_model_subdirectories(model_path)
    return RasaNLUInterpreter(nlu_model)
Ejemplo n.º 16
0
# from rasa.core.channels import HttpInputChannel
from rasa.core.agent import Agent
# from rasa.core.interpreter import RegexInterpreter
from rasa.core.interpreter import RasaNLUInterpreter
from slack import SlackInput
# import SLACK_DEV_TOKEN, SLACK_CLIENT_TOKEN, VERIFICATION_TOKEN
# load your agent
import logging
logging.basicConfig(level=logging.DEBUG)
nlu_interpreter = RasaNLUInterpreter('./models/nlu')
agent = Agent.load('./models/', interpreter=nlu_interpreter)
print('------------------')
print(agent.is_core_ready())
print('---------------------------')

input_channel = SlackInput('',
                           'random',
                           slack_retry_reason_header='x-slack-retry-reason',
                           slack_retry_number_header='x-slack-retry-num')

agent.handle_channels(
    [input_channel],
    5005,
    "/",
)
print('test')
Ejemplo n.º 17
0
domain = Domain.load('domain.yml')
db_conf = config['bluelog']
mongo_tracker = MongoTrackerStore(domain,
                                  host=db_conf['host'],
                                  db=db_conf['db'],
                                  username=db_conf['username'],
                                  password=db_conf['password'],
                                  auth_source=db_conf['authsource'],
                                  collection=config['template']['module'])

agent_all = {}

try:
    if os.path.isdir('./models/nlu'):
        if os.path.isdir('./models/nlu/idn'):
            nlu_interpreter_idn = RasaNLUInterpreter('./models/nlu/idn/')
            agent_idn = Agent.load('./models/core/core.tar.gz',
                                   interpreter=nlu_interpreter_idn,
                                   action_endpoint=action_endpoint,
                                   generator=nlg_endpoint,
                                   tracker_store=mongo_tracker)
            agent_all["idn"] = agent_idn
        else:
            pass
        if os.path.isdir('./models/nlu/en'):
            nlu_interpreter_en = RasaNLUInterpreter('./models/nlu/en/latest')
            agent_en = Agent.load('./models/core/core.tar.gz',
                                  interpreter=nlu_interpreter_en,
                                  action_endpoint=action_endpoint,
                                  generator=nlg_endpoint,
                                  tracker_store=mongo_tracker)
Ejemplo n.º 18
0
import logging
from rasa.core.agent import Agent
from rasa.core.interpreter import RegexInterpreter
from rasa.core.policies.keras_policy import KerasPolicy
from rasa.core.policies.memoization import MemoizationPolicy
from rasa.core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_weather_online(interpreter,
                       domain_file="weather_domain.yml",
                       training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(), KerasPolicy()],
                  interpreter=interpreter)

    agent.train(training_data_file,
                max_history=2,
                batch_size=50,
                epochs=200,
                max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/weathernlu')
    run_weather_online(nlu_interpreter)
Ejemplo n.º 19
0
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
from ga_connector import GoogleConnector
from rasa.utils.endpoints import EndpointConfig

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('./models/current/nlu_model')
agent = Agent.load('./models/current/dialogue', interpreter = nlu_interpreter, action_endpoint=action_endpoint)

input_channel = GoogleConnector()
agent.handle_channels([input_channel], 5004, serve_forever=True)
Ejemplo n.º 20
0
from rasa.core.channels import HttpInputChannel
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
from rasa_twilio_connector import TwilioInput

print("initial")
nlu_interpreter = RasaNLUInterpreter('./models/20190720-123019/nlu')
agent = Agent.load('./models/20190720-123019/core',
                   interpreter=nlu_interpreter)
print("before")
input_channel = TwilioInput(
    'ACf11ed3930668c68e3ea357bb6543902e',
    '012d8bd5856136d5fac10fc05514bd1d',
    #'012d8bd5856136d5fac10fc05514bd',
    '+13367938385')

print(input_channel)
agent.handle_channels(HttpInputChannel(5500, input_channel))
Ejemplo n.º 21
0
# -*- coding: utf-8 -*-
"""
Created on Thu May  7 11:40:40 2020

@author: hung.td170078
"""


from rasa.core.channels.facebook import FacebookInput
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
import os
from rasa.core.utils import EndpointConfig
# load your trained agent
interpreter = RasaNLUInterpreter("models/nlu/")
MODEL_PATH = "models/20200521-171510.tar.gz"
action_endpoint = EndpointConfig(url="https://lunachatbot-prj2-actions.herokuapp.com/webhook")

agent = Agent.load(MODEL_PATH, interpreter=interpreter, action_endpoint=action_endpoint)
input_channel = FacebookInput(
    fb_verify="jackfrost",
    # you need tell facebook this token, to confirm your URL
    fb_secret="4ad8cdf285aeef2548b23c130cd6f56c", # your app secret
    fb_access_token="EAASmSto8E9IBANlkhOp0pcoMXdWJanepzZBBAmQ9ZBsm07CYlwG7qqIgb5ccUvGWGdZCJRS6U72W4j1MctoZBUhACihyuAhEUp5wAxsPBSkiMXADiKHWPA8LPErMz5WywZBWg043qnsBJZBr42HpPdPxcoAnWYJKQfc2DNANgERwZDZD"
    
    # 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], int(os.environ.get('PORT',5004)))
Ejemplo n.º 22
0
from rasa.model import get_model_subdirectories, get_model
from rasa.core.channels.socketio import SocketIOInput
from rasa.core.agent import Agent
from rasa.core.interpreter import RegexInterpreter
from rasa.core.interpreter import RasaNLUInterpreter
from rasa.core.utils import EndpointConfig
from rasa.core.policies.keras_policy import KerasPolicy
from rasa.core.policies.memoization import MemoizationPolicy
# load your trained agent
model_path = get_model('./models/nlu/')

_, nlu_model = get_model_subdirectories(model_path)

interpreter = RasaNLUInterpreter(nlu_model)

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")

agent = Agent.load('models/core/core-20200417-162634.tar.gz',
                   interpreter=interpreter,
                   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=True if you want to keep the server running
s = agent.handle_channels([input_channel], 5500, route='/webhooks/',
Ejemplo n.º 23
0
# PART 3: Start the Bot

from rasa.core.agent import Agent
from rasa.nlu.model import Trainer, Metadata
from rasa.core.interpreter import RasaNLUInterpreter
from rasa.utils.endpoints import EndpointConfig

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/chatter')
action_endpoint = EndpointConfig("http://localhost:5055/webhook")
agent = Agent.load('./models/dialogue', interpreter = nlu_interpreter)

# Part 4:Talk to Bot
print("start the conversation")
print()
print("Hi! How can I help you today? ")
while True:
    a=input()
    if a == 'stop' :
        break
    responses = agent.handle_message(a)
    for response in responses:
        print(response['text'])
from rasa.core.channels.socketio import SocketIOInput
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
from rasa.utils.endpoints import EndpointConfig
#from MyIo import RestInput

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('/data/xingyang/Documents/Hangzhou Dianzi University - Chatbot/capstone-master/models/20190717-114901/nlu')
agent = Agent.load('/data/xingyang/Documents/Hangzhou Dianzi University - Chatbot/capstone-master/models/20190717-114901/core', interpreter=nlu_interpreter, action_endpoint=action_endpoint)
#input_channel = RestInput()

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
    )
    
#s = agent.handle_channels([input_channel],5005, serve_forever=True)
agent.handle_channels([input_channel], http_port=5005,route="/webhooks/",cors="*")
Ejemplo n.º 25
0
def load_interpreter(model_dir, model):
    path_str = str(pathlib.Path(model_dir) / model)
    model = get_validated_path(path_str, "model")
    model_path = get_model(model)
    _, nlu_model = get_model_subdirectories(model_path)
    return RasaNLUInterpreter(nlu_model)
Ejemplo n.º 26
0
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
import asyncio
interpreter = RasaNLUInterpreter("/home/pulkit/bot/chatbot/models/nlu")
agent = Agent.load("/home/pulkit/bot/chatbot/models/20200706-002358.tar.gz",
                   interpreter=interpreter)


async def inter(str):
    a = await agent.handle_text(str)
    # b=await interpreter.parse(str)
    c = await agent.parse_message_using_nlu_interpreter(str)
    # return (a,b,c)
    # return a,c
    first = a[0]['text']
    if not first or first[0] == '1':
        first = None
    second = None
    if not first:
        users = "100 users"
        ms = "10 motion"
        ds = "10 door"
        ts = "10 temperature"
        for x in c['entities']:
            if x['extractor'] == 'CRFEntityExtractor':
                if x['entity'] == "users":
                    users = x['value']
                elif x['entity'] == "ms":
                    ms = x['value']
                elif x['entity'] == "ds":
                    ds = x['value']
Ejemplo n.º 27
0
import IPython
from IPython.display import clear_output, HTML, display
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
import time
import json

interpreter = RasaNLUInterpreter('models/nlu')
messages = [
    "Hi! you can chat in this window. Type 'stop' to end the conversation."
]
agent = Agent.load('models/', interpreter=interpreter)


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(HTML(chatlogs_html(messages)))
    time.sleep(0.3)
    a = input()
    messages.append(a)
    print(messages)
    if a == 'stop':
        break
    responses = agent.parse_message_using_nlu_interpreter(a)
Ejemplo n.º 28
0
import os
import api
import requests
from rasa.core.agent import Agent
from rasa.core.interpreter import RasaNLUInterpreter
import asyncio
import speech_recognition as sr

import nest_asyncio
nest_asyncio.apply()
token = "xoxb-101944332577-698195991045-QpfdLEMbpRI3oaSnp8DN6ks3"
agent = Agent.load("models/depot",
                   interpreter=RasaNLUInterpreter("models/depot/nlu"))

client = api.WebClient(token=token, run_async=True)


def sendMsg(msg, channel):
    event_loop = asyncio.get_event_loop()
    response = event_loop.run_until_complete(
        client.chat_postMessage(channel=channel, text=msg))


def response(txt):
    event_loop = asyncio.get_event_loop()
    result = event_loop.run_until_complete(
        agent.handle_text(txt, None, None, "jesenchen"))
    client.chat_postMessage(channel='#general', text=result[0]["text"])


def downloadFile(url):