Constructor

ApiAiAssistant

new ApiAiAssistant(options)

Parameters

Name Description

options

Object

JSON configuration.

Example

const ApiAiAssistant = require('actions-on-google').ApiAiAssistant;
const assistant = new ApiAiAssistant({request: request, response: response,
  sessionStarted:sessionStarted});

Abstract types

Context

Object

API.AI Context.

Properties

Name Description

name

string

Full name of the context.

parameters

Object

Parameters carried within this context. See here.

lifespan

number

Remaining number of intents

DeviceLocation

Object

User's permissioned device location.

Properties

Name Description

coordinates

Object

{latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION.

address

string

Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION.

zipCode

string

Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION.

city

string

Device city. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION.

User

Object

User object.

Properties

Name Description

userId

string

Random string ID for Google user.

userName

UserName

User name information. Null if not requested with askForPermission(SupportedPermissions.NAME).

accessToken

string

Unique Oauth2 token. Only available with account linking.

UserName

Object

User's permissioned name info.

Properties

Name Description

displayName

string

User's display name.

givenName

string

User's given name.

familyName

string

User's family name.

Enumerations

BuiltInArgNames

read-only

string

List of built-in argument names.

Property

Name Description

PERMISSION_GRANTED

Permission granted argument.

ConversationStages

read-only

number

List of possible conversation stages, as defined in the Conversation object.

Properties

Name Description

UNSPECIFIED

Unspecified conversation state.

NEW

A new conversation.

ACTIVE

An active (ongoing) conversation.

StandardIntents

read-only

string

List of standard intents that the Assistant provides.

Properties

Name Description

MAIN

Assistant fires MAIN intent for queries like [talk to $action].

TEXT

Assistant fires TEXT intent when action issues ask intent.

PERMISSION

Assistant fires PERMISSION intent when action invokes askForPermission.

SupportedPermissions

read-only

string

List of supported permissions the Assistant supports.

Properties

Name Description

NAME

The user's name as defined in the UserProfile object

DEVICE_PRECISE_LOCATION

The location of the user's current device, as defined in the Location object.

DEVICE_COARSE_LOCATION

City and zipcode corresponding to the location of the user's current device, as defined in the Location object.

Methods

askForPermission

askForPermission(context, permission, dialogState)

Asks the Assistant to guide the user to grant a permission. For example, if you want your action to get access to the user's name, you would invoke the askForPermission method with a context containing the reason for the request, and the assistant.SupportedPermissions.NAME permission. With this, the Assistant will ask the user, in your agent's voice, the following: '[Context with reason for the request], I'll just need to get your name from Google, is that OK?'.

Once the user accepts or denies the request, the Assistant will fire another intent: assistant.intent.action.PERMISSION with a boolean argument: assistant.BuiltInArgNames.PERMISSION_GRANTED and, if granted, the information that you requested.

Read more:

Parameters

Name Description

context

string

Context why permission is asked; it's the TTS prompt prefix (action phrase) we ask the user.

permission

string

One of the permissions Assistant supports, each of which comes from Assistant.SupportedPermissions.

dialogState

Optional

Object

JSON object the action uses to hold dialog state that will be circulated back by Assistant.

Returns

A response is sent to the Assistant to ask for the user's permission; for any invalid input, we return null.

Example

const assistant = new ApiAiAssistant({request: req, response: res});
const REQUEST_PERMISSION_ACTION = 'request_permission';
const GET_RIDE_ACTION = 'get_ride';

function requestPermission (assistant) {
  const permission = assistant.SupportedPermissions.NAME;
  assistant.askForPermission('To pick you up', permission);
}

function sendRide (assistant) {
  if (assistant.isPermissionGranted()) {
    const displayName = assistant.getUserName().displayName;
    assistant.tell('I will tell your driver to pick up ' + displayName);
  } else {
    // Response shows that user did not grant permission
    assistant.tell('Sorry, I could not figure out who to pick up.');
  }
}
const actionMap = new Map();
actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission);
actionMap.set(GET_RIDE_ACTION, sendRide);
assistant.handleRequest(actionMap);

askForPermissions

askForPermissions(context, permissions, dialogState)

Equivalent to askForPermission, but allows you to prompt the user for more than one permission at once.

Notes:

  • The order in which you specify the permission prompts does not matter - it is controlled by the assistant to provide a consistent user experience.
  • The user will be able to either accept all permissions at once, or none. If you wish to allow them to selectively accept one or other, make several dialog turns asking for each permission independently with askForPermission.
  • Asking for DEVICE_COARSE_LOCATION and DEVICE_PRECISE_LOCATION at once is equivalent to just asking for DEVICE_PRECISE_LOCATION

Parameters

Name Description

context

string

Context why the permission is being asked; it's the TTS prompt prefix (action phrase) we ask the user.

permissions

Array of string

Array of permissions Assistant supports, each of which comes from Assistant.SupportedPermissions.

dialogState

Optional

Object

JSON object the action uses to hold dialog state that will be circulated back by Assistant.

Returns

A response is sent to Assistant to ask for the user's permission; for any invalid input, we return null.

Example

const assistant = new ApiAiAssistant({request: req, response: res});
const REQUEST_PERMISSION_ACTION = 'request_permission';
const GET_RIDE_ACTION = 'get_ride';

function requestPermission (assistant) {
  const permission = [
    assistant.SupportedPermissions.NAME,
    assistant.SupportedPermissions.DEVICE_PRECISE_LOCATION
  ];
  assistant.askForPermissions('To pick you up', permissions);
}

function sendRide (assistant) {
  if (assistant.isPermissionGranted()) {
    const displayName = assistant.getUserName().displayName;
    const address = assistant.getDeviceLocation().address;
    assistant.tell('I will tell your driver to pick up ' + displayName +
        ' at ' + address);
  } else {
    // Response shows that user did not grant permission
    assistant.tell('Sorry, I could not figure out where to pick you up.');
  }
}
const actionMap = new Map();
actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission);
actionMap.set(GET_RIDE_ACTION, sendRide);
assistant.handleRequest(actionMap);

getUserName

getUserName() returns UserName

If granted permission to user's name in previous intent, returns user's display name, family name, and given name. If name info is unavailable, returns null.

Returns

UserName Null if name permission is not granted.

Example

const assistant = new ApiAiAssistant({request: req, response: res});
const REQUEST_PERMISSION_ACTION = 'request_permission';
const SAY_NAME_ACTION = 'get_name';

function requestPermission (assistant) {
  const permission = assistant.SupportedPermissions.NAME;
  assistant.askForPermission('To know who you are', permission);
}

function sayName (assistant) {
  if (assistant.isPermissionGranted()) {
    assistant.tell('Your name is ' + assistant.getUserName().displayName));
  } else {
    // Response shows that user did not grant permission
    assistant.tell('Sorry, I could not get your name.');
  }
}
const actionMap = new Map();
actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission);
actionMap.set(SAY_NAME_ACTION, sayName);
assistant.handleRequest(actionMap);

handleRequest

handleRequest(handler)

Handles the incoming Assistant request using a handler or Map of handlers. Each handler can be a function callback or Promise.

Parameter

Name Description

handler

(function() or Map)

The handler (or Map of handlers) for the request.

Example

// Actions SDK
const assistant = new ActionsSdkAssistant({request: request, response: response});

function mainIntent (assistant) {
  const inputPrompt = assistant.buildInputPrompt(true, '<speak>Hi! <break time="1"/> ' +
        'I can read out an ordinal like ' +
        '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>',
        ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
  assistant.ask(inputPrompt);
}

function rawInput (assistant) {
  if (assistant.getRawInput() === 'bye') {
    assistant.tell('Goodbye!');
  } else {
    const inputPrompt = assistant.buildInputPrompt(true, '<speak>You said, <say-as interpret-as="ordinal">' +
      assistant.getRawInput() + '</say-as></speak>',
        ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
    assistant.ask(inputPrompt);
  }
}

const actionMap = new Map();
actionMap.set(assistant.StandardIntents.MAIN, mainIntent);
actionMap.set(assistant.StandardIntents.TEXT, rawInput);

assistant.handleRequest(actionMap);

// API.AI
const assistant = new ApiAiAssistant({request: req, response: res});
const NAME_ACTION = 'make_name';
const COLOR_ARGUMENT = 'color';
const NUMBER_ARGUMENT = 'number';

function makeName (assistant) {
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  const color = assistant.getArgument(COLOR_ARGUMENT);
  assistant.tell('Alright, your silly name is ' +
    color + ' ' + number +
    '! I hope you like it. See you next time.');
}

const actionMap = new Map();
actionMap.set(NAME_ACTION, makeName);
assistant.handleRequest(actionMap);

ask

ask(inputPrompt, noInputs) returns Object

Asks Assistant to collect the user's input.

NOTE: Due to a bug, if you specify the no-input prompts, the mic is closed after the 3rd prompt, so you should use the 3rd prompt for a bye message until the bug is fixed.

Parameters

Name Description

inputPrompt

string

The input prompt text.

noInputs

Optional

Array of string

Array of re-prompts when the user does not respond (max 3).

Returns

Object HTTP response.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (assistant) {
  assistant.ask('Welcome to action snippets! Say a number.',
    ['Say any number', 'Pick a number', 'What is the number?']);
}

function numberIntent (assistant) {
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  assistant.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);

getArgument

getArgument(argName) returns Object

Get the argument value by name from the current intent. If the argument is included in originalRequest, and is not a text argument, the entire argument object is returned.

Parameter

Name Description

argName

string

Name of the argument.

Returns

Object Argument value matching argName or null if no matching argument.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (assistant) {
  assistant.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (assistant) {
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  assistant.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);

getContext

getContext() returns Object

Returns the incoming context by name for this intent.

Returns

Object Context value matching name or null if no matching context.

Example

const action = new ApiAiAction({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (action) {
  action.setContext(CONTEXT_NUMBER);
  action.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (action) {
  let context = action.getContext(CONTEXT_NUMBER);
  // context === {
  //   name: 'number',
  //   lifespan: 0,
  //   parameters: {
  //     myNumber: '23',
  //     myNumber.original: '23'
  //   }
  // }
  const number = action.getArgument(NUMBER_ARGUMENT);
  action.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
action.handleRequest(actionMap);

getContextArgument

getContextArgument(contextName, argName) returns Object

Get the context argument value by name from the current intent. Context arguments include parameters collected in previous intents during the lifespan of the given context. If the context argument has an original value, usually representing the underlying entity value, that will be given as part of the return object.

Parameters

Name Description

contextName

string

Name of the context.

argName

string

Name of the argument.

Returns

Object Object containing value property and optional original property matching context argument. Null if no matching argument.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';
const OUT_CONTEXT = 'output_context';
const NUMBER_ARG = 'myNumberArg';

function welcomeIntent (assistant) {
  const parameters = {};
  parameters[NUMBER_ARG] = '42';
  assistant.setContext(OUT_CONTEXT, 1, parameters);
  assistant.ask('Welcome to action snippets! Ask me for your number.');
}

function numberIntent (assistant) {
  const number = assistant.getContextArgument(OUT_CONTEXT, NUMBER_ARG);
  // number === { value: 42 }
  assistant.tell('Your number is  ' + number.value);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);

getContexts

getContexts() returns Array of Context

Returns the incoming contexts for this intent.

Returns

Array of Context Empty if no active contexts.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (assistant) {
  assistant.setContext(CONTEXT_NUMBER);
  assistant.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (assistant) {
  let contexts = assistant.getContexts();
  // contexts === [{
  //   name: 'number',
  //   lifespan: 0,
  //   parameters: {
  //     myNumber: '23',
  //     myNumber.original: '23'
  //   }
  // }]
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  assistant.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);

getDeviceLocation

getDeviceLocation() returns DeviceLocation

If granted permission to device's location in previous intent, returns device's location (see askForPermissions). If device info is unavailable, returns null.

Returns

DeviceLocation Null if location permission is not granted.

Example

const assistant = new ApiAiAssistant({request: req, response: res});
assistant.askForPermission("To get you a ride",
  assistant.SupportedPermissions.DEVICE_PRECISE_LOCATION);
// ...
// In response handler for permissions fallback intent:
if (assistant.isPermissionGranted()) {
  sendCarTo(assistant.getDeviceLocation().coordinates);
}

getIntent

getIntent() returns string

Get the current intent. Alternatively, using a handler Map with handleRequest, the client library will automatically handle the incoming intents.

Returns

string Intent id or null if no value.

Example

const assistant = new ApiAiAssistant({request: request, response: response});

function responseHandler (assistant) {
  const intent = assistant.getIntent();
  switch (intent) {
    case WELCOME_INTENT:
      assistant.ask('Welcome to action snippets! Say a number.');
      break;

    case NUMBER_INTENT:
      const number = assistant.getArgument(NUMBER_ARGUMENT);
      assistant.tell('You said ' + number);
      break;
  }
}

assistant.handleRequest(responseHandler);

getRawInput

getRawInput() returns string

Gets the user's raw input query.

Returns

string User's raw query or null if no value.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
assistant.tell('You said ' + assistant.getRawInput());

getUser

getUser() returns User

Gets the User object. The user object contains information about the user, including a string identifier and personal information (requires requesting permissions, see askForPermissions).

Returns

User Null if no value.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const userId = assistant.getUser().userId;

isPermissionGranted

isPermissionGranted() returns boolean

Returns true if the request follows a previous request asking for permission from the user and the user granted the permission(s). Otherwise, false. Use with askForPermissions.

Returns

boolean True if permissions granted.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
assistant.askForPermissions("To get you a ride", [
  assistant.SupportedPermissions.NAME,
  assistant.SupportedPermissions.DEVICE_PRECISE_LOCATION
]);
// ...
// In response handler for permissions fallback intent:
if (assistant.isPermissionGranted()) {
 // Use the requested permission(s) to get the user a ride
}

isRequestFromApiAi

isRequestFromApiAi(key, value) returns boolean

Verifies whether the request comes from API.AI.

Parameters

Name Description

key

string

The header key specified by the developer in the API.AI Fulfillment settings of the action.

value

string

The private value specified by the developer inside the fulfillment header.

Returns

boolean True if the request comes from API.AI.

setContext

setContext(name, lifespan, parameters)

Set a new context for the current intent.

Parameters

Name Description

name

string

Name of the context. API.AI converts to lowercase.

lifespan

Optional

int

Context lifespan.

parameters

Optional

Object

Context JSON parameters.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const CONTEXT_NUMBER = 'number';
const NUMBER_ARGUMENT = 'myNumber';

function welcomeIntent (assistant) {
  assistant.setContext(CONTEXT_NUMBER);
  assistant.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (assistant) {
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  assistant.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);

tell

tell(textToSpeech)

Tells the Assistant to render the speech response and close the mic.

Parameter

Name Description

textToSpeech

string

Final spoken response. Spoken response can be SSML.

Returns

The response that is sent back to Assistant.

Example

const assistant = new ApiAiAssistant({request: request, response: response});
const WELCOME_INTENT = 'input.welcome';
const NUMBER_INTENT = 'input.number';

function welcomeIntent (assistant) {
  assistant.ask('Welcome to action snippets! Say a number.');
}

function numberIntent (assistant) {
  const number = assistant.getArgument(NUMBER_ARGUMENT);
  assistant.tell('You said ' + number);
}

const actionMap = new Map();
actionMap.set(WELCOME_INTENT, welcomeIntent);
actionMap.set(NUMBER_INTENT, numberIntent);
assistant.handleRequest(actionMap);