RiveScript - Rendering Intelligence Very Easily
use RiveScript;
# Create a new RiveScript interpreter. my $rs = new RiveScript;
# Load a directory of replies.
$rs->loadDirectory ("./replies");
# Load another file.
$rs->loadFile ("./more_replies.rs");
# Stream in some RiveScript code.
$rs->stream (q~
+ hello bot
- Hello, human.
~);
# Sort all the loaded replies. $rs->sortReplies;
# Chat with the bot.
while (1) {
print "You> ";
chomp (my $msg = <STDIN>);
my $reply = $rs->reply ('localuser',$msg);
print "Bot> $reply\n";
}
RiveScript is a simple trigger/response language primarily used for the creation of chatting robots. It's designed to have an easy-to-learn syntax but provide a lot of power and flexibility. For more information, visit http://www.rivescript.com/
Create a new instance of a RiveScript interpreter. The instance will become its own "chatterbot," with its own set of responses and user variables. You can pass in any global variables here. The two standard variables are:
debug - Turns on debug mode (a LOT of information will be printed to the
terminal!). Default is 0 (disabled).
verbose - When debug mode is on, all debug output will be printed to the
terminal if 'verbose' is also true. The default value is 1.
debugfile - Optional: paired with debug mode, all debug output is also written
to this file name. Since debug mode prints such a large amount of
data, it is often more practical to have the output go to an
external file for later review. Default is '' (no file).
depth - Determines the recursion depth limit when following a trail of replies
that point to other replies. Default is 50.
It's recommended that if you set any other global variables that you do so by
calling setGlobal or defining it within the RiveScript code. This will avoid
the possibility of overriding reserved globals. Currently, these variable names
are reserved:
topics sorted sortsthat thats arrays subs person client bot objects reserved debugopts
Note: the options "verbose" and "debugfile", when provided, are noted and then deleted from the root object space, so that if your RiveScript code uses variables by the same values it won't conflict with the values that you passed here.
Load a directory full of RiveScript documents. $PATH must be a path to a
directory. @EXTS is optionally an array containing file extensions, including
the dot. By default @EXTS is ('.rs').
Returns true on success, false on failure.
Load a single RiveScript document. $PATH should be the path to a valid
RiveScript file. Returns true on success; false otherwise.
Stream RiveScript code directly into the module. This is for providing RS code from within the Perl script instead of from an external file. Returns true on success.
Call this method after loading replies to create an internal sort buffer. This is necessary for trigger matching purposes. If you fail to call this method yourself, RiveScript will call it once when you request a reply. However, it will complain loudly about it.
Manually create a RiveScript object (a dynamic bit of Perl code that can be
provoked in a RiveScript response). $NAME should be a single-word,
alphanumeric string. $CODEREF should be a pointer to a subroutine or an
anonymous sub.
Set one or more global variables, in hash form, where the keys are the variable names and the values are their value. This subroutine will make sure that you don't override any reserved global variables, and warn if that happens.
This is equivalent to ! global in RiveScript code.
Set one or more bot variables (things that describe your bot's personality).
This is equivalent to ! var in RiveScript code.
Set one or more substitution patterns. The keys should be the original word, and the value should be the word to substitute with it.
$rs->setSubstitution (
q{what's} => 'what is',
q{what're} => 'what are',
);
This is equivalent to ! sub in RiveScript code.
Set a person substitution. This is equivalent to ! person in RiveScript code.
Set a variable for a user. $USER should be their User ID, and %DATA is a
hash containing variable/value pairs.
This is like <set> for a specific user.
Get all the variables about a user. If a username is provided, returns a hash reference containing that user's information. Else, a hash reference of all the users and their information is returned.
This is like <get> for a specific user or for all users.
Clears all variables about $USER. If no $USER is provided, clears all
variables about all users.
Fetch a response to $MESSAGE from user $USER. RiveScript will take care of
lowercasing, running substitutions, and removing punctuation from the message.
Returns a response from the RiveScript brain.
Prints a debug message to the terminal. Called from within in debug mode.
Called internally to report an issue (similar to a warning). If debug mode is
active, it will print the issue to STDOUT with a # sign prepended. Otherwise,
the issue is sent to STDERR via warn.
This method is called internally to parse a file or streamed RiveScript code.
$FILENAME is only there so it can keep internal track of files and line
numbers, in case syntax errors appear.
This method sorts all the +Trigger lines that are paired with a common
%Previous line. This is necessary for when one question by the bot could
have multiple replies. I found a bug with the following RS code:
+ how [are] you [doing] - I'm doing great, how are you? - Good -- how are you? - Fine, how are you?
+ [*] @good [*] % * how are you - That's good. :-)
+ [*] @bad [*] % * how are you - Aww. :-( What's the matter?
+ * % * how are you - I see...
The effective trigger order was "[*] @good [*]", "*", "[*] @bad [*]",
because there was no sort buffer and it was relying on Perl's hash sorting.
This method was introduced to fix that problem and sort these triggers too.
You don't need to call this method yourself; it is called automatically
on a sortReplies() request.
This is used internally to sort arrays (namely, person and substitution pattern
arrays). Sets $rs-{sortlist}->{$NAME}> to an array reference of the sorted
values in @LIST. The values are sorted by number of words from greatest to
smallest, with each group of same-word-count items sorted by length amongst
themselves.
Do NOT call this method yourself. This method assumes a few things about the
user's input that is taken care of by reply(). There is no reason to call
this method manually.
This method takes a raw trigger $TRIGGER and formats it for a matching
attempt in a regular expression. It removes {weight} tags, processes arrays,
processes bot variables and other tags, and returns something ready for the
regular expression engine.
Process tags in the bot's response. $USER and $MSG are the values
originally passed to the reply engine. $REPLY is the bot's raw response.
$STARS and $BOTSTARS are array references containing any wildcards matched
in a trigger or %Previous command, respectively. Returns a reply with all the
tags processed.
Formats a message to prepare it for reply matching. Lowercases the string, runs substitutions, and sanitizes what's left.
Runs string modifiers on $STRING (uppercase, lowercase, sentence, formal).
Runs person substitutions on $STRING.
This interpreter tries its best to follow RiveScript standards. Currently it supports RiveScript 2.0 documents. A current copy of the RiveScript working draft is included with this package: see the RiveScript::WD manpage.
Most of the Perl warnings that the module will emit are self-explanatory, and when parsing RiveScript files, file names and line numbers will be given. This section of the manpage instead outlines error strings that may turn up in responses to the bot's queries.
The deep recursion depth limit has been reached (a response redirected to a different trigger, which redirected somewhere else, etc.).
How to fix: override the global variable depth. This can be done via
setGlobal or in the RiveScript code:
! global depth = 100
No match was found for the client's message.
How to fix: create a catch-all trigger of just *.
+ * - I don't know how to reply to that.
A match to the client's message was found, but no response to it was found. This
might mean you had a set of conditionals after it, and no -Reply to fall back
on, and every conditional returned false.
How to fix: make sure you have at least one -Reply to every +Trigger, even
if you don't expect that the -Reply will ever be used.
You called a math tag on a variable, and the current value of the variable contains something that isn't a number.
How to fix: verify that the variable you're working with is a number. If
necessary, reset the variable via <set>.
("add" may also be sub, mult, or div). You tried to run a math function on a variable, but the value you used wasn't a number.
How to fix: verify that you're adding, subtracting, multiplying, or dividing using numbers.
A <div> tag was found that attempted to divide a variable by zero.
How to fix: make sure your division isn't dividing by zero. If you're using a variable to provide the divisor, validate that the variable isn't zero by using a conditional.
* <get divisor> == 0 => The divisor is zero so I can't do that. - <div myvar=<get divisor>>I divided the variable by <get divisor>.
RiveScript attempted to call an object that doesn't exist. This may be because a syntax error in the object prevented Perl from evaluating it, or the object was written in a different programming language.
How to fix: verify that the called object was loaded properly. You will receive notifications on the terminal if the object failed to load for any reason.
the RiveScript::WD manpage - A current snapshot of the Working Draft that defines the standards of RiveScript.
http://www.rivescript.com/ - The official homepage of RiveScript.
1.17 Sep 15 2008
- Updated the rsdemo tool to be more flexible as a general debugging and
developing program. Also updated rsdemo and rsup to include POD documentation
that can be read via `perldoc`.
- Added a global variable $RiveScript::basedir which is the the path to your
Perl lib/RiveScript folder. This is used by `rsdemo` as its default location
to search for replies.
- Tweak: Triggers of only # and _ can exist now alongside the old single-wildcard
trigger of *.
- Bugfix: The lookahead code would throw Perl warnings if the following line
had a single space in it, but was otherwise empty.
- Bugfix: Inline comment removing has been fixed.
- Bugfix: In conditionals, any blank side of the equality will get a default
value of "undefined". This way you can use a matching array inside an optional
and check if that <star> tag is defined.
+ i am wearing a [(@colors)] shirt
* <star> ne undefined => Why are you wearing a <star> shirt?
- What color is it?
- Updated the RiveScript Working Draft.
1.16 Jul 22 2008
- New options to the constructor: 'verbose' and 'debugfile'. See the new()
constructor for details.
- Added new wildcard variants:
* matches anything (previous behavior)
# matches only numbers
_ matches only letters
So you can have a trigger like "+ i am # years old" and "+ i am * years old",
with the latter trigger telling them to try that again and use a NUMBER this
time. :)
- Bugfix: when there were multiple +trigger's that had a common %previous,
there was no internal sort buffer for those +trigger's. As a result, matching
wasn't very efficient. Added the method sortThatTriggers() to fix this.
- Bugfix: tags weren't being processed in @Redirects when they really
should've!
- Bugfix: The ^Continue lookahead code wouldn't work if the next line began
with a tab. Fixed!
- Updated the RiveScript Working Draft.
1.15 Jun 19 2008
- Person substitutions support multiple-word patterns now.
- Message substititons also support multiple-word patterns now.
- Added syntax tracking, so Deep Recursion errors can give you a filename and
line number where the problem occurred.
- Added a handler for detecting when a user was put into an empty topic.
- Rearranged tag priority.
- Updated the RiveScript Working Draft.
1.14 Apr 2 2008
- Bugfix: If a BEGIN/request trigger didn't exist, RiveScript would not fetch
any replies for the client's message. Fixed.
- Bugfix: Tags weren't being re-processed for the text of the BEGIN statement,
so i.e. {uppercase}{ok}{/uppercase} wasn't working as expected. Fixed.
- Bugfix: RiveScript wasn't parsing out inline comments properly.
- Rearranged tag priorities.
- Optimization: When substituting <star>s in, an added bit of code will insert
'' (nothing) if the variable is undefined. This prevents Perl warnings that
occurred frequently with the Eliza brain.
- Updated the RiveScript Working Draft.
1.13 Mar 18 2008
- Included an "rsup" script for upgrading old RiveScript code.
- Attempted to fix the package for CPAN (1.12 was a broken upload).
- Bugfix: <bot> didn't have higher priority than <set>, so
i.e. <set name=<bot name>> wouldn't work as expected. Fixed.
1.12 Mar 16 2008 - Initial beta release for a RiveScript 2.00 parser.
Casey Kirsle, http://www.cuvou.com/
bot, chatbot, chatterbot, chatter bot, reply, replies, script, aiml, alpha
RiveScript - Rendering Intelligence Very Easily Copyright (C) 2008 Casey Kirsle
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA