### Start and Stop Session with JSAPI
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/jsapi/start-session
This snippet demonstrates how to start and stop a session using the `$jsapi.startSession()` and `$jsapi.stopSession()` methods. `$jsapi.startSession()` clears existing session data and initializes a new one, including the current user query and assistant response. `$jsapi.stopSession()` terminates the current session.
```script
theme: /
state: Приветствие
q!: * *start
q!: (привет|hello) *
script:
$jsapi.startSession();
a: Здравствуйте! Чем я могу Вам помочь?
state: Прощание
q!: (пока|до свидания|bye) *
script:
$jsapi.stopSession();
random:
a: Всего доброго.
a: До свидания!
```
--------------------------------
### NLP matchExamples Function
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/nlp/match-examples
The matchExamples function performs text matching against a given set of examples. It returns the closest example, the count of matched words, and a similarity weight.
```APIDOC
## NLP matchExamples Function
### Description
Performs text matching against a given set of examples. It returns the closest example, the count of words in the user's phrase that match the examples, and a similarity weight.
### Method
N/A (This is a function description, not an HTTP endpoint)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```
state: Common
q!: ...
script:
var res = $nlp.matchExamples("раз раз", ["раз", "два", "три"]);
log(res);
```
### Response
#### Success Response (200)
- **example** (string) - The closest matching example from the provided list.
- **weight** (float) - The similarity weight of the match (0.0 to 1.0).
- **aligned** (integer) - The number of words in the user's input that were found in the examples.
#### Response Example
```json
{
"example": "раз",
"weight": 0.5,
"aligned": 1
}
```
```
--------------------------------
### $fetch.get(url, settings)
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/fetch/get
Fetches data from an external server. This is equivalent to calling $fetch.query(url, settings) when settings.method is 'GET'.
```APIDOC
## GET $fetch.get(url, settings)
### Description
Retrieves data from an external server. This function is equivalent to calling `$fetch.query(url, settings)` if `settings.method` is set to 'GET'.
### Method
GET
### Endpoint
`$fetch.get(url, settings)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters (within settings object)
* **url** (string) - Required - The server address as a string. May contain parameters that will be populated from the `query` field passed in the `settings` parameter.
* **settings** (JSON object) - Optional - A valid JSON object with request parameters.
### Request Example
```javascript
// Example using the function within a script context
var url = "https://api.apixu.com/v1/current.json?key=" + $injector.wheatherApiKey + "&q=" + q;
var response = $fetch.get(url);
```
### Response
#### Success Response (200)
- **isOk** (boolean) - Indicates if the request was successful.
- **data** (object) - Contains the response data from the server.
#### Response Example
```json
{
"isOk": true,
"data": {
"current": {
"temp_c": 25
}
}
}
```
### Error Handling
- If the request fails, `response.isOk` will be false. Further error details may be available in the `response` object.
```
--------------------------------
### Go Tag Absolute Path Examples (DSL)
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/reaction-tags
Demonstrates how to construct absolute paths for the 'go' tag, starting from the root or a named theme, to navigate through nested states.
```dsl
theme: /
state: Один
a: Это стейт один
state: Два
a: Это стейт два
state: Три
a: Это стейт три
go: /Один/Два/Три
theme: /Главный
state: Один
a: Это стейт один
state: Два
a: Это стейт два
state: Три
a: Это стейт три
go: /Главный/Один/Два/Три
```
--------------------------------
### startSession() Method
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/jsapi/start-session
The $jsapi.startSession() method is used to initiate a new session. Upon invocation, all data within the current $session is cleared. The user's current question and the assistant's response are immediately included in the newly started session.
```APIDOC
## $jsapi.startSession()
### Description
Initiates a new session and clears all data in the current `$session`. The current user question and assistant response are immediately added to the new session.
### Method
JavaScript Method
### Endpoint
N/A (Client-side JavaScript method)
### Parameters
None
### Request Example
```javascript
$jsapi.startSession();
```
### Response
No direct response object. Session data is cleared and updated internally.
```
--------------------------------
### Go Tag Path Examples (DSL)
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/reaction-tags
Provides examples of various ways to specify paths for the 'go' tag, including absolute, relative paths, and paths using parent directory navigation.
```dsl
go: /path
go: /путь
go: ./anotherPath
go: ../first state/second state
```
--------------------------------
### Match Examples with Text using $nlp.matchExamples
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/nlp/match-examples
This JavaScript code snippet demonstrates how to use the $nlp.matchExamples function to find the closest match for a user's query within a list of predefined examples. It returns the best matching example, the number of aligned words, and the weight of the match. This function is useful for natural language understanding tasks.
```javascript
state: Common
q!: ...
script:
var res = $nlp.matchExamples("раз раз", ["раз", "два", "три"]);
log(res);
```
--------------------------------
### Fetch Data with $fetch.get(url, settings)
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/fetch/get
Retrieves data from an external server using an HTTP GET request. It's equivalent to $fetch.query with method 'GET'. Accepts URL and settings object as parameters.
```javascript
patterns:
$city = (москв*:moscow/питер*:saint_petersburg) || converter = function($pt){return $pt.value.replace("_","%20");}
state: Weather
q!: Сколько градусов в $city
script:
var q = $parseTree.value;
var url = "https://api.apixu.com/v1/current.json?key=" + $injector.wheatherApiKey + "&q=" + q;
var response = $fetch.get(url);
if (response.isOk) {
$temp.degree = response.data.current.temp_c;
}
a: Сейчас {{ $temp.degree }}°C.
```
--------------------------------
### Set Base URL and Make HTTP GET Request
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/config
Configures the base URL for HTTP requests and then performs a GET request to a specific path. This is useful for setting up API endpoints. The configuration includes protocol, host, and port.
```javascript
init:
$http.config({
url: {
protocol: 'http',
host: 'example.com',
port: '80'
}
});
state:
q!: *
script:
$http.get('/path');
```
--------------------------------
### POST /api/caila/p/{accessToken}/nlu/markup-internal
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/initial-markup-internal
Creates markup for patterns, examples, and dictionaries using the provided access token and an array of texts.
```APIDOC
## POST /api/caila/p/{accessToken}/nlu/markup-internal
### Description
Creates markup for patterns, examples, and dictionaries.
### Method
POST
### Endpoint
https://smartapp-code.sberdevices.ru/cailapub//api/caila/p/{accessToken}/nlu/markup-internal
### Parameters
#### Path Parameters
- **accessToken** (string) - Required - The access token, which can be found in the project settings.
#### Request Body
- **Required** - application/json
- An array of texts for processing.
- Array of strings
### Request Example
```json
[
"string"
]
```
### Response
#### Success Response (200)
- Returns the result of the markup.
- application/json
- **Schema**
- Array of objects:
- **source** (string) - Required - The original source text.
- **correctedText** (string) - Required - The corrected text after markup.
- **words** (Array of WordMarkupData) - Required - An array of word markup data.
- **annotations** (object) - Optional - Annotation details for the word.
- **lemma** (string) - The lemma of the word.
- **pos** (string) - The part of speech.
- **startPos** (integer) - The starting position of the word in the text.
- **endPos** (integer) - The ending position of the word in the text.
- **pattern** (boolean) - Indicates if the word is part of a pattern.
- **punctuation** (boolean) - Indicates if the word is punctuation.
- **source** (string) - The source of the annotation.
- **word** (string) - The word itself.
### Response Example
```json
[
{
"source": "string",
"correctedText": "string",
"words": [
{
"annotations": {
"lemma": "string",
"pos": "string"
},
"startPos": 0,
"endPos": 0,
"pattern": true,
"punctuation": true,
"source": "string",
"word": "string"
}
]
}
]
```
```
--------------------------------
### SmartApp API Usage Examples
Source: https://developers.sber.ru/docs/ru/va/code/js-api/variables/request
Examples demonstrating how to use the SmartApp API request object in different scenarios, such as retrieving user IDs, saving user preferences, and processing intents.
```APIDOC
## SmartApp API Usage Examples
### Description
This section provides practical examples of how to utilize the SmartApp API's request object within different conversational flows.
### Examples
#### 1. Retrieving User ID
This example shows how to get the `channelUserId` and greet the user.
```
theme: /
state: Start
q!: $regex
a: Начнем.
state: Приветствие
intent!: /привет
a: Ваш идентификатор {{ $request.channelUserId }}
```
#### 2. Saving User's City
This example demonstrates how to save the user's city from their query and clear their cart.
```
state: RememberCity
script:
$client.city = $request.query;
$session.cart = [];
go!: /ChoosePizza
```
#### 3. Getting Assistant Intent and Voice Information
This example shows how to access raw request payload to get the intent and original intent, and how to save the character name.
```
state: Request
q!: интент из запроса
a: {{ $request.rawRequest.payload.intent }}, {{ $request.rawRequest.payload.original_intent }}
state: getCharacter
script:
$session.character = $request.rawRequest.payload.character.name
```
```
--------------------------------
### Go! Tag with Absolute Path Example
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/reaction-tags
Demonstrates constructing an absolute path to a nested state using the 'go!:' tag. The path starts from the root or the 'theme' name and follows the state hierarchy, separated by '/'.
```va-code
theme: /
state: Один
a: Это стейт один
state: Два
a: Это стейт два
state: Три
a: Это стейт три
go!: /Один/Два/Три
```
```va-code
theme: /Главный
state: Один
a: Это стейт один
state: Два
a: Это стейт два
state: Три
a: Это стейт три
go: /Главный/Один/Два/Три
```
--------------------------------
### Console Output for Sequential Requests
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/fetch/post
This example demonstrates the expected console output when using sequential $fetch.post requests with `then()` and `catch()` callbacks. It shows the order of execution for both successful requests and errors, highlighting when the main script completes versus when the callbacks are executed.
```javascript
//При успешном запросе
Выполнение всего скрипта завершено
Выполнение функции successHandlerParseResponseJson() завершено
//При ошибке
Выполнение всего скрипта завершено
Выполнение функции errorHandler() завершено
```
--------------------------------
### Result of $nlp.matchExamples Function
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/nlp/match-examples
This JSON object represents the expected output from the $nlp.matchExamples function. It includes the matched example string, a numerical weight indicating the confidence of the match, and the count of aligned words between the user's input and the matched example. This structure helps in understanding the results of the text matching process.
```json
{
"example": "раз",
"weight": 0.5,
"aligned": 1
}
```
--------------------------------
### Response Body Example for initialMarkupInternal API (200 OK)
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/initial-markup-internal
This example illustrates the structure of a successful response (HTTP 200 OK) from the initialMarkupInternal API. It returns an array of objects, each containing the original source text, the corrected text, and detailed word-level markup data, including annotations like lemma and part-of-speech.
```JSON
[
{
"source": "string",
"correctedText": "string",
"words": [
{
"annotations": {
"lemma": "string",
"pos": "string"
},
"startPos": 0,
"endPos": 0,
"pattern": true,
"punctuation": true,
"source": "string",
"word": "string"
}
]
}
]
```
--------------------------------
### Request Body Example for initialMarkupInternal API
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/initial-markup-internal
This example demonstrates the expected format for the request body when calling the initialMarkupInternal API. It should be a JSON array containing strings that represent the texts to be processed for markup generation.
```JSON
[
"string"
]
```
--------------------------------
### JavaScript object and logging examples
Source: https://developers.sber.ru/docs/ru/va/code/js-api/functions/to-pretty-string
This snippet shows a sample customer object and demonstrates how different logging methods handle object serialization. It contrasts the default object string representation with the output of toPrettyString, highlighting the improved readability of formatted JSON.
```javascript
var customer = {
firstName: 'John',
lastName: 'Doe',
id: 5566,
cart: [
{ itemName: 'Удочка', price: 432 },
{ itemName: 'Леска', price: 34 },
],
};
console.log(customer);
console.log("Customer info:\n" + customer);
console.log(toPrettyString(customer));
console.log("Customer info:\n" + toPrettyString(customer));
```
--------------------------------
### Simple HTTP GET Request
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/query
Demonstrates a basic HTTP GET request using `$http.query`. It fetches data from a specified URL and extracts a text field from the response. No external dependencies are explicitly mentioned beyond the `$http` service itself.
```Custom Script
state:
q!: test 1
script:
$reactions.answer($http.query('http://localhost:9001/method1').data.text);
```
--------------------------------
### cURL Example for Training NLU Model
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/train-nlu
Provides a cURL command to execute the NLU model training request. This example demonstrates how to make a POST request to the specified endpoint, including the necessary access token. The command is designed for direct execution in a terminal environment.
```bash
curl -L -g -X POST 'https://smartapp-code.sberdevices.ru/cailapub/api/caila/p/{accessToken}/nlu/train'
```
--------------------------------
### Пример объявления темы со значением в SmartApp DSL
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/declarative-tags
Показывает объявление 'theme:' со значением '/Start', где значение не влияет на код, и вложенным стейтом 'start'.
```yaml
theme: /Start
state: start
q!: *
a: Начинаем!
```
--------------------------------
### Get User ID using SmartApp API
Source: https://developers.sber.ru/docs/ru/va/code/js-api/variables/request
This example demonstrates how to retrieve the user's unique identifier (`channelUserId`) from the request object within a SmartApp scenario. It uses a regular expression to trigger the start state and then displays the user ID in the greeting.
```SmartApp
theme: /
state: Start
q!: $regex
a: Начнем.
state: Приветствие
intent!: /привет
a: Ваш идентификатор {{$request.channelUserId}}
```
--------------------------------
### GET /api/resource
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/get
The `get` method is used to fetch resources from a specified URL. It is a wrapper around the `$http.query` method for GET requests and can handle both absolute and relative URLs. A limit of 15 calls per request is enforced.
```APIDOC
## GET /api/resource
### Description
Fetches resources from a specified URL. This method is equivalent to `$http.query(url, settings)` when `settings.method` is 'GET'. It can handle absolute or relative URLs, and a maximum of 15 calls are allowed in a single request.
### Method
GET
### Endpoint
/api/resource
### Parameters
#### Path Parameters
None
#### Query Parameters
- **url** (string) - Required - The URL to fetch data from.
- **settings** (object) - Optional - Configuration settings for the request, including `method`, `headers`, etc.
#### Request Body
Not applicable for GET requests.
### Request Example
```javascript
// Example using an absolute URL
$http.get('https://api.example.com/data');
// Example using a relative URL with configuration
$http.config({ baseUrl: 'https://api.example.com'});
$http.get('/data');
```
### Response
#### Success Response (200)
- **data** (object) - The data returned from the server.
- **isOk** (boolean) - Indicates if the request was successful.
#### Error Response
- **error** (string) - A message describing the error.
- **status** (number) - The status code of the error.
- **isOk** (boolean) - `false` indicating the request failed.
#### Response Example (Error)
```json
{
"error": "Callback limit reached",
"status": -1,
"isOk": false
}
```
```
--------------------------------
### JavaScript: Making GET Requests with $http.get
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/get
The $http.get function is used to make HTTP GET requests. It's equivalent to calling $http.query with the method set to 'GET'. The function can handle absolute or relative URLs and has a limit of 15 calls per request. An error object is returned if the callback limit is reached.
```javascript
function get(url, settings)
// Equivalent to $http.query(url, settings) if settings.method == 'GET'.
// Can contain a third-party address.
// Maximum 15 calls per request. Returns an error if exceeded:
// {
// "error": "Callback limit reached",
// "status": -1,
// "isOk": false
// }
// Address can be absolute or relative. For relative addresses, set the base URL using $http.config(settings).
```
```javascript
var q = $parseTree.value;
var url = "https://api.apixu.com/v1/current.json?key=" + $injector.wheatherApiKey + "&q=" + q;
var response = $http.get(url);
if (response.isOk) {
$temp.degree = response.data.current.temp_c;
}
```
--------------------------------
### Get Speller Dictionary API Response Example (text/plain)
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/get-speller-dictionary
This snippet shows an example of a successful response (HTTP 200 OK) from the getSpellerDictionary API when requesting the speller dictionary. The response content is a string representing the dictionary.
```text
"string"
```
--------------------------------
### Go Tag Relative Path Examples (DSL)
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/reaction-tags
Illustrates the use of relative paths with the 'go' tag, showing how to navigate to child states using './' and to parent states using '../'.
```dsl
state: One
a: Это верхнеуровневый стейт
state: Two
a: Это текущий стейт
go: ./Three
state: Three
a: Это целевой стейт
state: One
a: Это самый верхнеуровневый стейт
state: Two
a: Это стейт на уровень выше
state: Three
a: Это текущий стейт
go: ../Four
state: Four
a: Это целевой стейт
```
--------------------------------
### Пример объявления темы без значения в SmartApp DSL
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/declarative-tags
Демонстрирует объявление 'theme:' без указания конкретного значения, с вложенным стейтом 'start'.
```yaml
theme: /
state: start
q!: *
a: Начинаем!
```
--------------------------------
### Start NLU Model Training (POST)
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/train-nlu
Initiates the training of an NLU model. This API requires an access token for authentication. It supports incremental training to optimize resource usage by only retraining modified components of the model. The response indicates whether the training has been successfully initiated.
```HTTP
POST https://smartapp-code.sberdevices.ru/cailapub//api/caila/p/{accessToken}/nlu/train
```
--------------------------------
### Пример файла сценария смартапа на SmartApp DSL
Source: https://developers.sber.ru/docs/ru/va/code/project/sc
Демонстрирует базовую структуру файла сценария смартапа, включая определение паттернов, тем, состояний, вопросов (q!) и ответов (a). Пример включает обработку команды '/start' и диалоговую логику.
```SmartApp DSL
patterns:
$hello = (start)
theme: /
state: Hello
q!: $hello *
a: Здравствуйте!
go!: /Can I Help You?
state: Can I Help You?
a: Я могу вам помочь?
state: Yes
q!: * { (*можете|*можешь) * помочь } *
q: * [думаю] (да|*можете|*можешь|надеюсь|хотелось бы) *
a: Что Вас интересует?
state: No
q: * [да] [уже] (ничем|не надо|не нужно) [спасибо] *
a: Хорошо. Буду рад помочь вам в следующий раз!
```
--------------------------------
### Code: Initialize Pre/Post-processes with bind()
Source: https://developers.sber.ru/docs/ru/va/code/js-api/pre-post-process
Demonstrates how to bind pre- and post-process functions using the `bind()` function within the `init:` tag. `preProcess` can initialize data or handle state transitions, while `postProcess` can add data to responses or log statistics. The example shows calculating circle circumference and handling transitions based on its length.
```Code
patterns:
$num = $regexp<\d+>
theme: /myApp
init:
bind("preProcess", function($context) {
// Запускается перед выполнением каждого блока
if ($context.parseTree._num) {
$context.session.L = 2 * 3.14 * $context.parseTree._num;
}
}, "/myApp");
bind("postProcess", function($context) {
// Запускается после выполнением каждого блока
if ($context.session.L > 50) {
$reactions.transition('/myApp/bigCircle');
$context.session.L = 0;
}
}, "/myApp");
state: start
q!: *start
a: Задайте радиус круга, а я посчитаю длину его окружности!
state: radius
q!: $num
script:
$session.radius = $parseTree._num;
$reactions.transition('/myApp/diameter');
state: diameter
a: Длина окружности: {{ $session.L }}
state: bigCircle
a: Длина окружности больше 50
```
--------------------------------
### NLU Model Training Status Response Example
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/get-nlu-status
This JSON object represents a successful response (200 OK) when querying the NLU model training status. It includes the training status, last error message, and timestamps for various training-related events.
```json
{
"trainingStatus": "NONE",
"lastError": "string",
"lastChangeInIntents": "2024-07-29T15:51:28.071Z",
"lastChangeInEntities": "2024-07-29T15:51:28.071Z",
"lastModelTrainStart": "2024-07-29T15:51:28.071Z",
"lastModelTrainTime": "2024-07-29T15:51:28.071Z",
"cachedModelTrainStart": "2024-07-29T15:51:28.071Z",
"cachedModelTrainTime": "2024-07-29T15:51:28.071Z"
}
```
--------------------------------
### Example of Sending Email using $mail.send
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/mail/send
A practical example demonstrating how to invoke the `$mail.send` function with specific parameters for sending an email. This snippet shows the instantiation of the `mailRequest` object with sample data for testing purposes.
```javascript
state:
q!: *
script:
$mail.send({
from: "asd@asd.com",
hiddenCopy: [],
to: ["recipient@cscs.com"],
subject: "Subject",
content: "Message",
smtpHost: "localhost",
smtpPort: "25000",
user: "user",
password: "password"
});
```
--------------------------------
### Initialize and Set $client Property
Source: https://developers.sber.ru/docs/ru/va/code/js-api/variables/client
This code snippet demonstrates how to initialize a session object and set a boolean property 'welcome' to true on the $client object. This is useful for tracking initial user interactions or states.
```script
state: Welcome
script:
$context.session = {}
var $session = $context.session;
$client.welcome = true;
```
--------------------------------
### Buttons Tag Syntax and Examples (DSL)
Source: https://developers.sber.ru/docs/ru/va/code/sa-dsl/tags/reaction-tags
Demonstrates the basic syntax for the 'buttons' tag, including defining single and multiple buttons, and how to specify button text.
```dsl
state: NormalButtons
q!: * start
a: Кнопки могут быть заданы текстом:
buttons:
"Это кнопка"
state: NormalButtons
q!: * start
a: Несколько кнопок:
buttons:
"Это кнопка"
buttons:
"Это вторая кнопка"
buttons:
"Это третья кнопка"
"Это четвертая кнопка"
"Это пятая кнопка"
```
--------------------------------
### GET /api/caila/p/{accessToken}/nlu/status
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/get-nlu-status
Retrieves the NLU model training status. It provides details about the training process, including potential errors and timestamps of training-related events.
```APIDOC
## GET /api/caila/p/{accessToken}/nlu/status
### Description
Retrieves the NLU model training status. It provides details about the training process, including potential errors and timestamps of training-related events.
### Method
GET
### Endpoint
https://smartapp-code.sberdevices.ru/cailapub/api/caila/p/{accessToken}/nlu/status
### Parameters
#### Path Parameters
- **accessToken** (string) - Required - Access token, which can be found in the project settings.
### Request Example
```
curl -L -g 'https://smartapp-code.sberdevices.ru/cailapub/api/caila/p/{accessToken}/nlu/status' \
-H 'Accept: application/json'
```
### Response
#### Success Response (200)
- **trainingStatus** (string) - Training status. Possible values: [`NONE`, `TRAINING`, `READY`, `FAILED`].
- **lastError** (string) - Description of the last error, if any.
- **lastChangeInIntents** (date-time) - Timestamp of the last change in intents.
- **lastChangeInEntities** (date-time) - Timestamp of the last change in entities.
- **lastModelTrainStart** (date-time) - Timestamp when the last model training started.
- **lastModelTrainTime** (date-time) - Duration of the last model training.
- **cachedModelTrainStart** (date-time) - Timestamp when the cached model training started.
- **cachedModelTrainTime** (date-time) - Duration of the cached model training.
#### Response Example
```json
{
"trainingStatus": "NONE",
"lastError": "string",
"lastChangeInIntents": "2024-07-29T15:51:28.071Z",
"lastChangeInEntities": "2024-07-29T15:51:28.071Z",
"lastModelTrainStart": "2024-07-29T15:51:28.071Z",
"lastModelTrainTime": "2024-07-29T15:51:28.071Z",
"cachedModelTrainStart": "2024-07-29T15:51:28.071Z",
"cachedModelTrainTime": "2024-07-29T15:51:28.071Z"
}
```
```
--------------------------------
### Initializing Context Objects in a Welcome State
Source: https://developers.sber.ru/docs/ru/va/code/js-api/variables/context
This example illustrates initializing various context-related objects within a 'Welcome' state's script. It shows how to create empty objects for session, client, temporary data, and response, all accessed via the $context object. This is typically done at the beginning of a script to ensure necessary data structures are available.
```javascript
state: Welcome
q!: * *start
a: Привет! Я электронный помощник.
script:
$context.session = {}
$context.client = {}
$context.temp = {}
$context.response = {}
go!: /ChooseCity
```
--------------------------------
### JSON Response Example for Classification Result
Source: https://developers.sber.ru/docs/ru/va/code/nlp/api/inference-multiple
An example JSON response from the API after classifying a phrase. It returns an array of results, each containing the original phrase, potential intent variants with confidence scores, and spelling correction suggestions.
```json
[
{
"phrase": {
"text": "string",
"entities": [
{
"entity": "string",
"slot": "string",
"startPos": 0,
"endPos": 0,
"text": "string",
"default": true,
"system": true,
"entityId": 0
}
],
"stagedPhraseIdx": 0
},
"variants": [
{
"intent": {
"id": 0,
"path": "string",
"answer": "string",
"customData": "string",
"business": true,
"slots": [
{
"name": "string",
"entity": "string",
"required": true,
"prompts": [
"string"
],
"array": false,
"client": false
}
]
},
"confidence": 0,
"slots": [
{
"name": "string",
"array": false,
"client": false
}
],
"debug": {}
}
],
"spelledWords": [
{
"source": "string",
"startPos": 0,
"endPos": 0,
"variants": [
"string"
],
"type": "mlps"
}
]
}
]
```
--------------------------------
### JavaScript Transition Function Usage
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/reactions/transition
Demonstrates how to use the `transition` function in JavaScript to navigate to different states. It shows examples using both a direct path string and an object with a path and a deferred flag.
```javascript
script: $reactions.transition('/Welcome');
$reactions.transition({ value: '/Welcome', deferred: true });
```
--------------------------------
### Work with Sounds in Code
Source: https://developers.sber.ru/docs/ru/va/code/templates/smartapp-templates
Demonstrates using pre-loaded sounds and the difference between text-to-speech with and without SSML markup. Sounds are sourced from the built-in library, with smart app sounds defined in `/src/dicts/libSound.yaml`. Sounds do not play in the test widget.
```yaml
# Example structure for /src/dicts/libSound.yaml
sounds:
welcome_sound: "sounds/welcome.mp3"
notification_alert: "sounds/alert.wav"
positive_feedback: "builtin:sounds/positive.ogg"
# Example of SSML usage within a response (conceptual)
# The actual implementation would involve a function to play these sounds or use SSML.
smartAppResponseWithSSML: {
type: "text",
data: "Hello! Welcome to our app."
}
smartAppResponseWithoutSSML: {
type: "text",
data: "Hello! Welcome to our app."
}
```
--------------------------------
### Use Variables in Chatbot Responses
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/reactions/answer
This example demonstrates how to insert variables into chatbot responses. Variables and JavaScript expressions can be embedded within double curly braces `{{ }}` in the response text. The `$client.name` variable is used here as an example.
```javascript
script: $reactions.answer('Привет {{ $client.name }}!');
```
--------------------------------
### mockData с JSON ответом
Source: https://developers.sber.ru/docs/ru/va/code/testing/test-tags
Настройка mockData для GET-запроса к 'http://example.com'. Включает параметры запроса 'path', 'p1', 'p2' и возвращает JSON-ответ с статус-кодом 200.
```xml
http://example.com/${path}/?param1=${p1}¶m2=${p2}
путьvalue 1value 2
{"json": "response"}
```
--------------------------------
### Cache HTTP GET Request - Script
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/cache
This script shows how to make a cached HTTP GET request to an external API. The cachingRequired flag is set to true, and the result is stored in a temporary variable.
```script
$temp.m = $http.get('https://www.random.org/strings/?num=1&len=10&digits=on&unique=on&format=plain&rnd=new', {
cachingRequired: true,
});
```
--------------------------------
### Example Phrase with System Entity
Source: https://developers.sber.ru/docs/ru/va/code/nlp/project/advanced-classifer-settings
This example demonstrates how to include a system entity within a training phrase for an intent. The `@duckling.number` represents a placeholder for a numerical entity that the system will try to recognize.
```nlu
Мне нужно @duckling.number яблок
```
--------------------------------
### list_card Component Example
Source: https://developers.sber.ru/docs/ru/va/code/js-api/variables/response
An example structure for a 'list_card' component, which can be passed within the 'items.card' field of an assistant's response. It includes paddings and various cell types like text and left-right views.
```json
{
"type": "list_card",
"paddings": {
"top": "4x",
"bottom": "4x"
},
"cells": [
{
"type": "text_cell_view",
"paddings": {
"top": "6x",
"left": "8x",
"right": "8x"
},
"content": {
"text": "Название списка",
"typeface": "title1",
"text_color": "default"
}
},
{
"type": "text_cell_view",
"paddings": {
"top": "4x",
"left": "8x",
"right": "8x",
"bottom": "6x"
},
"content": {
"text": "Подзаголовок",
"typeface": "footnote1",
"text_color": "secondary"
}
},
{
"type": "left_right_cell_view",
"paddings": {
"top": "8x",
"left": "8x",
"right": "8x",
"bottom": "8x"
},
"divider": {
"style": "default",
"size": "d5"
},
"left": {
"type": "simple_left_view",
"icon_vertical_gravity": "center",
"texts": {
"title": {
"text": "Первый пункт",
"typeface": "body1",
"text_color": "default"
},
"subtitle": {
"text": "Подзаголовок",
"typeface": "footnote1",
"text_color": "secondary",
"margins": {
"top": "1x"
}
}
}
},
"right": {
"type": "detail_right_view",
"margins": {
"left": "2x"
},
"detail": {
"text": "Кнопка пункта",
"typeface": "body1",
"text_color": "brand"
},
"vertical_gravity": "top"
},
"actions": [
{
"text": "Первый пункт",
"type": "text"
}
]
},
{
"type": "left_right_cell_view",
"paddings": {
"top": "8x",
"left": "8x",
"right": "8x",
"bottom": "8x"
},
"divider": {
"style": "default",
"size": "d5"
},
"left": {
"type": "simple_left_view",
"icon_vertical_gravity": "center",
"texts": {
"title": {
"text": "Второй пункт",
"typeface": "body1",
"text_color": "default"
},
"subtitle": {
"text": "Подзаголовок",
"typeface": "footnote1",
```
--------------------------------
### Default Configuration and Weather API Call
Source: https://developers.sber.ru/docs/ru/va/code/js-api/services/http/config
Sets a default HTTP configuration, including cache time-to-live, and then performs a script to fetch weather data from an external API. It outputs the temperature in Saint Petersburg. Dependencies include the $http service and a valid API key.
```javascript
init:
$http.config({
cacheTimeToLiveInSeconds: 1 * 60 * 30
});
state: Weather
q!: Сколько градусов в питере
script:
var url = "https://api.apixu.com/v1/current.json?key=d43686318b1647dabb8181701181811&q=saint%20petersburg”;
var settings = {
method: "GET",
cachingRequired: true
};
var response = $http.query(url, settings);
if (response.isOk) {
$temp.degree = response.data.current.temp_c;
}
a: Сейчас в Питере {{ $temp.degree }}°C.
```