ELIZA and AIML
“We are automata in three quarters of our actions.”
Gottfried Wilhelm Leibniz
Objective
Explore how ELIZA processes text, applies transformation rules, and influenced later conversational systems. Learn how AIML makes rule-based chatbots more modular.
2.1 Introduction
ELIZA was one of the earliest natural language processing programs. Joseph Weizenbaum introduced it at MIT in 1966 (Weizenbaum 1966).
Weizenbaum called the set of patterns and predefined responses a conversation script. ELIZA kept that script separate from the engine that identified keywords and applied rules. Loading a different script could change the program’s persona or subject matter without changing the engine. A text editor let users modify the scripts themselves, as shown in Figure 2.1.

Figure 2.1. ELIZA’s source code, conversation script, and script editor.
The DOCTOR script made ELIZA famous. It loosely imitated the style of a Rogerian psychotherapist by reflecting the user’s statements back as questions. In the following conversation from the original paper, ELIZA’s lines appear in uppercase. Notice how it reuses the user’s words and asks follow-up questions that encourage the user to keep talking.
Men are all alike.
IN WHAT WAY
They're always bugging us about something or other.
CAN YOU THINK OF A SPECIFIC EXAMPLE
Well, my boyfriend made me come here.
YOUR BOYFRIEND MADE YOU COME HERE
He says I'm depressed much of the time.
I AM SORRY TO HEAR YOU ARE DEPRESSED
It's true. I am unhappy.
DO YOU THINK COMING HERE WILL HELP YOU NOT TO BE UNHAPPY
I need some help, that much seems certain.
WHAT WOULD IT MEAN TO YOU IF YOU GOT SOME HELP
Perhaps I could learn to get along with my mother.
TELL ME MORE ABOUT YOUR FAMILY
My mother takes care of me.
WHO ELSE IN YOUR FAMILY TAKES CARE OF YOU
My father.
YOUR FATHER
You are like my father in some ways.
WHAT RESEMBLANCE DO YOU SEE
You are not very aggressive but I think you don't want me to
notice that.
WHAT MAKES YOU THINK I AM NOT VERY AGGRESSIVE
You don't argue with me.
WHY DO YOU THINK I DON'T ARGUE WITH YOU
You are afraid of me.
DOES IT PLEASE YOU TO BELIEVE I AM AFRAID OF YOU
My father is afraid of everybody.
WHAT ELSE COMES TO MIND WHEN YOU THINK OF YOUR FATHER
Bullies.
DOES THAT HAVE ANYTHING TO DO WITH THE FACT THAT YOUR BOYFRIEND MADE YOU COME HERE
2.2 Processing Input
ELIZA uses keyword-based pattern matching (Mittmann 2021). On each turn, it scans the user’s text from left to right and looks for keywords defined in the script. The script assigns ranks to keywords, so when several candidates are available, ELIZA can try the rules associated with a higher-ranked word first.
In the DOCTOR script, words such as ALIKE and SAME have high priority. In “Men are all alike,” ELIZA recognizes ALIKE and uses its associated rule to produce “In what way?”
ELIZA separates the input into words, a step we would now call word tokenization. If it reaches a comma or period after finding a keyword, it discards the remainder of the input. For example, given “I am sick. But today it is raining,” a script that recognizes SICK can process “I am sick” and ignore the second sentence.
If ELIZA finds no keyword, it can fall back on a general response such as “I see” or “Please go on.” The original program could also store a response for later use. If the user had mentioned family earlier, ELIZA could return to that topic after a later input gave it little to work with. That simple memory mechanism helped sustain the appearance of continuity.
2.3 Transformation Rules
Once ELIZA selects a keyword, it tries the transformation rules associated with it. A decomposition rule identifies and captures pieces of the input. A reassembly rule places those pieces into a response template.
For “You are very helpful,” a decomposition rule might match “You are X” and capture “very helpful” as X. The reassembly rule “What makes you think I am X?” then yields “What makes you think I am very helpful?” The shift from “you” to “I” changes the perspective from the user to the chatbot. Simple substitutions such as “my” to “your” help reflected material fit the new sentence.
The adapted excerpt below gives REMEMBER a rank of 5 and IF a rank of 3. Under each keyword, decomposition patterns are followed by candidate responses. Numbers inside a response refer to pieces captured from the input.
(REMEMBER 5
(
(0 YOU REMEMBER 0)
(DO YOU OFTEN THINK OF 4)
(DOES THINKING OF ~ BRING ANYTHING ELSE TO MINO)
(WHAT ELSE OO YOU REMEMBER)
(WHY DO YOU REMEMBER 4 JUST NOW)
(WHAT IN THE PRESENT SITUATION REMINDS YOU OF 4)
(WHAT IS THE CONNECTION BETWEEN ME AND 4)
)
(
(0 DO I REMEMBER 0)
(DID YOU THINK I WOULD FORGET 5)
(WHY DO YOU THINK I SHOULD RECALL 5 NOW)
(WHAT ABOUT 5)
(=WHAT)
(YOU MENTIONED S)
)
)
(IF 3
(
(0 IF 0)
(DO YOU THINK ITS LIKELY THAT 3)
(DO YOU WISH THAT 3)
(WHAT DO YOU THINK ABOUT 3)
(REALLY, 2 3)
)
)
2.4 Implementation and Variants
The original ELIZA was written in MAD-SLIP and ran on an IBM 7094 under MIT’s Compatible Time-Sharing System (CTSS). The main program implemented the matching engine. The conversation rules were supplied separately in a list-based format. Weizenbaum’s 1966 article did not include the full program. The original MAD-SLIP source was recovered decades later from MIT’s archives (Lane et al. 2025).
Developers have since reimplemented ELIZA in languages including Lisp, PL/I, BASIC, Pascal, Prolog, Java, Python, Oz, and JavaScript. Many versions reproduce or adapt the therapist script. ELIZA also inspired other systems. In 1972, psychiatrist Kenneth Colby developed PARRY, which simulated a patient experiencing paranoia. PARRY combined an internal model of emotions and attitudes with rule-based dialogue and was even paired with ELIZA in an experimental conversation.
In 1995, Richard Wallace developed ALICE (Artificial Linguistic Internet Computer Entity), which put pattern matching to work at a much larger scale. ALICE used AIML, an XML-based format, to organize thousands of pattern-response categories (Wallace 2000). It won the Loebner Prize three times in the early 2000s. Other projects, including Jabberwacky, explored ways to learn new phrases. Rule-based chatbots continued to develop as statistical and machine learning approaches gained ground.
2.5 Keyword Ranking and Attention
In ELIZA, the script author assigns keyword ranks directly. Those ranks determine which patterns the system tries first. A Transformer-based language model instead computes attention weights for each input sequence (Vaswani et al. 2017). It works with tokens, which may be whole words or parts of words. Queries and keys help determine how strongly one token position should draw on information at another. The same token can therefore receive different attention weights in different contexts.
A language model learns dense representations and uses them to capture relationships that exact keyword matching would miss. Chapter 4 explains the Transformer in more detail.
2.6 Text Generation
ELIZA processes each turn with a narrow view of the conversation. It can retrieve a stored response or change pronouns to give the exchange a sense of continuity. If the user changes subjects abruptly, it searches for a new keyword and can fall back on a generic response.
Modern language models can use prior turns that fit within their context window. If you mention a brother named Alex and later ask, “Can he help me with this problem?”, the model may infer that “he” refers to Alex. ELIZA would need rules and a way to store the name for that particular case.
ELIZA assembles replies from predefined templates and fragments of the user’s input. A language model generates a response token by token using a probability distribution conditioned on the context. It can formulate explanations, analogies, and follow-up questions across many topics. Its replies can still be inaccurate or inconsistent.
Users sometimes attributed understanding or emotion to ELIZA even though it was following a script. This tendency is known as the ELIZA effect. The greater fluency and variety of modern chatbots can make the same impression stronger.
2.7 ELIZA in Python
Start with an echo program. The function prefixes a message with “You said:” and returns it. This illustrates the simplest way to reuse the user’s words in a reply.
def response(user_input):
return "You said: " + user_input
for message in ("I am happy", "I am excited"):
print(f"User: {message}")
print(f"ELIZA: {response(message)}")
User: I am happy
ELIZA: You said: I am happy
User: I am excited
ELIZA: You said: I am excited
The next program uses regular expressions to recognize greetings, family references, and constructions such as “I am” or “I need.” Chapter 3 covers regular expressions in more detail.
import re
import random
rng = random.Random(0)
rules = [
(re.compile(r'\b(hello|hi|hey)\b', re.IGNORECASE),
["Hello. How do you do. Please tell me your problem."]), # rule 1
(re.compile(r'\b(I am|I\'?m) (.+)', re.IGNORECASE), # rule 2
["How long have you been {1}?",
"Why do you think you are {1}?"]),
(re.compile(r'\bI need (.+)', re.IGNORECASE), # rule 3
["Why do you need {1}?",
"Would it really help you to get {1}?"]),
(re.compile(r'\bI can\'?t (.+)', re.IGNORECASE), # rule 4
["What makes you think you can't {1}?",
"Have you tried {1}?"]),
(re.compile(r'\bmy (mother|father|mom|dad)\b', re.IGNORECASE), # rule 5
["Tell me more about your family.",
"How do you feel about your parents?"]),
(re.compile(r'\b(sorry)\b', re.IGNORECASE), # rule 6
["Please don't apologize."]),
(re.compile(r'\b(maybe|perhaps)\b', re.IGNORECASE), # rule 7
["You don't seem certain."]),
(re.compile(r'\bbecause\b', re.IGNORECASE), # rule 8
["Is that the real reason?"]),
(re.compile(r'\b(are you|do you) (.+)\?$', re.IGNORECASE), # rule 9
["Why do you ask that?"]),
(re.compile(r'\bcomputer\b', re.IGNORECASE), # rule 10
["Do computers worry you?"]),
]
fallback_replies = [
"I see.",
"Please tell me more.",
"Can you elaborate on that?"
]
def response(user_input):
for pattern, replies in rules:
match = pattern.search(user_input)
if match:
reply = rng.choice(replies)
if match.groups():
reply = reply.format(*(group.rstrip(".?!") for group in match.groups()))
return reply
return rng.choice(fallback_replies)
print("User: Hello.")
print("Bot: " + response("Hello."))
print("User: I am feeling sad.")
print("Bot: " + response("I am feeling sad."))
print("User: Maybe I was not good enough.")
print("Bot: " + response("Maybe I was not good enough."))
print("User: My mother tried to help.")
print("Bot: " + response("My mother tried to help."))
User: Hello.
Bot: Hello. How do you do. Please tell me your problem.
User: I am feeling sad.
Bot: Why do you think you are feeling sad?
User: Maybe I was not good enough.
Bot: You don't seem certain.
User: My mother tried to help.
Bot: How do you feel about your parents?
The response function tries rules in order and uses the first one that matches. If a rule offers several replies, the program chooses one at random. In the rule for “I am,” capture group 1 matches the opening phrase and capture group 2 matches the words that follow. Python’s str.format uses zero-based positions, so {1} inserts the second capture group. For “I am sad,” it inserts “sad” into the selected reply. If no rule matches, the chatbot chooses a generic reply such as “I see.”
The following example illustrates how different rules handle a longer exchange. Each reply depends on the current message and the rule it matches (Abdul-Kader and Woods 2015).
User: Hello
Bot: Hello. How do you do. Please tell me your problem.
User: I am feeling sad
Bot: Why do you think you are feeling sad?
User: Because I lost my job
Bot: Is that the real reason?
User: Maybe I was not good enough.
Bot: You don't seem certain.
User: My mother tried to help.
Bot: Tell me more about your family.
2.8 ELIZA with Python and Gradio
Gradio is an open-source Python library for giving models and functions an interactive web interface. Install it in your Python environment before running the examples.
python -m pip install gradio
The first version returns the same reply to every message. Gradio supplies the current message and the conversation history to the callback.
import gradio as gr
def chatbot(message, history):
return "Hello! I'm a chatbot. How can I help you?"
demo = gr.ChatInterface(fn=chatbot, title="Simple Chatbot")
demo.launch()
Save the program as chatbot.py and run it from the directory where you saved it.
python chatbot.py
Open the local address printed in the terminal, typically http://127.0.0.1:7860. Try sending “Hello” and “Goodbye.” Both messages receive the same reply in this version.

Figure 2.2. The basic Gradio interface in the original Portuguese edition.
You can now add rules. Normalizing case and whitespace lets the chatbot recognize “Hello” and “hello” as the same greeting.
import gradio as gr
def chatbot(message, history):
normalized = message.strip().casefold().rstrip(".!?")
if normalized in {"hi", "hello"}:
return "Hello! I'm a chatbot. How can I help you?"
if normalized == "who are you":
return "I'm a chatbot built to help answer your questions."
return "I didn't understand that. Could you try again?"
demo = gr.ChatInterface(fn=chatbot, title="Simple Chatbot")
demo.launch()
Another option is to choose a fallback reply at random. The rules still handle the greeting and the question about the chatbot’s identity.
import random
import gradio as gr
def chatbot(message, history):
normalized = message.strip().casefold().rstrip(".!?")
if normalized in {"hi", "hello"}:
return "Hello! I'm a chatbot. How can I help you?"
if normalized == "who are you":
return "I'm a chatbot built to help answer your questions."
return random.choice([
"Interesting!",
"Tell me more.",
"I'm not sure what to say to that.",
])
demo = gr.ChatInterface(fn=chatbot, title="Simple Chatbot")
demo.launch()

Figure 2.3. The Gradio chatbot with rules and random fallback replies in the original Portuguese edition.
The same interface can wrap the regular-expression chatbot from the previous section or a machine learning model. For task automation or customer support, replace generic fallback replies with guidance that helps the user take the next step.
2.9 Artificial Intelligence Markup Language (AIML)
Decades after ELIZA, the growth of the web made markup languages such as HTML familiar. AIML emerged in this setting as an XML-based specification for writing chatbots (Wallace 2009). Its small set of building blocks was designed to make knowledge bases easier to write, including for people with little programming experience. Figure 2.4 shows the basic architecture of an AIML interpreter.

Figure 2.4. Architecture of an AIML interpreter. Adapted from Silva and Costa (2007).
AIML relies on pattern matching, an approach widely used in question-and-answer chatbots (Abdul-Kader and Woods 2015). One design goal was to allow authors to combine knowledge bases from chatbots specializing in different domains. In principle, an interpreter could merge them and remove duplicate categories (Wallace 2000).
AIML has been described as a third-generation chatbot technology (Maria et al. 2010). Its extensions include iAIML, which introduced tags and an intent concept drawing on conversation analysis (Neves and Barros 2005). Web-based tools also help authors build AIML knowledge bases (Krassmann et al. 2017). ALICE is a prominent example, with roughly 16,000 categories that could contain nested XML tags (Wallace 2000).

Figure 2.5. A visual representation of the ALICE knowledge base. From Wallace (2003).
Wallace (2000) drew a parallel between AIML interpreters and case-based reasoning. An AIML category acts like a case by associating an input pattern with a response template. The interpreter selects a category based on the input, following the stimulus-response model illustrated in Figure 2.6. Some systems extend AIML with case-based reasoning to consult external information and expand their knowledge bases (Kraus and Fernandes 2008).

Figure 2.6. The stimulus-response model applied to AIML. From Lima (2017).
An AIML chatbot is a retrieval-based system. It selects a predefined response or response template based on the user’s message and any context encoded in the rules. This approach is often used for chatbots that operate in a narrowly defined domain (Borah et al. 2018).
The file below contains a single <category>. Inside it, <pattern> defines which input to match, and <template> specifies the response. The opening tag <template> and the closing tag </template> enclose the reply. With the wildcard * as its only pattern, this chatbot responds “Hello!” to any nonempty input it can match.
<aiml>
<category>
<pattern>*</pattern>
<template>Hello!</template>
</category>
</aiml>

Figure 2.7. An abstract view of an AIML knowledge base. Source listed in the original edition as Pandorabots, AIML Fundamentals.
The person who maintains an AIML knowledge base is called a botmaster (Wallace 2000). Botmasters edit categories, review dialogue logs to identify recurring requests, and add or refine replies. Developers, writers, and subject-matter specialists can all take on this role.
Extensions can add other ways of representing and looking up knowledge. For example, an interpreter that supports the Resource Description Framework (RDF) can store facts as subject-predicate-object triples. The chatbot can then query those facts as part of constructing a response.
Standard AIML has no explicit intent model of the kind used by many natural language understanding systems (Höhn 2019). An author can approximate one by routing variants of a request to a single category. The <srai> tag redirects processing to a different pattern. For example, separate categories for “HI” and “HEY THERE” can both route to a shared greeting category. The same technique can bring different ways of asking about an order or delivery into a single flow.

Figure 2.8. Redirecting a pattern with <srai>. From De Gasperis et al. (2013).
Mitsuku, developed by Steve Worswick, won the Loebner Prize multiple times, following earlier wins by ALICE. In a study that compared eight chatbots using a standard set of questions, Mitsuku placed first, followed by Google Assistant and Siri. ALICE placed fourth and ELIZA came last (Sharma et al. 2020).
2.9.1 AIML Tags
An AIML document starts with <aiml>. Each <category> connects an input <pattern> to a response <template>. The following file combines the main tags into one small knowledge base. Save it as brain.aiml.
<?xml version="1.0" encoding="UTF-8"?>
<aiml version="1.0.1">
<category>
<pattern>HELLO</pattern>
<template>
<random>
<li>Hello! How can I help you?</li>
<li>Hi there! What would you like to talk about?</li>
</random>
</template>
</category>
<category>
<pattern>HI</pattern>
<template><srai>HELLO</srai></template>
</category>
<category>
<pattern>I LIKE *</pattern>
<template>What do you like about <star/>?</template>
</category>
<category>
<pattern>WHAT IS YOUR NAME</pattern>
<template>My name is Neo Chatbot.</template>
</category>
<category>
<pattern>MY NAME IS *</pattern>
<template>
<think><set name="name"><star/></set></think>
Hello, <formal><get name="name"/></formal>!
</template>
</category>
<category>
<pattern>ASK ME ABOUT PROGRAMMING</pattern>
<template>Do you enjoy programming?</template>
</category>
<category>
<pattern>YES</pattern>
<that>DO YOU ENJOY PROGRAMMING</that>
<template>Great! Which language do you prefer?</template>
</category>
<category>
<pattern>LETS TALK ABOUT SPORTS</pattern>
<template>
<think><set name="topic">SPORTS</set></think>
Sure! Ask me for a recommendation.
</template>
</category>
<topic name="SPORTS">
<category>
<pattern>WHAT DO YOU RECOMMEND</pattern>
<template>Try a sport you can play with a friend.</template>
</category>
</topic>
<category>
<pattern>I AM HAPPY</pattern>
<template>
<think><set name="mood">happy</set></think>
I'm glad to hear that.
</template>
</category>
<category>
<pattern>HOW AM I FEELING</pattern>
<template>
<condition name="mood">
<li value="happy">You told me you were happy.</li>
<li>You haven't told me yet.</li>
</condition>
</template>
</category>
<category>
<pattern>REFLECT *</pattern>
<template><person><star/></person></template>
</category>
<category>
<pattern>CAPITALIZE *</pattern>
<template><sentence><star/></sentence></template>
</category>
<category>
<pattern>THANK YOU</pattern>
<template>You're welcome!</template>
</category>
</aiml>
-
<pattern>matches normalized input. The wildcards*and_match sequences of words, and<star/>inserts the captured text. The patternMY NAME IS *can capture “Ana” without requiring a separate category for each name. -
<set>stores a value, and<get>retrieves it. Wrapping a<set>in<think>keeps the assigned value from appearing twice in the reply. -
<that>checks what the bot just said. A bare “yes” can then receive a reply tailored to the preceding programming question.<topic>scopes a group of categories across turns. The example activates the sports group by setting thetopicvariable. -
<random>chooses among its child<li>elements.<condition>selects a branch by comparing a stored value with the options in its list. An item without a value can serve as the default. -
<srai>processes another pattern as input. Here “HI” and “HELLO” use the same greeting logic. -
<person>,<person2>, and<gender>transform pronouns according to the interpreter’s substitution tables.<formal>,<uppercase>,<lowercase>, and<sentence>change capitalization. The last of these capitalizes the start of the captured text.
2.9.2 Running an AIML Chatbot in Python
Install a compatible AIML interpreter in an isolated Python environment. The original example uses the legacy aiml package and a Python version that the package supports. Save the following program next to brain.aiml and run it from that directory.
import aiml
def main():
kernel = aiml.Kernel()
kernel.learn("brain.aiml")
while True:
try:
message = input("User: ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if message.lower() in {"exit", "quit"}:
break
if message:
print("Bot:", kernel.respond(message))
if __name__ == "__main__":
main()
Try “hi,” “my name is Ana,” and “thank you.” The greeting can vary because the first category uses <random>. A larger project can load several AIML files. Some projects use a startup file such as std-startup.xml to collect the rules that load the rest of the knowledge base.