API Reference

Question answering

corpus

corpus is a predefined function that allows you to retrieve data from static and dynamic data sources and utilize it to address user queries. For details, see Question answering.

Static corpus

Syntax

Function syntax

corpus(resource1 [, resource2, …, resourceN])

Parameters

Name

Type

Is Required

Description

title

string

False

Corpus title.

urls

string array

True

List of URLs from which information must be retrieved. You can define URLs of website folders and pages.

exclude

string array

False

List of URLs to be excluded from indexing. You can define URLs of website folders and pages.

depth

integer

False

Crawl depth for web and PDF resources. The minimum value is 0 (crawling only the page content without linked resources).

maxPages

integer

True

Maximum number of pages and files to index. If not set, only 1 page with the defined URL will be indexed.

priority

integer

False

Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed.

query

function

False

Transforms function used to process user queries.

transforms

function

False

Transforms function used to format the corpus output.

Example

Dialog script
corpus({
    title: `HTTP corpus`,
    urls: [
        `https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview`,
        `https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages`,
        `https://developer.mozilla.org/en-US/docs/Web/HTTP/Session`],
    exclude: [`https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP`],
    depth: 1,
    maxPages: 5,
    priority: 0,
});

Dynamic corpus

Syntax

Function syntax

corpus(resource1 [, resource2, …, resourceN])

Parameters

Name

Type

Is Required

Description

title

string

False

Corpus title.

input

function

False

Function used to provide context data to the dynamic corpus.

query

function

True

Transforms function used to process user queries and generate code to retrieve necessary data.

output

function

False

Function used to clean up data passed to the dynamic corpus.

transforms

function

False

Transforms function used to format the corpus output.

priority

integer

False

Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed.

Example

Dialog script
corpus({
   title: `Infrastructure requests`,
   input: project.objects,
   query: transforms.vms_queries,
   output: project.cleanObjects,
   transforms: transforms.vms_answer,
   priority: 1
});

Data transformation

You can use the following function for data preprocessing and transformation: transforms.

transforms

The transforms() function can be used to pre-process and format the input data to the required format using the defined template. For details, see Data transformation.

Syntax

Function syntax

transforms.transformName({input, query})

Parameters

Name

Type

Description

tranformName

string

Name of the transform created in the AI assistant project.

input

object

An object containing the data input passed to the transform.

query

function

An object containing the transform query.

Example

In the example below, the text in the input is formatted by the rules specified in the format transform:

  • Common query: The input contains user data in JSON, the query contains fields description, the result contains formatted text

  • Input: JSON, {"name": "Jerry Welsh", "age": "16", "address": "3456 Oak Street"}

  • Query: Name is the user's name, age is the user's age, address is the user's address

  • Result: Markdown

Results field
## User: user's name

- **Name**: user's name
- **Age**: user's age
- **Address**: user's address
Dialog script
intent(`Show user data`, async (p)=> {
    let u = await transforms.format({
        input: {"name": "John Smith", "age": "56", "address": "1234 Main Street"},
        query: "Name is the user's name, age is the user's age, address is the user's address"
    });
    p.play(u);
});

Intent-driven dialogs

Intent

intent() is a predefined function to define a voice or text command. In the function, you specify expected user inputs — patterns, conditions on when the command must be available for the user — visual filters, and actions that must occur when the user’s input matches one of the patterns. For details, see User commands.

Syntax

Function syntax

intent([filter,] [noctx,] pattern1 [, pattern2, …, patternN], action)

Parameters

Name

Type

Description

filter

function

Defines the conditions on when the intent can be invoked.

noctx

function

Signals that the intent must not switch the current context. For details, see noContext intents.

pattern

string

Comma separated strings, each represents a pattern invoking the intent.

action

function

Defines what actions must be taken when one of the intent patterns is matched. Either an anonymous arrow function or the reply() function.

Play

play() is a predefined function used to provide voice or text responses or to send JSON commands to the web/mobile client app. If more than one response is passed to the play() function, only one response will be played at random. For details, see play().

Syntax

Function syntax

play([voice(lang),] response1 [, response2, …, responseN] [, opts(options)])

Or

Function syntax

play(command [, opts(options)])

Parameters

Reply

reply() is a predefined action function providing the specified voice or text response to the user. If more than one response is passed to the reply() function, only one response will be played at random. For details, see reply().

Syntax

Function syntax

reply(response1 [, response2, …, responseN])

Parameters

Name

Type

Description

response

string

String representing a response from the AI assistant.

Contexts

Then

then() is a predefined function used to activate the context. If you need to share data between the current context and the activated one, you can pass this data with the state object. For details, see Activating contexts.

Syntax

Function syntax

then(context[, state])

Parameters

Name

Type

Description

context

function

Represents the variable name with which context is defined.

state

object

Predefined object that exists in every context.

Resolve

resolve() is a predefined function used to manually deactivate the current context and return to its parent context. You can pass any data to it, this data will be available in the parrent context. For details, see Exiting contexts.

Syntax

Function syntax

resolve([returnValue])

Parameters

Name

Type

Description

returnValue

object

Represents the object returned to the parent context.

Fallback

For each context, you can define a fallback response which will be activated if this context is active and no intent from this context has been matched. For details, see Error handling and re-prompts.

Syntax

Function syntax

fallback(pattern1 [, pattern2, …, patternN])

Parameters

Name

Type

Description

pattern

string

Comma separated strings, each represents a pattern of a response from Alan AI.

noContext

The noContext function wraps all intents that must not switch the current context, for example, general questions in the dialog. For details, see noContext intents.

Syntax

Function syntax

noContext(() => {intent1 [, intent2, …, intentN]});

Parameters

Name

Type

Description

intent

function

An intent that must not switch the current context when invoked.

State

Each context has a special predefined object — state. You can access it via p.state. This object should be treated as the knowledge base that is available to Alan AI in the current conversational context. You can store any data in it. For details, see state.

Title

title() is a special predefined function used to label a context. For details, see Labeling contexts.

Syntax

Function syntax

title(contextName)

Parameters

Name

Type

Description

contextName

string

Represents the name of a context that will be shown in logs

Session-specific objects and methods

Session-specific objects and methods are available via the predefined p object. These methods and objects persist during a user session, until the session is terminated. The user session is terminated after 30 minutes of inactivity or if the user quits the app.

userData

p.userData is a runtime object that can be used to store any data. You can access it at any time from any script of your project regardless of the context. Take a note that the data stored in p.userData is available only during the given user session. For details, see userData.

authData

p.authData is a runtime object that can be used to provide static device- or user-specific data, such as the user’s credentials, to Alan AI. If you need to receive dynamic data from the app, use the visual state instead.

For details, see authData.

visual

p.visual is a runtime object that can contain an arbitrary JSON object. It should be used to provide any dynamic data of the app state to Alan’s script or project. For details, see Visual state.

Global objects and methods

project

project is a global object that can be used to store any data you may need in separate dialog scripts of your project. When Alan AI builds the dialog model for your project, it loads scripts in the order defined in the scripts panel, from top to bottom. The project object will be available in any script that is below the script where it is defined.

Dialog script
// Script 1
project.config = {initValue: 1};

// Script 2
console.log(`Init value is ${project.config.initValue}`);

project API

The project API can be used if you want to send data from the client app to the dialog script or perform some script logic without a voice or text command from the user. This can be done by setting up the logic for the project API and then calling it with Alan AI SDK method — callProjectApi(). For details, see Project API.

Syntax

Function syntax

projectAPI.functionName = function(p, data, callback) {}

Parameters

Name

Type

Description

p

object

Predefined object containing the user session data and exposing Alan AI’s methods.

data

object

An object containing the data you want to pass to your script.

callback

function

A callback function used to receive data back to the app.

Example

Dialog script
projectAPI.setToken = function(p, param, callback) {
    if (!param || !param.token) {
        callback("error: token is undefined");
    }
    p.userData.token = param.token;
    callback();
};

Predefined callbacks

After you create an AI assistant with Alan AI, the dialog goes through several states: the project is created, the user connects to the app and so on. When the dialog state changes, you may want to perform activities that are appropriate to this state. For example, when a new user connects to the dialog session, it may be necessary to set user-specific data.

To perform actions at different stages of the dialog lifecycle, you can use the following predefined callback functions:

onCreateProject

onCreateProject is invoked when the dialog model for the dialog script is created. You can use this function to perform activities required immediately after the dialog model is built, for example, for any data initialization.

Syntax

Function syntax

onCreateProject(()=> {action})

Parameters

Name

Type

Description

action

function

Defines what actions must be taken when the dialog model is created on the server in Alan AI Cloud.

Example

In the example below, onCreateProject is used to define values for project.drinks.

Dialog script
onCreateProject(() => {
    project.drinks = "green tea, black tea, oolong";
});

intent(`Get me $(DRINKS: ${project.drinks})`, p => {
    p.play(`Adding ${p.DRINKS.value} to your order...`)
});;

onCreateUser

onCreateUser is invoked when a new user starts a dialog session. You can use this function to set user-specific data.

Syntax

Function syntax

onCreateUser(p => {action})

Parameters

Name

Type

Description

p

object

Predefined object containing the user session data and exposing Alan AI’s methods.

action

function

Defines what actions must be taken when a new user starts a dialog session.

Example

In the example below, the onCreateUser function is used to assign the value to p.userData.favorites:

Dialog script
onCreateUser(p => {
    p.userData.name = "John Smith";
});

onUserEvent((p, e) => {
    if (e.event == 'firstClick') {
        p.play(`Hi, ${p.userData.name}, how can I help you today?`);
    }
});

onCleanupUser

onCleanupUser is invoked when the user session ends. You can use this function for any cleanup activities.

Syntax

Function syntax

onCleanupUser(p => {action})

Parameters

Name

Type

Description

p

object

Predefined object containing the user session data and exposing Alan AI’s methods.

action

function

Defines what actions must be taken when the user session ends.

Example

In the example below, the onCleanupUser function is used to reset p.userData.favorites value:

Dialog script
onCleanupUser(p => {
    p.userData.name = "";
});

onVisualState

onVisualState is invoked when the visual state object is set. You can use this function, for example, to process data passed in the visual state.

Syntax

Function syntax

onVisualState((p, s) => {action})

Parameters

Name

Type

Description

p

object

Predefined object containing the user session data and exposing Alan AI’s methods.

s

object

JSON object passed with the visual state.

action

function

Defines what actions must be taken when the visual state is sent.

Example

In the example below, when the user opens the Admittance section of the website, the AI assistant plays a greeting to the user.

Setting the visual state in the app:

Client app
<script>
  function myFunction() {
    alanBtnInstance.setVisualState({"page": "admittance"});
  }
</script>

Playing a greeting in the dialog script:

Dialog script
onVisualState((p, s) => {
    if (p.visual.page === "admittance") {
        p.play("Hello there! I'm your AI assistant, here to guide you through your journey towards academic success.")
    }
});

onUserEvent

onUserEvent is invoked when Alan AI emits a specific event driven by users’ interactions with the AI assistant. For the events list, see User events.

Syntax

Function syntax

onUserEvent((p, e) => {action})

Parameters

Name

Type

Description

p

object

Predefined object containing the user session data and exposing Alan AI’s methods.

e

object

Event fired by Alan AI.

action

function

Defines what actions must be taken when the event is fired.

Example

In the example below, the AI assistant listens to the firstClick event and, if the user activates the assistant for the first time, plays a greeting to the user.

Dialog script
onCreateUser(p => {
    p.userData.name = "John Smith";
});

onUserEvent((p, e) => {
    if (e.event == 'firstClick') {
        p.play(`Hi, ${p.userData.name}, how can I help you today?`);
    }
});

onEnter

onEnter() is a special predefined callback activated each time the script enters a context. For details, see onEnter() callback.

Syntax

Function syntax

onEnter(action)

Parameters

Name

Type

Description

action

function

Defines what actions must be taken when the context is activated.

Example

In the example below, when the user enters the countContext, the p.state.result value is set to 0:

Dialog script
let countContext = context(() => {
    onEnter(p => {
        p.state.result = 0;
    });

    intent('Yes', p => {
        p.state.result += 1;
        p.play(p.state.result.toString());
    });
});

intent("Count the number of times I've said yes", p =>{
    p.play("Sure, let's go");
    p.then(countContext);
});

Debugging

console.log

The console.log() function is used to write all sort of info messages to Alan AI Studio logs. With it, you can check objects, variables and slots values, capture events and so on.

Syntax

Function syntax

console.log(message)

Parameters

Name

Type

Description

message

string

Message to be logged.

Example

Dialog script
intent('Save this location as my $(L home|office|work) (address|)', p => {
    console.log(p.L.value);
    p.play('The location is saved');
})

console.error

The console.error() function is used to write error messages to Alan AI Studio logs. With it, you can troubleshoot and debug your dialog script.

Syntax

Function syntax

console.error(message)

Parameters

Name

Type

Description

message

string

Message to be logged.

Example

Dialog script
try {
    // your code
}
catch (e) {
    console.error(e)
}