API Reference¶
Data corpuses¶
Static corpus¶
Defines a corpus of static documents to be processed and indexed. For details, see Static corpus.
Syntax
Function syntax
corpus({ [title,] urls [, auth] [, include] [, exclude] [, depth] [, maxPages] [, query] [, transforms] [, priority] })
Function syntax
corpus({ [title,] text [, query] [, transforms] [, priority] })
Parameters
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
string |
Optional |
Corpus title. |
|
string array |
Required |
List of URLs from which information must be retrieved. You can define URLs of website folders and pages. |
|
JSON object |
Optional |
Credentials to access resources that require basic authentication: |
|
string array |
Optional |
Resources to be obligatory indexed. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
string array |
Optional |
Resources to be excluded from indexing. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
function |
Optional |
Transforms function used to process user queries. For details, see Static corpus transforms. |
|
function |
Optional |
Transforms function used to format the corpus output. For details, see Static corpus transforms. |
|
integer |
Optional |
Crawl depth for web and PDF resources. The minimum value is 0 (crawling only the page content without linked resources). For details, see Crawling depth. |
|
integer |
Optional |
Maximum number of pages and files to index. If not set, only 1 page with the defined URL will be indexed. |
|
integer |
Optional |
Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed. For details, see Corpus priority. |
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
string |
Optional |
Corpus title. |
|
plain text or Markdown-formatted strings |
Required |
Text corpus presented as plain text strings or Markdown-formatted strings. |
|
function |
Optional |
Transforms function used to process user queries. For details, see Static corpus transforms. |
|
function |
Optional |
Transforms function used to format the corpus output. For details, see Static corpus transforms. |
|
integer |
Optional |
Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed. For details, see Corpus priority. |
Example
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`],
auth: {username: 'johnsmith', password: 'password'},
include: [/.*\.pdf/],
exclude: [`https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP`],
query: transforms.queries,
transforms: transforms.answers,
depth: 1,
maxPages: 5,
priority: 0,
});
corpus({
title: `HTTP corpus`,
text: `
# Understanding **async/await** in JavaScript
**async/await** is a feature in JavaScript that makes working with asynchronous code easier and more readable. It allows you to write asynchronous code that looks and behaves like synchronous code, making it easier to follow and understand.
## How Does **async/await** Work?
### **async** Keyword:
- The **async** keyword is used to declare a function as asynchronous.
- An **async** function returns a **Promise**, and it can contain **await** expressions that pause the execution of the function until the awaited **Promise** is resolved.
### **await** Keyword:
- The **await** keyword can only be used inside an **async** function.
- It pauses the execution of the function until the **Promise** passed to it is settled (either fulfilled or rejected).
- The resolved value of the **Promise** is returned, allowing you to work with it like synchronous code.
## Why Use **async/await**?
### Readability:
- By using **async/await**, you can avoid the complexity of chaining multiple **.then()** methods when dealing with Promises.
- Your code looks more like traditional synchronous code, making it easier to read.
### Error Handling:
- Error handling with **async/await** is simpler and more consistent with synchronous code.
- You can use **try/catch** blocks to handle errors.
`,
query: transforms.queries,
transforms: transforms.answers,
priority: 0,
});
Dynamic corpus¶
Defines a dynamic corpus of data to be processed.
The dynamic corpus allows retrieving JSON data from external data sources and using it to answer user queries in natural language. For details, see Dynamic corpus.
Syntax
Function syntax
corpus({ [title,] [input,] query [, output] [, transforms] [, priority] })
Parameters
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
string |
Optional |
Corpus title. |
|
function |
Optional |
Function used to populate the |
|
function |
Required |
Transforms function used to process user queries and generate code to retrieve necessary data. |
|
function |
Optional |
Function used to process obtained data, before it is passed to the |
|
function |
Optional |
Transforms function used to process and format data obtained with the |
|
integer |
Optional |
Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed. For details, see Corpus priority. |
Example
corpus({
title: `Infrastructure requests`,
input: project.objects,
query: transforms.vms_queries,
output: project.cleanObjects,
transforms: transforms.vms_answer,
priority: 1
});
Corpus with the Puppeteer crawler¶
Defines a corpus of pages with complex structures or interactions.
The corpus with the Puppeteer crawler allows crawling specific page content and dynamically loaded resources and using the retrieved content to answer user queries. For details, see Puppeteer crawler.
Syntax
Function syntax
corpus({ [title,] urls, crawler [, auth] [, include] [, exclude] [, depth] [, maxPages] [, query] [, transforms] [, priority] })
Parameters
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
string |
Optional |
Corpus title. |
|
string array |
Required |
List of URLs from which information must be retrieved. You can define URLs of website folders and pages. |
|
JSON object |
Required |
Type of crawler and function to be used to index corpus content:
|
|
JSON object |
Optional |
Credentials to access resources that require basic authentication: |
|
string array |
Optional |
Resources to be obligatory indexed. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
string array |
Optional |
Resources to be excluded from indexing. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
function |
Optional |
Transforms function used to process user queries. For details, see Puppeteer transforms. |
|
function |
Optional |
Transforms function used to format the corpus output. For details, see Puppeteer transforms. |
|
integer |
Optional |
Crawl depth for web and PDF resources. The minimum value is 0 (crawling only the page content without linked resources). For details, see Crawling depth. |
|
integer |
Optional |
Maximum number of pages and files to index. If not set, only 1 page with the defined URL will be indexed. |
|
integer |
Optional |
Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed. For details, see Corpus priority. |
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
string |
Optional |
Corpus title. |
|
string array |
Required |
List of URLs from which information must be retrieved. You can define URLs of website folders and pages. |
|
JSON object |
Required |
Type of crawler and function to be used to index corpus content. Crawler parameters:
|
|
JSON object |
Optional |
Credentials to access resources that require basic authentication: |
|
string array |
Optional |
Resources to be obligatory indexed. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
string array |
Optional |
Resources to be excluded from indexing. You can define an array of URLs or use RegEx to specify a rule. For details, see Corpus includes and excludes. |
|
function |
Optional |
Transforms function used to process user queries. For details, see Puppeteer transforms. |
|
function |
Optional |
Transforms function used to format the corpus output. For details, see Puppeteer transforms. |
|
integer |
Optional |
Crawl depth for web and PDF resources. The minimum value is 0 (crawling only the page content without linked resources). For details, see Crawling depth. |
|
integer |
Optional |
Maximum number of pages and files to index. If not set, only 1 page with the defined URL will be indexed. |
|
integer |
Optional |
Priority level assigned to the corpus. Corpuses with higher priority are considered more relevant when user requests are processed. For details, see Corpus priority. |
Example
corpus({
title: `Slack docs`,
urls: [
`https://slack.com/help/articles/360017938993-What-is-a-channel`,
`https://slack.com/help/articles/205239967-Join-a-channel`,
`https://slack.com/help/articles/201402297-Create-a-channel`,
],
crawler: {
puppeteer: api.defaultCrawler({
waitAfterLoad: 1000,
excludeSelectors: [
`header.header`,
`section.banner`,
`.hidden`,
`.category_list`,
`.article_footer`,
`footer.c-nav--expanded-footer`,
`#onetrust-consent-sdk`
]
}),
},
auth: {username: 'johnsmith', password: 'password'},
include: [/.*\.pdf/],
exclude: [/.*\.zip/],
query: transforms.queries,
transforms: transforms.answers,
depth: 3,
maxPages: 3,
priority: 1
});
corpus({
title: `Knowledge Base`,
urls: [`urls to crawl`]
crawler: {
puppeteer: crawlPages(),
browserLog: 'on',
args: {arg1: 'value1', agr2: 'value2'},
},
auth: {username: 'johnsmith', password: 'password'},
include: [/.*\.pdf/],
exclude: [/.*\.zip/],
query: transforms.queries,
transforms: transforms.answers,
depth: 10,
maxPages: 10,
priority: 1
});
async function* crawlPages({url, page, document, args}) {
// crawlPages function code ...
}
api.sleep¶
Pauses the execution of the current script for the specified number of milliseconds.
Use api.sleep()
in the data crawling function if a page takes a long time to load and there is no selector to wait for. For details, see Puppeteer crawler.
Syntax
Function syntax
api.sleep(time)
Parameters
Name |
Type |
Description |
---|---|---|
|
integer |
Duration for which the script should be paused in milliseconds. |
Example
async function* crawlKB({url, page, document}) {
if (url.includes(`knowledge.hubspot.com/search?`)) {
let linksSelector = `a.st-search-result-link`;
await page.waitForSelector(linksSelector, { timeout: 20000 });
const urls = await page.evaluate(() => {
let linksSelector = `a.st-search-result-link`;
return Array.from(document.querySelectorAll(linksSelector)).map(e=>e.href);
});
console.log(`# index [](${url}) => `, urls);
yield {urls};
} else if (url.includes(`knowledge.hubspot.com`)) {
console.log(`# parse [](${url})`);
await page.waitForSelector(`div.blog-post-wrapper.cell-wrapper`, {timeout: 20000});
await api.sleep(4000);
const html = await page.evaluate(() => {
const selector = 'div.blog-post-wrapper.cell-wrapper';
return document.querySelector(selector).innerHTML;
});
let content = await api.html2md_v2({html, url});
yield {content, mimeType: 'text/markdown'};
}
}
api.html2md_v2¶
Converts the HTML content into Markdown format, preserving the structure of the original HTML. For details, see Puppeteer crawler.
Syntax
Function syntax
api.html2md_v2(html [, url])
Parameters
Name |
Type |
Description |
---|---|---|
|
HTML string |
A string of HTML content to be converted to Markdown. |
|
URL |
The URL of a crawled page. The function uses the URL of a crawled page to replace relative links with the full domain value. |
Example
async function* crawlPages({url, page, document}) {
const html = await page.evaluate(() => {
const selector = 'div.content_col';
return document.querySelector(selector).innerHTML;
});
let content = await api.html2md_v2({html, url});
yield {content, mimeType: 'text/markdown'};
}
Transforms¶
Pre-processes and formats input data according to the defined template. For details, see Transforms.
Syntax
Function syntax
query: transforms.transformName
Or
Function syntax
transform: transforms.transformName
Function syntax
transforms.transformName({input, query})
Parameters
Name |
Type |
Description |
---|---|---|
|
string |
Name of the transform created in the AI agent project. |
Name |
Type |
Description |
---|---|---|
|
string |
Name of the transform created in the AI agent project. |
|
object |
An object containing the data input passed to the transform. |
|
function |
An object containing the transform query. |
Example
corpus({
title: `Infrastructure requests`,
query: transforms.infrastructure_queries,
transform: transforms.infrastructure_queries,
priority: 1
});
let data = {
"apartments": [
{
"name": "Modern Apartment in the City Center",
"location": "123 Main Street, Cityville",
"price": "$500,000",
"bedrooms": 2,
"bathrooms": 2,
"image": "https://vmts.ch/wp-content/uploads/2017/06/v1.jpg",
"url": "https://vmts.ch/en/portfolio/project-gasterzimmer/"
}
]
}
intent("Show available apartments", async p => {
p.play("Just a second...");
// Transform apartments data
let a = await transforms.render({
input: data,
query: 'Show available apartments'
});
p.play(a);
});
Action Transformer¶
act¶
Allows controlling the behavior of the Action Transformer: provide UI context, prioritize data, gather additional information and execute tasks. For details, see Action Transformer.
Syntax
Function syntax
act({[uiContext,] [context,] [fallback,] [execution,] [merge] })
Parameters
Name |
Type |
Required/Optional |
Description |
---|---|---|---|
|
function |
Optional |
Function used to retrieve the UI context of the page currently open in the app when the user query is given. For details, see UI context. |
|
function |
Optional |
Function used to gather conversational context to pass it to the Action Transformer. For details, see UI context. |
|
function |
Optional |
Transforms function used to handle unclear queries that require additional information, sensitive or biased queries. For details, see Fallback transforms. |
|
function |
Optional |
Transforms function used to specify what actions the AI agent must take in response to the user query. For details, see Action execution. |
|
function |
Optional |
Transforms function used to combine data from different corpuses to provide a comprehensive response. For details, see Data merging. |
Example
act({
uiContext: getUiContext,
context: getContext,
fallback: transforms.act_fallback,
execution: transforms.act_execute,
merge: transforms.act_merge
})
Intent-driven dialogs¶
Intent¶
Defines a user command to perform. For details, see User commands.
Syntax
Function syntax
intent([filter,] [noctx,] pattern1 [, pattern2, …, patternN], action)
Parameters
Name |
Type |
Description |
---|---|---|
|
function |
Defines the conditions on when the intent can be invoked. |
|
function |
Signals that the intent must not switch the current context. For details, see noContext intents. |
|
string |
Comma separated strings, each represents a pattern invoking the intent. |
|
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¶
Provides a voice or text response or sends a JSON command to the client app. For details, see play().
Syntax
Function syntax
play([voice(lang),] response1 [, response2, …, responseN] [, opts(options)])
Or
Function syntax
play(command [, opts(options)])
Parameters
Name |
Type |
Description |
---|---|---|
|
function |
Settings defining how the voice of the agent must be customized.
For details, see Voice settings. |
|
string/number |
String representing a response from the AI agent. |
|
object |
An arbitrary JSON object used to send commands to the client app. |
|
function |
Options defining how the
For details, see Play options. |
Contexts¶
Then¶
Activates the context in the dialog. For details, see Activating contexts.
Syntax
Function syntax
then(context[, state])
Parameters
Name |
Type |
Description |
---|---|---|
|
function |
Represents the variable name with which context is defined. |
|
object |
Predefined object that exists in every context. |
Resolve¶
Used to manually deactivate the current context in the dialog to return to the parent context. For details, see Exiting contexts.
Syntax
Function syntax
resolve([returnValue])
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Represents the object returned to the parent context. |
Fallback¶
Handles situations when the AI agent cannot understand or process the user request effectively. For details, see Error handling and re-prompts.
Syntax
Function syntax
fallback(pattern1 [, pattern2, …, patternN])
Parameters
Name |
Type |
Description |
---|---|---|
|
string |
Comma separated strings, each represents a pattern of a response from Alan AI. |
noContext¶
Encloses intents that should not change the current context, such as general questions in a conversation. For details, see noContext intents.
Syntax
Function syntax
noContext(() => {intent1 [, intent2, …, intentN]});
Parameters
Name |
Type |
Description |
---|---|---|
|
function |
An intent that must not switch the current context when invoked. |
Title¶
Assigns a label or name to a context in the dialog script. For details, see Labeling contexts.
Syntax
Function syntax
title(contextName)
Parameters
Name |
Type |
Description |
---|---|---|
|
string |
Represents the name of a context that will be shown in logs |
Session-specific objects and methods¶
Session-specific objects and methods are accessible through the predefined p
object. They persist throughout a user session, which lasts until either 30 minutes of inactivity or when the user ends the dialog with the AI agent and closes the app/AI chat.
userData¶
A runtime object used to store any relevant data. The data in p.userData
is available only for the duration of the user session. You can access it at any time from any dialog script in the AI agent project, regardless of the context. For details, see userData.
authData¶
A runtime object used to store static data specific to the device or user, such as user credentials or product version. For details, see authData.
visual¶
A runtime object used to store any arbitrary JSON data. Use it to provide dynamic information about the app’s state or visual context to the AI agent. For details, see Visual state.
Global objects and methods¶
project¶
A global object used to store data that can be accessed by any dialog scripts in the project.
When Alan AI builds the dialog model, it loads scripts from top to bottom as listed in the scripts panel. As a result, the project
object will be accessible in any script that follows the one where it was defined.
// Script 1
project.config = {initValue: 1};
// Script 2
console.log(`Init value is ${project.config.initValue}`);
project API¶
Allows sending data from the client app to the dialog script or executing script logic without a user command.
Define the logic using projectAPI
in the dialog script and then invoke it with the callProjectApi()
method in the Alan AI SDK. For details, see Project API.
Syntax
Function syntax
projectAPI.functionName = function(p, data, callback) {}
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Predefined object containing the user session data and exposing Alan AI’s methods. |
|
object |
An object containing the data you want to pass to your script. |
|
function |
A callback function used to receive data back to the app. |
Example
projectAPI.setToken = function(p, param, callback) {
if (!param || !param.token) {
callback("error: token is undefined");
}
p.userData.token = param.token;
callback();
};
Predefined callbacks¶
To perform actions at different stages of the dialog lifecycle, use the following predefined callback functions:
onCreateProject¶
onCreateProject
is invoked when the dialog model for the dialog script is built. Use this function for activities that must be accomplished after the creation of the dialog model, such as data initialization.
Syntax
Function syntax
onCreateProject(()=> {action})
Parameters
Name |
Type |
Description |
---|---|---|
|
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
.
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. Use this function to set up user-specific data.
Syntax
Function syntax
onCreateUser(p => {action})
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Predefined object containing the user session data and exposing Alan AI’s methods. |
|
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
:
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. Use this function for cleanup tasks.
Syntax
Function syntax
onCleanupUser(p => {action})
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Predefined object containing the user session data and exposing Alan AI’s methods. |
|
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:
onCleanupUser(p => {
p.userData.name = "";
});
onVisualState¶
onVisualState
is invoked when the visual state object is set. Use this function to process any data stored in the visual state or to accomplish tasks to be performed when the new visual state is set.
Syntax
Function syntax
onVisualState((p, s) => {action})
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Predefined object containing the user session data and exposing Alan AI’s methods. |
|
object |
JSON object passed with the visual state. |
|
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 agent plays a greeting to the user.
Setting the visual state in the app:
<script>
function myFunction() {
alanBtnInstance.setVisualState({"page": "admittance"});
}
</script>
Playing a greeting in the dialog script:
onVisualState((p, s) => {
if (p.visual.page === "admittance") {
p.play("Hello there! I'm your AI agent, here to guide you through your journey towards academic success.")
}
});
onUserEvent¶
onUserEvent
is invoked when Alan AI emits an event driven by users’ interactions with the AI agent. For the events list, see User events.
Syntax
Function syntax
onUserEvent((p, e) => {action})
Parameters
Name |
Type |
Description |
---|---|---|
|
object |
Predefined object containing the user session data and exposing Alan AI’s methods. |
|
object |
Event fired by Alan AI. |
|
function |
Defines what actions must be taken when the event is fired. |
Example
In the example below, the AI agent listens to the firstClick
event and, if the user activates the AI agent for the first time, plays a greeting to the user.
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 invoked when the dialog script enters a context. For details, see onEnter() callback.
Syntax
Function syntax
onEnter(action)
Parameters
Name |
Type |
Description |
---|---|---|
|
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:
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¶
Outputs informational messages to Alan AI Studio logs. Use console.log()
for debugging purposes to display slot values, messages and other data.
Syntax
Function syntax
console.log(message)
Parameters
Name |
Type |
Description |
---|---|---|
|
string |
Message to be logged. |
Example
intent('Save this location as my $(LOCATION: home|office|work) address', p => {
console.log(p.LOCATION.value);
p.play('The location is saved');
})
console.error¶
Outputs error messages to Alan AI Studio logs. Use it to report errors or exceptions that occur during the dialog script execution.
Syntax
Function syntax
console.error(message)
Parameters
Name |
Type |
Description |
---|---|---|
|
string |
Message to be logged. |
Example
try {
// your code
}
catch (e) {
console.error(e)
}