aiml.js v1.0.1

Classes

Bots

Core

Interfaces

Type Aliases

Functions

Parsers

Other


aiml.js / AIMLBot

Class: AIMLBot

Defined in: bots/AIMLBot.ts:101

Base class for all AIML bots.

AIMLBot provides the complete bot runtime: pattern matching, template evaluation, session management, file loading, and serialisation. The two specialised subclasses (AIML1Bot and AIML2Bot) add version-specific helpers but share this API.


Quick-start (Node.js)

import { AIML1Bot } from 'aiml.js';

const bot = new AIML1Bot({ properties: { name: 'Alice' } });
await bot.loadDirectory('./aiml');          // load all .aiml files

const { response } = await bot.talk('hello');
console.log(response); // "Hi there!"

Quick-start (browser)

import { AIML1Bot } from 'aiml.js';

const bot = new AIML1Bot();
// Pass File objects from <input type="file"> or pre-loaded content:
await bot.loadFile({ name: 'greetings.aiml', content: xmlString });

const { response, sessionId } = await bot.talk('hello');

Session continuity

// First turn — a default session is created automatically
const r1 = await bot.talk('my name is Alice');

// Pass the sessionId back to continue the same conversation
const r2 = await bot.talk('what is my name', r1.sessionId);
console.log(r2.response); // "Your name is Alice."

Extended by

Accessors

categoryCount

Get Signature

get categoryCount(): number

Defined in: bots/AIMLBot.ts:444

Total number of loaded categories.

Returns

number

Constructors

Constructor

new AIMLBot(options?): AIMLBot

Defined in: bots/AIMLBot.ts:127

Parameters

options?

AIMLBotOptions = {}

Returns

AIMLBot

Methods

addCategory()

addCategory(pattern, template, options?): void

Defined in: bots/AIMLBot.ts:431

Programmatically add a single AIML category.

The pattern and template strings use AIML XML syntax (tags are allowed).

Parameters

pattern

string

AIML input pattern.

template

string

AIML response template.

options?

Optional that and topic constraints.

that?

string

topic?

string

Returns

void

Example

bot.addCategory('HELLO', 'Hi there!');
bot.addCategory('DO YOU LIKE *', 'I love <star/>!', { topic: 'ANIMALS' });

addSubstitution()

addSubstitution(type, find, replace): void

Defined in: bots/AIMLBot.ts:363

Append a single substitution rule to a table.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to extend.

find

string

The text to find.

replace

string

The replacement.

Returns

void

Example

bot.addSubstitution('normal', "ain't", 'am not');

createSession()

createSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:464

Create a new session.

Sessions are created automatically by talk, so you only need this if you want to pre-configure a session (set predicates, topic, etc.).

Parameters

sessionId?

string

Optional explicit ID. A unique ID is generated if omitted.

Returns

Session

The new session.

Example

const session = bot.createSession('user-42');
session.setPredicate('name', 'Alice');
const { response } = await bot.talkSession('hello', session);

deleteSession()

deleteSession(sessionId): boolean

Defined in: bots/AIMLBot.ts:502

Delete a session and free its memory.

Parameters

sessionId

string

Session to delete.

Returns

boolean

true if the session existed and was deleted.


getOrCreateSession()

getOrCreateSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:489

Get an existing session or create one if it does not exist.

When sessionId is omitted a persistent default session (__default__) is used for all calls without an ID.

Parameters

sessionId?

string

Optional session ID.

Returns

Session


getProperty()

getProperty(name): string

Defined in: bots/AIMLBot.ts:305

Get a bot property value.

Parameters

name

string

Property name (case-insensitive).

Returns

string

The property value, or "" if not set.


getSession()

getSession(sessionId): Session | undefined

Defined in: bots/AIMLBot.ts:477

Retrieve an existing session by ID.

Parameters

sessionId

string

The session ID to look up.

Returns

Session | undefined

The session, or undefined if not found.


handleGossip()

protected handleGossip(_text): void

Defined in: bots/AIMLBot.ts:705

Called whenever a <gossip> tag is encountered. Override to log or store gossip messages.

Parameters

\_text

string

Returns

void


handleNoMatch()

protected handleNoMatch(_input, _session): Promise<string>

Defined in: bots/AIMLBot.ts:586

Called when no category matches the user's input.

Override in a subclass to provide a custom fallback response. The default implementation returns "".

Parameters

\_input

string

\_session

Session

Returns

Promise<string>


loadAllSerializedSessions()

loadAllSerializedSessions(data): string[]

Defined in: bots/AIMLBot.ts:669

Restore all sessions from a JSON string produced by serializeAllSessions.

Parameters

data

string

Serialised sessions JSON.

Returns

string[]

Array of restored session IDs.


loadDirectory()

loadDirectory(dirPath, recursive?, extensions?): Promise<void>

Defined in: bots/AIMLBot.ts:265

Recursively load all .aiml files from a directory.

Node.js only. Throws in browser environments.

Parameters

dirPath

string

Absolute or relative path to the directory.

recursive?

boolean = true

Whether to descend into subdirectories. Default true.

extensions?

string[] = ...

File extensions to include. Default ['.aiml'].

Returns

Promise<void>

Example

await bot.loadDirectory('./knowledge-base');
await bot.loadDirectory('./kb', true, ['.aiml', '.xml']);

loadFile()

loadFile(source): Promise<void>

Defined in: bots/AIMLBot.ts:227

Load a single AIML file from any FileSource.

Works on both Node.js (string path) and in the browser (File object or pre-loaded { name, content } object).

Parameters

source

FileSource

The file to load.

Returns

Promise<void>

Example

// Node.js
await bot.loadFile('/path/to/greetings.aiml');

// Browser (from <input type="file">)
const [file] = inputElement.files;
await bot.loadFile(file);

// Pre-loaded content (both platforms)
await bot.loadFile({ name: 'greeting.aiml', content: xmlString });

loadFiles()

loadFiles(sources): Promise<void>

Defined in: bots/AIMLBot.ts:246

Load multiple AIML files concurrently.

Parameters

sources

FileSource[]

Array of FileSource values.

Returns

Promise<void>

Example

await bot.loadFiles([
  '/path/to/greetings.aiml',
  '/path/to/personality.aiml',
  { name: 'custom.aiml', content: inlineXml },
]);

loadMap()

loadMap(name, data): void

Defined in: bots/AIMLBot.ts:404

Register a named map for use in <map name="..."> template tags.

Parameters

name

string

Map name (case-insensitive).

data

string | Map<string, string> | Record<string, string>

Map content: plain object, Map<string, string>, JSON object, or key:value text.

Returns

void

Example

bot.loadMap('capitals', { france: 'Paris', japan: 'Tokyo' });
bot.loadMap('colors', 'red : #FF0000\ngreen : #00FF00');
bot.loadMap('scores', '{"alice":"100","bob":"200"}');

loadProperties()

loadProperties(data): void

Defined in: bots/AIMLBot.ts:322

Load bot properties from a text or JSON data source.

Accepts the same formats as parseProperties:

  • Plain object
  • JSON string ({ "key": "value" })
  • Text file (key:value or key=value, one per line)

Parameters

data

string | Record<string, string>

Returns

void

Example

bot.loadProperties('name:Alice\nversion:2.0');
bot.loadProperties({ name: 'Alice', version: '2.0' });
bot.loadProperties('{"name":"Alice"}');

loadSerializedSession()

loadSerializedSession(data): string

Defined in: bots/AIMLBot.ts:643

Restore a session from a JSON string produced by serializeSession.

Parameters

data

string

Serialised session JSON.

Returns

string

The restored session's ID.


loadSet()

loadSet(name, data): void

Defined in: bots/AIMLBot.ts:387

Register a named set for use in pattern matching.

Sets enable patterns like I LIKE <set>color</set> to match any member of the named set.

Parameters

name

string

Set name (case-insensitive).

data

string | string[] | Set<string>

Set content: string array, Set<string>, JSON array, or one-per-line text.

Returns

void

Example

bot.loadSet('color', ['red', 'green', 'blue']);
bot.loadSet('animal', 'cat\ndog\nbird');
bot.loadSet('fruit', '["apple","banana","cherry"]');

loadSubstitutions()

loadSubstitutions(type, data): void

Defined in: bots/AIMLBot.ts:345

Replace a substitution table entirely.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to replace ('normal', 'person', etc.).

data

string | SubstitutionPair[]

Text, JSON, or already-parsed pairs.

Returns

void

Example

// Load contractions from text
bot.loadSubstitutions('normal', "can't : cannot\nwon't : will not");
// Load from JSON array
bot.loadSubstitutions('person', '[{"find":"I","replace":"he or she"}]');

loadXMLString()

loadXMLString(xml, fileName?): Promise<void>

Defined in: bots/AIMLBot.ts:197

Parse and load an AIML XML string directly.

Parameters

xml

string

AIML XML content.

fileName?

string

Optional name shown in validation error messages.

Returns

Promise<void>

Throws

If the XML contains parse errors.

Example

await bot.loadXMLString(`
  <aiml version="1.0">
    <category>
      <pattern>HELLO</pattern>
      <template>Hi!</template>
    </category>
  </aiml>
`);

serializeAllSessions()

serializeAllSessions(): string

Defined in: bots/AIMLBot.ts:655

Serialise all active sessions to a single JSON string.

Useful for persisting a multi-user application's full state. Restore with loadAllSerializedSessions.

Returns

string


serializeSession()

serializeSession(sessionId): string

Defined in: bots/AIMLBot.ts:631

Serialise a single session to a JSON string.

Store the result and pass it to loadSerializedSession later to resume the conversation.

Parameters

sessionId

string

The session to serialise.

Returns

string

Throws

If the session does not exist.

Example

const json = bot.serializeSession(sessionId);
localStorage.setItem('mySession', json);

// Later…
const saved = localStorage.getItem('mySession')!;
const id = bot.loadSerializedSession(saved);
const { response } = await bot.talk('hello again', id);

setProperty()

setProperty(name, value): void

Defined in: bots/AIMLBot.ts:293

Set a single bot property.

Bot properties are accessed in AIML templates via <bot name="..."/>.

Parameters

name

string

Property name (case-insensitive).

value

string

Property value.

Returns

void

Example

bot.setProperty('name', 'Alice');
// In AIML: <bot name="name"/> → "Alice"

talk()

talk(input, sessionId?): Promise<TalkResult>

Defined in: bots/AIMLBot.ts:532

Send a message to the bot and get a response.

If sessionId is omitted, a shared default session (__default__) is used so that consecutive calls without a session ID maintain conversational state.

Parameters

input

string

The user's message.

sessionId?

string

Optional session ID. Pass the sessionId from a previous result to continue that conversation.

Returns

Promise<TalkResult>

An object with the bot's response and the sessionId used.

Example

const r1 = await bot.talk('my name is Alice');
// r1.sessionId is '__default__' (or whatever was used)

const r2 = await bot.talk('what is my name', r1.sessionId);
console.log(r2.response); // "Your name is Alice."

// Multi-user: pass explicit session IDs
await bot.talk('hello', 'user-1');
await bot.talk('hello', 'user-2');

talkSession()

talkSession(input, session): Promise<string>

Defined in: bots/AIMLBot.ts:547

Send a message using an explicit Session object.

Useful when you manage sessions yourself rather than by ID.

Parameters

input

string

The user's message.

session

Session

The session to use.

Returns

Promise<string>

The bot's response string.


validateXML()

validateXML(xml, fileName?): ValidationResult

Defined in: bots/AIMLBot.ts:605

Validate an AIML XML string without loading it.

Returns a ValidationResult with valid, errors, and warnings.

Parameters

xml

string

fileName?

string

Returns

ValidationResult

Example

const result = bot.validateXML(xmlString, 'mybot.aiml');
if (!result.valid) {
  result.errors.forEach(e => console.error(e.message));
}

aiml.js / AIML1Bot

Class: AIML1Bot

Defined in: bots/AIML1Bot.ts:93

AIML 1.0 bot.

Extends AIMLBot with helpers tailored to the AIML 1.0 ecosystem:

  • .properties text files (key:value or key=value)
  • Substitution text files (find : replace per line)
  • Set text files (one item per line)
  • Standard AIML 1.0 directory layout auto-loader

All AIML 1.0 template tags are supported: <star>, <srai>, <sr>, <set>, <get>, <bot>, <think>, <condition>, <random>, <uppercase>, <lowercase>, <formal>, <sentence>, <person>, <person2>, <gender>, <input>, <that>, <thatstar>, <topicstar>, <learn>, <gossip>, <system>, <javascript>, <date>, <version>, <size>, <id>, <br>.


Basic usage

import { AIML1Bot } from 'aiml.js';

const bot = new AIML1Bot({ properties: { name: 'Alice' } });
await bot.loadDirectory('./alice');

const { response, sessionId } = await bot.talk('hello');
console.log(response); // "Hi there!"

Loading individual files

await bot.loadFile('/path/to/greetings.aiml');
await bot.loadPropertiesFile('/path/to/bot.properties');
await bot.loadSubstitutionFile('normal', '/path/to/normal.txt');
await bot.loadSetFile('color', '/path/to/colors.txt');

Standard directory layout (auto-loader)

/alice/
  *.aiml
  bot.properties          ← key:value
  normal.txt              ← substitutions
  person.txt
  person2.txt
  gender.txt
  sets/
    color.txt             ← one item per line
    animal.txt
await bot.loadDataDirectory('/alice');

Extends

Accessors

categoryCount

Get Signature

get categoryCount(): number

Defined in: bots/AIMLBot.ts:444

Total number of loaded categories.

Returns

number

Inherited from

AIMLBot.categoryCount

Constructors

Constructor

new AIML1Bot(options?): AIML1Bot

Defined in: bots/AIML1Bot.ts:94

Parameters

options?

AIML1BotOptions = {}

Returns

AIML1Bot

Overrides

AIMLBot.constructor

Methods

addCategory()

addCategory(pattern, template, options?): void

Defined in: bots/AIML1Bot.ts:238

Programmatically add an AIML 1.0 category.

Parameters

pattern

string

AIML input pattern.

template

string

AIML response template (XML tags are allowed).

options?

Optional that and topic constraints.

that?

string

topic?

string

Returns

void

Example

bot.addCategory('HELLO', 'Hi there!');
bot.addCategory('ARE YOU *', 'I am <star/>!', { topic: 'ROBOTS' });

Overrides

AIMLBot.addCategory


addSubstitution()

addSubstitution(type, find, replace): void

Defined in: bots/AIMLBot.ts:363

Append a single substitution rule to a table.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to extend.

find

string

The text to find.

replace

string

The replacement.

Returns

void

Example

bot.addSubstitution('normal', "ain't", 'am not');

Inherited from

AIMLBot.addSubstitution


createSession()

createSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:464

Create a new session.

Sessions are created automatically by talk, so you only need this if you want to pre-configure a session (set predicates, topic, etc.).

Parameters

sessionId?

string

Optional explicit ID. A unique ID is generated if omitted.

Returns

Session

The new session.

Example

const session = bot.createSession('user-42');
session.setPredicate('name', 'Alice');
const { response } = await bot.talkSession('hello', session);

Inherited from

AIMLBot.createSession


deleteSession()

deleteSession(sessionId): boolean

Defined in: bots/AIMLBot.ts:502

Delete a session and free its memory.

Parameters

sessionId

string

Session to delete.

Returns

boolean

true if the session existed and was deleted.

Inherited from

AIMLBot.deleteSession


getOrCreateSession()

getOrCreateSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:489

Get an existing session or create one if it does not exist.

When sessionId is omitted a persistent default session (__default__) is used for all calls without an ID.

Parameters

sessionId?

string

Optional session ID.

Returns

Session

Inherited from

AIMLBot.getOrCreateSession


getProperty()

getProperty(name): string

Defined in: bots/AIMLBot.ts:305

Get a bot property value.

Parameters

name

string

Property name (case-insensitive).

Returns

string

The property value, or "" if not set.

Inherited from

AIMLBot.getProperty


getSession()

getSession(sessionId): Session | undefined

Defined in: bots/AIMLBot.ts:477

Retrieve an existing session by ID.

Parameters

sessionId

string

The session ID to look up.

Returns

Session | undefined

The session, or undefined if not found.

Inherited from

AIMLBot.getSession


handleGossip()

protected handleGossip(_text): void

Defined in: bots/AIMLBot.ts:705

Called whenever a <gossip> tag is encountered. Override to log or store gossip messages.

Parameters

\_text

string

Returns

void

Inherited from

AIMLBot.handleGossip


handleNoMatch()

protected handleNoMatch(_input, _session): Promise<string>

Defined in: bots/AIMLBot.ts:586

Called when no category matches the user's input.

Override in a subclass to provide a custom fallback response. The default implementation returns "".

Parameters

\_input

string

\_session

Session

Returns

Promise<string>

Inherited from

AIMLBot.handleNoMatch


loadAllSerializedSessions()

loadAllSerializedSessions(data): string[]

Defined in: bots/AIMLBot.ts:669

Restore all sessions from a JSON string produced by serializeAllSessions.

Parameters

data

string

Serialised sessions JSON.

Returns

string[]

Array of restored session IDs.

Inherited from

AIMLBot.loadAllSerializedSessions


loadDataDirectory()

loadDataDirectory(dirPath): Promise<void>

Defined in: bots/AIML1Bot.ts:119

Load a complete AIML 1.0 data directory using the standard layout.

Automatically discovers and loads (in order):

  1. bot.properties / properties.txt / properties
  2. normal.txt, person.txt, person2.txt, gender.txt (also looks in substitutions/ subdirectory)
  3. All *.txt files from a sets/ subdirectory
  4. All *.aiml files (recursively)

Node.js only.

Parameters

dirPath

string

Absolute or relative path to the data directory.

Returns

Promise<void>

Example

const bot = new AIML1Bot();
await bot.loadDataDirectory('./alice-aiml');

loadDirectory()

loadDirectory(dirPath, recursive?, extensions?): Promise<void>

Defined in: bots/AIMLBot.ts:265

Recursively load all .aiml files from a directory.

Node.js only. Throws in browser environments.

Parameters

dirPath

string

Absolute or relative path to the directory.

recursive?

boolean = true

Whether to descend into subdirectories. Default true.

extensions?

string[] = ...

File extensions to include. Default ['.aiml'].

Returns

Promise<void>

Example

await bot.loadDirectory('./knowledge-base');
await bot.loadDirectory('./kb', true, ['.aiml', '.xml']);

Inherited from

AIMLBot.loadDirectory


loadFile()

loadFile(source): Promise<void>

Defined in: bots/AIMLBot.ts:227

Load a single AIML file from any FileSource.

Works on both Node.js (string path) and in the browser (File object or pre-loaded { name, content } object).

Parameters

source

FileSource

The file to load.

Returns

Promise<void>

Example

// Node.js
await bot.loadFile('/path/to/greetings.aiml');

// Browser (from <input type="file">)
const [file] = inputElement.files;
await bot.loadFile(file);

// Pre-loaded content (both platforms)
await bot.loadFile({ name: 'greeting.aiml', content: xmlString });

Inherited from

AIMLBot.loadFile


loadFiles()

loadFiles(sources): Promise<void>

Defined in: bots/AIMLBot.ts:246

Load multiple AIML files concurrently.

Parameters

sources

FileSource[]

Array of FileSource values.

Returns

Promise<void>

Example

await bot.loadFiles([
  '/path/to/greetings.aiml',
  '/path/to/personality.aiml',
  { name: 'custom.aiml', content: inlineXml },
]);

Inherited from

AIMLBot.loadFiles


loadMap()

loadMap(name, data): void

Defined in: bots/AIMLBot.ts:404

Register a named map for use in <map name="..."> template tags.

Parameters

name

string

Map name (case-insensitive).

data

string | Map<string, string> | Record<string, string>

Map content: plain object, Map<string, string>, JSON object, or key:value text.

Returns

void

Example

bot.loadMap('capitals', { france: 'Paris', japan: 'Tokyo' });
bot.loadMap('colors', 'red : #FF0000\ngreen : #00FF00');
bot.loadMap('scores', '{"alice":"100","bob":"200"}');

Inherited from

AIMLBot.loadMap


loadProperties()

loadProperties(data): void

Defined in: bots/AIMLBot.ts:322

Load bot properties from a text or JSON data source.

Accepts the same formats as parseProperties:

  • Plain object
  • JSON string ({ "key": "value" })
  • Text file (key:value or key=value, one per line)

Parameters

data

string | Record<string, string>

Returns

void

Example

bot.loadProperties('name:Alice\nversion:2.0');
bot.loadProperties({ name: 'Alice', version: '2.0' });
bot.loadProperties('{"name":"Alice"}');

Inherited from

AIMLBot.loadProperties


loadPropertiesFile()

loadPropertiesFile(source): Promise<void>

Defined in: bots/AIML1Bot.ts:189

Load bot properties from a file.

The file may use key:value, key=value, or JSON { "key": "value" } format.

Parameters

source

FileSource

A FileSource (path, File, or preloaded content).

Returns

Promise<void>

Example

await bot.loadPropertiesFile('/path/to/bot.properties');
await bot.loadPropertiesFile({ name: 'bot.properties', content: 'name:Alice' });

loadSerializedSession()

loadSerializedSession(data): string

Defined in: bots/AIMLBot.ts:643

Restore a session from a JSON string produced by serializeSession.

Parameters

data

string

Serialised session JSON.

Returns

string

The restored session's ID.

Inherited from

AIMLBot.loadSerializedSession


loadSet()

loadSet(name, data): void

Defined in: bots/AIMLBot.ts:387

Register a named set for use in pattern matching.

Sets enable patterns like I LIKE <set>color</set> to match any member of the named set.

Parameters

name

string

Set name (case-insensitive).

data

string | string[] | Set<string>

Set content: string array, Set<string>, JSON array, or one-per-line text.

Returns

void

Example

bot.loadSet('color', ['red', 'green', 'blue']);
bot.loadSet('animal', 'cat\ndog\nbird');
bot.loadSet('fruit', '["apple","banana","cherry"]');

Inherited from

AIMLBot.loadSet


loadSetFile()

loadSetFile(name, source): Promise<void>

Defined in: bots/AIML1Bot.ts:222

Load a named set from a file (one item per line).

Parameters

name

string

Set name used in patterns (e.g. color for <set>color</set>).

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadSetFile('color', '/path/to/colors.txt');

loadSubstitutionFile()

loadSubstitutionFile(type, source): Promise<void>

Defined in: bots/AIML1Bot.ts:205

Load a substitution table from a file.

The file uses find : replace text format (one rule per line).

Parameters

type

"normal" | "person" | "person2" | "gender"

Which substitution table to replace ('normal', 'person', etc.).

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadSubstitutionFile('normal', '/path/to/normal.txt');

loadSubstitutions()

loadSubstitutions(type, data): void

Defined in: bots/AIMLBot.ts:345

Replace a substitution table entirely.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to replace ('normal', 'person', etc.).

data

string | SubstitutionPair[]

Text, JSON, or already-parsed pairs.

Returns

void

Example

// Load contractions from text
bot.loadSubstitutions('normal', "can't : cannot\nwon't : will not");
// Load from JSON array
bot.loadSubstitutions('person', '[{"find":"I","replace":"he or she"}]');

Inherited from

AIMLBot.loadSubstitutions


loadXMLString()

loadXMLString(xml, fileName?): Promise<void>

Defined in: bots/AIMLBot.ts:197

Parse and load an AIML XML string directly.

Parameters

xml

string

AIML XML content.

fileName?

string

Optional name shown in validation error messages.

Returns

Promise<void>

Throws

If the XML contains parse errors.

Example

await bot.loadXMLString(`
  <aiml version="1.0">
    <category>
      <pattern>HELLO</pattern>
      <template>Hi!</template>
    </category>
  </aiml>
`);

Inherited from

AIMLBot.loadXMLString


serializeAllSessions()

serializeAllSessions(): string

Defined in: bots/AIMLBot.ts:655

Serialise all active sessions to a single JSON string.

Useful for persisting a multi-user application's full state. Restore with loadAllSerializedSessions.

Returns

string

Inherited from

AIMLBot.serializeAllSessions


serializeSession()

serializeSession(sessionId): string

Defined in: bots/AIMLBot.ts:631

Serialise a single session to a JSON string.

Store the result and pass it to loadSerializedSession later to resume the conversation.

Parameters

sessionId

string

The session to serialise.

Returns

string

Throws

If the session does not exist.

Example

const json = bot.serializeSession(sessionId);
localStorage.setItem('mySession', json);

// Later…
const saved = localStorage.getItem('mySession')!;
const id = bot.loadSerializedSession(saved);
const { response } = await bot.talk('hello again', id);

Inherited from

AIMLBot.serializeSession


setProperty()

setProperty(name, value): void

Defined in: bots/AIMLBot.ts:293

Set a single bot property.

Bot properties are accessed in AIML templates via <bot name="..."/>.

Parameters

name

string

Property name (case-insensitive).

value

string

Property value.

Returns

void

Example

bot.setProperty('name', 'Alice');
// In AIML: <bot name="name"/> → "Alice"

Inherited from

AIMLBot.setProperty


talk()

talk(input, sessionId?): Promise<TalkResult>

Defined in: bots/AIMLBot.ts:532

Send a message to the bot and get a response.

If sessionId is omitted, a shared default session (__default__) is used so that consecutive calls without a session ID maintain conversational state.

Parameters

input

string

The user's message.

sessionId?

string

Optional session ID. Pass the sessionId from a previous result to continue that conversation.

Returns

Promise<TalkResult>

An object with the bot's response and the sessionId used.

Example

const r1 = await bot.talk('my name is Alice');
// r1.sessionId is '__default__' (or whatever was used)

const r2 = await bot.talk('what is my name', r1.sessionId);
console.log(r2.response); // "Your name is Alice."

// Multi-user: pass explicit session IDs
await bot.talk('hello', 'user-1');
await bot.talk('hello', 'user-2');

Inherited from

AIMLBot.talk


talkSession()

talkSession(input, session): Promise<string>

Defined in: bots/AIMLBot.ts:547

Send a message using an explicit Session object.

Useful when you manage sessions yourself rather than by ID.

Parameters

input

string

The user's message.

session

Session

The session to use.

Returns

Promise<string>

The bot's response string.

Inherited from

AIMLBot.talkSession


validateXML()

validateXML(xml, fileName?): ValidationResult

Defined in: bots/AIMLBot.ts:605

Validate an AIML XML string without loading it.

Returns a ValidationResult with valid, errors, and warnings.

Parameters

xml

string

fileName?

string

Returns

ValidationResult

Example

const result = bot.validateXML(xmlString, 'mybot.aiml');
if (!result.valid) {
  result.errors.forEach(e => console.error(e.message));
}

Inherited from

AIMLBot.validateXML


aiml.js / AIML2Bot

Class: AIML2Bot

Defined in: bots/AIML2Bot.ts:89

AIML 2.0 bot.

Extends AIMLBot with the full AIML 2.0 feature set:

Additional wildcards

  • # — zero or more words (highest priority)
  • ^ — zero or more words (lower priority than *)

Additional template tags

Tag Description
<sraix service="..."> Call an external service
<map name="..."> Look up a value in a named map
<normalize> / <denormalize> Apply normalisation transforms
<explode> Insert spaces between each character
<first> / <rest> First word / remaining words of a string
<request index="N"> Nth previous user input
<response index="N"> Nth previous bot response
<learn> / <learnf> Teach the bot new categories at runtime
<eval> Evaluate AIML inside <learn>
<loop/> Loop a <condition> branch
<oob> Pass out-of-band instructions to the caller
<addtriple> / <deletetriple> Manage the session triple store
<select> / <uniq> Query the triple store

Data file formats Properties, substitutions, sets, and maps are all accepted as either plain text or JSON — the format is auto-detected.


Basic usage

import { AIML2Bot } from 'aiml.js';

const bot = new AIML2Bot({
  properties: { name: 'Rosie' },
  sraixHandler: async (service, input) => fetchExternalBot(service, input),
});
await bot.loadDataDirectory('./rosie');

const { response } = await bot.talk('hello');

Triple store

// AIML:  <addtriple><subj><star/></subj><pred>likes</pred><obj><star index="2"/></obj></addtriple>
await bot.talk('Alice likes cats');
const session = bot.getSession(sessionId)!;
session.queryTriples('alice', 'likes'); // → [{ subject:'alice', predicate:'likes', object:'cats' }]

Extends

Accessors

categoryCount

Get Signature

get categoryCount(): number

Defined in: bots/AIMLBot.ts:444

Total number of loaded categories.

Returns

number

Inherited from

AIMLBot.categoryCount

Constructors

Constructor

new AIML2Bot(options?): AIML2Bot

Defined in: bots/AIML2Bot.ts:92

Parameters

options?

AIML2BotOptions = {}

Returns

AIML2Bot

Overrides

AIMLBot.constructor

Methods

addCategory()

addCategory(pattern, template, options?): void

Defined in: bots/AIML2Bot.ts:295

Programmatically add an AIML 2.0 category.

AIML 2.0 wildcards (#, ^) are supported in the pattern.

Parameters

pattern

string

AIML 2.0 input pattern.

template

string

AIML 2.0 response template.

options?

Optional that constraint.

that?

string

topic?

string

Returns

void

Example

bot.addCategory('# HELLO ^', 'Hello yourself!');
bot.addCategory('MY NAME IS *', 'Nice to meet you, <set name="name"><star/></set>!');

Overrides

AIMLBot.addCategory


addSubstitution()

addSubstitution(type, find, replace): void

Defined in: bots/AIMLBot.ts:363

Append a single substitution rule to a table.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to extend.

find

string

The text to find.

replace

string

The replacement.

Returns

void

Example

bot.addSubstitution('normal', "ain't", 'am not');

Inherited from

AIMLBot.addSubstitution


createSession()

createSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:464

Create a new session.

Sessions are created automatically by talk, so you only need this if you want to pre-configure a session (set predicates, topic, etc.).

Parameters

sessionId?

string

Optional explicit ID. A unique ID is generated if omitted.

Returns

Session

The new session.

Example

const session = bot.createSession('user-42');
session.setPredicate('name', 'Alice');
const { response } = await bot.talkSession('hello', session);

Inherited from

AIMLBot.createSession


deleteSession()

deleteSession(sessionId): boolean

Defined in: bots/AIMLBot.ts:502

Delete a session and free its memory.

Parameters

sessionId

string

Session to delete.

Returns

boolean

true if the session existed and was deleted.

Inherited from

AIMLBot.deleteSession


getOrCreateSession()

getOrCreateSession(sessionId?): Session

Defined in: bots/AIMLBot.ts:489

Get an existing session or create one if it does not exist.

When sessionId is omitted a persistent default session (__default__) is used for all calls without an ID.

Parameters

sessionId?

string

Optional session ID.

Returns

Session

Inherited from

AIMLBot.getOrCreateSession


getProperty()

getProperty(name): string

Defined in: bots/AIMLBot.ts:305

Get a bot property value.

Parameters

name

string

Property name (case-insensitive).

Returns

string

The property value, or "" if not set.

Inherited from

AIMLBot.getProperty


getSession()

getSession(sessionId): Session | undefined

Defined in: bots/AIMLBot.ts:477

Retrieve an existing session by ID.

Parameters

sessionId

string

The session ID to look up.

Returns

Session | undefined

The session, or undefined if not found.

Inherited from

AIMLBot.getSession


handleGossip()

protected handleGossip(_text): void

Defined in: bots/AIMLBot.ts:705

Called whenever a <gossip> tag is encountered. Override to log or store gossip messages.

Parameters

\_text

string

Returns

void

Inherited from

AIMLBot.handleGossip


handleNoMatch()

protected handleNoMatch(_input, _session): Promise<string>

Defined in: bots/AIMLBot.ts:586

Called when no category matches the user's input.

Override in a subclass to provide a custom fallback response. The default implementation returns "".

Parameters

\_input

string

\_session

Session

Returns

Promise<string>

Inherited from

AIMLBot.handleNoMatch


loadAllSerializedSessions()

loadAllSerializedSessions(data): string[]

Defined in: bots/AIMLBot.ts:669

Restore all sessions from a JSON string produced by serializeAllSessions.

Parameters

data

string

Serialised sessions JSON.

Returns

string[]

Array of restored session IDs.

Inherited from

AIMLBot.loadAllSerializedSessions


loadDataDirectory()

loadDataDirectory(dirPath): Promise<void>

Defined in: bots/AIML2Bot.ts:219

Load a complete AIML 2.0 data directory using the standard layout.

Expected structure (all optional):

<dir>/
  *.aiml                          ← AIML files (non-recursive)
  properties.json | properties.txt
  substitutions/
    normal.json | normal.txt
    person.json | person.txt
    person2.json | person2.txt
    gender.json | gender.txt
    denormal.json | denormal.txt
  sets/
    <name>.json | <name>.txt      ← set name = file basename
  maps/
    <name>.json | <name>.txt      ← map name = file basename

Node.js only.

Parameters

dirPath

string

Absolute or relative path to the data directory.

Returns

Promise<void>

Example

const bot = new AIML2Bot();
await bot.loadDataDirectory('./rosie');

loadDirectory()

loadDirectory(dirPath, recursive?, extensions?): Promise<void>

Defined in: bots/AIMLBot.ts:265

Recursively load all .aiml files from a directory.

Node.js only. Throws in browser environments.

Parameters

dirPath

string

Absolute or relative path to the directory.

recursive?

boolean = true

Whether to descend into subdirectories. Default true.

extensions?

string[] = ...

File extensions to include. Default ['.aiml'].

Returns

Promise<void>

Example

await bot.loadDirectory('./knowledge-base');
await bot.loadDirectory('./kb', true, ['.aiml', '.xml']);

Inherited from

AIMLBot.loadDirectory


loadFile()

loadFile(source): Promise<void>

Defined in: bots/AIMLBot.ts:227

Load a single AIML file from any FileSource.

Works on both Node.js (string path) and in the browser (File object or pre-loaded { name, content } object).

Parameters

source

FileSource

The file to load.

Returns

Promise<void>

Example

// Node.js
await bot.loadFile('/path/to/greetings.aiml');

// Browser (from <input type="file">)
const [file] = inputElement.files;
await bot.loadFile(file);

// Pre-loaded content (both platforms)
await bot.loadFile({ name: 'greeting.aiml', content: xmlString });

Inherited from

AIMLBot.loadFile


loadFiles()

loadFiles(sources): Promise<void>

Defined in: bots/AIMLBot.ts:246

Load multiple AIML files concurrently.

Parameters

sources

FileSource[]

Array of FileSource values.

Returns

Promise<void>

Example

await bot.loadFiles([
  '/path/to/greetings.aiml',
  '/path/to/personality.aiml',
  { name: 'custom.aiml', content: inlineXml },
]);

Inherited from

AIMLBot.loadFiles


loadMap()

loadMap(name, data): void

Defined in: bots/AIMLBot.ts:404

Register a named map for use in <map name="..."> template tags.

Parameters

name

string

Map name (case-insensitive).

data

string | Map<string, string> | Record<string, string>

Map content: plain object, Map<string, string>, JSON object, or key:value text.

Returns

void

Example

bot.loadMap('capitals', { france: 'Paris', japan: 'Tokyo' });
bot.loadMap('colors', 'red : #FF0000\ngreen : #00FF00');
bot.loadMap('scores', '{"alice":"100","bob":"200"}');

Inherited from

AIMLBot.loadMap


loadMapFile()

loadMapFile(name, source): Promise<void>

Defined in: bots/AIML2Bot.ts:184

Load a named map from a file (JSON object or text, auto-detected).

Parameters

name

string

Map name.

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadMapFile('capitals', '/path/to/capitals.json');  // {"france":"Paris"}
await bot.loadMapFile('capitals', '/path/to/capitals.txt');   // france : Paris

loadProperties()

loadProperties(data): void

Defined in: bots/AIMLBot.ts:322

Load bot properties from a text or JSON data source.

Accepts the same formats as parseProperties:

  • Plain object
  • JSON string ({ "key": "value" })
  • Text file (key:value or key=value, one per line)

Parameters

data

string | Record<string, string>

Returns

void

Example

bot.loadProperties('name:Alice\nversion:2.0');
bot.loadProperties({ name: 'Alice', version: '2.0' });
bot.loadProperties('{"name":"Alice"}');

Inherited from

AIMLBot.loadProperties


loadPropertiesFile()

loadPropertiesFile(source): Promise<void>

Defined in: bots/AIML2Bot.ts:133

Load bot properties from a file (JSON or key:value text, auto-detected).

Parameters

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadPropertiesFile('/path/to/properties.json');
await bot.loadPropertiesFile('/path/to/properties.txt');

loadSerializedSession()

loadSerializedSession(data): string

Defined in: bots/AIMLBot.ts:643

Restore a session from a JSON string produced by serializeSession.

Parameters

data

string

Serialised session JSON.

Returns

string

The restored session's ID.

Inherited from

AIMLBot.loadSerializedSession


loadSet()

loadSet(name, data): void

Defined in: bots/AIMLBot.ts:387

Register a named set for use in pattern matching.

Sets enable patterns like I LIKE <set>color</set> to match any member of the named set.

Parameters

name

string

Set name (case-insensitive).

data

string | string[] | Set<string>

Set content: string array, Set<string>, JSON array, or one-per-line text.

Returns

void

Example

bot.loadSet('color', ['red', 'green', 'blue']);
bot.loadSet('animal', 'cat\ndog\nbird');
bot.loadSet('fruit', '["apple","banana","cherry"]');

Inherited from

AIMLBot.loadSet


loadSetFile()

loadSetFile(name, source): Promise<void>

Defined in: bots/AIML2Bot.ts:169

Load a named set from a file (JSON array or text, auto-detected).

Parameters

name

string

Set name.

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadSetFile('color', '/path/to/colors.json');  // ["red","green","blue"]
await bot.loadSetFile('color', '/path/to/colors.txt');   // one per line

loadSubstitutionFile()

loadSubstitutionFile(type, source): Promise<void>

Defined in: bots/AIML2Bot.ts:151

Load a substitution table from a file (JSON or text, auto-detected).

JSON array format: [{ "find": "...", "replace": "..." }] JSON object format: { "find": "replace" } Text format: find : replace (one per line)

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to replace.

source

FileSource

A FileSource.

Returns

Promise<void>

Example

await bot.loadSubstitutionFile('normal', '/path/to/normal.json');

loadSubstitutions()

loadSubstitutions(type, data): void

Defined in: bots/AIMLBot.ts:345

Replace a substitution table entirely.

Parameters

type

"normal" | "person" | "person2" | "gender" | "denormal"

Which table to replace ('normal', 'person', etc.).

data

string | SubstitutionPair[]

Text, JSON, or already-parsed pairs.

Returns

void

Example

// Load contractions from text
bot.loadSubstitutions('normal', "can't : cannot\nwon't : will not");
// Load from JSON array
bot.loadSubstitutions('person', '[{"find":"I","replace":"he or she"}]');

Inherited from

AIMLBot.loadSubstitutions


loadXMLString()

loadXMLString(xml, fileName?): Promise<void>

Defined in: bots/AIMLBot.ts:197

Parse and load an AIML XML string directly.

Parameters

xml

string

AIML XML content.

fileName?

string

Optional name shown in validation error messages.

Returns

Promise<void>

Throws

If the XML contains parse errors.

Example

await bot.loadXMLString(`
  <aiml version="1.0">
    <category>
      <pattern>HELLO</pattern>
      <template>Hi!</template>
    </category>
  </aiml>
`);

Inherited from

AIMLBot.loadXMLString


serializeAllSessions()

serializeAllSessions(): string

Defined in: bots/AIMLBot.ts:655

Serialise all active sessions to a single JSON string.

Useful for persisting a multi-user application's full state. Restore with loadAllSerializedSessions.

Returns

string

Inherited from

AIMLBot.serializeAllSessions


serializeSession()

serializeSession(sessionId): string

Defined in: bots/AIMLBot.ts:631

Serialise a single session to a JSON string.

Store the result and pass it to loadSerializedSession later to resume the conversation.

Parameters

sessionId

string

The session to serialise.

Returns

string

Throws

If the session does not exist.

Example

const json = bot.serializeSession(sessionId);
localStorage.setItem('mySession', json);

// Later…
const saved = localStorage.getItem('mySession')!;
const id = bot.loadSerializedSession(saved);
const { response } = await bot.talk('hello again', id);

Inherited from

AIMLBot.serializeSession


setProperty()

setProperty(name, value): void

Defined in: bots/AIMLBot.ts:293

Set a single bot property.

Bot properties are accessed in AIML templates via <bot name="..."/>.

Parameters

name

string

Property name (case-insensitive).

value

string

Property value.

Returns

void

Example

bot.setProperty('name', 'Alice');
// In AIML: <bot name="name"/> → "Alice"

Inherited from

AIMLBot.setProperty


setSraixHandler()

setSraixHandler(handler): void

Defined in: bots/AIML2Bot.ts:120

Set or replace the <sraix> handler after construction.

Parameters

handler

(service, input) => Promise<string>

A function that receives the service name and input text and returns the service's response.

Returns

void

Example

bot.setSraixHandler(async (service, input) => {
  const res = await fetch(`https://api.example.com/${service}?q=${input}`);
  return res.text();
});

talk()

talk(input, sessionId?): Promise<TalkResult>

Defined in: bots/AIMLBot.ts:532

Send a message to the bot and get a response.

If sessionId is omitted, a shared default session (__default__) is used so that consecutive calls without a session ID maintain conversational state.

Parameters

input

string

The user's message.

sessionId?

string

Optional session ID. Pass the sessionId from a previous result to continue that conversation.

Returns

Promise<TalkResult>

An object with the bot's response and the sessionId used.

Example

const r1 = await bot.talk('my name is Alice');
// r1.sessionId is '__default__' (or whatever was used)

const r2 = await bot.talk('what is my name', r1.sessionId);
console.log(r2.response); // "Your name is Alice."

// Multi-user: pass explicit session IDs
await bot.talk('hello', 'user-1');
await bot.talk('hello', 'user-2');

Inherited from

AIMLBot.talk


talkSession()

talkSession(input, session): Promise<string>

Defined in: bots/AIMLBot.ts:547

Send a message using an explicit Session object.

Useful when you manage sessions yourself rather than by ID.

Parameters

input

string

The user's message.

session

Session

The session to use.

Returns

Promise<string>

The bot's response string.

Inherited from

AIMLBot.talkSession


validateXML()

validateXML(xml, fileName?): ValidationResult

Defined in: bots/AIMLBot.ts:605

Validate an AIML XML string without loading it.

Returns a ValidationResult with valid, errors, and warnings.

Parameters

xml

string

fileName?

string

Returns

ValidationResult

Example

const result = bot.validateXML(xmlString, 'mybot.aiml');
if (!result.valid) {
  result.errors.forEach(e => console.error(e.message));
}

Inherited from

AIMLBot.validateXML


aiml.js / Session

Class: Session

Defined in: core/Session.ts:33

Represents a single user's conversation state.

A Session stores everything that makes one user's conversation distinct: named predicates (variables), conversation history, the current topic, and — for AIML 2.0 — a triple store for subject/predicate/object facts.

Sessions are created automatically by AIMLBot.talk when no sessionId is supplied, or explicitly via AIMLBot.createSession. They can be serialised to JSON and restored later to resume a conversation.

Example

const bot = new AIML1Bot();
await bot.loadFile('alice.aiml');

// Start a named session
const session = bot.createSession('user-42');
session.setPredicate('name', 'Alice');

const { response } = await bot.talkSession('hello', session);

// Serialise and restore later
const saved = session.toJSON();
const restored = Session.fromJSON(saved);

Constructors

Constructor

new Session(id?): Session

Defined in: core/Session.ts:45

Parameters

id?

string

Optional explicit session ID; a unique ID is generated if omitted.

Returns

Session

Methods

addTriple()

addTriple(subject, predicate, object): void

Defined in: core/Session.ts:194

Add a subject/predicate/object triple.

Called by <addtriple> template tags. Keys are lower-cased; duplicate triples are silently ignored.

Parameters

subject

string

predicate

string

object

string

Returns

void

Example

session.addTriple('alice', 'likes', 'cats');
session.queryTriples('alice', 'likes'); // → [{ subject:'alice', predicate:'likes', object:'cats' }]

addTurn()

addTurn(input, response): void

Defined in: core/Session.ts:123

Append a completed conversation turn to the history. Called automatically after each AIMLBot.talk call.

Parameters

input

string

response

string

Returns

void


clearHistory()

clearHistory(): void

Defined in: core/Session.ts:178

Clear all conversation history.

Returns

void


deletePredicate()

deletePredicate(name): void

Defined in: core/Session.ts:85

Delete a named predicate.

Parameters

name

string

Predicate name.

Returns

void


deleteTriple()

deleteTriple(subject, predicate, object): void

Defined in: core/Session.ts:209

Delete a specific triple. Called by <deletetriple>.

Parameters

subject

string

predicate

string

object

string

Returns

void


getAllPredicates()

getAllPredicates(): Record<string, string>

Defined in: core/Session.ts:93

Return all predicates as a plain object snapshot. Useful for debugging or serialisation.

Returns

Record<string, string>


getHistory()

getHistory(): ConversationTurn[]

Defined in: core/Session.ts:173

Return a copy of the full conversation history.

Returns

ConversationTurn[]


getInput()

getInput(index?): string

Defined in: core/Session.ts:140

Return the Nth previous user input (1-based, 1 = most recent).

Used by the <input index="N"/> template tag.

Parameters

index?

number = 1

1-based index into history (1 = last input).

Returns

string


getPredicate()

getPredicate(name): string

Defined in: core/Session.ts:61

Read a named predicate value.

Predicate names are case-insensitive. Returns "" if the predicate has not been set (matching AIML semantics for <get name="..."/>).

Parameters

name

string

Predicate name (case-insensitive).

Returns

string


getResponse()

getResponse(index?): string

Defined in: core/Session.ts:152

Return the Nth previous bot response (1-based, 1 = most recent).

Used by the <response index="N"/> template tag (AIML 2.0).

Parameters

index?

number = 1

1-based index (1 = last response).

Returns

string


getThat()

getThat(responseIndex?, sentenceIndex?): string

Defined in: core/Session.ts:165

Return the Mth sentence of the Nth previous bot response.

Used by <that index="N,M"/>. Sentences are split on ., !, ?.

Parameters

responseIndex?

number = 1

Response index (1 = most recent).

sentenceIndex?

number = 1

Sentence index within that response (1 = first).

Returns

string


getTopic()

getTopic(): string

Defined in: core/Session.ts:103

Return the current conversation topic.

Returns

string

Default

"default"

queryTriples()

queryTriples(subject?, predicate?, object?): TripleEntry[]

Defined in: core/Session.ts:226

Query the triple store. Pass undefined to a field to act as a wildcard.

Parameters

subject?

string

Filter by subject (optional).

predicate?

string

Filter by predicate (optional).

object?

string

Filter by object (optional).

Returns

TripleEntry[]

Matching triples.


serialize()

serialize(): SessionData

Defined in: core/Session.ts:247

Serialise the session to a plain SessionData object.

Pass the result to JSON.stringify() and store it. Restore with Session.deserialize.

Returns

SessionData


setPredicate()

setPredicate(name, value): void

Defined in: core/Session.ts:76

Set a named predicate.

This is called automatically by <set name="..."> template tags. Setting "topic" also updates the session topic.

Parameters

name

string

Predicate name.

value

string

New value.

Returns

void


setTopic()

setTopic(topic): void

Defined in: core/Session.ts:111

Set the current conversation topic. Also updates the "topic" predicate so <get name="topic"/> works.

Parameters

topic

string

Returns

void


toJSON()

toJSON(): string

Defined in: core/Session.ts:288

Serialise the session to a JSON string.

Use Session.fromJSON to restore.

Returns

string

Example

localStorage.setItem('session', session.toJSON());

deserialize()

static deserialize(data): Session

Defined in: core/Session.ts:267

Restore a session from a SessionData object.

Parameters

data

SessionData

Returns

Session

Example

const saved = session.serialize();
// … store saved somewhere …
const session2 = Session.deserialize(saved);

fromJSON()

static fromJSON(json): Session

Defined in: core/Session.ts:298

Restore a session from a JSON string produced by Session.toJSON.

Parameters

json

string

Returns

Session

Example

const session = Session.fromJSON(localStorage.getItem('session')!);

Properties

created

readonly created: number

Defined in: core/Session.ts:41

Unix timestamp (ms) when the session was created.


id

readonly id: string

Defined in: core/Session.ts:35

Unique session identifier.


aiml.js / PatternMatcher

Class: PatternMatcher

Defined in: core/PatternMatcher.ts:145

Low-level pattern matching engine.

Stores a list of Category objects and efficiently finds the highest-priority match for a given (input, that, topic) triple.

Priority follows the AIML specification:

  • AIML 1.0: _ > exact > *
  • AIML 2.0: # > _ > exact/set > ^ > *

You do not normally need to use this class directly — the bot classes (AIMLBot, AIML1Bot, AIML2Bot) manage it internally.

Example

const matcher = new PatternMatcher();
matcher.addCategories(parseAIML(xml).categories);

const result = matcher.match('hello world', '*', '*');
if (result) {
  console.log('stars:', result.stars); // wildcard captures
}

Accessors

size

Get Signature

get size(): number

Defined in: core/PatternMatcher.ts:205

Total number of loaded categories.

Returns

number

Constructors

Constructor

new PatternMatcher(): PatternMatcher

Returns

PatternMatcher

Methods

addCategories()

addCategories(cats): void

Defined in: core/PatternMatcher.ts:164

Add multiple categories at once. More efficient than calling addCategory in a loop.

Parameters

cats

Category[]

Returns

void


addCategory()

addCategory(cat): void

Defined in: core/PatternMatcher.ts:155

Add a single category to the matcher. Triggers a re-sort on the next match call.

Parameters

cat

Category

Returns

void


clear()

clear(): void

Defined in: core/PatternMatcher.ts:181

Remove all categories.

Returns

void


match()

match(input, that, topic): MatchResult | null

Defined in: core/PatternMatcher.ts:234

Find the highest-priority category that matches the given triple.

All three strings are tokenised and matched against the stored patterns. Returns null if no category matches.

Parameters

input

string

Normalised user input.

that

string

Last bot sentence (use "*" if no prior response).

topic

string

Current conversation topic (use "default" if unset).

Returns

MatchResult | null

Example

const result = matcher.match('my name is Alice', '*', 'default');
// result.category → the matched Category
// result.stars[0] → 'Alice'

removeByFile()

removeByFile(file): void

Defined in: core/PatternMatcher.ts:175

Remove all categories that were loaded from a specific file. Useful for hot-reloading individual AIML files.

Parameters

file

string

The file name/path to remove categories from.

Returns

void


setBotProperties()

setBotProperties(props): void

Defined in: core/PatternMatcher.ts:200

Provide the current bot properties so <bot name="..."> pattern tokens can be evaluated during matching.

Parameters

props

Record<string, string>

Returns

void


setSet()

setSet(name, set): void

Defined in: core/PatternMatcher.ts:192

Register a named set for use in <set name="..."> pattern tokens.

Parameters

name

string

Set name (case-insensitive).

set

AIMLSet

Set of lower-cased strings.

Returns

void


aiml.js / Normalizer

Class: Normalizer

Defined in: core/Normalizer.ts:122

Text normalisation engine.

The Normalizer applies ordered substitution tables to transform text before matching (input normalisation) and after generation (denormalisation). It also provides the pronoun-swap transforms used by AIML template tags (<person>, <person2>, <gender>) and string-case helpers.

All substitutions are applied in a single pass (see applySubstitutions), so rules cannot inadvertently match text introduced by earlier rules.

Example

const norm = new Normalizer();
norm.updateSubstitutions('normal', [
  buildSubstitutionPair("can't", 'cannot'),
  buildSubstitutionPair("won't", 'will not'),
]);

norm.normalize("I can't do it"); // → "I cannot do it"
norm.person("I am happy");       // → "he or she is happy"
norm.gender("he called her");    // → "she called him"

Constructors

Constructor

new Normalizer(substitutions?): Normalizer

Defined in: core/Normalizer.ts:129

Parameters

substitutions?

Partial<Substitutions>

Override any built-in table. Omitted tables fall back to createDefaultSubstitutions.

Returns

Normalizer

Methods

addSubstitutions()

addSubstitutions(type, pairs): void

Defined in: core/Normalizer.ts:154

Append rules to an existing substitution table.

Parameters

type

keyof Substitutions

Which table to extend.

pairs

SubstitutionPair[]

Rules to append.

Returns

void


denormalize()

denormalize(text): string

Defined in: core/Normalizer.ts:180

Reverse normalisation applied to bot output. Uses the denormal substitution table.

Parameters

text

string

Returns

string


explode()

explode(text): string

Defined in: core/Normalizer.ts:231

Insert a space between every character. Used by the <explode> template tag.

Parameters

text

string

Returns

string

Example

explode('abc') // → 'a b c'

formal()

formal(text): string

Defined in: core/Normalizer.ts:215

Capitalise the first letter of every word (Title Case).

Parameters

text

string

Returns

string


gender()

gender(text): string

Defined in: core/Normalizer.ts:204

Apply gender pronoun substitution (he↔she, him↔her, …). Used by the <gender> template tag.

Parameters

text

string

Returns

string


lowercase()

lowercase(text): string

Defined in: core/Normalizer.ts:212

Convert text to lower case.

Parameters

text

string

Returns

string


normalize()

normalize(text): string

Defined in: core/Normalizer.ts:164

Normalise user input before pattern matching.

Applies the normal substitution table (contractions, punctuation, etc.) and collapses multiple spaces.

Parameters

text

string

Returns

string


person()

person(text): string

Defined in: core/Normalizer.ts:188

Apply first↔third person pronoun substitution. Used by the <person> template tag.

Parameters

text

string

Returns

string


person2()

person2(text): string

Defined in: core/Normalizer.ts:196

Apply first↔second person pronoun substitution. Used by the <person2> template tag.

Parameters

text

string

Returns

string


sentence()

sentence(text): string

Defined in: core/Normalizer.ts:220

Capitalise only the very first character (Sentence case).

Parameters

text

string

Returns

string


updateSubstitutions()

updateSubstitutions(type, pairs): void

Defined in: core/Normalizer.ts:145

Replace an entire substitution table.

Parameters

type

keyof Substitutions

Which table to replace.

pairs

SubstitutionPair[]

New substitution rules.

Returns

void


uppercase()

uppercase(text): string

Defined in: core/Normalizer.ts:209

Convert text to UPPER CASE.

Parameters

text

string

Returns

string