Introduction to setting up a chatbot using Python AIML

Source: Internet
Author: User
Tags session id sessions in python

The full name of AIML Is Artificial Intelligence Markup Language (Artificial Intelligence Markup Language). It is an XML Language used to create a natural Language software proxy. dr. Wallace and the Alicebot open source software organization were invented in-years. AIML is an XML format that defines rules for matching patterns and determining responses.

The AIML design goals are as follows:

AIML should be easy to learn and learn.
AIML should make the smallest concept encoded to support a stimulus-response discipline system component based on L. I .C.E.
AIML should be compatible with XML.
Writing AIML processable program files should be simple and convenient.
AIML objects should have good readability and clarity for people.
The AIML design should be formal and concise.
AIML should contain the dependence on other languages.
For more information about AIML, see Alice Bot's AIML Primer. You can also learn more about AIML on the AIML Wikipedia page and what it can do. With the help of the Python AIML package, we can easily implement AI chatbots.

1. Install the Python aiml Library

Pipinstallaiml
2. Get alice resources

After installing Python aiml, the Lib/site-packages/aiml directory under the Python installation directory contains the alice subdirectory, which is a simple corpus that comes with the system.

3. Load alice in Python

After obtaining alice resources, you can directly use the Python aiml library to load alice brain.

#-*-Coding: UTF-8 -*-
Importaiml
Importsys
Importos
 
 
Defget_module_dir (name ):
Path = getattr (sys. modules [name], '_ file _', None)
If not path:
RaiseAttributeError ('Module % s has not attribute _ file _ '% name)
Return OS. path. dirname (OS. path. abspath (path ))
 
 
Alice_path = get_module_dir ('iml') + '/alice'
# Switch to the working directory of the Corpus
OS. chdir (alice_path)
 
Alice = aiml. Kernel ()
Alice. learn ("startup. xml ")
Alice. respond ('load ALICE ')
 
While True:
Printalice. respond (raw_input ("Enter your message> "))
The above process is very simple. Next we need to create our own robots from scratch.

Create a standard startup file

The standard practice is to create a startup file named std-startup.xml as the primary entry point for loading the AIML file. In this example, we will create a basic file that matches a pattern and returns a corresponding one. We want to match the pattern load aiml B and then let it load our aiml brain as a response. We will create the basic_chat.aiml file in step.

<Aimlversion = "1.0.1" encoding = "UTF-8">
<! -- Std-startup.xml -->
 
<! -- Category is an automatic AIML unit -->
<Category>
 
<! -- Pattern is used to match user input -->
<! -- If the user inputs "load aiml B" -->
<Pattern> loadaiml B </pattern>
 
<! -- Template is the mode response -->
<! -- Learn an aiml file here -->
<Template>
<Learn> basic_chat.aiml </learn>
<! -- You can add more aiml files here -->
<! -- <Learn> more_aiml.aiml </learn> -->
</Template>
 
</Category>
 
</Aiml>
Create an AIML file

The AIML file we created can only process one mode: load aiml B. When we input the command to the robot, it will try to load basic_chat.aiml. It is invalid unless we create it. The following content can be written into basic_chat.aiml. We will match two basic modes and responses.

<Aimlversion = "1.0.1" encoding = "UTF-8">
<! -- Basic_chat.aiml -->
<Aiml>
 
<Category>
<Pattern> HELLO </pattern>
<Template>
Well, hello!
</Template>
</Category>
 
<Category>
<Pattern> WHATAREYOU </pattern>
<Template>
I'm a bot, silly!
</Template>
</Category>
 
</Aiml>
Random response

You can also add a random response as follows. It will respond randomly when receiving a message starting with "One time I. * Is a wildcard that matches anything.

<Category>
<Pattern> onetime I * </pattern>
<Template>
<Random>
<Li> Goon. </li>
<Li> Howoldareyou? </Li>
<Li> Bemorespecific. </li>
<Li> I didnot knowthat. </li>
<Li> Areyoutellingthetruth? </Li>
<Li> I don't knowwhatthatmeans. </li>
<Li> Try to tellmethatanotherway. </li>
<Li> Areyoutalkingaboutananimal, vegetableor mineral? </Li>
<Li> Whatis it? </Li>
</Random>
</Template>
</Category>
Use an existing AIML file

Writing your own AIML file is a very interesting thing, but it will take a lot of effort. I think it takes about 10,000 models to get real. Fortunately, the ALICE Foundation provides a large number of Free AIML files. Browse the AIML file on Alice Bot website.

Test the new robot

So far, all AIML files in XML format are ready. As part of the robot brain, they are all important, but currently they are only information. Robots need to survive. You can customize AIML in any language. Python is used here.

#-*-Coding: UTF-8 -*-
Importaiml
Importos
 
 
Mybot_path = './mybot'
# Switch to the working directory of the Corpus
OS. chdir (mybot_path)
 
Mybot = aiml. Kernel ()
Mybot. learn ("std-startup.xml ")
Mybot. respond ('load aiml B ')
 
While True:
Printmybot. respond (raw_input ("Enter your message> "))
This is the simplest program we can start. It creates an aiml object, learns the startup file, and then loads the remaining aiml files. Then, it is ready to chat, and we enter an infinite loop that keeps prompting users of messages. You will need to enter a model that the robot knows. This mode depends on which AIML files are loaded. We create the startup file as a separate entity, so that we can add more aiml files to the robot without modifying any program source code. We can add more files for learning in the startup xml file.

Accelerate Brain loading

When you start to have many AIML files, it will take a long time to learn. This is where the brain file comes from. After the robot learns all the AIML files, it can directly save its brain to a file, which will dynamically accelerate the loading time in subsequent operations.

#-*-Coding: UTF-8 -*-
Importaiml
Importos
 
 
Mybot_path = './mybot'
# Switch to the working directory of the Corpus
OS. chdir (mybot_path)
 
Mybot = aiml. Kernel ()
 
If OS. path. isfile ("mybot_brain.brn "):
Mybot. bootstrap (brainFile = "mybot_brain.brn ")
Else:
Mybot. bootstrap (learnFiles = "std-startup.xml", commands = "load aiml B ")
Mybot. saveBrain ("mybot_brain.brn ")
 
While True:
Printmybot. respond (raw_input ("Enter your message> "))
Remember, if you use the brain method written above, the new changes will not be saved to the brain during the load operation. You will need to delete the brain file so that it can be rebuilt at the next startup, or you need to modify the code so that it can save the brain at a certain time point after reload.

Add Python commands

If you want to provide some special commands for running Python functions for your robot, you should capture the input message for the robot and then send it to mybot. handle it before respond. In the preceding example, the user input is obtained from raw_input. However, we can get the input from anywhere. It may be a TCP socket or a speech recognition source code. Process the message before it enters AIML. You may want to skip AIML processing on certain messages.

While True:
Message = raw_input ("Enter your message> ")
If message = "quit ":
Exit ()
Elifmessage = "save ":
Mybot. saveBrain ("bot_brain.brn ")
Else:
Bot_response = mybot. respond (message)
# Do something with bot_response
Sessions and assertions

By specifying a session, AIML can crop different sessions for different people. For example, if someone tells a robot that his name is Alice, and another tells the robot that his name is Bob, the robot can distinguish different people. To specify the session you are using, pass it as the second parameter to respond ()

SessionId = 12345
Mybot. respond (raw_input (">>>"), sessionId)
This is very helpful for customizing personalized conversations for each client. You will have to generate your session ID in some form and trace it. Note: Saving the brain file does not save all session values.

SessionId = 12345
 
# Obtain session information as a dictionary, including input and output history,
# And any known assertions
SessionData = mybot. getSessionData (sessionId)
 
# A unique value is required for each session ID.
# Assertion name is some/a name that the robot has learned in the conversation with you
# The robot may know that you are Billy, and your dog name is Brandy"
Mybot. setPredicate ("dog", "Brandy", sessionId)
Clients_dogs_name = mybot. getPredicate ("dog", sessionId)
 
Mybot. setBotPredicate ("hometown", "127.0.0.1 ")
Bot_hometown = mybot. getBotPredicate ("hometown ")
In AIML, we can use the set response in the template to set assertions.

<Aimlversion = "1.0.1" encoding = "UTF-8">
<Category>
<Pattern> MYDOGSNAMEIS * </pattern>
<Template>
Thatis interestingthatyouhave a dognamed <setname = "dog"> <star/> </set>
</Template>
</Category>
<Category>
<Pattern> whatis mydogsname </pattern>
<Template>
Yourdog's nameis <getname = "dog"/>.
</Template>
</Category>
</Aiml>
With the above AIML, you can tell the robot:

Mydogsnameis Max
The robot will answer you:

Thatis interestingthatyouhave a dognamedMax
Then, if you ask the robot:

Whatis mydogsname?
The robot will answer:

Yourdog's nameis Max.
Aiml can be used to implement chatbots, but the following problems occur when used in Chinese:

There are few Chinese rule libraries. The rule repository is equivalent to the "brain" of the chatbot. Generally, the richer the rule repository, the more human chatbots respond. At present, the English rule Library is rich and wide-covering and publicly available. However, no public Chinese rule repository is available.
The AIML interpreter does not support Chinese characters. In fact, Python's Pyaiml module (parser) already supports Chinese, but there are also the following problems: English words generally have spaces or punctuation, therefore, it has a "natural word segmentation" feature. Chinese input is not separated by spaces, which may cause some inconvenience in practice. For example, to match existing/empty input, you need to include both modes in the rule repository.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.