<p>I want to build a bot that asks someone a few simple questions and branches based on the answer.  I realize parsing meaning from the human responses will be challenging, but how do you setup the program to deal with the "state" of the conversation?</p>

<p>It will be a one-to-one conversation between a human and the bot.</p>

[{'answer_id': 55049, 'author': 'EBGreen', 'author_id': 1358, 'author_profile': 'https://Stackoverflow.com/users/1358', 'pm_score': 0, 'selected': False, 'text': '<p>I would suggest looking at Bayesian probabilities. Then just monitor the chat room for a period of time to create your probability tree.</p>\n'}, {'answer_id': 55053, 'author': 'argv0', 'author_id': 5595, 'author_profile': 'https://Stackoverflow.com/users/5595', 'pm_score': 6, 'selected': True, 'text': '<p>You probably want to look into <a href="http://en.wikipedia.org/wiki/Markov_chain" rel="noreferrer">Markov Chains</a> as the basics for the bot AI.   I wrote something a long time ago (the code to which I\'m not proud of at all, and needs some mods to run on Python > 1.5) that may be a useful starting place for you: <a href="http://sourceforge.net/projects/benzo/" rel="noreferrer"><a href="http://sourceforge.net/projects/benzo/" rel="noreferrer">http://sourceforge.net/projects/benzo/</a></a></p>\n\n<p>EDIT:  Here\'s a minimal example in Python of a Markov Chain that accepts input from stdin and outputs text based on the probabilities of words succeeding one another in the input.  It\'s optimized for IRC-style chat logs, but running any decent-sized text through it should demonstrate the concepts:</p>\n\n<pre><code>import random, sys\n\nNONWORD = "\\n"\nSTARTKEY = NONWORD, NONWORD\nMAXGEN=1000\n\nclass MarkovChainer(object):\n    def __init__(self):\n        self.state = dict()\n\n    def input(self, input):\n        word1, word2 = STARTKEY\n        for word3 in input.split():\n            self.state.setdefault((word1, word2), list()).append(word3)\n            word1, word2 = word2, word3 \n        self.state.setdefault((word1, word2), list()).append(NONWORD)\n\n    def output(self):\n        output = list()\n        word1, word2 = STARTKEY\n        for i in range(MAXGEN):\n            word3 = random.choice(self.state[(word1,word2)])\n            if word3 == NONWORD: break\n            output.append(word3)\n            word1, word2 = word2, word3\n        return " ".join(output)\n\nif __name__ == "__main__":\n    c = MarkovChainer()\n    c.input(sys.stdin.read())\n    print c.output()\n</code></pre>\n\n<p>It\'s pretty easy from here to plug in persistence and an IRC library and have the basis of the type of bot you\'re talking about.</p>\n'}, {'answer_id': 55055, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 2, 'selected': False, 'text': '<p>I think you can look at the code for <a href="http://kookybot.org/" rel="nofollow noreferrer">Kooky</a>, and IIRC it also uses Markov Chains.</p>\n\n<p>Also check out the <a href="http://quotes.kookybot.org/top" rel="nofollow noreferrer">kooky quotes</a>, they were featured on Coding Horror not long ago and some are hilarious.</p>\n'}, {'answer_id': 55062, 'author': 'nutario', 'author_id': 5334, 'author_profile': 'https://Stackoverflow.com/users/5334', 'pm_score': 2, 'selected': False, 'text': '<p>I think to start this project, it would be good to have a database with questions (organized as a tree. In every node one or more questions).\nThese questions sould be answered with "yes " or "no".</p>\n\n<p>If the bot starts to question, it can start with any question from yuor database of questions marked as a start-question. The answer is the way to the next node in the tree.</p>\n\n<p>Edit: Here is a somple one written in ruby you can start with: <a href="http://snippets.dzone.com/posts/show/1785" rel="nofollow noreferrer">rubyBOT</a></p>\n'}, {'answer_id': 55464, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure this is what you\'re looking for, but there\'s an old program called <a href="http://en.wikipedia.org/wiki/ELIZA" rel="nofollow noreferrer">ELIZA</a> which could hold a conversation by taking what you said and spitting it back at you after performing some simple textual transformations.</p>\n\n<p>If I remember correctly, many people were convinced that they were "talking" to a real person and had long elaborate conversations with it.</p>\n'}, {'answer_id': 94936, 'author': 'Josh Millard', 'author_id': 13600, 'author_profile': 'https://Stackoverflow.com/users/13600', 'pm_score': 4, 'selected': False, 'text': '<p>Folks have mentioned already that statefulness isn\'t a big component of typical chatbots:</p>\n\n<ul>\n<li><p>a pure Markov implementations may express a very loose sort of state if it is growing its lexicon and table in real time&mdash;earlier utterances by the human interlocutor may get regurgitated by chance later in the conversation&mdash;but the Markov model doesn\'t have any inherent mechanism for selecting or producing such responses.</p></li>\n<li><p>a parsing-based bot (e.g. ELIZA) generally attempts to respond to (some of the) semantic content of the most recent input from the user without significant regard for prior exchanges.</p></li>\n</ul>\n\n<p>That said, you certainly <i>can</i> add some amount of state to a chatbot, regardless of the input-parsing and statement-synthesis model you\'re using.  How to do that depends a lot on what you want to accomplish with your statefulness, and that\'s not really clear from your question.  A couple general ideas, however:</p>\n\n<ul>\n<li><p>Create a keyword stack.  As your human offers input, parse out keywords from their statements/questions and throw those keywords onto a stack of some sort.  When your chatbot fails to come up with something compelling to respond to in the most recent input&mdash;or, perhaps, just at random, to mix things up&mdash;go back to your stack, grab a previous keyword, and use that to seed your next synthesis.  For bonus points, have the bot explicitly acknowledge that it\'s going back to a previous subject, e.g. "Wait, HUMAN, earlier you mentioned foo.  [Sentence seeded by foo]".</p></li>\n<li><p>Build RPG-like dialogue logic into the bot.  As your parsing human input, toggle flags for specific conversational prompts or content from the user and conditionally alter what the chatbot can talk about, or how it communicates.  For example, a chatbot bristling (or scolding, or laughing) at foul language is fairly common; a chatbot that will get het up, and conditionally <i>remain so until apologized to</i>, would be an interesting stateful variation on this.  Switch output to ALL CAPS, throw in confrontational rhetoric or demands or sobbing, etc.</p></li>\n</ul>\n\n<p>Can you clarify a little what you want the state to help you accomplish?</p>\n'}, {'answer_id': 217861, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 3, 'selected': False, 'text': '<p>Imagine a neural network with parsing capabilities in each node or neuron. Depending on rules and parsing results, neurons fire. If certain neurons fire, you get a good idea about topic and semantic of the question and therefore can give a good answer.</p>\n\n<p>Memory is done by keeping topics talked about in a session, adding to the firing for the next question, and therefore guiding the selection process of possible answers at the end.</p>\n\n<p>Keep your rules and patterns in a knowledge base, but compile them into memory at start time, with a neuron per rule. You can engineer synapses using something like listeners or event functions.</p>\n'}, {'answer_id': 1235616, 'author': 'dlamblin', 'author_id': 459, 'author_profile': 'https://Stackoverflow.com/users/459', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re just dabbling, I believe <a href="http://pidgin.im/" rel="nofollow noreferrer">Pidgin</a> allows you to script chat style behavior. Part of the framework probably tacks the state of who sent the message when, and you\'d want to keep a log of your bot\'s internal state for each of the last N messages. Future state decisions could be hardcoded based on inspection of previous states and the content of the most recent few messages. Or you could do something like the Markov chains discussed and use it both for parsing and generating.</p>\n'}, {'answer_id': 12791406, 'author': 'Erk', 'author_id': 386587, 'author_profile': 'https://Stackoverflow.com/users/386587', 'pm_score': 0, 'selected': False, 'text': '<p>If you do not require a learning bot, using AIML (<a href="http://www.aiml.net/" rel="nofollow">http://www.aiml.net/</a>) will most likely produce the result you want, at least with respect to the bot parsing input and answering based on it.</p>\n\n<p>You would reuse or create "brains" made of XML (in the AIML-format) and parse/run them in a program (parser). There are parsers made in several different languages to choose from, and as far as I can tell the code seems to be open source in most cases.</p>\n'}, {'answer_id': 23901502, 'author': 'user3513316', 'author_id': 3513316, 'author_profile': 'https://Stackoverflow.com/users/3513316', 'pm_score': 1, 'selected': False, 'text': "<p>naive chatbot program. No parsing, no cleverness, just a training file and output.</p>\n\n<p>It first trains itself on a text and then later uses the data from that training to generate responses to the interlocutor’s input. The training process creates a dictionary where each key is a word and the value is a list of all the words that follow that word sequentially anywhere in the training text. If a word features more than once in this list then that reflects and it is more likely to be chosen by the bot, no need for probabilistic stuff just do it with a list.</p>\n\n<p>The bot chooses a random word from your input and generates a response by choosing another random word that has been seen to be a successor to its held word. It then repeats the process by finding a successor to that word in turn and carrying on iteratively until it thinks it’s said enough. It reaches that conclusion by stopping at a word that was prior to a punctuation mark in the training text. It then returns to input mode again to let you respond, and so on.</p>\n\n<p>It isn’t very realistic but I hereby challenge anyone to do better in 71 lines of code !! This is a great challenge for any budding Pythonists, and I just wish I could open the challenge to a wider audience than the small number of visitors I get to this blog. To code a bot that is always guaranteed to be grammatical must surely be closer to several hundred lines, I simplified hugely by just trying to think of the simplest rule to give the computer a mere stab at having something to say.</p>\n\n<p>Its responses are rather impressionistic to say the least ! Also you have to put what you say in single quotes.</p>\n\n<p>I used War and Peace for my “corpus” which took a couple of hours for the training run, use a shorter file if you are impatient…</p>\n\n<p>here is the trainer</p>\n\n<pre><code>#lukebot-trainer.py\nimport pickle\nb=open('war&amp;peace.txt')\ntext=[]\nfor line in b:\n    for word in line.split():\n        text.append (word)\nb.close()\ntextset=list(set(text))\nfollow={}\nfor l in range(len(textset)):\n    working=[]\n    check=textset[l]\n    for w in range(len(text)-1):\n        if check==text[w] and text[w][-1] not in '(),.?!':\n            working.append(str(text[w+1]))\n    follow[check]=working\na=open('lexicon-luke','wb')\npickle.dump(follow,a,2)\na.close()\n</code></pre>\n\n<p>here is the bot</p>\n\n<pre><code>#lukebot.py\nimport pickle,random\na=open('lexicon-luke','rb')\nsuccessorlist=pickle.load(a)\na.close()\ndef nextword(a):\n    if a in successorlist:\n        return random.choice(successorlist[a])\n    else:\n        return 'the'\nspeech=''\nwhile speech!='quit':\n    speech=raw_input('&gt;')\n    s=random.choice(speech.split())\n    response=''\n    while True:\n        neword=nextword(s)\n        response+=' '+neword\n        s=neword\n        if neword[-1] in ',?!.':\n            break\n    print response\n</code></pre>\n\n<p>You tend to get an uncanny feeling when it says something that seems partially to make sense. </p>\n"}, {'answer_id': 51896174, 'author': 'Ratnakar Chinchkar', 'author_id': 3723257, 'author_profile': 'https://Stackoverflow.com/users/3723257', 'pm_score': 0, 'selected': False, 'text': '<p>You can use "ChatterBot", and host it locally using - \'flask-chatterbot-master" </p>\n\n<p><strong>Links:</strong> </p>\n\n<ol>\n<li>[ChatterBot Installation] \n<a href="https://chatterbot.readthedocs.io/en/stable/setup.html" rel="nofollow noreferrer">https://chatterbot.readthedocs.io/en/stable/setup.html</a> </li>\n<li>[Host Locally using - flask-chatterbot-master]: <a href="https://github.com/chamkank/flask-chatterbot" rel="nofollow noreferrer">https://github.com/chamkank/flask-chatterbot</a> </li>\n</ol>\n\n<p>Cheers, </p>\n\n<p>Ratnakar</p>\n'}]
['https://Stackoverflow.com/questions/55042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337/']