Click here to Skip to main content
Click here to Skip to main content

Building an AI Chatbot using a Regular Expression Engine

By , 21 Jun 2007
 

Screenshot - VerbotSDK.gif

Introduction

This article describes how to build an Artificial Intelligence (AI) Chatterbot using an open source, Regular Expression-based natural language processing engine called Verbot. Chatterbot technology is not new, but has been growing in popularity and usage as people experiment with new ways of interacting with computers. Chatterbots, Animated Characters, Speech Recognition and Voice Synthesis are being used to facilitate new human–computer interaction (HCI) channels.

Background

The original chatterbot, ELIZA was developed by Joseph Weizenbaum in 1966. ELIZA was a virtual psychotherapist that would attempt to engage the user by staying on topic and sounding concerned with his/her problems. In 1994, Michael Mauldin -- the creator of the first Verbot, Sylvie -- coined the term "ChatterBot." Since then, Verbots have evolved and matured into the current Verbot 4 version created by Conversive. In 2006, Conversive released the Verbot SDK as open source to allow people to easily create their own 'bots and embed them in their own applications. This article describes some of the basics behind the Verbot Engine SDK and how the SDK can be integrated into another application.

How the Verbot works

Before delving into code, I thought it would be useful to explain at a high level how the Verbot SDK works. All chatterbots have an idea of a "KnowledgeBase" or script, which tells the 'bot what keywords or phrases to recognize. The corresponding output is then sent to the user when a match is found. Verbot KnowledgeBases are made up of a collection of rules that are the fundamental building blocks of Verbot conversations. Rules must have one or more Inputs, which recognize what the user says. They must also have one or more Outputs, which are what the 'bot responds when an input in the rule is matched. When the Verbot Engine loads a KnowledgeBase file, it turns the simple text inputs found in the script into regular expressions that can then be used as the basis for matching.

For example, let's say we have an input which is:

What is your name?

The resulting regular expression generated by the engine looks like this:

^(|.*?\b|.*?\s)What\b.+?\bis\b.+?\byour\b.+?\bname(|\b.*?|\s.*?)$

This may be a bit daunting if you are unfamiliar with Regular Expression syntax. Even if you are familiar, it may still seem a bit cryptic. Basically, the engine has put wildcards between words, as well as at the start and end of the phrase. This regular expression will match to, "So, what the heck is your name?" but not to, "What's your name?" To match to this, we could use the Synonym feature in Verbots, which you can learn more about at their website along with other, more advanced scripting topics. Also, there is a good Regular Expression syntax reference over at dotnetcoders if you'd like to learn more about regex.

Verbot KnowledgeBases (.vkb extension) are XML files that define the rules, inputs and outputs of the KnowledgeBase. They may also reference other Verbot 4 file types such as Synonyms, Replacement Profiles and Code Modules. Verbots allows you to "compile" your VKB files into a more compact binary "Compiled KnowledgeBase" (.ckb extension) file format.

Testing the application

Execute the VerbotWindowsApplicationSample.exe file found within the VerbotWindowsApplicationSample\bin\Release folder. Once the application is running, choose the File -> Load... menu item and browse to the VerbotWindowsApplicationSample\Resources\sample.ckb file to open the sample KnowledgeBase. Once the file is loaded into the engine, you may interact with the 'bot. Try typing "notepad" to test out one of the rules included in the sample KnowledgeBase.

Notice how the program has started Windows Notepad. This is behavior coded into the Sample application to parse commands in the script. I'll talk more about this later.

Using the code

To use the Verbot Engine SDK inside your own application, simply include the Verbot4Library reference in your project, create an instance of the Verbot4Engine and call either AddCompiledKnowledgeBase or AddKnowledgeBase to load your 'bot's knowledge. To interact with the 'bot when user input comes in, create a State object to uniquely identify your user. Add the paths to the KnowledgeBases you want your user to interact with. Then call the GetReply method on the Verbot4Engine object to find a match in the loaded script(s).

Let's look at the getReply() function in our VerbotWinApp.cs file:

private void getReply()
{
    string stInput = this.inputTextBox.Text.Trim();
    this.inputTextBox.Text = "";
    Reply reply = this.verbot.GetReply(stInput, this.state);
    if(reply != null)
    {
        this.outputTextBox.Text = reply.Text;
        this.parseEmbeddedOutputCommands(reply.AgentText);
        this.runProgram(reply.Cmd);
    }
    else
        this.outputTextBox.Text = "No reply found.";
}

This method takes the text in the input text box and sends it to the engine's GetReply method. It gets a Reply object back, which we can then process. The Reply object has a member "Text" that we will just put in the output box. It also has an "AgentText" member, which is a version of the Text meant to be sent to a Text-To-Speech (TTS) engine. It has a "Cmd" (Command) member, too, that we can use for special processing as necessary.

Finally, take a look at the parseEmbeddedOutputCommands and runEmbeddedOutputCommand methods. These methods do custom processing based on our requirements. This is where the "run" command opens Notepad, as I mentioned above.

Depending on how your own application works, you can make customizations to how the Reply object is handled. For example, in an online 'bot engine you may want to process URLs by opening a popup window, etc.

Creating knowledge

There are some freely available tools to help you create a Verbot KnowledgeBase. Verbot GPL Editor and VCompiler are a couple of options to get you started. You can also use the Verbot Editor, which costs $10 to unlock with a registration code. If you'd like to create your own KnowledgeBase creation tool, the code is pretty straightforward. You may also want to look at the source code for the Verbot GPL Editor I mentioned above as a good reference. Here is a summary of the steps required to create a KnowledgeBase in code:

  1. First, create an instance of the KnowledgeBase class:
    KnowledgeBase kb = new KnowledgeBase();
  2. Then we'll want to create a rule to add to our KB:
    Rule r = kb.AddRule();
  3. Finally, for each rule you create you'll want to have at least one input and one output. We could manually create and add inputs and outputs or we could simply call the AddInput and AddOutput methods in the rule class:
    r.AddInput("Input Text", "");
    r.AddOutput("Output Text", "", "");

Now we've got a KnowledgeBase object with one rule that has one input and one output. Of course, in a real application we wouldn't want to hard-code the "Input Text" and "Output Text" fields and would probably want to allow the user to add these themselves, but you get the idea. Next, we probably want to save our KB to a file. To do this, we need an instance of the XMLToolbox class. Then we simply call the SaveXML method to save the file:

XMLToolbox xmlToolbox = new XMLToolbox(typeof(KnowledgeBase));
xmlToolbox.SaveXML(kb, @"C:\mykbpath.vkb");

Then we want to be able to load our KnowledgeBase into the Verbot Engine and be able to interact with it. Here is the code to do that:

Verbot4Engine engine = new Verbot4Engine();
KnowledgeBaseItem kbi = new KnowledgeBaseItem();
kbi.Fullpath = @"C:\";
kbi.Filename = "mykbpath.vkb";
engine.AddKnowledgeBase(kb, kbi);
State state = new State();
state.CurrentKBs.Add(@"C:\mykbpath.vkb");

Finally, to interact with the loaded knowledge bases just call the GetReply method on the Engine, as discussed above.

Further reading

If you are interested in learning more about Verbots, visit the Verbot community forums or browse Verbots wiki to learn more about scripting your own Verbot.

History

  • 22 March, 2007 -- First draft of article.
  • 28 March, 2007 -- Updated article for new version of SDK 4.1.3.2, which includes a simple console application as a sample and a new KnowledgeBase method, AddRule, which returns the new rule. Also, small changes in article instructions were made.
  • 21 June, 2007 -- Article edited and moved to the main CodeProject.com article base.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

MattsterP
Web Developer
United States United States
Member
Matt Palmerlee is a Software Engineer that has been working in the Microsoft.NET environment developing C# WebServices, Windows Applications, Web Applications, and Windows Services since 2003.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalnice jobmembergreenknt16 Apr '09 - 4:44 
Just what I wanted thanks Smile | :)
QuestionSynonyms - SDK (C#)memberPhil Bartie18 Dec '08 - 11:18 
Hi....
Thanks for this cool Codeproject article....
 
Just wondering how do you use synonym files, or build them live, when in C# using the Verbot SDK?
 
I've found some .vsn files on the Verbot forums, and tried to use them without any success.....
 

Also in code I tried the following
 
Synonym s = new Synonym();
s.AddPhrase("what's, what is");
s.GetNewPhraseId();
 
but not sure how to load this into a KB or something to actually use it?
 
Does anyone have examples of using Synonyms from C#?
 
Thanks for any tips!
Phil
GeneralNeed help to load KBmemberDinesh Vitharana24 May '08 - 10:21 
// verbot variables
Verbot4Engine verbot = new Verbot4Engine();
KnowledgeBase kb = new KnowledgeBase();
KnowledgeBaseItem kbi = new KnowledgeBaseItem();
State state = new State();
 
// load the knowledgebase item
kbi.Filename = "kbi.vkb";
kbi.Fullpath = @"C:\";
 
// set the knowledge base for verbot
verbot.AddKnowledgeBase(kb, kbi);
 
state.CurrentKBs.Add(@"C:\kbi.vkb");

string msg = TextBox1.Text.ToString();
 
Reply reply = verbot.GetReply(msg, state);
if (reply != null)
TextBox1.Text = reply.AgentText;
 

 
This is my code. The KB is allready created in C as "kbi.vkb".
But it always returns Null when i call GetReplt().
 
(I removed the coding part which creates the KB after i created it..)
 
When the removed coding part is there in the coding it works. What i understood is, that it won't use the created KB.
 
Can some one help me with this
AnswerRe: Need help to load KBmemberLars Brandt15 Aug '08 - 11:07 
Use the following approach instead:
 
1) Create and compile your knowledge base in the Verbot script editor etc.
 
2) Load it in your application like this:
(note that the engine will freeze if you try to
load one of the standard .ckb's like Sylvie.ckb)

 

        private static void InvokeBot()
        {
            Verbot4Engine verbot = new Verbot4Engine();
            State state = new State();
 
            verbot.AddCompiledKnowledgeBase(Environment.CurrentDirectory + "\\Custom.ckb");
           
            state.CurrentKBs.Clear();
            state.CurrentKBs.Add(Environment.CurrentDirectory + "\\Custom.ckb");
 
            Console.WriteLine("Hi, how may I help you?");
            Console.WriteLine("(type \"exit\" to exit)");
            string tmpInput = "";
 
            while (true)
            {
                tmpInput = Console.ReadLine();
 
                // check for exit
                if (tmpInput == "exit")
                {
                    return;
                }
                
 
                Reply reply = verbot.GetReply(tmpInput, state);
                if (reply != null)
                {
                    Console.WriteLine(reply.Text);
                }
                else
                {
                    Console.WriteLine("I couldn't find any data regarding your request.");
                }
            }
        }

 
Lars Brandt MCP/C#

GeneralLoad knowladge basememberahmedmakki14 May '08 - 4:19 
hi there,
is it possible to provide information on how to load more than one knowladge base file (.vkb)to the app? this is in case if i want to saperate my knowladge into different vkb xml files..
 
thanks for your help
 
Ahmed
General[Message Deleted]memberDanny Rodriguez27 Jan '08 - 9:12 
[Message Deleted]
QuestionWannt integration with AIM, MSN, YAhoo???membervijaymodi_8121 Jun '07 - 18:51 
Hi,
You can find an article to integrate ASP.net with AIM, MSN, Yahoo using the following link:
 
http://vijaymodi.wordpress.com/2007/06/20/aim-yahoo-msn-icq-chat-bots/[^]
 
Regards,Smile | :)
Vijay Modi
 
Vijay Modi
Software Engineer.

QuestionDo they have rules here about people coming on and schleping their products?membersherifffruitfly21 Jun '07 - 15:47 
If not, they should.
AnswerRe: Do they have rules here about people coming on and schleping their products?memberMattsterP22 Jun '07 - 6:34 
There are many articles about using and developing code on CodeProject which are released by Companies who would like to generate additional interest.
This article uses freely available open-source code that is of general interest to anyone that is interested in the field of Artificial Intelligence and pattern matching, there is no cost to use the Verbots SDK for GPL, it just happens to be provided by Conversive, Inc.
 
-Matt
GeneralRe: Do they have rules here about people coming on and schleping their products?membersherifffruitfly22 Jun '07 - 6:39 
Alright - now you're just freakin lying to my freakin face.
 
"The easiest way to get started would be to download and install the Verbot, to be able to script you'll need to purchase a registration code for $10,"
 
(1) Coming to a place like this to schlep is sleazy.
(2) Doing so without disclosing that's what you're doing is sleazier.
(3) Doing so without disclosing and then lying to someone's face about is about as sleazy as it gets. Good job, Conversive - you get a blog post.
 
Sheesh.
GeneralRe: Do they have rules here about people coming on and schleping their products?memberMattsterP25 Jun '07 - 10:14 
Spending $10 on the registration for the Verbots product is optional, that's why I said "The easiest way to get started..." People can use the open source SDK for free and develop NLP chatterbots without shelling out any money. The $10 just unlocks the scripting interface to make it easy to develop your own A.I. knowledgebases, but you can also use the Verbot GPL Editor or the VCompiler completely for free.
 
Hope this clears it up,
-Matt
QuestionHow to create a rule/knowledgebasemembermerlin98128 Mar '07 - 10:47 
Thank you for your article.
 
I'm having trouble creating a knowledgebase. Can you provide an simple example (like input = hello, output = hi)? I've tried searching the verbots site, but can't find any c# support.
 
Thank you
AnswerRe: How to create a rule/knowledgebase [modified]memberMattsterP28 Mar '07 - 12:59 
I'm sorry for the confusion, I realize that I didn't include instructions on how to create a KnowledgeBase in this article.
 
The easiest way to get started would be to download and install the Verbot, to be able to script you'll need to purchase a registration code for $10, then all you'll need to do is use the Verbot Editor to create knowledgebases, check out the wiki pages to learn more. If you just want to get started creating a knowledgebase without having to shell out any money, you can try out the GPL Verbot Editor I started creating, it's not done, but it also includes the code if you'd like to play with it. Also, Aaron created a cool VCompiler that allows you to create knowledgebases from text files. So, there are many options for you to get started, to really get into how to write the code you'll probably want to delve into the source code in the GPL Verbot Editor or in the SDK source itself.
 
Hopefully this makes sense, let me know if you have any questions or need more help. I've updated this article to have more instructions on creating knowledgebases in code as well. Item kbi = new KnowledgeBaseItem();
kbi.Fullpath = @"C:\";
kbi.Filename = "mykbpath.vkb";
engine.AddKnowledgeBase(kb, kbi);

 
Finally, to interact with the loaded knowledge bases just call the GetReply method on the enigine. (This part is explained in more detail in the article.
 
Hopefully this makes sense, let me know if you have any questions or need more help. I'll try to update this article to have more instructions on creating knowledgebases too.
GeneralRe: How to create a rule/knowledgebasemembermerlin98129 Mar '07 - 0:12 
Thank you for the fast and detailed response. One question: what are the conditions when adding a new rule? I see we can pass an empty string, but what else can be pass?
GeneralRe: How to create a rule/knowledgebasememberMattsterP29 Mar '07 - 6:28 
About the Condition field:
It can be any C# code that evaluates to true or false, as if you were putting the condition field inside an if(...) block, between the parens. i.e. if you put "false" in the condition field the rule will never fire.
 
This is often used with the variables feature in verbots, where for each user's "State" object there is a table of name/value pairs that you can access in the condition field.
 
There are some good examples of using these features in the Verbot Wiki pages on CSharp and on Code Modules
GeneralRe: How to create a rule/knowledgebasemembermerlin98129 Mar '07 - 9:01 
Thank you for all the help you've given so far.
 
I'm still having a problem getting my rule to work. As a test, I created a console app, one rule with two inputs. The code is below. I always get "No reply found", no matter how I write my input.
 

 

static void Main(string[] args)
{
// verbot variables
Verbot4Engine verbot = new Verbot4Engine();
KnowledgeBase kb = new KnowledgeBase();
KnowledgeBaseItem kbi = new KnowledgeBaseItem();
State state = new State();
 
// build the knowledgebase
Rule vRule = new Rule();
vRule.AddInput("Hello", "");
vRule.AddInput("Hi", "");
vRule.AddOutput("Hello, World", "", "");
kb.Rules.Add(vRule);
 
// save the knowledgebase
XMLToolbox xToolbox = new XMLToolbox(typeof(KnowledgeBase));
xToolbox.SaveXML(kb, @"c:\temp2\kbi.vkb");
 
// load the knowledgebase item
kbi.Filename = "kbi.vkb";
kbi.Fullpath = @"c:\temp2\";
 
// set the knowledge base for verbot
verbot.LoadKnowledgeBase(kb, kbi);
 

// get input
Console.WriteLine("Please enter your message");
string msg = Console.ReadLine();
 

// process the reply
Reply reply = verbot.GetReply(msg, state);
if (reply != null)
Console.WriteLine(reply.AgentText);
else
Console.WriteLine("No reply found.");
 

// wait for user to exit
Console.ReadLine();
}
 

GeneralRe: How to create a rule/knowledgebasememberMattsterP29 Mar '07 - 10:32 
Thanks for your patience getting this to work, I've taken your code and changed a couple of things to make it work.
 
First off, the State object needs to know what knowledgebases the user is talking with, we can just add that once before we call the "GetReply" method:
state.CurrentKBs.Add(@"c:\temp2\kbi.vkb");
 

Also, instead of calling verbot.LoadKnowledgebase, we need to call the AddKnowledgeBase method (to add it to the engine's currently loaded kb's):
// set the knowledge base for verbot
verbot.AddKnowledgeBase(kb, kbi);

 
Finally, one more line you'll need after creating your rule, you need to call a function to create a unique id for our new rule using the GetNewRuleId() method in the knowledgebase
 
// build the knowledgebase
Rule vRule = new Rule();
vRule.Id = kb.GetNewRuleId();

 
Then this should work, you may also want to make a loop for reading the users input, something like this is what I did:
 
// get input
Console.WriteLine("Please enter your message");
 
while(true)
{
string msg = Console.ReadLine();

// process the reply
Reply reply = verbot.GetReply(msg, state);
if (reply != null)
Console.WriteLine(reply.AgentText);
else
Console.WriteLine("No reply found.");
}

GeneralRe: How to create a rule/knowledgebasememberMattsterP29 Mar '07 - 15:01 
Also, by the way, I've updated the article with a new SDK version that has a new method in the KnowledgeBase class called AddRule which creates the new ID for you and returns the new rule, the new version also has a console app that should help you if you don't understand my previous instructions.
 
-Matt
GeneralRe: How to create a rule/knowledgebasemembermerlin98130 Mar '07 - 4:32 
Thanx Matt. Everything is working now. 5 stars from me
AnswerRe: How to create a rule/knowledgebasememberchineng8731 Mar '10 - 18:51 
Hi merlin.. can share you example code with me..
I have no idea to start it, because i'm new in C#..

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 21 Jun 2007
Article Copyright 2007 by MattsterP
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid