Tutorial
Any feature of Syn.Bot not discussed here may be in its experimental stage.
Adding SIML Bot Library to your Project
You can use the Package Manager Console
in Visual Studio and typePM> Install-Package Syn.Bot
and the library will be downloaded and referenced automatically. The same can be done when using MonoDevelop on Linux or Mac using the Manage NuGet Package option.
Syn.Bot
is updated on a regular basis we recommend usingPM> Update-Package Syn.Bot
command in NuGet console to check for updates.
Add the using statement
using Syn.Bot.Siml;
Creating a new instance of SimlBot
To create a simple Syn Bot object use the following code.
var simlBot= new SimlBot();
Creating a new instance of BotUser
There are multiple ways of creating a user for a Bot. The important part is that a unique ID should be allocated to all new users. If you do not wish to handle creation of Id then you may initialize a bot user using the following code.
var botUser = simlBot.CreateUser();
A bot user is a user that interacts with a particular bot. If an ID is not specified the User will receive a new ID
from the Bot. This ID
is a GUID and has the least collision rate.
Loading SIML Files into the Bot
There are multiple ways of adding SIML files into the Bot’s knowledge base.
- Adding SIML files as strings
- Adding SIML files as ”XDocument”s
- Adding Multiple SIML files as List of ”XDocument”s
- Directly loading an SIML Package as string.
The first 3 options require that the function Load()
is called after the files have been added. This is essential because in SIML all the settings files have to loaded prior to the files containing Concepts.
If you do not use the Load()
function then the Bot will automatically call this function when it receives its first chat request. This behaviour may not be intended as it will make the first interaction slower.
Every SIML file ends with the extension .Siml
and an SIML Package file ends with the extension .SimlPk
.
Example code to load SIML from a package file
var packageString = File.ReadAllText(@"C:BotMyBot.simlpk");
simlBot.PackageManager.LoadFromString(packageString);
Example code to load multiple files
foreach (var simlFile in Directory.GetFiles(@"C:\Bot", "*.siml"))
{
var fileString = File.ReadAllText(simlFile);
simlBot.Import(fileString);
}
In the example above we call the function Load()
after we have added the desired files.
Example Code to load SIML files as XDocument
foreach (var simlFile in Directory.GetFiles(@"C:\Bot", "*.siml"))
{
var simlDocument= XDocument.Load(simlFile);
simlBot.Import(simlDocument);
}
Note
If file editing is not required after your Bot has been deployed it's highly recommended that you initialize your Bot using an SIML Package instead of SIML files.
Interacting with the Bot
Every interaction between the User and Bot is done by creating a Chat Request.
Example code to create a Chat Request
var chatRequest = new ChatRequest("how are you", RequestType.UserMessage, botUser);
In SIML 1.0 the chat request should always be of the type UserMessage
. Other types have been reserved for future implementations. Once a chat request is created the request can then be sent to the Bot. A ChatRequest sent to a Bot will yield a ChatResult
which is the final processed response from the Bot.
var chatResult = simlBot.Chat(chatRequest);
var botMessage = chatResult.BotMessage;
In the above the botMessage
variable contains the textual reply the Bot generated for the chat request it received.
To check if the result was successful i.e. the Bot could find a response for the chat request use the Success
property, which yields True if a response was generated. This property is NOT set to True if the response is the default response the Bot is meant to send when no response is generated.
Example
if (chatResult.Success)
{
//Do Something
}
A response in SIML may contain a Hint. A Hint is the next input the Bot expects from the current user. To get the Hint for the current response use the Hint
property. This property yields an empty string if no Hint is specified for a response.
Example
var hint = chatResult.Hint;
A ChatResult
has the following properties:
BotEmotion
– Emotion of the BotUserEmotion
– Emotion of the UserSuccess
– Determines if a response was generated successfullyStack
– Stack frames generated for the responseStats
– Statistics regarding the response generatedHint
– Any Hint specified in the responseLastLabel
– Label that was attached previouslyLastResponse
– Response that was generated previouslyBotMessage
– Current textual message from the Bot
Using Stack
A ChatResult
contains a stack that gives information as to where the response came from and what all redirections it went through before the final output was generated. A developer may use this information to debug the SIML code whenever and wherever necessary.
Example usage of Stack Frames
var chatRequest = new ChatRequest("how are you", RequestType.UserMessage, botUser);
var chatResult = simlBot.Chat(chatRequest);
foreach (var frame in chatResult.Stack)
{
DisplayInGrid(frame);
}
DisplayInGrid
can be any function defined by the developer that projects the stack information to the user.
Getting Bot Stats
Syn Bot will internally monitor and store its statistics. Stats are stored not just for retrieval purpose but for run-time modifications that the Bot makes to improve its speed and responses. To get the Bot stats use the Stats
property available for the Bot.
Though a number of stats are available the following shows a few properties that are updated from time to time.
var interactions = simlBot.Stats.Interactions;
var idleTime = simlBot.Stats.IdleTime;
var loadTime = simlBot.Stats.LoadTime;
var mappingTime = simlBot.Stats.MappingTime;
//.....
Most of these Stat properties are used by Syn Bot Studio to generate the Stats Chart.
Main Bot Instance
SimlBot
class comes with a static Instance
property that can be used to share an instance of SimlBot
with other components. The Instance
property during its first Get call automatically creates a new instance of SimlBot and returns it. Developers can even Set the Instance
property with their own instance of SimlBot
by first calling the Set property and later using the Get property throughout development.
Example
var sharedBot = SimlBot.Instance; //Because Get is called before Set - A new SimlBot instance gets created.
Example
var myBot = new SimlBot();
SimlBot.Main = myBot;
var sharedBot = SimlBot.Instance;
//SimlBot.Instance and myBot are now the same instance of SimlBot class.
Collecting Logs
Logs generated by the Bot are not stored internally ( to reduce memory usage ) but an event is fired whenever a log is generated. The event argument however contains everything that was added to be logged.
To catch all the logs generated by the Bot an event handler has to be added to the LogAdded
event.
Example
SimlBot.Logger.LogReceived+= Logger_LogAdded;
Example event handler
void Logger_LogAdded(object sender, LogReceivedEventArgs e)
{
//Do Something here
}
Getting Examples after a Package is Loaded
Every atomic pattern in SIML gets stored as an example within the Bot whenever a package or an SIML document, consisting of Concepts is loaded into the Bot’s graph. These examples can be used to give the user a hint of what all atomic patterns have been pre-defined or can also be used to auto-complete any input interface.
For complex patterns a Bot developer can explicitly specify an example using the SIML <Example>
element. The inner content of which is taken as the value for the Example to be stored. Duplicate entries are automatically discarded to maintain optimum memory usage.
Explicit Example declaration
<Model>
<Pattern>Play (music|song)</Pattern>
<Example>Play music</Example>
<Response>Playing music...</Response>
</Model>
To extract the list of all the Examples stored by the Bot you can make use of the Examples property as shown below.
var simlbBot= new SimlBot();
var storedExamples = simlBot.Examples;
foreach (var example in storedExamples)
{
//Do something
}
Cache Manager
As Syn Bot is a Portable Class Library it can be assumed that the library maybe used in an environment that has some memory limitations. Under such circumstances memory management can be done by using the ICacheManager
interface.
Everytime the Bot is about to save some textual data within a variable it requests the Cache Manager to provide a unique key for the textual data and saves the key instead. The textual data or string can be stored anywhere by the Cache Manager, it can be within a database, a file, some persistent storage mechanism or any other location but not the machine’s Random Access Memory.
Syn Bot ( in Nuget ) comes with its own ICacheManager
implementation class that prevents memory from being allocated to duplicate entries.
2 Important functions that play a major role in the ICacheManager
interface are:
- GetKey
- GetValue
GetKey
function is called by the Bot whenever the Bot tries to save some textual data.
GetValue
function is called ( on a regular basis ) when the Bot tries to retrieve the actual textual data that was previously saved.
It’s upto the developer as to how a Key is generated for a string and where the string is finally saved. It’s recommend that the GetValue
function should always be an O(1) operation otherwise the performance of the Bot will be highly impacted.
Timeouts
When Syn Bot is integrated with an application its important that the developer takes care of how much time is given to each ChatRequest
. This is important as extremely recursive requests MAY require both CPU Time Slice and Memory. By default a ”ChatRequest” is timedout if the Bot is not able to generate a response within 60 seconds.
This time out value can be changed by setting up the Timeout
variable for the Bot. This can be done internally using the Settings
property of the Bot or by editing the element within in your SIML project.
The value of the Value
attribute above indicates a value in milliseconds before a ChatRequest
is timed out. A value of 3000 means that the ChatRequest
is supposed to be timed out after 3 Seconds.
Certain situations where timeouts play an important role
- SIML Element stuck in an infinite loop
- ChatRequest exceeds its maximum request length rendering the Bot unstable.