Skip to content

Latest commit

 

History

History
650 lines (494 loc) · 24.6 KB

docs.md

File metadata and controls

650 lines (494 loc) · 24.6 KB

Classes

Processor

Room and message processor. Handles the mechanics of classifying and responding to messages, including bot to person interactions.

Room

Representation of a chat room which acts as a container for messages. Each chat system room that we have ever seen messages in has exactly one Room object which is stored down to the database, and is uniquely identified by its (provider, room_name) tuple.

Message

Representation of a chat message in any system. Messages are associated with Rooms and may have Classifications and Appeals logged against them.

StateMachine

Statemachine class with emphasis on quick initialisation, lightweight state storage, and easy state visualisation.

Database

Implements a SQL based store for all Polite.ai applications Stores rooms, messages with associated classifications and appeals into a SQL database with a schema which is optimised for bulk manipulation.

All interfaces apart from constructor are async returning a Promise which resolves or rejects when database operation completes.

Database methods are not normally called from application code which should use the Room and Message class abstractions. The interface classes automatically push their objects out to the database using the methods provided by this class.

Language

Generate responses in different languages, based on language packs in languages/[language].json

Classify

Classification engine interface, select engine and handle mechanics of calling it.

Processor

Room and message processor. Handles the mechanics of classifying and responding to messages, including bot to person interactions.

Kind: global class

new Processor()

Constructor

processor.message(text, provider, roomId, eventId, userId, timestamp, classifierName, language, personality) ⇒ Promise.<Object>

Handle a chat room message between users, detect anything we should be detecting and return a response to inject back into the room if appropriate.

Kind: instance method of Processor
Returns: Promise.<Object> - Resolves to object with properties status:, triggered and response:

Param Type Description
text String message text
provider String
roomId String
eventId String
userId String
timestamp String
classifierName String
language String
personality String

processor.dialogue(text, provider, roomId, eventId, userId, timestamp, classifierName, language, personality) ⇒ Promise.<Object>

Conduct a dialogue with the bot

Kind: instance method of Processor
Returns: Promise.<Object> - Resolves to object with properties status: and response: text

Param Type Description
text String message text
provider String
roomId String
eventId String
userId String
timestamp String
classifierName String
language String
personality String

processor.join(provider, roomId, eventId, userId, botName, classifierName, language, personality) ⇒ Promise.<Object>

Process a join request

Kind: instance method of Processor

Param Type
provider String
roomId String
eventId String
userId String
botName String
classifierName String
language String
personality String

Room

Representation of a chat room which acts as a container for messages. Each chat system room that we have ever seen messages in has exactly one Room object which is stored down to the database, and is uniquely identified by its (provider, room_name) tuple.

Kind: global class

new Room(room, provider)

Create a Room.

Param Type Description
room * If this is an Object then it's properties are copied to the new Room, otherwise it is regarded as a String and considered to be the unique room name
provider String Entity within who's namespace this room name is unique. If the logical room provider can have several rooms with the same name in different scopes or domains then provider will include the scope or domain to ensure uniqueness of room name.

Example

development = new Room ('#developent:polite.ai', 'matrix');
development.exists.then(e => console.log('room',(e)?'exists':'notExist'));
var messages = development.getList({allData: true, limit:100});

room.id : String

Database assigned internal unique identifier

Kind: instance property of Room

room.provider_id : String

Room name

Kind: instance property of Room

room.provider : String

Provider namespace

Kind: instance property of Room

room.initialised : bool

Is this room initialised with all data (owner, type etc)

Kind: instance property of Room

room.type : String

Type of discussion that can nbe expected in this room: technical, social, political, business, strategy etc At some point there will be a taxonomy of these things, but for now self description by the owner

Kind: instance property of Room

room.owner : String

Who seems to own this room? (userId of person that invited us generally)

Kind: instance property of Room

room.dialogState : String

Current state of Dialogue StateMachine for bot conversation in this room

Kind: instance property of Room

room.key : String

Guaranteed unique key with at least 128 bits of entropy, can be used for secure URLs

Kind: instance property of Room

room.time : Date

Time/Date that this Room object was created

Kind: instance property of Room

room.updated : Promise.<bool>

Outstanding updates complete

Kind: instance property of Room

room.exists : Promise.<bool>

Resolves to true if room exists in Database

Kind: instance property of Room

room.getMessages([flags]) ⇒ Promise.<Array.<Message>>

Get a list of Message objects associated with a room

Kind: instance method of Room
Returns: Promise.<Array.<Message>> - Resolves to an array of matching message objects

Param Type Default Description
[flags] Object Search flags
flags.allData bool false return deep data on Message objects - all classifications and appeals (may return lots of data)
flags.offset number 0 start at this ones based offset in the list (skip offset-1 entries)
flags.limit number 50 return limited number of records
flags.reverse bool false list returned in most recent first date order

room.destroy() ⇒ Promise

Removes persitent database object associated with this Room.

Kind: instance method of Room
Returns: Promise - Resolves or rejects depending on whether the destroy succeeds.

Room.getList(provider, [partial_id]) ⇒ Promise.<Array.<Room>>

Get a list of Rooms in the database

Kind: static method of Room
Returns: Promise.<Array.<Room>> - Resolves to an Array of Room objects or rejects if no match based on the specified search criteria

Param Type Description
provider String Name of provider
[partial_id] String Restrict to rooms which have this string anywhere in their room name

Message

Representation of a chat message in any system. Messages are associated with Rooms and may have Classifications and Appeals logged against them.

Kind: global class

new Message(message, provider, room_name, event_id, user, [time], [flags])

Create a Message. When new, well formed Message objects are created, they are asynchronously written down to a SQL database. If an existing message with the same unique (provider, event_id) exists in the database then these are assumed to be the same message and the object is populated from the database version.

Param Type Default Description
message * If this is an Object then it's properties are copied to the new message object otherwise it is the UTF8 message body as a String
provider String Unique provider ID
room_name String Name of the room that this message was seen in
event_id String Unique ID for this message - usually generated by the provider and tuple (provider, event_id) should be globally unique. Multiple records with same vales for this tuple will be assumed to be same message even if other properties differ
user String User id associated with this message, usually the author, as identified by the provider
[time] Date now creation time for this message
[flags] Object Search flags
flags.allData bool false return deep data on Message objects - all classifications and appeals (may return lots of data)

Example

var m = new Message("hello world", "myChat", "general", "12345", "[email protected]");
m.status.then(s => {
  if(s)
     console.log('message in database for id=', m.id);
  else
     console.log('message could not be created');
  m.exists.then(e => {
    console.log('message ', m.id, (e)?'already existed':'newly created');
  })
}).catch(err => console.log('create', err));

message.id : String

Database assigned internal unique identifier

Kind: instance property of Message

message.text : String

Message text in UTF-8

Kind: instance property of Message

message.provider : String

Provider identifier

Kind: instance property of Message

message.room : Room

Room object this message comes from

Kind: instance property of Message

message.user : String

User identity associated with message

Kind: instance property of Message

message.event_id : String

Unique message ID within this provider

Kind: instance property of Message

message.time : Date

Time/Date that this Message object was created

Kind: instance property of Message

message.classification : Array

Array of classifications that have been applied to this message.

Kind: instance property of Message

message.appeals : Array

Array of appeals that have been lodged against this message

Kind: instance property of Message

message.exists : Promise.<bool>

Resolves when the database status of this message is known to true if the entry already existed or false if it didn't exist in the database prior to this instantiation.

Kind: instance property of Message

message.status : Promise.<bool>

After a new Message is instantiated the database is checked asynchronoulsy and the message is either retrieved from the database or written to it. When this completes, the exists Promise resolves to true if the message was well formed and now in the database. Resolves to false if there was a problem with the message and it wasn't backed to the database.

Kind: instance property of Message

message.classify(classifier, classification) ⇒ Promise.<number>

Add a classification to a message

Kind: instance method of Message
Returns: Promise.<number> - Resolves when saved to database to unique database ID

Param Type Description
classifier String Which classifier generated this classification
classification String What was the classification

message.appeal(type, text, user) ⇒ Promise.<number>

[appeal description]

Kind: instance method of Message
Returns: Promise.<number> - Resolves when appeal is stored to unique database ID of appeal

Param Type Description
type String 'report' unclassified message
'appeal' existing positive classification
text String free form text comment by reporter
user String identifier for user reporting issue

message.destroy() ⇒ Promise

Removes all persitent database objects associated with this Message. Doesn't affect the Room record that contains it, but removes all associated Classification and Appeal objects

Kind: instance method of Message
Returns: Promise - Resolves or rejects depending on whether the destroy succeeds.

StateMachine

Statemachine class with emphasis on quick initialisation, lightweight state storage, and easy state visualisation.

Kind: global class

new StateMachine(states, env, initial)

Create a statemachine instance

Param Type Default Description
states Object State machine definition
env Object none The environment available to any exec functions
initial String from-definition Name of initial state

stateMachine.validTransition(action) ⇒ Object

Get a transition from current state to new state based on Action (if valid)

Kind: instance method of StateMachine
Returns: Object - Transition object (null if not a valid action in this state)

Param Type Description
action String Name of action

stateMachine.action(name) ⇒ String

Apply an action to cause a transition

Kind: instance method of StateMachine
Returns: String - The 'emit' string for this action (or return from exec function if this exists)

Param Type Description
name String Action name

stateMachine.describe() ⇒ String

Get a GraphViz compatible digraph description of this state machine.

Kind: instance method of StateMachine
Returns: String - Text of GraphViz Description
Example

foo = new StateMachine(snowmanDefinition)
console.log(foo.describe());


Outputs:
digraph "Snowman State Transitions" {
   "snow" [color=red];
   "snowman";
   "water";
   "clouds";
   "snow" -> "snowman" [ label="Action: build\nSay: lets build a snowman"]
   "snow" -> "water" [ label="Action: melt\nSay: oh no, it melted too quickly"]
   "snowman" -> "water" [ label="Action: melt\nSay: help, I'm melting"]
   "water" -> "clouds" [ label="Action: evaporate\nSay: it's very warm today"]
   "clouds" -> "snow" [ label="Action: snowing\nSay: hey it's snowing"]
}

Database

Implements a SQL based store for all Polite.ai applications Stores rooms, messages with associated classifications and appeals into a SQL database with a schema which is optimised for bulk manipulation.

All interfaces apart from constructor are async returning a Promise which resolves or rejects when database operation completes.

Database methods are not normally called from application code which should use the Room and Message class abstractions. The interface classes automatically push their objects out to the database using the methods provided by this class.

Kind: global class

new Database(credentials, MessageClass, RoomClass)

Create a new database worker

Param Type Default Description
credentials Object from_config Postgres database credentials
MessageClass Message Class definition to be used when creating messages
RoomClass Room Class definition to be used when creating rooms

Language

Generate responses in different languages, based on language packs in languages/[language].json

Kind: global class

new Language(language, personality)

Initialises a language outputter based on language and personality required

Throws:

  • Error If the language pack doesn't exist in this implementation, or the personality requested doesn't exist within the language pack.
Param Type Default Description
language String english Name of a valid language pack
personality String first Name of a valid personality, defaults to first

language.response(classification) ⇒ String

Generates a language response for a classification or dialog. Returns the first matching phrase from the langauage pack which is in the set of topic objects. If the language pack contains an array of possible responses for the topic then one is returned at random and if there is no specific response then the default tag is used.

Kind: instance method of Language
Returns: String - Human output string in this language and personality

Param Type Description
classification * If a string then the dialog type, otherwise an object with named properties that are matched to language responses if they are true.

Classify

Classification engine interface, select engine and handle mechanics of calling it.

Kind: global class

new Classify(classifier)

Create a classifier

Throws:

  • Error if the classifier name doesn't exist in this implementation
Param Type Default Description
classifier String default Name of classification engine to use, if not set then defaults arbitrarily to first available

classify.classify(text, lang) ⇒ Promise.<Object>

Send a text string to the classification server and await results

Kind: instance method of Classify
Returns: Promise.<Object> - Resolves to the result object or rejects if there are communication problems with the classification server

Param Type Default Description
text String Text to be classified
lang String english The language that the text can be expected to be in