Giter VIP home page Giter VIP logo

rasa-sdk's Introduction

Rasa Python-SDK

Join the chat on Rasa Community Forum Build Status Coverage Status PyPI version

Python SDK for the development of custom actions for Rasa.


💡 We're migrating issues to Jira 💡

Starting January 2023, issues for Rasa Open Source are located in this Jira board. You can browse issues without being logged in; if you want to create issues, you'll need to create a Jira account.


Installation

To install the SDK run

pip install rasa-sdk

Compatibility

rasa-sdk package:

SDK version compatible Rasa version
1.0.x >=1.0.x

old rasa_core_sdk package:

SDK version compatible Rasa Core version
0.12.x >=0.12.x
0.11.x 0.11.x
not compatible <=0.10.x

Usage

Detailed instructions can be found in the Rasa Documentation about Custom Actions.

Docker

Usage

In order to start an action server using implemented custom actions, you can use the available Docker image rasa/rasa-sdk.

Before starting the action server ensure that the folder containing your actions is handled as Python module and therefore has to contain a file called __init__.py

Then start the action server using:

docker run -p 5055:5055 --mount type=bind,source=<ABSOLUTE_PATH_TO_YOUR_ACTIONS>,target=/app/actions \
	rasa/rasa-sdk:<version>

The action server is then available at http://localhost:5055/webhook.

Custom Dependencies

To add custom dependencies you enhance the given Docker image, e.g.:

# Extend the official Rasa SDK image
FROM rasa/rasa-sdk:<version>

# Change back to root user to install dependencies
USER root

# To install system dependencies
RUN apt-get update -qq && \
    apt-get install -y <NAME_OF_REQUIRED_PACKAGE> && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# To install packages from PyPI
RUN pip install --no-cache-dir <A_REQUIRED_PACKAGE_ON_PYPI>

# Switch back to non-root to run code
USER 1001

Building from source

Rasa SDK uses Poetry for packaging and dependency management. If you want to build it from source, you have to install Poetry first. This is how it can be done:

curl -sSL https://install.python-poetry.org | python3 -

There are several other ways to install Poetry. Please, follow the official guide to see all possible options.

To install dependencies and rasa-sdk itself in editable mode execute

make install

Code Style

To ensure a standardized code style we use the formatter black. If your code is not formatted properly, GitHub CI will fail to build.

If you want to automatically format your code on every commit, you can use pre-commit. Just install it via pip install pre-commit and execute pre-commit install.

To check and reformat files execute

make lint

Steps to release a new version

Releasing a new version is quite simple, as the packages are build and distributed by GitHub Actions.

Release steps:

  1. Switch to the branch you want to cut the release from (main in case of a major / minor, the current release branch for patch releases).
  2. If this is a minor / major release: Make sure all fixes from currently supported minor versions have been merged from their respective release branches (e.g. 3.3.x) back into main.
  3. Run make release
  4. Create a PR against main or the release branch (e.g. 1.2.x)
  5. Once your PR is merged, pull the release branch locally.
  6. Create a tag for a new release (this SHOULD always happen on main or release branches), e.g. using
    git tag 1.2.0 -m "next release"
    git push origin 1.2.0
    GitHub Actions will build this tag and push a package to pypi.
  7. If this is a minor release, a new release branch should be created pointing to the same commit as the tag to allow for future patch releases, e.g.
    git checkout -b 1.2.x
    git push origin 1.2.x

License

Licensed under the Apache License, Version 2.0. Copyright 2021 Rasa Technologies GmbH. Copy of the license.

A list of the Licenses of the dependencies of the project can be found at the bottom of the Libraries Summary.

rasa-sdk's People

Contributors

akelad avatar alwx avatar ancalita avatar arjaanbuijk avatar carlad avatar dependabot[bot] avatar dingusagar avatar donodje avatar erohmensing avatar federicotdn avatar ghostvv avatar hotthoughts avatar hsm207 avatar indam23 avatar joejuzl avatar m-vdb avatar metcalfetom avatar mprazz avatar rasa-aadlv avatar rasa-jmac avatar ricwo avatar sancharigr avatar souvikg10 avatar tabergma avatar tawakalt avatar tmbo avatar twerkmeister avatar urkem avatar vcidst avatar wochinge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rasa-sdk's Issues

"Received an action call without an action" - Custom Action, POST Request

Rasa version: 1.4.3

Python version: 3.7

Operating system (windows, osx, ...): Mac OS X High Sierra

Issue: Custom Action via POST Request not working

Error (including full traceback): I have set up a custom action and defined it in my domain.yml, and also set up the endpoint in endpoint.yml at "http://localhost:5055/webhook", however, when I call the post request I get a 200 response but there is no output by the bot and I get a warning that "Received an action call without an action". If I call the action just by conversing with the bot it works well, the message is dispatched.

2019-11-05 19:14:14 WARNING rasa_sdk.endpoint - You are using an old version of rasa which might not be compatible with this version of rasa_sdk (1.4.0).
To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa and rasa_sdk.
2019-11-05 19:14:14 WARNING rasa_sdk.executor - Received an action call without an action.
127.0.0.1 - - [2019-11-05 19:14:14] "POST /webhook HTTP/1.1" 200 144 0.005133

Content of configuration file (config.yml) (if relevant):

language: en
pipeline: supervised_embeddings
policies:
- name: MemoizationPolicy
- name: KerasPolicy
- name: MappingPolicy
Content of domain file (domain.yml) (if relevant):
intents:
- greet
- goodbye
- affirm
- deny
- mood_great
- mood_unhappy
- bot_challenge
- bored
- joke


templates:
  utter_greet:
  - text: Hey! How are you?
  utter_cheer_up:
  - text: 'Here is something to cheer you up:'
    image: https://i.imgur.com/nGF1K8f.jpg
  utter_did_that_help:
  - text: Did that help you?
  utter_happy:
  - text: Great, carry on!
  utter_goodbye:
  - text: Bye
  utter_iamabot:
  - text: I am a bot, powered by Rasa.
  utter_joke:
  - text: Would you like to hear a joke?
  utter_onejoke:
  - text: There was once a person talking to a bot.
  utter_nojoke:
  - text: Alright, suit yourself.
  
  
actions:
- utter_greet
- utter_cheer_up
- utter_did_that_help
- utter_happy
- utter_goodbye
- utter_iamabot
- utter_joke
- utter_onejoke
- utter_nojoke
- action_main

ACTION.PY

from rasa_sdk import Action
from rasa_sdk.events import SlotSet
from datetime import datetime
from crontab import CronTab
import schedule
import timE

class ActionMain(Action):

def name(self):
    return "action_main"


def run(self, dispatcher, tracker, domain):
    
    dispatcher.utter_message("Our chatbot is live")

    return []


POST REQUEST:

import requests
import json

url = 'http://localhost:5055/webhook'

#url = "http://localhost:5055/conversations/default/execute"

headers = {'Content-type': 'application/json'}

dx = json.dumps({"name": "action_main"})

requests.post(url, data=dx, headers=headers)

Please help me, I am not being able to call my custom action when running via post. Thanks.

Slots set during a form not useable during validation

Rasa Core SDK version: 0.12.1

Python version: 3.6.8

Operating system : Ubuntu 18.04

Issue: From what I've read about conversational UX, it is a good practice when collecting information from the user to offer some kind of confirmation that the bot has properly understood what the user was saying. Right now, with the FormAction in the SDK, one can generate easily a conversation of the following kind, with two slots called "name" and "email" respectively :

  • User : I'd like to register
    • Bot : Ok! What's your name? <-- produced from utter_ask_name
  • User : My name is John
    • Bot : Alright! And what is your e-mail address? <--- produced from utter_ask_email
  • User : My e-mail address is [email protected]
    • Bot : Alright John! We've sent you an e-mail at [email protected] for you to create your account.

(The "submit" function can do the e-mail sending and has access to the slots to perform this.)

However, if you wanna do something like this :

  • User : I'd like to register
    • Bot : Ok! What's your name? <-- produced from utter_ask_name
  • User : My name is John
    • Bot : Nice to meet you, John! <-- produced because name validation was successful via an utter_template in the validate function
    • Bot : May I ask for your e-mail address? <--- produced from utter_ask_email
  • User : My e-mail address is [email protected]
    • Bot : Alright John! We've sent you an e-mail at [email protected] for you to create your account.

this is impossible because if you utter a template during the validation process (i.e. by using the tracker passed to the validate function of the form), the "name" slot is not set there yet. The "_validate_if_required" function returns the return value of the "validate" function, which itself returns the list of slots that were set while calling the validate function.

I don't know what exactly would be ideal for the chatbot writer, but I'm guessing that the validate function should only be used to return a dictionary of booleans containing entries of the kind {slot_name : bool} as a function of the currently used slots and the last user message where the slots are extracted from. Then, instead of only be able to utter, there should be a function which allows actions to be taken by the bot (and not just a utterance) with the validated slots values stored in the tracker, including utter_ask_{slotname}. In other words, validate should only validate, and there should be another function allowing you to do stuff after validation.

That's just an idea ; I'm open for other suggestions, but that's what feels most natural to me right now.

Can not Registered function for both of 'Action' and 'FormAction'

Rasa SDK version: 1.1.0

Python version: 3.7.3

Operating system (windows, osx, ...): Windows 10

Issue:
I can not register function for both of 'Action' and 'FormAction' at the same time.
When i use 'python -m rasa_core_sdk.endpoint --actions actions'. It's only register for Action. Otherwise,when use 'rasa run actions'. It's only register for FormAction.
How can I use both of them at the same time.

Content of domain file (if used & relevant):

Form's helper validation method being called twice when form is triggered with pre-existing slot with invalid value

Rasa version: 1.1.3

Rasa SDK version: 1.1.0

Python version: 3.6.5

Operating system (windows, osx, ...): Windows Server 2016

Issue:
I am using forms to obtain some info, fill two slots and execute a custom action. When the user sends a message which contains an entity belonging to a certain intent, it fills the corresponding slot and triggers the form. I have a helper validation method, to validate the slots, where i'm returning {<slot_name>, value} if validation succeeds else print an error message and return {<slot_name>, None}.
The issue here is that in case of an invalid value the helper validation method is being called subsequently twice and hence the error message is being printed twice.
I could observe this behavior only in the case where the form is triggered when the first of the two slots is prefilled with an invalid value. It works fine when triggered with none of the slots filled or when the second slot filled with an invalid value.

Error (including full traceback):


Command or request that led to error:


Content of configuration file (config.yml) (if relevant):

Content of domain file (domain.yml) (if relevant):

Contents of stories.md

## Form story
* intent_slot1
  - action_form
  - form{"name": "action_form"}
  - form{"name": null}
  - utter_done

Contents of actions.py (if relevant):

class ActionForm(FormAction):"

	def name(self) -> Text:
		return "action_form"

	@staticmethod
	def required_slots(tracker: Tracker) -> List[Text]:
		return ["slot1", "slot2"]

	def request_next_slot(self, dispatcher, tracker, domain):
		
		for slot in self.required_slots(tracker):
			if self._should_request_slot(tracker, slot):
				if slot == 'slot1':
					dispatcher.utter_button_message("Select an option for slot1",slot1_buttons)
					
				if slot == 'slot2':
					dispatcher.utter_button_message("Select an option for slot2",slot2_buttons)
					
				return [SlotSet("requested_slot", slot)]
		return None

	def validate_slot1(
		self,
		value: Text,
		dispatcher: CollectingDispatcher,
		tracker: Tracker,
		domain: Dict[Text, Any],
	) -> Optional[Text]:

		if type(value)==type([]):
			value=value[-1]
		value=value.lower()

		if value in valid_values_for_slot1:
			return {"application": value}
		else:
			dispatcher.utter_message(f"I'm sorry, entered value for {slot1} is invalid! Please try again...")
			return {"application": None}

	def validate_slot2(
		self,
		value: Text,
		dispatcher: CollectingDispatcher,
		tracker: Tracker,
		domain: Dict[Text, Any],
	) -> Optional[Text]:

		if type(value)==type([]):
			value=value[-1]
		value=value.lower()

		if value in valid_values_for_slot2:
			return {"application": value}
		else:
			dispatcher.utter_message(f"I'm sorry,  entered value for {slot2} is invalid! Please try again...")
			return {"application": None}

	def submit(
		self,
		dispatcher: CollectingDispatcher,
		tracker: Tracker,
		domain: Dict[Text, Any],
	) -> List[Dict]:

		if tracker.get_slot("slot3"):
			return [{"event": "followup", "name": "action_do_something"}]
		
		return [{"event": "reset_slots"}]

List type slot is filled by the first element of the list only while using FormAction

Python version: 3.6.5

Rasa core sdk version: 0.11.5

Issue: I have a list type slot and I am writing a custom FormAction with the same slot being one of the required_field. While performing online training, the list type slot is storing only the first element of the entity list detected by the NLU server while ignoring the others. While going through the code, I found the following line of code being the reason for this behavior:

https://github.com/RasaHQ/rasa_core_sdk/blob/5b2356e2e0f43a95fbc988f66104948c7aed9ae6/rasa_core_sdk/forms.py#L44

This line of code works if the slot type is nonlist. For list type we need something like value = list(tracker.get_latest_entity_values(self.entity_name)). I don't know if there is a way to check the type of slot before filling it. If there's, this should be an easy fix.

FormAction is not working

Rasa Core SDK version:
0.11.0 . (taken from pip show rasa_core_sdk)
Python version:
3.6.5
Operating system (windows, osx, ...):
osx
Issue:
I'm running python -m rasa_core_sdk.endpoint --actions actions where I have a class in my actions which inherits FormAction and overrides required_fields(), name() and submit() functions. In my IDE, I can see in the rasa_core_sdk.forms.py that my overriden function for name is being shown, but when I execute endpoint, I get the NotImplementedError for name() function.

All the other actions (other than FormAction) are working perfectly.

FormAction

from rasa_core_sdk.forms import FormAction, EntityFormField
class ActionProvideOfferFillSlots(FormAction):
    RANDOMIZE = False

    @staticmethod
    def required_fields():
        return [
            EntityFormField("Firstname", "Firstname"),
            EntityFormField("Email", "Email"),
        ]

    def name(self):
        return 'action_provide_offer_fill_slots'

    def submit(self, dispatcher, tracker, domain):
        ... ... ... ...

Stack trace

Traceback (most recent call last):
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.6/site-packages/rasa_core_sdk/endpoint.py", line 89, in <module>
    action_package_name=cmdline_args.actions)
  File "/usr/local/lib/python3.6/site-packages/rasa_core_sdk/endpoint.py", line 55, in endpoint_app
    executor.register_package(action_package_name)
  File "/usr/local/lib/python3.6/site-packages/rasa_core_sdk/executor.py", line 153, in register_package
    self.register_action(action)
  File "/usr/local/lib/python3.6/site-packages/rasa_core_sdk/executor.py", line 105, in register_action
    self.register_function(action.name(), action.run)
  File "/usr/local/lib/python3.6/site-packages/rasa_core_sdk/forms.py", line 96, in name
    raise NotImplementedError
NotImplementedError

Update FormAction to use both Utter templates and Custom Action

Issue: The form action currently Only uses the utter_ask template to ask for user inputs. But it would be nicer if instead only for checking the utter_ask templates, it could also check the custom Actions for actions that have name in the form of "utter_ask_{slot_name}" or "ask_{slot_name}". In that way it would get much more simpler to implement more complex entry/validation for a particular entity while still keeping things simple for the other less complex entities.

To implement this, my initial plan was to update the following lines from forms.py and check whether a custom action for asking exists before calling the utter_template. But I wasn't sure what would be the best way to access the existing ActionExecutor to run the proper custom action.

        for slot in self.required_slots(tracker):
            if self._should_request_slot(tracker, slot):
                logger.debug("Request next slot '{}'".format(slot))
                dispatcher.utter_template(
                    "utter_ask_{}".format(slot),
                    tracker,
                    silent_fail=False,
                    **tracker.slots
                )
                return [SlotSet(REQUESTED_SLOT, slot)]

        # no more required slots to fill
        return None

support all message types in sdk (quick replies)

alternatively we could deprecate support for quick replies and only keep the very general stuff supported in templates, with channel-specifc (e.g. quick replies) stuff delegated to custom json payloads.

how to test action under pytest

Any one write a test for custom action?

I don't want to just use server to test action, it's better to have some helper class for writing tests

FormAction utterances do not use preceding extracted slots

Hello @RasaHQ,

I've created a running custom FormAction that is supposed to extract the forename and surname to finally submit the extracted slots. I have noticed the following unwanted behavior:

B: Hey there, I'm Rasa Bot.
B: Please tell me your forename.
U: Thomas
B: Alright None. Please tell me your surname.
U: Hesse
B: Thanks, Thomas None.

So apparently preceding extracted slots are not substituted into the utter_ask_{SLOT} utterances which is quite unfortunate as it takes a lot of power from the FormActions. As of now, I was not able to narrow down the source of the problem, though, I was asked (in the forums) to file this issue. However, I shall point out that the response of the action server seems fine to me! That is, it contains the extracted slots and the next requested_slot but (IMO on the rasa-core side) the bot utters before the slot is set.

Looking forward to any help, I'm back debugging. :-)

My Rasa Core Version: 0.12.2 and my actions.py:

class TestFormAction(FormAction):
    """Example of a custom form action"""

    def name(self):
        # type: () -> Text
        """Unique identifier of the form"""

        return "action_test_form"

    def slot_mappings(self):
        # type: () -> Dict[Text: Union[Text, Dict, List[Text, Dict]]]
        """A dictionary to map required slots to
            - an extracted entity
            - intent: value pairs
            - a whole message
            or a list of them, where the first match will be picked"""

        return {
            'surname': [
                self.from_entity(entity='surname', intent='get_surname'),
                self.from_entity(entity='surname', intent='get_full_name'),
                self.from_text(intent='get_surname'),
            ],
            'forename': [
                self.from_entity(entity='forename'),
                self.from_text(intent='get_forename'),
            ],
        }

    @staticmethod
    def required_slots(tracker):
        # type: (Tracker) -> List[Text]
        """A list of required slots that the form has to fill"""

        return [
            'forename',
            'surname',
        ]

    def submit(self, dispatcher, tracker, domain):
        # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
        """Define what the form has to do
           after all required slots are filled"""

        # utter submit template
        dispatcher.utter_template('utter_data_full_name', tracker)
        return []

rasa 1.2.3 can not using rasa-sdk 1.3.0a1

Python version:
3.6
Operating system (windows, osx, ...):
linux

when I install rasa, it reports an error:
rasa 1.2.3 has requirement rasa-sdk~=1.1.0, but you'll have rasa-sdk 1.3.0a1 which is incompatible.

I tried reinstalling rasa-sdk 1.1.0, but when I reinstalled rasa,The same error occurred again (rasa automatically installed rasa-sdk1.3.0a1).

rasa_core_sdk not supported rasa_core?

Rasa Core SDK version:
0.13.1
Python version:
3.6
Operating system (windows, osx, ...):
windows
Issue:
Your versions of rasa_core and rasa_core_sdk might not be compatible. You are currently running rasa_core version 0.14.0 and rasa_core_sdk version 0.13.1.
To ensure compatibility use the same version for both, modulo the last number, i.e. using version A.B.x the numbers A and B should be identical for both rasa_core and rasa_core_sdk.

rasa_core_sdk.executor - Failed to register package 'actions'.

Rasa Core SDK version:13.3

Python version: 3.6

Operating system (windows, osx, ...):Windows 10

Issue: I am trying to run actions server for my custom actions to perform interactive training but when i try to run it it shows this error

C:\Users\ferar>python -m rasa_core_sdk.endpoint --actions actions
2019-04-24 05:35:38 INFO main - Starting action endpoint server...
2019-04-24 05:35:38 ERROR rasa_core_sdk.executor - Failed to register package 'actions'.
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\rasa_core_sdk\executor.py", line 144, in register_package
self._import_submodules(package)
File "C:\Python36\lib\site-packages\rasa_core_sdk\executor.py", line 131, in import_submodules
package = importlib.import_module(package)
File "C:\Python36\lib\importlib_init
.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'actions'
2019-04-24 05:35:38 INFO main - Action endpoint is up and running. on ('0.0.0.0', 5055)

it is running essentially but it has failed to register package 'actions'

Content of domain file (if used & relevant):

self.from_text() from console error

Operating system (windows, osx, ...): Windows

Issue: I want to store the latest message entered by user into a slot named 'doc_desc' from the console. But i am getting error saying for slot in self.required_slots(tracker):
TypeError: required_slots() takes 1 positional argument but 2 were given

The complete error is:
DEBUG:rasa_core_sdk.executor:Received request to run 'form_2' DEBUG:rasa_core_sdk.forms:There is no active form DEBUG:rasa_core_sdk.forms:Activated the form 'form_2' DEBUG:rasa_core_sdk.forms:Skipping validation ERROR:flask.app:Exception on /webhook [POST] Traceback (most recent call last): File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\flask_cors\decorator.py", line 128, in wrapped_function resp = make_response(f(*args, **kwargs)) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core_sdk\endpoint.py", line 83, in webhook response = executor.run(action_call) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core_sdk\executor.py", line 177, in run events = action(dispatcher, tracker, domain) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core_sdk\forms.py", line 392, in run domain) File "C:\Users\Laptop\AppData\Local\Programs\Python\Python36\lib\site-packages\rasa_core_sdk\forms.py", line 279, in request_next_slot for slot in self.required_slots(tracker): TypeError: required_slots() takes 1 positional argument but 2 were given 127.0.0.1 - - [2019-02-12 14:15:10] "POST /webhook HTTP/1.1" 500 412 0.046816

Content of action.py file :

# -*- coding: utf-8 -*-
from typing import Dict, Text, Any, List, Union

from rasa_core_sdk import ActionExecutionRejection
from rasa_core_sdk import Action, Tracker
from rasa_core_sdk.events import SlotSet
from rasa_core_sdk.executor import CollectingDispatcher
from rasa_core_sdk.forms import FormAction, REQUESTED_SLOT

class form_1(FormAction):
   """Example of a custom form action"""

   def name(self):
       # type: () -> Text
       """Unique identifier of the form"""

       return "form_1"
   
   @staticmethod
   def required_slots(tracker) -> List[Text]:
       # type: () -> List[Text]

       return ["region", "rel"]

   def slot_mapping(self, tracker):
       
       return {"region": self.from_entity(entity="region"), "rel": self.from_entity(entity="rel")}



   
   def submit(self, dispatcher, tracker, domain):
       # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
       """Define what the form has to do
           after all required slots are filled"""

       # utter submit template
       dispatcher.utter_template('utter_submit', tracker)
       return []

class form_2(FormAction):
   def name(self):
       return "form_2"

   def required_slots(tracker):
       # type: () -> List[Text]

       return ["doc_desc"]

   def slot_mapping(self):
       
       return {"doc_desc": self.from_text()}

   def submit(self, dispatcher, tracker, domain):
       # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
       """Define what the form has to do
           after all required slots are filled"""

       # utter submit template
       dispatcher.utter_message(tracker.get_slot('doc_desc'))
       dispatcher.utter_template('utter_submit', tracker)
       return []

the code in endpoint.yml

action_endpoint:
  url: "http://localhost:5055/webhook

This issue is pertaining, please help

Cannot load actions directory

Rasa Core SDK version: Docker rasa_core_sdk:latest

Python version: 3.6

Operating system (windows, osx, ...): CentOS7

Issue:
Assume that I have an actions directory with multiple *.py actions defined. If I am running this command:

docker run -p 5055:5055 --mount type=bind,source=$(pwd)/actions,target=/app/actions rasa/rasa_core_sdk

It will return

ERROR:rasa_core_sdk.executor:Failed to register package 'actions.actions'.
Traceback (most recent call last):
  File "/app/rasa_core_sdk/executor.py", line 144, in register_package
    self._import_submodules(package)
  File "/app/rasa_core_sdk/executor.py", line 131, in _import_submodules
    package = importlib.import_module(package)
  File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'actions.actions'
INFO:__main__:Action endpoint is up and running. on ('0.0.0.0', 5055)

It seems that this command did not recognize a dir (or sub-dir within dir) when handling multiple actions. Please check.

Thank you.

requests is in requirements.txt but has not been published to Docker Hub

Rasa SDK version: rasa-sdk 1.0.0rc2

Python version: 3.6 (from docker tag: rasa_sdk:latest)

Operating system (windows, osx, ...): linux

Issue: After some testing and seeing that requests was added to the requirements.txt I noticed that when trying to do an import requests, I was getting module not found when tryingimport requests. I ran docker exec <container_id> pip list and this is what I got back:

Package        Version  Location
-------------- -------- --------
Click          7.0      
coloredlogs    10.0     
ConfigArgParse 0.14.0   
Flask          1.0.2    
Flask-Cors     3.0.7    
future         0.17.1   
gevent         1.4.0    
greenlet       0.4.15   
humanfriendly  4.18     
itsdangerous   1.1.0    
Jinja2         2.10.1   
MarkupSafe     1.1.1    
pip            19.1.1   
rasa-sdk       1.0.0rc2 /app    
setuptools     41.0.1   
six            1.12.0   
Werkzeug       0.15.2   
wheel          0.33.1   

So requests is missing. I think the latest version of requirements.txt needs to be pushed up to Docker hub, as the last change on requirements.txt was 5 days ago as of 28-05-2019, but the last push to Docker Hub was 15 days ago.

Get client up address in radar tracker

Rasa SDK .11:

Python version :3.6

Operating system windows

How to sent client ip address to action. How i can get the ip address to trackor so can use in action

Content of domain file (if used & relevant):

NotImplementedError on EntityFormField

I am using the latest version of Rasa and when I try to run my actions as an endpoint:
python -m rasa_core_sdk.endpoint --actions actions

I keep on getting an NotImplementedError

I realised that even if I have one line of code in the actions.py file:
from rasa_core_sdk.forms import EntityFormField
I still get this error!

Is that a bug?

add activation function in forms

The idea is that we would add an activation function where any actions that need to be performed before the form starts go. Then we would maybe also want to reinforce that forms should be called directly after inputs (e.g. by checking stories and tellling people to put anything that came before the form action in their activation function to avoid undesired behavior like slots from activating input not filling)

Form(None) not working in custom reset action

Rasa version: 1.2.5

Rasa SDK version: 1.2.0

Python version: 3.7

Operating system (windows, osx, ...): Ubuntu (with WSL)

Issue:
I have created a custom action to fully reset the conversation, slots, and deactivate any form that could still be running (the reason being that the standard action_restart did not deactivate forms).

My action basically does: [Form(None), AllSlotsReset(None), Restarted(None)] (full code below).

The action is triggered by a mapped intent called reset. Typing Reset should trigger this action.

This usually works fine but we've had cases where the bot is just stuck in a form. It usually happens when we do not talk to the bot for a while and try to reset the conversation (but not always). It is quite erratic and the only solution we found was to delete the whole tracker for this conversation (directly in the DB).

Not sure if this is a bug with the rasa_sdk or if my custom action is wrong.

Thanks for your help!

Error (including full traceback):
No error

Command or request that led to error:

  • Start a form
  • Type "Reset" (identified as intent reset)
  • Type "Hi" (bot should start the conversation from the beginning)

Content of domain file (domain.yml) (if relevant):

actions:
...
- action_reset_full

intents:
...
- reset:
    name: reset
    triggers: action_reset_full

Contents of config file (if relevant):

policies:
  - name: MappingPolicy
  - ...

Contents of actions.py (if relevant):

# actions/reset_full.py
from rasa_sdk import Action
from rasa_sdk.events import Form, AllSlotsReset, Restarted


class ActionResetFull(Action):
    def name(self):
        return "action_reset_full"

    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_template("utter_reset_full", tracker)
        return [Form(None), AllSlotsReset(None), Restarted(None)]

Compatibility issue with rasa 1.2.2

Rasa SDK version: 1.1.1

Python version: 3.6

Operating system (windows, osx, ...): Ubuntu 18

Issue: Not compatible with rasa 1.2.2

Content of domain file (if used & relevant):

Pass valdate function in FormAction

Rasa SDK version: 1.1.0

Python version: 3.6.8

Operating system (windows, osx, ...): Ubuntu 18.04 LTS

Issue: I can't pass validate function in FormAction

class action_form_name(FormAction):
def name(self) -> Text:
return "action_form_name"

def validate(self, dispatcher, tracker, domain):

    if 'intent_name' == tracker.latest_message['intent']['name']:
        #I want to pass here, don't do anything
        return []
    if tracker.get_slot('slot_nane') is None:
        dispatcher.utter_template("utter_name", tracker)
    return []

Does someone help me. Thank you.

Content of domain file (if used & relevant):

How do I subclass Action without the executor trying to import it?

I would like to instrument a custom action. To do so, I was thinking I could just do something like this:

class InstrumentedAction(Action):
    pass
    # the code in here is not relevant for the issue

and my actions would then look like:

class SomeAction(InstrumentedAction):
    def name(self):
        return "my_name"
    def run(self, dispatcher, tracker, domain):
        pass

Interestingly having this class somewhere in my project will throw when calling register_package on the Executor. The reason for that is that in my example InstrumentedAction will also be included in the list of classes gathered here: https://github.com/RasaHQ/rasa_core_sdk/blob/47106d959767148d15b328a3a38a95cd697e0616/rasa_core_sdk/executor.py#L149-L154 which in turn raises an exception here: https://github.com/RasaHQ/rasa_core_sdk/blob/47106d959767148d15b328a3a38a95cd697e0616/rasa_core_sdk/executor.py#L104-L105 as the instance of InstrumentedAction will raise a NonImplementedError when calling name()

I do know I could hack around this by simply implementing a name() on my subclass, but it feels weird to register the class instance in the first place and it's also not very obvious when it comes to debugging.

Can you think of a nicer way of doing this? Could the SDK handle this case in some way or the other?

How to call a Form from Rasa actions.....

I had a requirement based on intent/entity that, if the entity is not filled i need to call the form.

Detail:

  1. i will get the mobile number from user
  2. if the user is already registered the it will ask the next question
  3. if not registered then the bot will ask the name from "form".

Kindly help...

A bug(when defined a self-defined action raise NotImplementedError)

when you defind a self-defind action in you file action.py like:

from rasa_core_sdk import Action
from rasa_core_sdk.forms import FormAction
class MyFormAction(FormAction):
      def submit():
            pass
      def name:
           return "my_form_action"

when you run you action whill raise the NotImplementedError

to solve this bug, change file excutor.py
in class ActionExecutor, change function register_package. changes mark by bold xx.
old:
`
def register_package(self, package):
try:
self._import_submodules(package)
except ImportError:
logger.exception("Failed to register package '{}'."
"".format(package))

    actions = utils.all_subclasses(Action)

    for action in actions:
        if not action.__module__.startswith("**rasa_core.**"):
            self.register_action(action)

new:
def register_package(self, package):
try:
self._import_submodules(package)
except ImportError:
logger.exception("Failed to register package '{}'."
"".format(package))

    actions = utils.all_subclasses(Action)

    for action in actions:
        if not action.__module__.startswith("**rasa_core**"):
            self.register_action(action)

`

In endpoint, could we factor the /health endpoint out of `endpoint_app`?

I am migrating an existing application running on 0.10 to 0.11. This necessitates the creation of a standalone server for custom action using the newly created SDK.

The application currently serves multiple bots, so I need to call endpoint.endpoint_app myself (the reasoning being able to use one action package per bot).

I lateron merge these WSGI apps as described here: http://flask.pocoo.org/docs/1.0/patterns/appdispatch/#combining-applications

The issue I am now running into is that each subapp has a dedicated /<botname>/health route, when ideally I would like to have my application would expose a single /health route at root level (so monitoring does not need to know about my content).

This could be worked around if attaching the health route would be factored out into a standalone function that is then only being called when the module is invoked via python -m rasa_core_sdk.endpoint. Consumers (like me) that are using the Python API would need to call this themselves.

Does this make sense? Would you accept a PR that contains the proposed changes?


https://github.com/RasaHQ/rasa_core_sdk/blob/acb6ec7d8f6dbcd24ff60453cc93a3cadb0bb936/rasa_core_sdk/endpoint.py#L59-L64

Option to not to add Next Slot Events if event includes `Restarted` or maybe Form Deactivation

I was trying to debug this

I'm returning [Restarted(), FollowupAction(name='show_menu')] from FormAction.
When I issue Restarted() I expected that no more utter_ask_SLOT to be uttered but it does.
Not entirely sure if this is a bug or not but by adding code like this in rasa_core_sdk.forms.FormAction.run line # 393-ish to below so that when custom
FormAction issue Restarted() maybe other qualififed event, it will not issue utter_ask_SLOT

next_slot_events = None
if not any(e['event']=='restart' for e in events):
    next_slot_events = self.request_next_slot(dispatcher, temp_tracker,
                                              domain)

Maybe you can do fine control by checking Form deactivation then do not add request_next_slot.
What do you think?

Multi-intent slot filling

Issue:

Currently, there is no logic to allow multiple slot filling functions when multi-intents are registered during an active form.

We should be able to fill multiple slots from a predicted “multi-intent” (e.g. intent_X + intent_Y) from within a Form.

Example:
Intent_X and and Intent_Y are registered in a FormAction, and each fill a corresponding slot and entity when they are predicted as separate intents. However, a user should be able to update multiple slots at once if such a setting is enabled to allow one to do so.

In other words, a user should be able to fills the slots tied to both Intent_X and Intent_Y if they communicate both intents and a multi-intent X+Y is returned.

https://forum.rasa.com/t/multiple-slot-filling-from-multi-intent-intent-x-intent-y/10759

Docker | actions.py can not link to another py file

[root@localhost actions]# ls
actions.py log.py
[root@localhost actions]# cd ..
[root@localhost multiplition]# docker run -v $(pwd)/actions:/app/actions rasa/rasa_core_sdk:latest run python -m rasa_core_sdk.endpoint --actions actions.actions
2019-02-23 10:02:24 INFO main - Starting action endpoint server...
2019-02-23 10:02:24 ERROR rasa_core_sdk.executor - Failed to register package 'actions.actions'.
Traceback (most recent call last):
File "/app/rasa_core_sdk/executor.py", line 144, in register_package
self._import_submodules(package)
File "/app/rasa_core_sdk/executor.py", line 131, in _import_submodules
package = importlib.import_module(package)
File "/usr/local/lib/python3.6/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in _load_unlocked
File "", line 678, in exec_module
File "", line 219, in _call_with_frames_removed
File "/app/actions/actions.py", line 3, in
from log import Log
ModuleNotFoundError: No module named 'log'

Interactive componenets for a slack bot

Rasa Core SDK version: 0.12.4

Python version: 3.6

Operating system (windows, osx, ...): ubuntu 14.04

Issue:

I am using rasa core to implement a bot and integrate it with a slack channel. I was able to do a basic bot with successful integration. I would like to take it further. Could you please tell me how display other interactive components like dialogues and message menu in slack using rasa? and how to track the users interactions with these components. Also how can i send a file from the rasa bot to the slack channel?

Content of domain file (if used & relevant):

Server should not start if module not found

I didn't provide the correct path, so it couldn't find any module with the name provided. In this case i think it makes sense that an exception be raised and a server not run.

rasa ❯ rasa run actions
2019-11-01 11:21:16 INFO     rasa_sdk.endpoint  - Starting action endpoint server...
2019-11-01 11:21:16 ERROR    rasa_sdk.executor  - Failed to register package 'actions'.
Traceback (most recent call last):
  File "/Users/ella/miniconda3/envs/rasa/lib/python3.7/site-packages/rasa_sdk/executor.py", line 175, in register_package
    self._import_submodules(package)
  File "/Users/ella/miniconda3/envs/rasa/lib/python3.7/site-packages/rasa_sdk/executor.py", line 160, in _import_submodules
    package = importlib.import_module(package)
  File "/Users/ella/miniconda3/envs/rasa/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'actions'
2019-11-01 11:21:16 INFO     rasa_sdk.endpoint  - Action endpoint is up and running on http ('0.0.0.0', 5055)

Perhaps raise an exception with an error message like:

Could not find a module `actions`. Did you provide the correct path to the actions file or folder via the '--actions' parameter?

Similar: #71

i think this place(forms.py) has a bug.

Rasa Core SDK version:0.12.1
Python version: 3.6

Operating system (windows, osx, ...):ubuntu16.04

Issue:
the function "extract_other_slots" in 170 line:
for other_slot_mapping in other_slot_mappings: intent = tracker.latest_message.get("intent", {}).get("name") # check whether the slot should be filled # by entity with the same name should_fill_slot = ( other_slot_mapping["type"] == "from_entity" and other_slot_mapping.get("entity") == slot and self.intent_is_desired(other_slot_mapping, tracker) ) if should_fill_slot: # list is used to cover the case of list slot type value = list(tracker.get_latest_entity_values(slot)) if len(value) == 1: value = value[0]

i think this place "other_slot_mapping.get("entity") == slot" should be removed,and this place "value = list(tracker.get_latest_entity_values(slot))" should be changed as "value = list(tracker.get_latest_entity_values(other_slot_mapping.get("entity")))",because in slot_mapping existing the case of inconsistency in the value of the slot
for example:
in demo-formbot->action.py->slot_mappings: there's a piece of code:
"num_people": [self.from_entity(entity="num_people", intent=["inform", "request_restaurant"]), self.from_entity(entity="number")],
the slot is "num_people",but the entity is "num_people" and "number",but it means the same.
Looking forward to your reply!
Content of domain file (if used & relevant):

TypeError: 'FollowupAction' object is not subscriptable

example:
bot: how can i help you?
user: yes
bot: sure, how can help you?

def validate()...:

		for slot, value in slot_values.items():
			elif slot == 'help':
				if value=='yes':
					dispatcher.utter_message('Sure, how may i help you?')
					return [SlotSet(slot, None),FollowupAction("action_listen")]
		return [SlotSet(slot, value) for slot, value in slot_values.items()]

Error

   if e["event"] == "slot":
if e["event"] == "slot":
TypeError: 'FollowupAction' object is not subscriptable

endpoint for listing all loaded actions

the action server is starting up with a list of available actions:

INFO rasa_core_sdk.executor - Registered function for 'action_joke'.

it would be nice to get a list of loaded actions during runtime e.g.

GET /actions

['action_joke']

__pycache__ is created as a root user, dockerfile should not run as priviledged user

Rasa version: 1.4.5 (not relevant for this issue)

Rasa SDK version: 1.4.0

Python version: 3.6

Operating system (windows, osx, ...): Docker

Issue:
When running the rasa-sdk container and loading the actions module via entrypoint.sh, actions/__pycache__ is created as a root user. Since this is typically a directory, attempts to delete __pycache__ as a non-root user will fail with error below.

Rasa's containers (in general) should not run as root.

Error (including full traceback):

rm: cannot remove 'actions/__pycache__/mappedActions.cpython-36.pyc': Permission denied
rm: cannot remove 'actions/__pycache__/slotChecks.cpython-36.pyc': Permission denied
rm: cannot remove 'actions/__pycache__/fillSlots.cpython-36.pyc': Permission denied

Note: obviously, running sudo rm -rf actions/__pycache is able to clear this folder out.

Command or request that led to error:

docker-compose run action-server

rm -rf actions/__pycache__

docker-compose.yml contents (abriged):

version: 3.0
services:
  # ...
  action-server:
    image: rasa/rasa-sdk:1.4.0
    networks: ['rasa-network']
    ports:
      - '5055:5055'
    volumes:
      - ./actions:/app/actions
    command:
      - start
      - --actions
      - actions

Add support for knowledge bases

We want to simplify the usage of knowledge bases (https://github.com/RasaHQ/tutorial-knowledge-base) by adding a basic action to the SDK that is able to query entities and attributes of an entity. For now, we will support a simple in-memory knowledge base. However, the solution should be easily extendable so that user can exchange the in-memory knowledge base with any data storage they want.

dispatcher.utter_message is not working

version = "1.5.0"

**actions.py**
# changed from dispatcher.utter_message(response)
dispatcher.utter_message(text= response)

**executor.py**
def utter_message(
        self,
        image: Optional[Text] = None,
        json_message: Dict[Text, Any] = None,
        template: Optional[Text] = None,
        attachment: Optional[Text] = None,
        text: Optional[Text] = None,
        buttons: Optional[List[Dict[Text, Any]]] = None,
        *elements: Dict[Text, Any],
        **kwargs: Any,
    ) -> None:

## if remove the comment it does not work.
message = {
            "text": text
            # "buttons": buttons,
            # "elements": elements,
            # "custom": json_message,
            # "template": template,
            # "image": image,
            # "attachment": attachment,
        }
         message.update(kwargs)

        self.messages.append(message)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.