sberdevices / salutejs Goto Github PK
View Code? Open in Web Editor NEWSmartApp Framework для создания навыков семейства Виртуальных Ассистентов "Салют" на языке JavaScript
Home Page: https://sber.ru/salute
License: Other
SmartApp Framework для создания навыков семейства Виртуальных Ассистентов "Салют" на языке JavaScript
Home Page: https://sber.ru/salute
License: Other
Error: Cannot find module '.../node_modules/@salutejs/types/dist/index.d.js'. Please verify that the package.json has a valid "main" entry
Сейчас:
"main": "dist/index.d.js",
дб
"main": "dist/index.js",
@salutejs/scenario
@salutejs/cli
@salutejs/memory
Swagger https://help.just-ai.com/docs/api/caila_direct_api
import { createOrder, registerPayment } from '@salutejs/payments';
handle: ({ req, res }) => {
const { delivery, items, order } = req.variables;
const order = createOrder({ dilevery, items, order });
const { invoiceId } = async registerPayment(order);
res.askPayment(invoiceId);
}
res.createPayment(invoiceId);
{
"command": "POLICY_RUN_APP",
"nodes": {
"server_action": {
"app_info": {
"systemName": "payment_app"
},
"parameters": {
"invoice_id": "XXX",
"app_info": {
"projectId": "XXX"
}
}
}
}
}
askPayment
curl --location --request POST 'https://smartmarket.online.sberbank.ru/smartpay/v1/invoices' \
--header 'accept: application/json' \
--header 'Authorization: Bearer XXXX'\
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
"ptype": 0,
"invoice": {
"purchaser": {
"email": string,
"phone": number,
"contact": "email"
},
"delivery_info": {
"address": {
"country": "RU",
"city": string,
"address": string
},
"delivery_type": "courier",
"description": "позвонить перед отправкой"
},
"invoice_params": [
{
"key": "packageName",
"value": string
}
],
"order": {
"order_id": string,
"order_number": number,
"order_date": DateTime,
"service_id": string,
"amount": number,
"currency": "RUB",
"purpose": string,
"description": string,
"language": "ru-RU",
"expiration_date": DateTime,
"autocompletion_date": DateTime,
"tax_system": 0,
"order_bundle": [
{
"position_id": 1,
"name": string,
"item_params": [
{
"key": "packageName",
"value": string
}
],
"quantity": {
"value": 1,
"measure": "кг."
},
"item_amount": numbrt,
"currency": "RUB",
"item_code": string,
"item_price": number,
"discount_type": "percent",
"discount_value": number,
"interest_type": "agentPercent",
"interest_value": number,
"tax_type": number,
"tax_sum": number
}
]
}
}
}'
PAY_DIALOG_FINISHED
NB: Graph reference
Docs https://developer.sberdevices.ru/docs/ru/payment_tools/payment_steps
Base on #45
https://smartapp-code.sberdevices.ru use as a default option in SmartAppBrain recognizer
@salutejs/i18n
-> examples/audiotour
while simultaneous requests _charecter
could be changed;
and user will get character from another request
https://github.com/sberdevices/salutejs/blob/master/packages/i18n/src/index.ts#L130-L138
/import
и /export
)/train
)Webhook
в студии/inference
API CailaSeparated checks:
i18n but for assistants: sber, afina, joy.
Proposal
phrases.i18n/sber.ts
export const sber = {
initialMessage: 'Здравствуйте!',
'{count} карточка': {
one: '{count} карточка',
some: '{count} карточки',
many: '{count} карточек',
none: '{count} карточек'
},
}
phrases.i18n/sber.ts
export const joy = {
initialMessage: 'Привет!',
'{count} карточка': {
one: '{count} карточка',
some: '{count} карточки',
many: '{count} карточек',
none: '{count} карточек'
},
}
phrases.i18n/sber.ts
export * from './sber';
export * from './joy';
scenario.ts
import i18nFactory, { setAssistant } from '@salutejs/i18n';
import * as keyset from './phrases.i18n';
const i18n = i18nFactory(keyset);
// ....
app.post('/hook', async ({ body }, response) => {
const req = createSaluteRequest(body);
const res = createSaluteResponse(body);
setAssistant(req.character);
// ...
console.log(i18n('intitalMessage')); // !!!!
console.log(i18n('{count} карточка', { count: 1 })); // !!!!
await scenarioWalker({ req, res, session });
// ...
response.status(200).json(res.message);
});
Отравляю команду следующим образом:
const helpPayload = { path: '/about' };
const helpCommand = { type: 'smart_app_data', payload: helpPayload };
res.appendCommand(helpCommand);
На клиент в onData приходит:
{"type":"smart_app_data","smart_app_data":{"type":"smart_app_data","payload":{"path":"/about"}},"sdk_meta":{"mid":1618346995063}}
кажется должно быть
{"type":"smart_app_data","smart_app_data":{"path":"/about"},"sdk_meta":{"mid":1618346995063}}
jest?
res.appendBubble('say', { expand: 'force_expand' });
Ref https://developer.sberdevices.ru/docs/ru/developer_tools/amp/smartapp_interface_elements
"expand_policy": "auto_expand"|"force_expand"|"preserve_panel_state" //optional, default value auto_expand
//актуально для ассистента в девайсах
//auto_expand - Если текст помещается в США, то он отобразится в ней, без разворачивания США.
Если текст не помещается в США, то США разверентся.
//force_expand - США развернется принудительно.
//preserve_panel_state - Если США уже свернуто, текст отобразится в США, не зависимо от размера текста.
Если США развернуто - текст отобразится в развернутой шторке ассистента (РаША).
res.appendBubble('say', { pronounce: true });
Instead of
res.setPronounceText('say');
res.appendBubble('say');
import * as yup from "yup";
let schema = yup
.object()
.shape({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
email: yup.string().email(),
website: yup.string().url(),
createdOn: yup.date().default(function () {
return new Date();
})
})
.required();
export const validateBody = <S extends yup.ObjectSchema<any>>({
schema,
body
}: {
schema: S;
body: any;
}) => {
return schema.validate(body, {
abortEarly: false,
stripUnknown: true
}) as Promise<yup.InferType<S>>;
};
const fn = async (q: any) => {
const a = await validateBody({ schema, body: q });
}
Also arrays support
В userScenario
Next: {
match: text("продолжить"),
handle: ({res}) => res.setPronounceText("хорошо, продолжаю"),
},
Если отправить
"original_text": "Продолжить"
то не матчит
Если отправить
"original_text": "продолжить"
то матчит
Как сделать StringSimilarityRecognizer регистронезависимым?
В appendCommand передаем сразу объект smart_app_data, формата { type, payload }
for example, res.setEmotion('bespokoistvo');
Use const item req.state.select(note)
(Ex) instead of
const item = req.state?.item_selector.items.find((i) => i.title.toLowerCase() === note.toLowerCase());
subj
Храним локально хеш от интентов после пула
На пуше проверяем хеши и если не совпадают падаем с ошибкой и предложением сделать пулл
Если рекогнайзер распознал интент, но его нет в локальном словаре интентов, то шлем варнинг. Потому что кажется, что надо сделать brain pull
.
В системных сценариях https://github.com/sberdevices/salutejs/tree/master/packages/scenario
указано:
CLOSE_UP...
дб
CLOSE_APP...
В логах:
TypeError: Cannot read property 'intent' of undefined
at Object.match (/workspace/node_modules/@salutejs/scenario/dist/lib/matchers.js:27:153)
at Object.resolve (/workspace/node_modules/@salutejs/scenario/dist/lib/createUserScenario.js:42:31)
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:9:36 - error TS2536: Type '"item_selector"' cannot be used to index type 'R["state"]'.
9 selectItem: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:9:36 - error TS2536: Type '"items"' cannot be used to index type 'R["state"]["item_selector"]'.
9 selectItem: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:9:36 - error TS2536: Type 'number' cannot be used to index type 'R["state"]["item_selector"]["items"]'.
9 selectItem: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:18:37 - error TS2536: Type '"item_selector"' cannot be used to index type 'R["state"]'.
18 selectItems: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:18:37 - error TS2536: Type '"items"' cannot be used to index type 'R["state"]["item_selector"]'.
18 selectItems: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:18:37 - error TS2536: Type 'number' cannot be used to index type 'R["state"]["item_selector"]["items"]'.
18 selectItems: (expected: Partial<R['state']['item_selector']['items'][number]>) => (req: R) => {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@salutejs/scenario/dist/lib/matchers.d.ts:27:24 - error TS2536: Type '"type"' cannot be used to index type 'R["serverAction"]'.
27 action: (expected: R['serverAction']['type']) => (req: R) => boolean;
~~~~~~~~~~~~~~~~~~~~~~~~~
import { intents } from './intents';
import { createScenario } from '@salutejs/scenario';
const globalScenario = createScenario(intents);
globalScenario.handle(req => req.intent === 'run_app'), ({ req, res, session }) => {/*...*/});
const mainPageScenario = createScenario(intents);
mainPageScenario.handle(req => req.state.screen === 'tourPage'), ({ req, res, session }) => {/*...*/});
mainPageScenario.handle(req => req.state.screen === 'tourPage' && req.intent === 'yes'), ({ req, res, session }) => {/*...*/});
mainPageScenario.handle(req => req.state.screen === 'tourPage' && req.intent === 'no'), ({ req, res, session }) => {/*...*/});
globalScenario.handle(req => req.intent === 'mainPage'), ({ req, res, session }) => {/*...*/});
globalScenario.handle(req => req.intent === 'mainPage'), mainPageScenario);
With object predicates
globalScenario.handle(req => req.intent === 'run_app'), ({ req, res, session }) => {/*...*/});
const mainPageScenario = createScenario(intents);
mainPageScenario.handle({ req: { state: { screen: 'tourPage' } } }, ({ req, res, session }) => {/*...*/});
mainPageScenario.handle({ req: { intent: 'yes', state: { screen: 'tourPage' } } }, ({ req, res, session }) => {/*...*/});
mainPageScenario.handle({ req: { intent: 'no', state: { screen: 'tourPage' } } }, ({ req, res, session }) => {/*...*/});
globalScenario.handle({ req: { intent: 'mainPage' } }, ({ req, res, session }) => {/*...*/});
globalScenario.handle({ req: { intent: 'mainPage' } }, mainPageScenario);
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.