Codebase for chirpy cardinal
- If you'd like to run the bot locally, start here
- To chat with chirpy on our web server, start here
- For a general overview of the codebase, start here
agent
: When you run chirpycardinal, you will create an agent. Agents manage data storage, logging, user message input, bot message output, connections to remote modules, and calls to the handler. Three agents are provided:
local_agent.py
: an agent that stores data and runs remote modules locally.remote_non_persistent_agent.py
: an agent that runs modules remotely, but stores data in memory.remote_psql_persistent_agent.py
: an agent that runs modules remotely and stores data in postgres. To use this agent, you will need to set up your own postgres instance.
servers
: Contains the code needed to run chirpycardinal servers
servers/local/shell_chat.py
: script to build docker modules locally and run chat in a loop.servers/local/local_callable_manager.py
defines the LocalCallableManager class, which is used to run docker containers locallyservers/local/local_callable_config.json
defines the ports, dockerfiles, and urls associated with each container
chirpy
: This directory contains the bot’s response generators, remote modules, and dialog management. The core logic of the bot is here. Code in this directory is invariant of agent specifications.
chirpy/annotators
When a user utterance is input, all annotators are run on it and their results are stored in state, so that they can be used by the response generators. Annotations include dialog act and user emotion, among others.
chirpy/core
The bot’s core logic components. Highlighted files are:
dialog_manager.py
: this contains the functionget_response_and_prompt
, which runs all response generators, ranks their responses, and returns the highest ranking response and prompt, and the functionexecute_turn
which loads the rg states from the previous turn, updates the state based on the response and prompt chosen byget_response_and_prompt
and then returns the bot’s next utterancehandler.py
deserializes the state, runs the NLP pipeline, updates the state based on it, calls dialog manager’sexecute_turn
, and then serializes the stateresponse_priority.py
: defines which RGs have the highest priority for tiebreaking if multiple RGs return responses with the same confidence levelpriority_ranking_strategy.py
Logic for ranking responses and promptsstate.py
: The State class defines what should be stored in each state and contains functions for serializing/deserializing the state.user_attributes.py
: The UserAttributes class defines which user attributes should be recorded and contains functions for serializing/deserializing user attributes.regex
: the regex directory contains code for creating and testing regular expressions that can be used by the bot. New regexes should be added totemplates.py
chirpy/response_generators
: Contains all response generators used by the bot. More detail can be found in the Creating a Response Generator section
docker
: This is where the dockerfiles, configs, and lambda functions of each remote module are defined.
scrapers
: Scrape data from Twitter and Reddit, so that it can be stored in elastic-search
test
: Integration tests for chirpy. These can be run with the command sh local_test_integ.sh
wiki-es-dump
: Processes and stores raw wiki files for use by the response generators. wiki-setup.md
contains detailed instructions for this step.
Agents manage the bot’s data storage, logging, message input/output, and connections to remote modules. The agent class provided, local_agent.py
stores data locally and inputs/outputs messages as text. By defining your own agent, you can alter any of these components, for example storing data in a Redis instance, or inputting messages as audio.
Highlighted features of the LocalAgent
are:
init
function, which initializes
last_state
andcurrent_state
dicts These are serialized/deserialized by the functions inchirpy/core/state.py.
If you change their attributes in your agent, then you should also updatestate.py
user_attributes
dict, which containsuser_id
: unique identifier for the usersession_id
: unique identifier for the current sessionuser_timezone
: the user’s timezone (if available) which is used by response generators to create time-specific responses, e.g. “good morning!”turn_num
: the number of the current turnpersist
function
- Manages storage of the
state
anduser_attributes
. If you want to store things non-locally, you would make this change hereshould_launch
function - Determine whether to launch the bot, for example based on specific commands
should_end_session
function - Determine whether to end the conversation, which may also be based on specific commands or heuristics
process_utterance
function - Retrieve the current state, previous state, and user attributes from your storage
- Call handler.execute() on the current state, previous state, and user attributes, which returns updated states and a response
- Persist the updated states in your storage
- Return the response and current state
To create a new response generator, you will need to
- Define a new class for your response generator
- Add your response generator to the handler
- (optional) Structure dialogue using treelets
You will need to create a new class for your response generator. To do this,
- Create a file
my_new_response_generator.py
inchirpy/response_generators
which defines a MyNewResponseGenerator class - Set the class’s name attribute to be 'NEW_NAME’
- Define the following functions of your class:
- init_state (returns a State object) which contains the state for your response generator which stores - - information about the response generator, e.g. topics discussed
- get_entity (returns an UpdateEntity object). This is used to override the entity linker, in cases where the response generator has a better contextual understanding of what the new entity should be.
- get_response (returns a ResponseGeneratorResult) based on the user’s utterance, annotations, and the response generator’s state. If the response generator doesn’t have any suitable responses, this returns an emptyResult object
- get_prompt (returns a PromptResult) based on the user’s utterance, annotations, and the response generator’s state. If the response generator doesn’t have any suitable prompts, this returns an emptyPrompt object
- update_state_if_chosen: updates the response generator’s conditional state if the response generator is chosen. For example, this might mean adding its response to a list of questions asked
- update_state_if_not_chosen: updates the response generator’s conditional state if the response generator was not chosen. For example, by setting the current topic to be None.
In order for your response generator to be called, it needs to be added to a) your handler and b) the response priority list. To do this,
- Add MyNewResponseGenerator to your handler’s list
response_generator_classes
in your agent. If you’re using the local agent, you would add this tolocal_agent.py
- Using the name you declared in your response generator class, set the following in
response_priority.py
:
TiebreakPriority
: how your response generator should rank if other response generators return equally high-priority responses- FORCE_START_PROMPT_DIST, CURRENT_TOPIC_PROMPT_DIST, CONTEXTUAL_PROMPT_DIST, and GENERIC_PROMPT_DIST, which determine the likelihood of a response generator’s prompt being chosen for the given prompt types. For detail about what different response and prompt types mean, see
response_priority.py
If your response generator has scripted components, then you may want to use treelets. Treelets handle branching options of a scripted response generator. Based on a user’s response, one treelet can determine which treelet should go next. This value is stored in the response_generator’s conditional_state. To see an example of how this works in code, look at categories_response_generator.py
, categories/treelets/introductory_treelet.py
, and categories/treelets/handle_answer_treelet.py
.
git clone https://github.com/stanfordnlp/chirpycardinal.git
- cd into the chirpycardinal directory2
- Run pwd to get the absolute path to this directory, e.g.
/Users/username/Documents/chirpycardinal
- Add the following 2 lines to ~/.bash_profile:
export CHIRPY_HOME=/Users/username/Documents/chirpycardinal
export PATH=$CHIRPY_HOME/bin:$PATH
- Run
source ~/.bash_profile
- cd into wiki-es-dump/ where the below scripts are located
- Follow the instructions in wiki-setup.md to
- Install dependencies
- Run scripts and set up the indices
- Set up the twitter opinions database (Skip this step if you don't need the opinions resonse generator
Configure the credentials for your es index as environment variables Step 1: copy the following into your ~/.bash_profile export ES_PASSWORD= your_password export ES_USER=your_username export ES_REGION=your_region export ES_HOST=your_host export ES_SCHEME=https export ES_PORT=your_port
Step 2: run source ~/.bash_profile
Replace credential in chirpy/core/es_config.json
“url”: your_es_url
- Make a new conda env:
conda create --name chirpy python=3.7
- Install pip3 --v19.0 or higher
- cd into your new directory
- run
conda activate chirpy
- run
pip3 install -r requirements.txt
Install docker Pull images from our dockerhub repositories
docker pull openchirpy/questionclassifier
docker pull openchirpy/dialogact
docker pull openchirpy/g2p
docker pull openchirpy/stanfordnlp
docker pull openchirpy/corenlp
docker pull openchirpy/gpt2ed
docker pull openchirpy/convpara
These images contain the model files as well. The images are large and can a while to download. We would recommend having 24G of disk space allocated to docker (otherwise it'll complain about the disk space being full).
Run python3 -m servers.local.shell_chat
To end your conversation, say “stop”
If the docker images don't exist (you didn't download them in the above step), the script will attempt to build them which might take a while.
Depending on which docker module you want to rebuild you would have to download one of the following models. Then run the respective Dockerfile to build there. There are issues with the python package versioning. Huggingface transformers has gotten breaking changes since we wrote the code, so the code needs to be updated, but that will likely not happen immedietly but might happen with next release.
- Add a model/ directory to docker/dialogact, docker/emotionclassifier, docker/gpt2ed, and docker/questionclassifier
- Download and unzip models in this folder, and move them into the chirpycardinal repo
- dialog-act.zip should go to docker/dialogact/model
- emotion-classifier.zip should go to docker/emotionclassifier/model
- gpt2ed.zip should go to docker/gpt2ed/model. Once unzipped, rename to gpt2ed
- question-classifier.zip should go to docker/questionclassifier/model
The code is licensed under GNU AGPLv3. There is an exception for currently participating Alexa Prize Teams to whom it is licensed under GNU GPLv3.