Lex Guida per gli sviluppatori Amazon Lex Guida per gli sviluppatori

Amazon Lex: Guida per gli sviluppatori Copyright © , Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon Lex Guida per gli sviluppatori

Table of Contents

Che cos'è Amazon Lex? ...... 1 Primo utilizzo di Amazon Lex? ...... 2 Come funziona ...... 3 Lingue supportate ...... 5 Lingue e lingue supportate ...... 5 Lingue e impostazioni locali supportate dalle caratteristicheAmazon Lex ...... 5 Modello di programmazione ...... 5 Operazioni API di costruzione dei modelli ...... 6 Operazioni API di runtime ...... 7 Funzioni Lambda come hook di codici ...... 7 Gestione dei messaggi ...... 10 Tipi di messaggi ...... 10 Contesti per la configurazione di messaggi ...... 11 Formati di messaggio supportati ...... 15 Gruppi di messaggi ...... 15 Schede di risposta ...... 16 Gestione del contesto di una conversazione ...... 20 Impostazione del contesto dell'intento ...... 20 Utilizzo dei valori di slot predefiniti ...... 22 Impostazione degli attributi di sessione ...... 23 Impostazione degli attributi di richiesta ...... 24 Impostazione del timeout di sessione ...... 26 Condivisione di informazioni tra intenti diversi ...... 27 Impostazione di attributi complessi ...... 27 Using Confidence Scores ...... 28 Session Management ...... 30 Log delle conversazioni ...... 30 Policy IAM per i log delle conversazioni ...... 31 Configurazione dei log delle conversazioni ...... 33 Crittografare i log delle conversazioni ...... 36 Visualizzare i log di testo in Amazon CloudWatch Logs ...... 37 Accesso ai log audio in ...... 39 Monitorare lo stato del log delle conversazioni con i parametri CloudWatch ...... 40 Gestione delle sessioni ...... 40 Cambiare intento ...... 41 Riprendere un intento precedente ...... 42 Avviare una nuova sessione ...... 42 Convalidare valori di slot ...... 43 Opzioni di distribuzione ...... 43 Intenti incorporati e tipi di slot ...... 43 Intenti incorporati ...... 43 Tipi di slot integrati ...... 55 Tipi di slot personalizzati ...... 62 Offuscamento degli slot ...... 63 Analisi delle emozioni ...... 64 Tagging di risorse ...... 65 Tagging delle risorse ...... 65 Restrizioni applicate ai tag ...... 66 Tagging delle risorse (console) ...... 66 Tagging delle risorse (AWS CLI) ...... 67 Nozioni di base ...... 69 Fase 1: impostazione di un account ...... 69 Registrazione ad AWS ...... 69 Creazione di un utente IAM ...... 70

iii Amazon Lex Guida per gli sviluppatori

Fase successiva ...... 70 Fase 2: configurazione diAWS CLI ...... 70 ...... 71 Fase 3: nozioni di base (console) ...... 71 Esercizio 1: Creazione di un bot utilizzando un piano ...... 72 Esercizio 2: Crea un bot personalizzato ...... 98 Esercizio 3. Pubblicazione di una versione e creazione di un alias ...... 109 Step 4: Getting Started (AWS CLI) ...... 110 Exercise 1: Create a Bot ...... 110 Exercise 2: Add a New Utterance ...... 122 Exercise 3: Add a Lambda Function ...... 126 Exercise 4: Publish a Version ...... 129 Exercise 5: Create an Alias ...... 133 Exercise 6: Clean Up ...... 134 Funzione Versioni multiple e alias ...... 136 Controllo delle versioni ...... 136 La versione $LATEST ...... 136 Pubblicazione di una versione di una risorsa di Amazon Lex ...... 137 Aggiornamento di una risorsa Amazon Lex ...... 137 Eliminazione di una risorsa o versione di Amazon Lex ...... 138 Alias ...... 138 Utilizzo delle funzioni Lambda ...... 140 Formato di evento di input e di risposta della funzione Lambda ...... 140 Formato dell'evento di input ...... 140 Formato della risposta ...... 145 Amazon Lex e piani AWS Lambda ...... 150 Aggiornamento di un piano per un'impostazione locale specifica ...... 150 Deploying Bots ...... 151 Deploying an Amazon Lex Bot on a Messaging Platform ...... 151 Integrating with Facebook ...... 153 Integrating with Kik ...... 155 Integrating with Slack ...... 158 Integrating with Twilio SMS ...... 162 Deploying an Amazon Lex Bot in Mobile Applications ...... 165 Importing and Exporting ...... 166 Exporting and Importing in Amazon Lex Format ...... 166 Exporting in Amazon Lex Format ...... 166 Importing in Amazon Lex Format ...... 167 JSON Format for Importing and Exporting ...... 168 Exporting to an Alexa Skill ...... 171 Esempi di bot ...... 173 Pianifica appuntamento ...... 173 Panoramica del piano di bot (ScheduleAppointment) ...... 175 Panoramica del piano della funzione Lambda (lex-make-appointment-python) ...... 176 Passaggio 1: Creare un bot Amazon Lex ...... 176 Passaggio 2: Creare una funzione Lambda ...... 178 Passaggio 3: Aggiornare l'intento: Configurazione di un hook di codice ...... 179 Passaggio 4: Distribuisci il bot sulla piattaforma Facebook Messenger ...... 180 Dettagli del flusso di informazioni ...... 180 Prenota viaggio ...... 192 Passaggio 1: Revisione del progetto ...... 193 Passaggio 2: Creare un bot Amazon Lex ...... 195 Passaggio 3: Creazione di una funzione Lambda ...... 198 Passaggio 4: Aggiungi il Lambda Fungere da hook di codice ...... 198 Dettagli del flusso di informazioni ...... 202 Esempio: Utilizzo di una scheda di risposta ...... 216 Aggiornamento delle enunciazioni ...... 220

iv Amazon Lex Guida per gli sviluppatori

Integrazione con un sito Web ...... 221 Assistente agente del call center ...... 221 Passaggio 1: Creazione di un Amazon Kendra Indice ...... 223 Passaggio 2: Creare un bot Amazon Lex ...... 223 Passaggio 3: Aggiungi un intento personalizzato e integrato ...... 224 Passaggio 4: Configurazione di Amazon Cognito ...... 225 Passaggio 5: Distribuisci il tuo bot come applicazione Web ...... 226 Passaggio 6: Usa il bot ...... 226 Sicurezza ...... 229 Protezione dei dati ...... 229 Crittografia dei dati inattivi ...... 230 Crittografia in transito ...... 231 Gestione delle chiavi ...... 231 Identity and Access Management ...... 231 Audience ...... 231 Autenticazione con identità ...... 232 Gestione dell'accesso tramite policy ...... 233 Ulteriori informazioni ...... 235 Come funziona Amazon Lex con IAM ...... 235 Esempi di policy basate su identità ...... 240 Risoluzione dei problemi ...... 243 Using Service-Linked Roles ...... 245 Service-Linked Roles Permissions for Amazon Lex ...... 245 Creating a Service-Linked Role for Amazon Lex ...... 245 Editing a Service-Linked Role for Amazon Lex ...... 245 Deleting a Service-Linked Role for Amazon Lex ...... 246 Supported Regions for Amazon Lex Service-Linked Roles ...... 246 Monitoraggio ...... 246 Monitoraggio di Amazon Lex con CloudWatch ...... 246 Registrazione di chiamate dell'API di Amazon Lex con AWS CloudTrail ...... 254 Convalida della conformità ...... 257 Resilienza ...... 258 Sicurezza dell'infrastruttura ...... 258 Guidelines and Quotas ...... 259 Supported Regions ...... 259 General Guidelines ...... 259 Quotas ...... 261 Runtime Service Quotas ...... 261 Model Building Quotas ...... 262 Riferimento alle API ...... 266 Actions ...... 266 Amazon Lex Model Building Service ...... 267 Amazon Lex Runtime Service ...... 417 Data Types ...... 447 Amazon Lex Model Building Service ...... 448 Amazon Lex Runtime Service ...... 494 Cronologia dei documenti ...... 508 Glossario AWS ...... 513 ...... dxiv

v Amazon Lex Guida per gli sviluppatori

Che cos'è Amazon Lex?

Amazon Lex è un servizio AWS per la creazione di interfacce di comunicazione tramite voce e testo in qualsiasi applicazione. Con Amazon Lex, lo stesso motore di comunicazione su cui si basa è ora a disposizione di tutti gli sviluppatori, permettendoti così di creare chatbot sofisticati e naturali nelle applicazioni nuove ed esistenti. Amazon Lex offre funzionalità e flessibilità avanzate per la comprensione del linguaggio naturale (NLU) e il riconoscimento vocale automatico (ASR), consentendoti di creare esperienze utente coinvolgenti con interazioni di comunicazione naturali, oltre che di creare nuove categorie di prodotti.

Amazon Lex consente a qualsiasi sviluppatore di creare rapidamente chatbot di conversazione. Con Amazon Lex, non è necessaria alcuna esperienza nell'apprendimento profondo, infatti per creare un bot è sufficiente che specifichi il flusso di conversazione di base nella console di Amazon Lex. Amazon Lex gestisce il dialogo e regola in modo dinamico le risposte nella conversazione. Tramite la console, puoi creare, testare e pubblicare chatbot di testo o vocali. Quindi puoi aggiungere ai bot le interfacce di comunicazione sui dispositivi mobili, le applicazioni Web e le piattaforme di chat (ad esempio, Facebook Messenger).

Amazon Lex fornisce l'integrazione predefinita con AWS Lambda e puoi eseguire facilmente l'integrazione con molti altri servizi sulla piattaforma AWS, tra cui Amazon Cognito, AWS Mobile Hub, Amazon CloudWatch e Amazon DynamoDB. L'integrazione con Lambda fornisce ai bot l'accesso ai connettori aziendali serverless predefiniti per effettuare il collegamento ai dati nelle applicazioni SaaS, come Salesforce, HubSpot o Marketo.

Alcuni dei vantaggi derivanti dall'utilizzo di Amazon Lex sono:

• Semplicità: Amazon Lex ti assiste nell'utilizzo della console per creare in pochi minuti il tuo chatbot. Tu fornisci solo alcune frasi di esempio e Amazon Lex crea un modello completo di linguaggio naturale tramite cui il bot può interagire utilizzando voce e testo per porre domande, ottenere risposte e completare operazioni sofisticate.

• Tecnologie di apprendimento profondo democratizzate: basato sulla stessa tecnologia di Alexa, Amazon Lex fornisce tecnologie ASR e NLU per creare un sistema di comprensione del linguaggio parlato (SLU). Tramite il sistema SLU, Amazon Lex ottiene l'input di testo e vocale del linguaggio naturale, comprende l'intento alla base dell'input e realizza l'intento dell'utente invocando la funzione aziendale appropriata.

In ambito informatico, il riconoscimento vocale e la comprensione del linguaggio naturale sono tra i problemi più complicati affrontati finora, tanto che necessitano di algoritmi di apprendimento approfondito molto complessi da addestrare con enormi quantità di dati e infrastrutture apposite. Basato sulla stessa tecnologia di Alexa, Amazon Lex mette a disposizione di tutti gli sviluppatori le tecnologie di apprendimento profondo. I chatbot di Amazon Lex convertono in testo le parti parlate in entrata e comprendono l'intento dell'utente per generare una risposta intelligente, permettendoti di concentrarti sulla creazione dei tuoi bot con un valore aggiunto diversificato per i tuoi clienti per definire categorie di prodotti completamente nuove grazie alle interfacce di comunicazione.

• Distribuzione e dimensionamento semplici: con Amazon Lex, puoi creare, testare e distribuire i tuoi chatbot direttamente dalla console di Amazon Lex. Amazon Lex ti permette di pubblicare facilmente i tuoi chatbot vocali e di testo da utilizzare sui dispositivi mobili, le applicazioni Web e i servizi di chat (ad esempio, Facebook Messenger). Amazon Lex ricalibra automaticamente le risorse, pertanto non devi

1 Amazon Lex Guida per gli sviluppatori Primo utilizzo di Amazon Lex?

pensare al provisioning di hardware e alla gestione dell'infrastruttura per sviluppare la tua esperienza con i bot.

• Integrazione predefinita con la piattaforma AWS: Amazon Lex dispone dell'interoperabilità nativa con altri servizi AWS, come Amazon Cognito, AWS Lambda, Amazon CloudWatch e AWS Mobile Hub. Puoi trarre vantaggio dalla potenza della piattaforma AWS per la sicurezza, il monitoraggio, l'autenticazione utente, la logica di business, lo storage e lo sviluppo di applicazioni mobili.

• Convenienza: con Amazon Lex, non vi sono costi anticipati o tariffe minime. Ti vengono addebitate solo le richieste vocali o di testo che effettui. I prezzi in base al consumo e i costi ridotti a richiesta rendono il servizio un modo conveniente di creare interfacce di comunicazione. Con il piano gratuito di Amazon Lex, puoi provare Amazon Lex facilmente, senza alcun investimento iniziale.

Primo utilizzo di Amazon Lex?

Se è la prima volta che utilizzi Amazon Lex, ti consigliamo di leggere le seguenti sezioni in ordine:

1. Nozioni di base su Amazon Lex (p. 69): in questa sezione puoi configurare il tuo account e testare Amazon Lex. 2. Riferimento alle API (p. 266) : in questa sezione vengono forniti ulteriori esempi che puoi utilizzare per esplorare Amazon Lex.

2 Amazon Lex Guida per gli sviluppatori

Amazon Lex: come funziona

Amazon Lex ti consente di creare applicazioni grazie a un'interfaccia vocale o di testo con la stessa tecnologia utilizzata da Amazon Alexa. Di seguito sono illustrate le normali fasi da eseguire quando si utilizza Amazon Lex:

1. Crea un bot e configuralo con uno o più intenti che desideri supportare. Configura il bot in modo che comprenda l'obiettivo dell'utente (intento), inizi una conversazione per ottenere le informazioni e realizzi l'intento dell'utente. 2. Esegui il test del bot. Puoi utilizzare il client della finestra di prova fornito dalla console di Amazon Lex. 3. Pubblica una versione e crea un alias. 4. Distribuisci il bot. Puoi distribuire il bot sulle piattaforme come le applicazioni mobili oppure su piattaforme di messaggistica come Facebook Messenger.

Prima di iniziare, acquisisci familiarità con i concetti principali e la terminologia di base di Amazon Lex riportati di seguito:

• Bot – Un bot esegue attività automatiche come ordinare una pizza, prenotare un hotel, ordinare fiori e così via. Un bot di Amazon Lex utilizza le funzionalità di riconoscimento automatico della voce (ASR) e di comprensione del linguaggio naturale (NLU). Ogni bot deve avere un nome univoco all'interno dell'account.

I bot di Amazon Lex sono in grado di comprendere l'input vocale o di testo dell'utente e convertirlo in linguaggio naturale. Puoi creare funzioni Lambda e aggiungerle come hook di codice nella tua configurazione di intenti per eseguire attività di convalida e adempimento dei dati dell'utente.

• Intento Un intento rappresenta un'operazione che l'utente desidera eseguire.– Si crea un bot per supportare uno o più intenti correlati. Ad esempio, potresti creare un bot che ordina pizze e bevande. Per ogni intento, fornisci le informazioni obbligatorie seguenti:

• Nome intento Un nome descrittivo per l'intento.– Ad esempio, OrderPizza. I nomi degli intenti devono essere univoci nell'account. • Affermazioni di esempio Come un utente può comunicare l'intento.– Ad esempio, un utente potrebbe dire "Posso ordinare una pizza per favore?" oppure "Vorrei ordinare una pizza". • Come adempiere l'intento Come vuoi adempiere l'intento dopo che l'utente ha fornito le informazioni necessarie (ad esempio, effettuare un ordine presso una pizzeria nei stessa punti vendita).– Per adempiere l'intento è consigliabile creare una funzione Lambda.

Puoi anche configurare l'intento in modo che Amazon Lex restituisca semplicemente le informazioni all'applicazione del client per eseguire l'adempimento necessario.

Oltre agli intenti personalizzati come ordinare una pizza, Amazon Lex fornisce anche intenti integrati per configurare rapidamente il tuo bot. Per ulteriori informazioni, consulta Intenti incorporati e tipi di slot (p. 43).

3 Amazon Lex Guida per gli sviluppatori

• Slot Un intento può richiedere zero o più slot o parametri.– Si aggiungono slot come parte della configurazione dell'intento. In fase di runtime, Amazon Lex richiede all'utente valori slot specifici. L'utente deve fornire i valori per tutti gli slot obbligatori prima che Amazon Lex possa adempiere all'intento.

Ad esempio, l'intento OrderPizza richiede slot come le dimensioni della pizza, il tipo di crosta e il numero di pizze. Tali slot devono essere aggiunti nella configurazione dell'intento. Per ogni slot, devi fornire un tipo di slot e un messaggio di richiesta che Amazon Lex invia al client per ottenere dati dall'utente. Un utente può rispondere con un valore di slot che includa parole aggiuntive, ad esempio: "Pizza grande, grazie" o "Direi una piccola". Amazon Lex può comunque comprendere il valore di slot previsto.

• Tipo di slot – Ogni slot ha un tipo. Puoi creare i tuoi tipi di slot personalizzati o utilizzare i tipi di slot incorporati. Ogni tipo di slot deve avere un nome univoco all'interno dell'account. Ad esempio, puoi creare e utilizzare i tipi di slot riportati sotto per l'intento OrderPizza:

• Dimensioni – Con valori di enumerazione Small, Medium e Large. • Crosta – Con valori di enumerazione Thick e Thin.

Amazon Lex fornisce inoltre tipi di slot incorporati. Ad esempio, AMAZON.NUMBER è un tipo di slot incorporato che puoi utilizzare per il numero di pizze ordinate. Per ulteriori informazioni, consulta Intenti incorporati e tipi di slot (p. 43).

Per un elenco di regioni AWS in cui è disponibile Amazon Lex, consulta Regioni ed endpoint AWS in Riferimenti generali di Amazon Web Services.

Negli argomenti seguenti vengono fornite informazioni aggiuntive. Consigliamo di leggerle in ordine e di esaminare gli esercizi Nozioni di base su Amazon Lex (p. 69).

Argomenti • Lingue supportate in Amazon Lex (p. 5) • Modello di programmazione (p. 5) • Gestione dei messaggi (p. 10) • Gestione del contesto di una conversazione (p. 20) • Using Confidence Scores (p. 28) • Log delle conversazioni (p. 30) • Gestione di sessioni con l'API Amazon Lex (p. 40) • Opzioni di distribuzione di bot (p. 43) • Intenti incorporati e tipi di slot (p. 43) • Tipi di slot personalizzati (p. 62) • Offuscamento degli slot (p. 63) • Analisi delle emozioni (p. 64) • Tagging delle risorse Amazon Lex (p. 65)

4 Amazon Lex Guida per gli sviluppatori Lingue supportate

Lingue supportate in Amazon Lex

Amazon Lex supporta un'ampia gamma di lingue e impostazioni locali. I linguaggi supportati e le caratteristiche che li supportano sono elencati nelle seguenti tabelle.

Lingue e lingue supportate

Amazon Lex supporta le seguenti lingue e impostazioni locali.

Code Lingua e lingua locale

de-DE Tedesco (tedesco)

en-AU Inglese (Australia)

en-GB Inglese (Regno Unito)

it-IT Inglese (Stati Uniti)

es-419 Spagnolo (America Latina)

es-ES Spagnolo (Spagna)

es-US Spagnolo (Stati Uniti)

fr-CA Francese (Canada)

fr-FR Francese (francse)

it-IT Italiano (Italia)

Lingue e impostazioni locali supportate dalle caratteristicheAmazon Lex

Tutte le caratteristiche di Amazon Lex sono supportate in tutti i linguaggi e le impostazioni locali, ad eccezione di quanto elencato in questa tabella.

Caratteristica Lingue e impostazioni locali supportate

Impostazione del contesto dell'intento (p. 20) Inglese (Stati Uniti) (en-US)

Modello di programmazione

Il bot è il tipo di risorsa principale di Amazon Lex. Gli altri tipi di risorsa di Amazon Lex sono l'intento, il tipo di slot, l'alias e l'associazione canale bot.

Puoi creare un bot utilizzando la console Amazon Lex o l'API di creazione del modello. La console fornisce un'interfaccia utente grafica che puoi usare per creare un bot pronto per la produzione per la tua applicazione. Se preferisci, puoi utilizzare l'API di costruzione del modello tramite la AWS CLI o il tuo programma personalizzato per creare un bot.

5 Amazon Lex Guida per gli sviluppatori Operazioni API di costruzione dei modelli

Dopo aver creato un bot, devi distribuirlo in una delle piattaforme supportate oppure devi integrarlo nella tua applicazione. Quando un utente interagisce con il bot, l'applicazione del client invia richieste al bot tramite l'API di runtime Amazon Lex. Ad esempio, quando un utente dice "Voglio ordinare una pizza", il tuo client invia questo input a Amazon Lex utilizzando una delle operazioni API di runtime. Gli utenti possono fornire input vocali o di testo.

È anche possibile creare funzioni Lambda e utilizzarle come intento. Utilizza questi hook dei codici funzione Lambda per eseguire attività di runtime quali l'inizializzazione, la convalida dell'input dell'utente e l'adempimento dell'intento. Nelle sezioni seguenti vengono fornite informazioni aggiuntive.

Argomenti • Operazioni API di costruzione dei modelli (p. 6) • Operazioni API di runtime (p. 7) • Funzioni Lambda come hook di codici (p. 7)

Operazioni API di costruzione dei modelli

Per creare in modo programmatico bot, intenti e tipi di slot, puoi utilizzare le operazioni API di costruzione dei modelli. Puoi anche utilizzare l'API di costruzione dei modelli per gestire, aggiornare ed eliminare risorse per il tuo bot. Le operazioni API di costruzione dei modelli includono:

• PutBot (p. 372), PutBotAlias (p. 383), PutIntent (p. 388) e PutSlotType (p. 400) per creare e aggiornare rispettivamente bot, alias dei bot, intenti e tipi di slot. • CreateBotVersion (p. 269), CreateIntentVersion (p. 274) e CreateSlotTypeVersion (p. 280) per creare e pubblicare rispettivamente versioni dei tuoi bot, intenti e tipi di slot. • GetBot (p. 302) e GetBots (p. 320) per ottenere rispettivamente un bot specifico o un elenco di bot che hai creato. • GetIntent (p. 338) e GetIntents (p. 344) per ottenere rispettivamente un intento specifico o elenco di intenti che hai creato. • GetSlotType (p. 357) e GetSlotTypes (p. 361) per ottenere rispettivamente uno tipo di slot specifico o elenco di tipi di slot che hai creato. • GetBuiltinIntent (p. 326), GetBuiltinIntents (p. 328) e GetBuiltinSlotTypes (p. 330) per ottenere rispettivamente un intento integrato Amazon Lex, un elenco di intenti integrati Amazon Lex o un elenco di tipi di slot integrati che puoi utilizzare nel tuo bot. • GetBotChannelAssociation (p. 313) e GetBotChannelAssociations (p. 317) per ottenere rispettivamente un'associazione tra il tuo bot e una piattaforma di messaggistica o un elenco di associazioni tra il tuo bot e piattaforme di messaggistica. • DeleteBot (p. 284), DeleteBotAlias (p. 286), DeleteBotChannelAssociation (p. 288), DeleteIntent (p. 292) e DeleteSlotType (p. 296) per rimuovere risorse non necessarie dal tuo account.

Puoi utilizzare API di costruzione dei modelli per creare strumenti personalizzati per la gestione di risorse Amazon Lex. Ad esempio, esiste un limite di 100 versioni per ogni bot, intento e tipo di slot. Puoi utilizzare l'API di costruzione dei modelli per creare uno strumento che elimini automaticamente le vecchie versioni quando il tuo bot si avvicina al limite.

Per essere certi che solo un'operazione aggiorni una risorsa alla volta, Amazon Lex utilizza i checksum. Quando utilizzi un'Putoperazione API —, PutBot (p. 372), PutBotAlias (p. 383) PutIntent (p. 388) o PutSlotType (p. 400)per aggiornare una risorsa, devi passare il checksum corrente della risorsa nella richiesta.— Se due strumenti tentano di aggiornare una risorsa contemporaneamente, entrambi forniscono lo stesso checksum corrente. La prima richiesta che raggiunge Amazon Lex corrisponde al checksum corrente della risorsa. Nel momento in cui arriva la seconda richiesta, il checksum è differente. Il secondo strumento riceve un'eccezione PreconditionFailedException e l'aggiornamento termina.

6 Amazon Lex Guida per gli sviluppatori Operazioni API di runtime

Le Getoperazioni —, GetBot (p. 302), GetIntent (p. 338) e GetSlotType (p. 357)—sono consistenti finali. Se utilizzi un'operazione Get immediatamente dopo aver creato o modificato una risorsa con una delle operazioni Put, le modifiche potrebbero non essere restituite. Dopo che un'operazione Get restituisce l'aggiornamento più recente, restituisce sempre quella risorsa aggiornata fino a quando la risorsa non viene nuovamente modificata. È possibile determinare se una risorsa aggiornata è stata restituita osservando il checksum. Operazioni API di runtime

Per comunicare con Amazon Lex le applicazioni del client utilizzano le operazioni API di runtime seguenti:

• PostContent (p. 425) – Acquisisce input vocale o di testo e restituisce informazioni sull'intento e un messaggio vocale o di testo da comunicare all'utente. Attualmente, Amazon Lex supporta i formati audio seguenti:

Formati audio di input – LPCM e Opus

Formati audio di output – MPEG, OGG e PCM

L'operazione PostContent supporta input audio a 8 kHz e 16 kHz. Le applicazioni in cui l'utente finale parla con Amazon Lex per telefono, ad esempio un call center automatizzato, possono trasmettere direttamente 8 audio kHz.

• PostText (p. 434) – Da testo come input e restituisce informazioni sull'intento e un messaggio di testo da comunicare all'utente.

L'applicazione client utilizza l'API di runtime per chiamare un bot Amazon Lex specifico per elaborare il testo dell'utente — o l'input vocale delle enunciazioni. Ad esempio, supponiamo che un utente dica "Voglio una pizza". Il client invia l'input dell'utente a un bot utilizzando una delle operazioni API di runtime Amazon Lex. Dall'input dell'utente, Amazon Lex riconosce che la richiesta dell'utente è relativa all'intento OrderPizza definito nel bot. Amazon Lex inizia una conversazione con l'utente per raccogliere le informazioni necessarie o dati slot quali dimensioni della pizza, condimenti e numero di pizze. Dopo che l'utente fornisce tutti i dati slot necessari, Amazon Lex richiama l'hook del codice funzione Lambda per adempiere all'intento o restituisce i dati dell'intento al client, a seconda di come è stato configurato l'intento.

Usa l'operazione PostContent (p. 425) quando il tuo bot utilizza l'input vocale. Ad esempio, un'applicazione call center automatizzata può inviare audio a un bot Amazon Lex anziché a un agente per inoltrare le richieste dei clienti. Puoi utilizzare il formato audio 8 kHz per inviare audio direttamente dal telefono a Amazon Lex.

La finestra di prova della console Amazon Lex PostContent (p. 425) utilizza l'API per inviare richieste di testo e vocali a Amazon Lex. Puoi usare questa finestra di prova negli esercizi Nozioni di base su Amazon Lex (p. 69). Funzioni Lambda come hook di codici

Puoi configurare il tuo bot Amazon Lex per richiamare una funzione Lambda come hook di codice. L'hook di codice può servire a più scopi:

• Consente di personalizzare l'interazione con l'utente—Ad esempio, quando Joe chiede quali siano i condimenti disponibili per la pizza, è possibile scegliere di visualizzare un sottoinsieme di condimenti in precedenza.

7 Amazon Lex Guida per gli sviluppatori Funzioni Lambda come hook di codici

• Convalida l'input dell'utente— Supponiamo che Jen voglia ritirare fiori dopo l'orario di chiusura. È possibile convalidare l'ora che Jen inserisce e inviare una risposta appropriata. • Soddisfa l'intento dell'utente—Dopo che Joe ha fornito tutte le informazioni per il suo ordine di pizza, Amazon Lex può richiamare una funzione Lambda per effettuare l'ordine con una pizzeria locale.

Quando configuri un intento, specifica le funzioni Lambda come hook dei codici nelle posizioni seguenti:

• Hook del codice di dialogo per l'inizializzazione e la convalida—Questa funzione Lambda viene richiamata per ogni input utente, presupponendo che Amazon Lex abbia compreso l'intento dell'utente. • Hook di codice dell'adempimento—Questa funzione Lambda viene richiamata dopo che l'utente ha fornito tutti i dati dello slot necessari per realizzare l'intento.

Si sceglie l'intento e si impostano gli hook dei codici nella console Amazon Lex, come mostrato nella schermata seguente:

8 Amazon Lex Guida per gli sviluppatori Funzioni Lambda come hook di codici

9 Amazon Lex Guida per gli sviluppatori Gestione dei messaggi

È anche possibile impostare gli hook dei codici utilizzando i campi dialogCodeHook e fulfillmentActivity nell'operazione PutIntent (p. 388).

Una funzione Lambda può eseguire l'inizializzazione, la convalida e l'adempimento. I dati evento che la funzione Lambda riceve hanno un campo che identifica il chiamante come hook del codice di dialogo o di adempimento. Puoi utilizzare queste informazioni per eseguire la parte appropriata del codice.

Puoi utilizzare una funzione Lambda per creare un bot che riesca a spostarsi tra dialoghi complessi. Si utilizza il campo dialogAction nella risposta di funzione Lambda per indirizzare Amazon Lex verso operazioni specifiche. Ad esempio, puoi utilizzare l'operazione di dialogo ElicitSlot per dire a Amazon Lex di chiedere all'utente un valore di slot che non è richiesto. Se è stato definito un prompt di chiarimento, è possibile utilizzare l'operazione della finestra di dialogo ElicitIntent per ottenere un nuovo intento quando l'utente ha terminato con quello precedente.

Per ulteriori informazioni, consulta Utilizzo delle funzioni Lambda (p. 140).

Gestione dei messaggi

Argomenti • Tipi di messaggi (p. 10) • Contesti per la configurazione di messaggi (p. 11) • Formati di messaggio supportati (p. 15) • Gruppi di messaggi (p. 15) • Schede di risposta (p. 16)

Quando crei un bot, puoi configurare messaggi illustrativi o informativi da inviare al client. Considerare i seguenti esempi:

• Puoi configurare il tuo bot con il prompt illustrativo seguente:

I don't understand. What would you like to do?

Amazon Lex invia questo messaggio al client se non capisce l'intento dell'utente.

• Supponi di creare un bot per supportare un intento denominato OrderPizza. Per un ordine di pizza, gli utenti devono fornire informazioni quali le dimensioni della pizza, i contorni e il tipo di crosta. È possibile configurare i seguenti prompt:

What size pizza do you want? What toppings do you want? Do you want thick or thin crust?

Dopo che Amazon Lex ha determinato l'intento dell'utente di ordinare una pizza, invia questi messaggi al client per ottenere informazioni dall'utente.

In questa sezione viene descritta la progettazione delle interazioni dell'utente nella configurazione del tuo bot. Tipi di messaggi

Un messaggio può essere un prompt o un'istruzione.

10 Amazon Lex Guida per gli sviluppatori Contesti per la configurazione di messaggi

• Un prompt è normalmente una domanda che prevede la risposta dell'utente. • Un'istruzione è informativa. Non prevede una risposta.

Un messaggio può includere riferimenti a slot, attributi di sessione e attributi di richiesta. In fase di runtime, Amazon Lex sostituisce questi riferimenti con valori effettivi.

Per fare riferimento ai valori slot che sono stati impostati, utilizza la sintassi seguente:

{SlotName}

Per fare riferimento agli attributi di sessione, utilizza la sintassi seguente:

[SessionAttributeName]

Per fare riferimento agli attributi di richiesta, utilizza la sintassi seguente:

((RequestAttributeName))

I messaggi possono includere valori di slot, attributi di sessione e attributi di richiesta.

Ad esempio, supponiamo che configuri il messaggio seguente nell'intento OrderPizza del tuo bot:

"Hey [FirstName], your {PizzaTopping} pizza will arrive in [DeliveryTime] minutes."

Questo messaggio fa riferimento sia ad attributi slot (PizzaTopping) sia ad attributi di sessione (FirstName e DeliveryTime). In fase di runtime, Amazon Lex sostituisce questi segnaposto con valori e restituisce il messaggio seguente al client:

"Hey John, your cheese pizza will arrive in 30 minutes."

Per includere parentesi quadre ([]) o graffe ({}) in un messaggio, utilizza il carattere escape della barra rovesciata (\). Ad esempio, il messaggio seguente include parentesi graffe e parentesi quadre:

\{Text\} \[Text\]

Il testo restituito all'applicazione del client ha questo aspetto:

{Text} [Text]

Per informazioni sugli attributi di sessione, consulta le operazioni API di runtime PostText (p. 434) e PostContent (p. 425). Per un esempio, consulta Prenota viaggio (p. 192).

Le funzioni Lambda possono anche generare messaggi e restituirli a Amazon Lex che li invia all'utente. Se aggiungi le funzioni Lambda durante la configurazione del tuo intento, puoi creare messaggi in modo dinamico. Fornendo tali messaggi durante la configurazione del bot, elimini la necessità di creare un prompt nella funzione Lambda. Contesti per la configurazione di messaggi

Quando crei un bot, puoi creare messaggi in diversi contesti, ad esempio prompt chiarificatori nel bot, prompt per valori slot e messaggi dagli intenti. Amazon Lex sceglie un messaggio adatto a ciascun contesto da restituire al tuo utente. Puoi fornire un gruppo di messaggi per ogni contesto. In questo caso, Amazon Lex sceglie a caso uno dei messaggi dal gruppo. Puoi specificare anche il formato del messaggio oppure raggruppare i messaggi. Per ulteriori informazioni, consulta Formati di messaggio supportati (p. 15).

11 Amazon Lex Guida per gli sviluppatori Contesti per la configurazione di messaggi

Se una funzione Lambda è associata a un intento, puoi sovrascrivere tutti i messaggi configurati al momento della compilazione. Tuttavia per utilizzare questi messaggi, la funzione Lambda non è necessaria. Messaggi bot

Puoi configurare il bot con prompt illustrativi e messaggi di fine sessione. In fase di runtime, se Amazon Lex non capisce l'intento dell'utente, utilizza il prompt chiarificatore. Puoi configurare il numero di volte in cui Amazon Lex richiede un chiarimento prima di inviare il messaggio di fine sessione. Puoi configurare messaggi a livello di bot nella sezione Gestione errori della console Amazon Lex, come segue:

Con l'API, si possono configurare messaggi impostando i campi clarificationPrompt e abortStatement nell'operazione PutBot (p. 372).

Se utilizzi una funzione Lambda con un intento, la funzione Lambda può restituire una risposta che indirizza Amazon Lex a chiedere un intento dell'utente. Se la funzione Lambda non fornisce questo messaggio, Amazon Lex utilizza il messaggio di richiesta illustrativo. Prompt di slot

È necessario specificare almeno un messaggio di prompt per ognuno degli slot obbligatori in un intento. In fase di runtime, Amazon Lex utilizza uno di questi messaggi per richiedere all'utente di fornire un valore per lo slot. Ad esempio, per uno slot cityName, il seguente è un prompt valido:

Which city would you like to fly to?

Puoi impostare uno o più prompt per ogni slot utilizzando la console. Puoi anche creare gruppi di prompt utilizzando l'operazione PutIntent (p. 388). Per ulteriori informazioni, consulta Gruppi di messaggi (p. 15). Responses

Nella console, utilizza la sezione Responses (Risposte) per creare conversazioni dinamiche e coinvolgenti per il tuo bot. Puoi creare uno o più gruppi di messaggi per una risposta. In fase di runtime, Amazon Lex

12 Amazon Lex Guida per gli sviluppatori Contesti per la configurazione di messaggi crea una risposta selezionando un messaggio da ogni gruppo di messaggi. Per ulteriori informazioni sui gruppi di messaggi, consulta Gruppi di messaggi (p. 15).

Ad esempio, il primo gruppo di messaggi potrebbe contenere diversi formule di saluto: "Ciao," "Ciao", "Ciao" e "Salve". Il secondo gruppo di messaggi potrebbe contenere diverse forme di introduzione: "Io sono il bot di prenotazione" e "Questo è il bot di prenotazione". Un terzo gruppo di messaggi potrebbe comunicare le funzionalità del bot: "Posso essere d'aiuto con i nozioni di auto e le prenotazioni degli hotel", "Puoi noleggiare un'auto e prenotare un albergo" e "Posso aiutarti a noleggiare un'auto e prenotare un albergo".

Lex utilizza un messaggio da ogni gruppo di messaggi e crea risposte dinamiche dando origine a una conversazione. Ad esempio, un'interazione potrebbe essere:

Un'altra potrebbe essere:

13 Amazon Lex Guida per gli sviluppatori Contesti per la configurazione di messaggi

In entrambi i casi, l'utente può rispondere con un nuovo intento, ad esempio l'intento BookCar o BookHotel.

È possibile impostare il bot in modo che ponga una domanda di follow-up nella risposta. Ad esempio, per l'interazione precedente, puoi creare un quarto gruppo di messaggi con le seguenti domande: "Posso aiutarmi con un'auto o un albergo?", "Desideri effettuare una prenotazione ora?" e "C'è qualcosa che posso fare per te?". Per messaggi che includono "No" come risposta, puoi creare un prompt di follow-up. Ad esempio:

Per creare un prompt di follow-up, scegli Attendi risposta utente. Successivamente digita il messaggio o i messaggi che desideri inviare quando un utente dice "No". Quando crei una risposta da utilizzare come prompt di follow-up, è necessario specificare anche un'istruzione se la risposta all'istruzione è "No". Ad esempio:

14 Amazon Lex Guida per gli sviluppatori Formati di messaggio supportati

Per aggiungere risposte a un intento con l'API, utilizza l'operazione PutIntent. Per specificare una risposta, imposta il campo conclusionStatement nella richiesta PutIntent. Per impostare un prompt di follow-up, imposta il campo followUpPrompt e includi l'istruzione da inviare se l'utente dice "No". Non puoi impostare entrambi i campi conclusionStatement e followUpPrompt nello stesso intento. Formati di messaggio supportati

Quando utilizzi l'operazione PostText (p. 434) o l'operazione PostContent (p. 425) con l'intestazione Accept impostata su text/plain;charset=utf8, Amazon Lex supporta i messaggi nei formati seguenti:

• PlainText—Il messaggio contiene testo normale UTF-8. • SSML—Il messaggio contiene testo formattato per l'output vocale. • CustomPayloadIl messaggio contiene un formato personalizzato che hai creato per il client.— Puoi definire il payload in base alle esigenze della tua applicazione. • CompositeIl messaggio è una raccolta di messaggi, una da ogni gruppo di messaggi.— Per ulteriori informazioni sui gruppi di messaggi, consulta Gruppi di messaggi (p. 15).

Per impostazione predefinita, Amazon Lex restituisce uno dei messaggi definiti per un particolare prompt. Ad esempio, se definisci cinque messaggi per ottenere un valore di slot, Amazon Lex sceglie uno dei messaggi a caso e lo restituisce al client.

Se desideri che Amazon Lex restituisca un tipo di messaggio specifico al client in una richiesta di runtime, imposta il parametro di richiesta x-amzn-lex:accept-content-types. La risposta si limita al tipo o ai tipi richiesti. Se esiste più di un messaggio del tipo specificato, Amazon Lex ne restituisce uno a caso. Per ulteriori informazioni sull'intestazione x-amz-lex:accept-content-types, consulta Impostazione del tipo di risposta (p. 25). Gruppi di messaggi

Un gruppo di messaggi è un insieme di risposte adatte a un particolare prompt. Utilizza gruppi di messaggi quando desideri che il tuo bot crei risposte dinamiche dando origine a una conversazione. Quando Amazon Lex restituisce una risposta all'applicazione del client, sceglie un messaggio a caso da ogni gruppo. Puoi creare un massimo di cinque gruppi di messaggi per ogni risposta. Ogni gruppo può contenere un

15 Amazon Lex Guida per gli sviluppatori Schede di risposta massimo di cinque messaggi. Per esempi su come creare gruppi di messaggi nella console, consulta Responses (p. 12).

Per creare un gruppo di messaggi, puoi utilizzare la console o le operazioni PutBot (p. 372), PutIntent (p. 388) o PutSlotType (p. 400) per assegnare il numero di gruppo a un messaggio. Se non crei un gruppo di messaggi o se crei solo un gruppo di messaggi, Amazon Lex invia un solo messaggio nel campo Message. Le applicazioni client ricevono più messaggi in una risposta solo quando hai creato più di un gruppo di messaggi nella console oppure quando crei più di un gruppo di messaggi durante la creazione o l'aggiornamento di un intento con l'operazione PutIntent (p. 388).

Quando Amazon Lex invia un messaggio da un gruppo, il campo Message della risposta contiene un oggetto JSON di escape che contiene i messaggi. L'esempio seguente mostra i contenuti del campo Message quando include più messaggi. Note

L'esempio è stato formattato per la leggibilità. In una risposta non sono contenuti ritorni a capo (CR).

{\"messages\":[ {\"type\":\"PlainText\",\"group\":0,\"value\":\"Plain text\"}, {\"type\":\"SSML\",\"group\":1,\"value\":\"SSML text\"}, {\"type\":\"CustomPayload\",\"group\":2,\"value\":\"Custom payload\"} ]}

È possibile impostare il formato dei messaggi. Il formato può essere uno dei seguenti:

• PlainText—Il messaggio è in solo testo UTF-8. • SSML—Il messaggio è SSML (Speech Synthesis Markup Language). • CustomPayload—Il messaggio è nel formato personalizzato che hai specificato.

Per controllare il formato dei messaggi che le operazioni PostContent e PostText restituiscono nel campo Message, imposta l'attributo della richiesta x-amz-lex:accept-content-types. Ad esempio, se si imposta l'intestazione a quanto segue, si ricevono solo messaggi di solo testo e SSML nella risposta: x-amz-lex:accept-content-types: PlainText,SSML

Se si richiede un formato di messaggio specifico e un gruppo di messaggi non contiene quel messaggio con quel formato, ottieni un'eccezione NoUsableMessageException. Quando usi un gruppo di messaggi per raggruppare i messaggi per tipo, non utilizzare l'intestazione x-amz-lex:accept-content-types.

Per ulteriori informazioni sull'intestazione x-amz-lex:accept-content-types, consulta Impostazione del tipo di risposta (p. 25). Schede di risposta

Una scheda di risposta contiene un insieme di risposte appropriate per un prompt. Usa le schede di risposta per semplificare le interazioni per i tuoi utenti e aumentare la precisione dei tuoi bot riducendo errori tipografici nelle interazioni di testo. Puoi inviare una scheda di risposta per ogni messaggio di richiesta che Amazon Lex invia all'applicazione del tuo client. Le schede di risposta possono essere utilizzate con Facebook Messenger, Slack, Twilio e le applicazioni del tuo client.

Ad esempio, in un'applicazione per taxi, è possibile configurare un'opzione nella scheda di risposta per "Casa" e impostare il valore sull'indirizzo di casa dell'utente. Quando l'utente seleziona questa opzione, Amazon Lex riceve l'intero indirizzo come testo di input.

16 Amazon Lex Guida per gli sviluppatori Schede di risposta

Puoi definire una scheda di risposta per i prompt seguenti:

• Istruzione di conclusione • Prompt di conferma • Prompt di follow-up • Istruzione di rifiuto • Enunciazioni tipo slot

Puoi definire solo una scheda di risposta per ogni prompt.

Puoi configurare le schede di risposta quando crei un intento. Puoi definire una scheda di risposta statica in fase di compilazione utilizzando la console o l'operazione PutIntent (p. 388). In alternativa puoi definire una scheda di risposta dinamica in fase di runtime in una funzione Lambda. Se definisci entrambe le schede di risposta statica e dinamica, la scheda di risposta dinamica ha la precedenza.

Amazon Lex invia schede di risposta nel formato compreso dal client. Questo trasforma le schede di risposta per Facebook Messenger, Slack e Twilio. Per altri client, Amazon Lex invia una struttura JSON nella risposta PostText (p. 434). Ad esempio, se il client è Facebook Messenger, Amazon Lex trasforma la scheda di risposta in un modello generico. Per ulteriori informazioni sui modelli generici di Facebook Messenger, consulta Modello generico sul sito Web di Facebook. Per un esempio della struttura JSON, consulta Generazione dinamica di schede di risposta (p. 19).

Puoi utilizzare le schede di risposta solo con l'operazione PostText (p. 434). Non puoi utilizzare le schede di risposta con l'operazione PostContent (p. 425). Definizione di Schede di risposta statica

Definisci le schede di risposta statica con l'operazione PutBot (p. 372) o la console Amazon Lex quando crei un intento. Una risposta statica viene definita contemporaneamente all'intento. Utilizza una scheda di risposta statica quando le risposte sono fisse. Supponiamo che stai creando un bot con un intento che ha uno slot per il gusto. Quando definisci lo slot del gusto, devi specificare i prompt, come illustrato nella schermata della console seguente:

17 Amazon Lex Guida per gli sviluppatori Schede di risposta

Quando si definiscono i messaggi di richiesta, hai la possibilità di associare una scheda di risposta e definire i dettagli con l'operazione PutBot (p. 372) oppure, nella console Amazon Lex, come illustrato nell'esempio seguente:

A questo punto, supponiamo che il tuo bot sia stato integrato con Facebook Messenger. L'utente può fare clic sui pulsanti per scegliere un gusto, come mostrato nell'illustrazione seguente:

18 Amazon Lex Guida per gli sviluppatori Schede di risposta

Per personalizzare il contenuto di una scheda di risposta, si può fare riferimento agli attributi della sessione. In fase di runtime, Amazon Lex sostituisce questi riferimenti con valori appropriati dagli attributi di sessione. Per ulteriori informazioni, consulta Impostazione degli attributi di sessione (p. 23). Per un esempio, consulta Utilizzo di una scheda di risposta (p. 216). Generazione dinamica di schede di risposta

Per generare dinamicamente schede di risposta in fase di runtime, utilizza la funzione Lambda di inizializzazione e convalida per l'intento. Utilizza una scheda di risposta dinamica quando le risposte sono determinate in fase di runtime nella funzione Lambda. Nella risposta all'input dell'utente, la funzione Lambda genera una scheda di risposta e la restituisce nella sezione dialogAction della risposta. Per ulteriori informazioni, consulta Formato della risposta (p. 145).

Di seguito è riportata una risposta parziale da una funzione Lambda che mostra l'elemento responseCard. Questo genera un'esperienza utente simile a quella illustrata nella sezione precedente.

responseCard: { "version": 1, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [ { "title": "What Flavor?", "subtitle": "What flavor do you want?", "imageUrl": "Link to image", "attachmentLinkUrl": "Link to attachment",

19 Amazon Lex Guida per gli sviluppatori Gestione del contesto di una conversazione

"buttons": [ { "text": "Lemon", "value": "lemon" }, { "text": "Raspberry", "value": "raspberry" }, { "text": "Plain", "value": "plain" } ] } ] }

Per un esempio, consulta Pianifica appuntamento (p. 173).

Gestione del contesto di una conversazione

Il contesto di una conversazione sono le informazioni che un utente, la tua applicazione o una funzione di Lambda fornisce a un bot di Amazon Lex per realizzare un intento. Il contesto include i dati dello slot forniti dall'utente, gli attributi di richiesta impostati dall'applicazione client e gli attributi di sessione creati dall'applicazione client o dalle funzioni di Lambda

Argomenti • Impostazione del contesto dell'intento (p. 20) • Utilizzo dei valori di slot predefiniti (p. 22) • Impostazione degli attributi di sessione (p. 23) • Impostazione degli attributi di richiesta (p. 24) • Impostazione del timeout di sessione (p. 26) • Condivisione di informazioni tra intenti diversi (p. 27) • Impostazione di attributi complessi (p. 27)

Impostazione del contesto dell'intento

È possibile avere intenti di Amazon Lex trigger basati sul contesto. Un contesto è una variabile di stato che può essere associata a un intento quando si definisce un bot.

Puoi configurare i contesti per un intento quando crei l'intento utilizzando la console o PutIntent (p. 388) l'operazione . Puoi utilizzare i contesti solo nelle impostazioni locali di inglese (Stati Uniti) (en-US) e solo se hai impostato il enableModelImprovements parametro su true quando hai creato il bot con PutBot (p. 372) l'operazione .

Esistono due tipi di relazioni per i contesti, i contesti di output e i contesti di input. Un contesto di output diventa attivo quando viene soddisfatto un intento associato. Un contesto di output viene restituito all'applicazione nella risposta PostText (p. 434) dall'operazione PostContent (p. 425) o ed è impostato per la sessione corrente. Dopo che un contesto è stato attivato, rimane attivo per il numero di curve o il limite di tempo configurato quando il contesto è stato definito.

Un contesto di input specifica le condizioni in base alle quali un intento può essere riconosciuto. Un intento può essere riconosciuto solo durante una conversazione quando tutti i relativi contesti di input sono attivi. Un intento senza contesti di input è sempre idoneo per il riconoscimento.

20 Amazon Lex Guida per gli sviluppatori Impostazione del contesto dell'intento

Amazon Lex gestisce automaticamente il ciclo di vita dei contesti che vengono attivati mediante l'adempimento degli intenti con i contesti di output. Puoi anche impostare contesti attivi in una chiamata PostContent all'operazione PostText o . Puoi anche impostare il contesto di una conversazione utilizzando la Lambda funzione per l'intento. Il contesto di output da Amazon Lex viene inviato all'evento di input Lambda della funzione . La Lambda funzione può inviare contesti nella risposta. Per ulteriori informazioni, consulta Formato di evento di input e di risposta della funzione Lambda (p. 140).

Ad esempio, supponiamo di avere un intento per prenotare un'auto a noleggio configurata per restituire un contesto di output denominato "book_car_fulfilled". Quando l'intento viene realizzato, Amazon Lex imposta la variabile di contesto di output "book_car_fulfilled". Poiché "book_car_fulfilled" è un contesto attivo, un intento con il set di contesto "book_car_fulfilled" come contesto di input è ora considerato per il riconoscimento, purché un'enunciazione utente sia riconosciuta come un tentativo di ottenere tale intento. È possibile utilizzarlo solo per intenti che hanno senso dopo aver prenotato un'automobile, ad esempio l'invio di e-mail a una ricevuta o la modifica di una prenotazione. Contesto di output

Amazon Lex rende attivi i contesti di output di un intento quando l'intento viene soddisfatto. Puoi utilizzare il contesto di output per controllare gli intenti idonei a seguire l'intento corrente.

Ogni contesto dispone di un elenco di parametri gestiti nella sessione. I parametri sono i valori di slot per l'intento realizzato. È possibile utilizzare questi parametri per precompilare i valori di slot per altri intenti. Per ulteriori informazioni, consulta Utilizzo dei valori di slot predefiniti (p. 22).

Puoi configurare il contesto di output quando crei un intento con la console o con PutIntent (p. 388) l'operazione . Puoi configurare un intento con più di un contesto di output. Quando l'intento viene realizzato, tutti i contesti di output vengono attivati e restituiti nella PostText (p. 434) risposta PostContent (p. 425) o .

Di seguito viene mostrato come assegnare un contesto di output a un intento utilizzando la console .

Quando definisci un contesto di output, definisci anche il time to live, l'intervallo di tempo o il numero di curve in cui il contesto è incluso nelle risposte da Amazon Lex. Un turno è una richiesta dall'applicazione a Amazon Lex. Una volta che il numero di curve o il tempo è scaduto, il contesto non è più attivo.

L'applicazione può utilizzare il contesto di output in base alle esigenze. Ad esempio, l'applicazione può utilizzare il contesto di output per:

• Modifica il comportamento dell'applicazione in base al contesto. Ad esempio, un'applicazione di viaggio potrebbe avere un'operazione diversa per il contesto "book_car_fulfilled" rispetto a "rental_Hotel_fulfilled". • Restituisce il contesto di output a Amazon Lex come contesto di input per l'enunciazione successiva. Se Amazon Lex riconosce l'enunciazione come un tentativo di ottenere un intento, utilizza il contesto per limitare gli intenti che possono essere restituiti a quelli con il contesto specificato.

21 Amazon Lex Guida per gli sviluppatori Utilizzo dei valori di slot predefiniti

Contesto di input

Puoi impostare un contesto di input per limitare i punti nella conversazione in cui l'intento viene riconosciuto. Gli intenti senza un contesto di input sono sempre idonei per essere riconosciuti.

Puoi impostare i contesti di input a cui un intento risponde utilizzando la console o PutIntent l'operazione . Un intento può avere più di un contesto di input. Di seguito viene mostrato come assegnare un contesto di input a un intento utilizzando la console .

Per un intento con più di un contesto di input, tutti i contesti devono essere attivi per attivare l'intento. Puoi impostare un contesto di input quando chiami PostText (p. 434) l'operazione PostContent (p. 425), PutSession (p. 442)o .

È possibile configurare gli slot in un in un intento per accettare i valori predefiniti dal contesto attivo corrente. I valori predefiniti vengono utilizzati quando Amazon Lex riconosce un nuovo intento, ma non riceve un valore di slot. Puoi specificare il nome del contesto e il nome dello slot nel modulo #context- name.parameter-name quando definisci lo slot. Per ulteriori informazioni, consulta Utilizzo dei valori di slot predefiniti (p. 22). Utilizzo dei valori di slot predefiniti

Quando utilizzi un valore predefinito, specifichi un'origine per un valore di slot da riempire per i nuovi intenti quando non viene fornito alcuno slot dall'input dell'utente. Questa origine può essere un precedente attributo di dialogo, di richiesta o di sessione o un valore fisso impostato in fase di compilazione.

Puoi utilizzare quanto segue come origine per i valori predefiniti.

• Finestra di dialogo precedente (contesti) – #context-name.parameter-name • Attributi di sessione – [attribute-name] • Attributi di richiesta – • Valore fisso – Qualsiasi valore che non corrisponde al precedente

Quando utilizzi PutIntent (p. 388) l'operazione per aggiungere slot a un intento, puoi aggiungere un elenco di valori predefiniti. I valori predefiniti vengono utilizzati nell'ordine in cui sono elencati. Ad esempio, supponiamo di avere un intento con uno slot con la seguente definizione:

"slots": [ { "name": "reservation-start-date", "defaultValueSpec": {

22 Amazon Lex Guida per gli sviluppatori Impostazione degli attributi di sessione

"defaultValueList": [ { "defaultValue": "#book-car-fulfilled.startDate" }, { "defaultValue": "[reservationStartDate]" } ] }, Other slot configuration settings } ]

Quando l'intento viene riconosciuto, lo slot denominato "reservation-start-date" ha il valore impostato su uno dei valori seguenti.

1. Se il contesto "book-car-fulfilled" è attivo, il valore del parametro "startDate" viene utilizzato come valore predefinito. 2. Se il contesto "book-car-fulfilled" non è attivo o se il parametro "startDate" non è impostato, il valore dell'attributo di sessione "reservationStartDate" viene utilizzato come valore predefinito. 3. Se non viene utilizzato nessuno dei primi due valori predefiniti, lo slot non ha un valore predefinito e Amazon Lex ottiene un valore come al solito.

Se per lo slot viene utilizzato un valore predefinito, lo slot non viene richiesto anche se è obbligatorio. Impostazione degli attributi di sessione

Gli attributi di sessione contengono informazioni specifiche sull'applicazione che vengono scambiate tra il bot e l'applicazione client durante una sessione. Amazon Lex invia gli attributi di sessione a tutte le funzioni di Lambda configurate per un bot. Se una funzione di Lambda aggiunge o aggiorna gli attributi di sessione, Amazon Lex invia le nuove informazioni all'applicazione client. Ad esempio:

• Nell'Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72), il bot dell'esempio utilizza l'attributo di sessione price per gestire il prezzo dei fiori. La funzione di Lambda imposta questo attributo in base al tipo di fiori ordinati. Per ulteriori informazioni, consulta Fase 5 (facoltativo): Revisione dei dettagli del flusso di informazioni (console) (p. 86). • Nell'Prenota viaggio (p. 192), il bot dell'esempio utilizza l'attributo di sessione currentReservation per mantenere una copia dei dati del tipo di slot durante la conversazione per prenotare un hotel o noleggiare un'automobile. Per ulteriori informazioni, consulta Dettagli del flusso di informazioni (p. 202).

Utilizza gli attributi di sessione nelle funzioni di Lambda per inizializzare un bot e personalizzare i messaggi di richiesta e le schede di risposta. Ad esempio:

• Inizializzazione — In un bot per ordinare una pizza, l'applicazione client passa la posizione dell'utente come attributo di sessione nella prima chiamata PostContent (p. 425) all'operazione PostText (p. 434) o . Ad esempio, "Location": "111 Maple Street". La Lambda funzione utilizza queste informazioni per trovare la pizzeria più vicina per effettuare l'ordine. • Personalizzazione dei prompt — Configura prompt e schede di risposta per fare riferimento agli attributi di sessione. Ad esempio, "Salve [Nome], quali ingredienti aggiuntivi desideri?" Se invii il nome dell'utente come attributo di sessione ({"FirstName": "Jo"}), Amazon Lex sostituisce il segnaposto con il nome e invia quindi un prompt personalizzato all'utente: "Salve Giovanni, quali ingredienti aggiuntivi desideri?"

Gli attributi di sessione vengono mantenuti per tutta la durata della sessione. Amazon Lex li archivia in un datastore crittografato fino alla fine della sessione. Il client può creare gli attributi di sessione in una richiesta chiamando l'operazione PostContent (p. 425) o PostText (p. 434) con il campo

23 Amazon Lex Guida per gli sviluppatori Impostazione degli attributi di richiesta sessionAttributes impostato su un valore. Una funzione di Lambda può creare un attributo di sessione in una risposta. Dopo che il client o una funzione di Lambda ha creato un attributo di sessione, il valore dell'attributo archiviato viene utilizzato ogni volta che l'applicazione client non include il campo sessionAttribute in una richiesta a Amazon Lex.

Ad esempio, supponiamo di avere due attributi di sessione, {"x": "1", "y": "2"}. Se il client chiama PostContent l'operazione PostText o senza specificare il sessionAttributes campo , Amazon Lex chiama la Lambda funzione con gli attributi di sessione archiviati ({"x": 1, "y": 2}). Se la funzione di Lambda non restituisce gli attributi di sessione, Amazon Lex restituisce gli attributi di sessione archiviati all'applicazione client.

Se l'applicazione client o la funzione di Lambda trasferisce gli attributi di sessione, Amazon Lex aggiorna gli attributi di sessione archiviati. Il trasferimento di un valore esistente, come {"x": 2}, determina l'aggiornamento del valore archiviato. Se invii un nuovo set di attributi di sessione, ad esempio {"z": 3}, i valori esistenti vengono rimossi e viene mantenuto solo il nuovo valore. Quando viene trasferita una mappa vuota, {}, i valori archiviati vengono cancellati.

Per inviare attributi di sessione a Amazon Lex devi creare una mappa stringa a stringa degli attributi. Di seguito viene spiegato come mappare gli attributi di sessione:

{ "attributeName": "attributeValue", "attributeName": "attributeValue" }

Per l'operazione PostText, inserisci la mappa nel corpo della richiesta utilizzando il campo sessionAttributes, come segue:

"sessionAttributes": { "attributeName": "attributeValue", "attributeName": "attributeValue" }

Per l'operazione PostContent, applica la codifica base64 alla mappa e inviala come l'intestazione x- amz-lex-session-attributes

Per inviare dati binari o strutturati in un attributo di sessione, devi dapprima trasformarli in una stringa semplice. Per ulteriori informazioni, consulta Impostazione di attributi complessi (p. 27). Impostazione degli attributi di richiesta

Gli attributi di richiesta contengono informazioni specifiche sulla richiesta e si applicano solo alla richiesta corrente. Un'applicazione client invia queste informazioni a Amazon Lex. Utilizza gli attributi di richiesta per inviare informazioni che non devono essere conservate per l'intera sessione. Puoi creare i tuoi attributi di richiesta personali oppure utilizzare quelli predefiniti. Per inviare gli attributi di richiesta, utilizza l'intestazione x-amz-lex-request-attributes in un the section called “ PostContent ” (p. 425) o il campo requestAttributes in una richiesta the section called “ PostText ” (p. 434) Poiché, a differenza degli attributi di sessione, gli attributi di richiesta non vengono mantenuti tra richieste diverse, non vengono restituiti nelle risposte PostContent o PostText Note

Per inviare informazioni che vengano mantenute tra richieste diverse, utilizza gli attributi di sessione.

Il namespace x-amz-lex: è riservato agli attributi di richiesta predefiniti. Non creare attributi di richiesta con il prefisso x-amz-lex:.

24 Amazon Lex Guida per gli sviluppatori Impostazione degli attributi di richiesta

Impostazione di attributi di richiesta predefiniti

Amazon Lex offre attributi di richiesta predefiniti per gestire la modalità di elaborazione delle informazioni inviate al tuo bot. Gli attributi non vengono salvati per l'intera sessione, quindi dovrai inviare gli attributi predefiniti in ogni richiesta. Tutti gli attributi predefiniti sono nel namespace x-amz-lex:

Oltre ai seguenti attributi predefiniti, Amazon Lex fornisce attributi predefiniti per le piattaforme di messaggistica. Per un elenco di questi attributi, consulta Deploying an Amazon Lex Bot on a Messaging Platform (p. 151). Impostazione del tipo di risposta

Se utilizzi due applicazioni client che hanno funzionalità diverse, potresti dover limitare il formato dei messaggi in una risposta. Ad esempio, potresti voler limitare i messaggi inviati a un client Web al testo normale, ma permettere a un client mobile di utilizzare sia testo normale sia il formato SSML (Speech Synthesis Markup Language). Per impostare il formato dei messaggi restituiti dalle operazioni PostContent (p. 425) e PostText (p. 434), utilizza l'attributo di richiesta x-amz-lex:accept-content-types"

Puoi impostare l'attributo su una qualsiasi combinazione dei seguenti tipi di messaggi:

• PlainText—Il messaggio contiene testo UTF-8. • SSML—Il messaggio contiene testo formattato per l'output vocale. • CustomPayload—Il messaggio contiene un formato personalizzato creato per il client. Puoi definire il payload in base alle esigenze della tua applicazione.

Amazon Lex restituisce solo i messaggi con il tipo specificato nel campo Message della risposta. Puoi impostare più di un valore separandoli con una virgola. Se utilizzi dei gruppi di messaggi, ogni gruppo di messaggi deve contenere almeno un messaggio del tipo specificato. In caso contrario, viene visualizzato un errore NoUsableMessageException Per ulteriori informazioni, consulta Gruppi di messaggi (p. 15). Note

L'attributo di richiesta x-amz-lex:accept-content-types non ha alcun effetto sul contenuto del corpo HTML. Il contenuto di una risposta dell'operazione PostText è sempre testo normale UTF-8. Il corpo di una risposta dell'operazione PostContent contiene dati nel formato impostato nell'intestazione Accept nella richiesta. Impostazione del fuso orario preferito

Per impostare il fuso orario dell'utente da utilizzare per risolvere le date, utilizza l'attributo di richiesta x- amz-lex:time-zone Se non specifichi un fuso orario nell'attributo x-amz-lex:time-zone, il valore predefinito dipende della regione che utilizzi per il tuo bot.

Regione Fuso orario predefinito

US East (N. Virginia) America/New_York

Stati Uniti occidentali (Oregon) America/Los_Angeles

Asia Pacifico (Singapore) Asia/Singapore

Asia Pacifico (Sydney) Australia/Sydney

Asia Pacifico (Tokyo) Asia/Tokyo

Regione Europa (Francoforte) Europe/Berlin

25 Amazon Lex Guida per gli sviluppatori Impostazione del timeout di sessione

Regione Fuso orario predefinito

Regione Europa (Irlanda) Europe/Dublin

Regione Europa (Londra) Europe/London

Ad esempio, se l'utente risponde tomorrow al prompt "Which day would you like your package delivered?" la data effettiva di consegna del pacchetto dipende dal fuso orario dell'utente. Ad esempio, quando sono le 02:00 del 16 settembre a New York, sono le 23:00 del 15 settembre a Los Angeles. Se il servizio è in esecuzione nella US East (N. Virginia) regione e una persona a Los Angeles ordina che un pacchetto venga consegnato "domani" utilizzando il fuso orario predefinito, il pacchetto verrà consegnato il 17th e non il 16th. Se invece imposti l'attributo di richiesta x-amz-lex:time-zone su America/Los_Angeles, il pacco verrà consegnato il giorno 16.

Puoi impostare l'attributo su uno dei nomi dei fusi orari della IANA (Internet Assigned Number Authority). Per l'elenco dei nomi dei fusi orari, consulta l'elenco dei fusi orari del database tz su Wikipedia. Impostazione di attributi di richiesta definiti dall'utente

Un attributo di richiesta definito dall'utente è costituito dai dati inviati al bot in ogni richiesta. Le informazioni vengono inviate amz-lex-request-attributes nell'intestazione di una PostContent richiesta o nel requestAttributes campo di una PostText richiesta.

Per inviare gli attributi di richiesta ad Amazon Lex, devi creare una mappa stringa a stringa degli attributi. Di seguito viene spiegato come mappare gli attributi di richiesta:

{ "attributeName": "attributeValue", "attributeName": "attributeValue" }

Per l'operazione PostText, inserisci la mappa nel corpo della richiesta utilizzando il campo requestAttributes, come segue:

"requestAttributes": { "attributeName": "attributeValue", "attributeName": "attributeValue" }

Per l'operazione PostContent, applica la codifica base64 alla mappa e inviala come l'intestazione x- amz-lex-request-attributes

Per inviare dati binari o strutturati in un attributo di richiesta, devi dapprima trasformarli in una stringa semplice. Per ulteriori informazioni, consulta Impostazione di attributi complessi (p. 27). Impostazione del timeout di sessione

Amazon Lex conserva le informazioni —sul contesto Dati dello slot e attributi —di sessione fino al termine di una sessione di conversazione. Per definire la durata di una sessione per un bot, imposta il timeout di sessione. Per impostazione predefinita, la durata di una sessione è di 5 minuti, ma puoi specificarne una diversa compresa tra 0 e 1.440 minuti (24 ore).

Ad esempio, supponi di creare un ShoeOrdering bot che supporti intenti come OrderShoes e GetOrderStatus. Quando Amazon Lex rileva che l'intento dell'utente è ordinare delle scarpe, richiede i dati dello slot. come, ad esempio, numero di scarpa, colore, marchio e così via. Se l'utente fornisce alcuni dati dello slot ma non completa l'acquisto, Amazon Lex ricorda tutti i dati dello slot e gli attributi di sessione

26 Amazon Lex Guida per gli sviluppatori Condivisione di informazioni tra intenti diversi per l'intera sessione. Se l'utente riprende la sessione prima che scada, può fornire i dati dello slot mancanti e completare l'acquisto.

Nella console di Amazon Lex, imposta il timeout della sessione quando crei un bot. Con l'interfaccia a riga di comando AWS (AWS CLI) o l'API, puoi impostare il timeout quando crei o aggiorni un bot con PutBot (p. 372) l'operazione impostando il idleSessionTTLInSeconds campo . Condivisione di informazioni tra intenti diversi

Amazon Lex consente la condivisione di informazioni tra intenti diversi mediante l'utilizzo degli attributi di sessione.

Ad esempio, un utente del bot ShoeOrdering inizia ordinando delle scarpe. Il bot avvia una conversazione con l'utente, acquisendo i dati dello slot come numero di scarpa, colore e marchio. Quando l'utente effettua un ordine, la funzione di Lambda che completa l'ordine imposta l'attributo di sessione orderNumber che contiene il numero dell'ordine. Per ricevere lo stato dell'ordine, l'utente utilizza l'intento GetOrderStatus Il bot può chiedere all'utente i dati dello slot, come il numero e la data dell'ordine. Quando il bot ottiene le informazioni richieste, restituisce lo stato dell'ordine.

Se pensi che i tuoi utenti possano cambiare intento nel corso della stessa sessione, puoi progettare il tuo bot affinché restituisca lo stato relativo all'ordine più recente. Invece di chiedere le informazioni dell'ordine all'utente, utilizza l'attributo di sessione orderNumber per condividere le informazioni tra intenti diversi e realizzare l'intento GetOrderStatus Il bot esegue questa operazione restituendo lo stato dell'ordine più recente effettuato dall'utente.

Per un esempio di condivisione di informazioni tra intenti, consulta Prenota viaggio (p. 192). Impostazione di attributi complessi

Gli attributi di richiesta e di sessione sono mappe stringa a stringa di attributi e valori. In molti casi puoi utilizzare la mappa stringa per trasferire i valori degli attributi tra l'applicazione client e un bot, mentre in alcuni casi potresti dover trasferire i dati binari o una struttura complessa che non può essere convertita facilmente in una mappa stringa. Ad esempio, il seguente oggetto JSON rappresenta una matrice delle città più popolose degli Stati Uniti:

{ "cities": [ { "city": { "name": "New York", "state": "New York", "pop": "8537673" } }, { "city": { "name": "Los Angeles", "state": "California", "pop": "3976322" } }, { "city": { "name": "Chicago", "state": "Illinois", "pop": "2704958" } } ] }

27 Amazon Lex Guida per gli sviluppatori Using Confidence Scores

Questa matrice di dati non si traduce altrettanto bene in una mappa stringa a stringa. In questo caso, puoi trasformare un oggetto in una stringa semplice per poterla inviare al tuo bot con le operazioni PostContent (p. 425) e PostText (p. 434)

Ad esempio, se utilizzi JavaScript, puoi utilizzare JSON.stringify l'operazione per convertire un oggetto in JSON e JSON.parse l'operazione per convertire il testo JSON in un JavaScript oggetto:

// To convert an object to a string. var jsonString = JSON.stringify(object, null, 2); // To convert a string to an object. var obj = JSON.parse(JSON string);

Per inviare gli attributi di sessione con PostContent l'operazione , è necessario codificare gli attributi base64 prima di aggiungerli all'intestazione della richiesta, come mostrato nel JavaScript codice seguente:

var encodedAttributes = new Buffer(attributeString).toString("base64");

Puoi inviare i dati binari alle operazioni PostContent e PostText convertendo dapprima i dati in una stringa con codifica base64, quindi inviando la stringa come valore negli attributi di sessione:

"sessionAttributes" : { "binaryData": "base64 encoded data" }

Using Confidence Scores

Quando un utente fa un'utteranza, Amazon Lex utilizza la comprensione della lingua naturale (NLU) per comprendere la richiesta dell’utente e restituire l’intento corretto. Per impostazione predefinita, Amazon Lex restituisce l'intento più probabile definito dal tuo bot.

In alcuni casi potrebbe essere difficile per Amazon Lex per determinare l'intento più probabile. Ad esempio, l’utente potrebbe fare un’utenza ambigua, oppure potrebbero esserci due intenti simili. Per aiutare a determinare l'intento corretto, è possibile combinare la conoscenza del dominio con il confidence scores di un elenco di intenti alternativi. Un punteggio di fiducia è una valutazione che Amazon Lex indica quanto sia sicuro che un intento sia l'intento corretto.

Per determinare la differenza tra due intenti alternativi, è possibile confrontare i propri punteggi di confidenza. Ad esempio, se un intento ha un punteggio di confidenza di 0,95 e un altro ha un punteggio di 0,65, il primo intento è probabilmente corretto. Tuttavia, se un intento ha un punteggio di 0,75 e un altro ha un punteggio di 0,72, esiste ambiguità tra i due intenti che potreste essere in grado di discriminare utilizzando la conoscenza del dominio nella vostra applicazione.

È inoltre possibile utilizzare punteggi di sicurezza per creare applicazioni di test che stabiliscano se le modifiche alle utteranze di un intento fanno la differenza nel comportamento del bot. Ad esempio, è possibile ottenere i punteggi di confidenza per gli intenti di un bot utilizzando una serie di utteranze, quindi aggiornare le intenti con nuove utenze. È quindi possibile controllare i punteggi di confidenza per vedere se si è verificato un miglioramento.

I punteggi di fiducia che Amazon Lex i rendimenti sono valori comparativi. Non dovete fare affidamento su di loro come punteggio assoluto. I valori possono cambiare in base ai miglioramenti a Amazon Lex.

Quando usate punteggi di fiducia, Amazon Lex restituisce l'intento più probabile e fino a 4 intenti alternativi con i punteggi associati in ogni risposta. Se tutti i punteggi di confidenza sono inferiori a una soglia,

28 Amazon Lex Guida per gli sviluppatori Using Confidence Scores

Amazon Lex include il AMAZON.FallbackIntent, il AMAZON.KendraSearchIntent, o entrambi, se sono configurati. È possibile utilizzare la soglia predefinita o impostare la propria soglia.

Il seguente codice JSON mostra il alternativeIntents nella risposta dalla PostText (p. 434) operazione.

"alternativeIntents": [ { "intentName": "string", "nluIntentConfidence": { "score": number }, "slots": { "string" : "string" } } ],

Impostare la soglia quando si crea o si aggiorna un bot. È possibile utilizzare l'API o il Amazon Lex console. Per le regioni elencate di seguito, è necessario scegliere di abilitare i miglioramenti della precisione e i punteggi di confidenza. Nella console, scegliere i punteggi di confidenza nel Opzioni avanzate sezione. Utilizzando l'API, impostare enableModelImprovements quando si chiama il PutBot (p. 372) operazione:

• US East (N. Virginia) (us-east-1) • Stati Uniti occidentali (Oregon) (us-west-2) • Asia Pacifico (Sydney) (ap-southeast-2) • Regione Europa (Irlanda) (eu-west-1)

In tutte le altre regioni, i miglioramenti della precisione e il supporto del punteggio di confidenza sono disponibili per impostazione predefinita.

Per modificare la soglia di confidenza, impostarla nella console o utilizzando il PutBot (p. 372) operazione. La soglia deve essere un numero compreso tra 1,00 e 0,00.

Per utilizzare la console, impostare la soglia di confidenza quando si crea o si aggiorna il bot.

Per impostare la soglia di confidenza quando si crea un bot (Console)

• Il Crea il tuo bot, inserire un valore nella Soglia del punteggio di confidenza campo.

Per aggiornare la soglia di confidenza (Console)

1. Dall'elenco dei bot, scegliere il bot da aggiornare. 2. Selezionare la scheda Settings (Impostazioni). 3. Nella barra di navigazione a sinistra, scegliere Generale. 4. Aggiornare il valore nella Soglia del punteggio di confidenza campo.

Per impostare o aggiornare la soglia di confidenza (SDK)

• Impostare il nluIntentConfidenceThreshold parametro del PutBot (p. 372) operazione. Il seguente codice JSON mostra il parametro da impostare.

"nluIntentConfidenceThreshold": 0.75,

29 Amazon Lex Guida per gli sviluppatori Session Management

Session Management

Per cambiare l’intento che Amazon Lex utilizza una conversazione con l'utente, è possibile utilizzare la risposta dal gancio del codice di dialogo Lambda oppure potete utilizzare le API di gestione delle sessioni nell'applicazione personalizzata. Using a Lambda function

Quando usi un Lambda , Amazon Lex la chiama con una struttura JSON che contiene l'input alla funzione. La struttura JSON contiene un campo chiamato currentIntent che contiene l'intento che Amazon Lex ha identificato come l'intento più probabile per l'utteranza dell'utente. La struttura JSON include anche un alternativeIntents che contiene fino a quattro intenti aggiuntivi che possono soddisfare l'intento dell'utente. Ogni intento include un campo chiamato nluIntentConfidenceScore che contiene il punteggio di fiducia che Amazon Lex assegnato all'intento.

Per utilizzare un intento alternativo, lo specifichi nel ConfirmIntent o il ElicitSlot azione di dialogo nella tua Lambda funzione.

Per ulteriori informazioni, vedi Utilizzo delle funzioni Lambda (p. 140). Using the Session Management API

Per utilizzare un intento diverso dall’intento attuale, utilizzare il PutSession (p. 442) operazione. Ad esempio, se decide che la prima alternativa è preferibile all’intento che Amazon Lex ha scelto, puoi usare il PutSession operazione per modificare gli intenti in modo che l'intento successivo che l'utente interagisce è quello selezionato.

Per ulteriori informazioni, vedi Gestione di sessioni con l'API Amazon Lex (p. 40).

Log delle conversazioni

È possibile abilitare i log delle conversazioni per memorizzare le interazioni bot. È possibile utilizzare questi log per esaminare le prestazioni del bot e risolvere problemi relativi alle conversazioni. È possibile registrare il testo per l'operazione PostText (p. 434). È possibile registrare testo e audio per l'operazione PostContent (p. 425). Abilitando i log delle conversazioni si ottiene una visualizzazione dettagliata delle conversazioni tra gli utenti e il bot.

Ad esempio, una sessione con il bot ha un ID di sessione. È possibile utilizzare questo ID per ottenere la trascrizione della conversazione, incluse le enunciazioni dell'utente e le risposte corrispondenti del bot. Puoi anche ottenere metadati quali il nome dell'intento e i valori di slot per un'enunciazione. Note

Non è possibile utilizzare i log delle conversazioni con un bot soggetto al Children's Online Privacy Protection Act (COPPA).

I log delle conversazioni sono configurati per un alias. Ogni alias può avere impostazioni diverse per i log audio e di testo. È possibile abilitare log di testo, log audio o entrambi per ciascun alias. I log di testo memorizzano input di testo, trascrizioni di input audio e metadati associati in CloudWatch Logs. I log audio memorizzano l'input audio in Amazon S3. Puoi abilitare la crittografia dei log di testo e audio utilizzando AWS KMS gestito dal cliente CMKs.

Per configurare la registrazione, utilizzare la console o l'operazione PutBotAlias (p. 383). Non è possibile registrare le conversazioni per l'alias $LATEST del bot o per il bot di test disponibile nella console Amazon Lex. Dopo aver abilitato i log delle conversazioni per un alias, le operazioni PostContent (p. 425) o

30 Amazon Lex Guida per gli sviluppatori Policy IAM per i log delle conversazioni

PostText (p. 434) per tale alias registrano le enunciazioni di testo o audio nel gruppo di log CloudWatch Logs configurato o nel bucket S3.

Argomenti • Policy IAM per i log delle conversazioni (p. 31) • Configurazione dei log delle conversazioni (p. 33) • Crittografare i log delle conversazioni (p. 36) • Visualizzare i log di testo in Amazon CloudWatch Logs (p. 37) • Accesso ai log audio in Amazon S3 (p. 39) • Monitorare lo stato del log delle conversazioni con i parametri CloudWatch (p. 40)

Policy IAM per i log delle conversazioni

A seconda del tipo di registrazione selezionato, Amazon Lex richiede l'autorizzazione per utilizzare i bucket Amazon CloudWatch Logs e Amazon Simple Storage Service (S3) per archiviare i log. È necessario creare ruoli e autorizzazioni AWS Identity and Access Management per consentire l'accesso di Amazon Lex a queste risorse. Creazione di un ruolo IAM e delle policy per i log delle conversazioni

Per abilitare i log delle conversazioni, è necessario concedere l'autorizzazione di scrittura per CloudWatch Logs e Amazon S3. Se si abilita la crittografia degli oggetti per gli oggetti S3, è necessario concedere l'autorizzazione di accesso alle chiavi AWS KMS utilizzate per crittografare gli oggetti.

È possibile utilizzare la console IAM, l'API IAM o l'AWS Command Line Interface per creare il ruolo e le policy. Queste istruzioni utilizzano l'AWS CLI per creare il ruolo e le policy. Note

Il codice seguente è formattato per Linux e MacOS. Per Windows, sostituire il carattere di continuazione della riga di Linux (\) con un accento circonflesso (^).

Per creare un ruolo IAM per i log delle conversazioni

1. Creare un documento nella directory corrente chiamato LexConversationLogsAssumeRolePolicyDocument.json, aggiungervi il seguente codice e salvarlo. Questo documento di policy aggiunge Amazon Lex come entità attendibile al ruolo. Ciò consente a Lex di assumere il ruolo di distribuire i log alle risorse configurate per i log delle conversazioni.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lex.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }

2. Nel comando dell'AWS CLI, eseguire il comando seguente per creare il ruolo IAM per i log delle conversazioni.

31 Amazon Lex Guida per gli sviluppatori Policy IAM per i log delle conversazioni

aws iam create-role \ --role-name role-name \ --assume-role-policy-document file:// LexConversationLogsAssumeRolePolicyDocument.json

Successivamente, creare e collegare una policy al ruolo che permetta a Amazon Lex di scrivere su CloudWatch Logs.

Per creare una policy IAM per la registrazione del testo della conversazione su CloudWatch Logs

1. Creare un documento nella directory corrente chiamato LexConversationLogsCloudWatchLogsPolicy.json, aggiungervi la seguente policy IAM e salvarlo.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:region:account-id:log-group:log-group-name:*" } ] }

2. Nell'AWS CLI, creare la policy IAM che concede l'autorizzazione di scrittura al gruppo di log CloudWatch Logs.

aws iam create-policy \ --policy-name cloudwatch-policy-name \ --policy-document file://LexConversationLogsCloudWatchLogsPolicy.json

3. Collegare la policy al ruolo IAM creato per i log delle conversazioni.

aws iam attach-role-policy \ --policy-arn arn:aws:iam::account-id:policy/cloudwatch-policy-name \ --role-name role-name

Se si sta registrando l'audio in un bucket S3, creare una policy che consenta a Amazon Lex di scrivere sul bucket.

Per creare una policy IAM per la registrazione audio in un bucket S3

1. Creare un documento nella directory corrente chiamato LexConversationLogsS3Policy.json, aggiungervi la seguente policy e salvarlo.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject" ],

32 Amazon Lex Guida per gli sviluppatori Configurazione dei log delle conversazioni

"Resource": "arn:aws:s3:::bucket-name/*" } ] }

2. Nell'AWS CLI, creare la policy IAM che concede l'autorizzazione di scrittura al bucket S3.

aws iam create-policy \ --policy-name s3-policy-name \ --policy-document file://LexConversationLogsS3Policy.json

3. Collegare la policy al ruolo creato per i log delle conversazioni.

aws iam attach-role-policy \ --policy-arn arn:aws:iam::account-id:policy/s3-policy-name \ --role-name role-name

Concessione dell'autorizzazione per il passaggio di un ruolo IAM

Quando utilizzi la console, l'AWS Command Line Interface o un SDK AWS per specificare un ruolo IAM da utilizzare per i log delle conversazioni, l'utente che specifica il ruolo IAM dei log delle conversazioni deve disporre dell'autorizzazione per passare il ruolo ad Amazon Lex. Per consentire all'utente di passare il ruolo ad Amazon Lex, è necessario concedere l'autorizzazione PassRole all'utente, ruolo o gruppo IAM dell'utente.

La policy seguente definisce l'autorizzazione da concedere all'utente, al ruolo o al gruppo. È possibile utilizzare le chiavi di condizione iam:AssociatedResourceArn e iam:PassedToService per limitare l'ambito dell'autorizzazione. Per ulteriori informazioni, consulta Concessione di autorizzazioni utente per il passaggio di un ruolo a un servizio AWS e Chiavi del contesto di condizione IAMe AWS STS nella Guida per l'utente di AWS Identity and Access Management.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::account-id:role/role-name", "Condition": { "StringEquals": { "iam:PassedToService": "lex.amazonaws.com" }, "StringLike": { "iam:AssociatedResourceARN": "arn:aws:lex:region:account-id:bot:bot- name:bot-alias" } } } ] }

Configurazione dei log delle conversazioni

Si possono abilitare e disabilitare i log delle conversazioni utilizzando la console o il campo conversationLogs dell'operazione PutBotAlias. È possibile attivare o disattivare i log audio, i log di testo o entrambi. La registrazione inizia nelle nuove sessioni del bot. Le modifiche apportate alle impostazioni dei log non si riflettono nelle sessioni attive.

33 Amazon Lex Guida per gli sviluppatori Configurazione dei log delle conversazioni

Per archiviare i log di testo, utilizzare un gruppo di log Amazon CloudWatch Logs nell'account AWS. È possibile utilizzare qualsiasi gruppo di log valido. Il gruppo di log deve trovarsi nella stessa regione del bot Amazon Lex. Per ulteriori informazioni sulla creazione di un gruppo di log CloudWatch Logs, consulta Utilizzo di gruppi di log e flussi di log nella Guida per l'utente di Amazon CloudWatch Logs.

Per archiviare i log audio, utilizzare un bucket Amazon S3 nell'account AWS. È possibile utilizzare qualsiasi bucket S3 valido. Il bucket deve trovarsi nella stessa regione del bot di Amazon Lex. Per ulteriori informazioni sulla creazione di un bucket S3, consulta la sezione relativa alla Creazione di un bucket nella Guida alle operazioni di base di Amazon Simple Storage Service.

È necessario fornire un ruolo IAM dotato di policy che permettono a Amazon Lex di scrivere nel gruppo di log o nel bucket configurato. Per ulteriori informazioni, vedi Creazione di un ruolo IAM e delle policy per i log delle conversazioni (p. 31).

Il ruolo IAM utilizzato per abilitare i log delle conversazioni deve disporre dell'autorizzazione iam:PassRole. Al ruolo deve essere collegata la policy seguente.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::account:role/role" } ] }

Abilitare i log delle conversazioni

Per attivare i log utilizzando la console

1. Aprire la console Amazon Lex https://console.aws.amazon.com/lex. 2. Dall'elenco, scegliere un bot. 3. Scegliere la scheda Settings (Impostazioni) quindi scegliere Conversation logs (Log delle conversazioni) dal menu a sinistra. 4. Nell'elenco degli alias, scegliere l'icona delle impostazioni per l'alias per il quale si desidera configurare i log delle conversazioni. 5. Scegliere se registrare testo, audio o entrambi. 6. Per la registrazione di testo, inserire il nome del gruppo di log Amazon CloudWatch Logs. 7. Per la registrazione dell'audio, inserire le informazioni del bucket S3. 8. Facoltativo. Per crittografare i log audio, scegliere la chiave AWS KMS da utilizzare per la crittografia. 9. Scegliere un ruolo IAM provvisto delle autorizzazioni richieste. 10. Scegliere Save (Salva) per iniziare a registrare le conversazioni.

Per attivare i log di testo utilizzando l'API

1. Chiamare l'operazione PutBotAlias (p. 383) con una voce nel membro logSettings del campo conversationLogs

• Impostare il membro destination su CLOUDWATCH_LOGS • Impostare il membro logType su TEXT • Impostare il membro resourceArn sull'Amazon Resource Name (ARN) del gruppo di log CloudWatch Logs a cui sono destinati i log

34 Amazon Lex Guida per gli sviluppatori Configurazione dei log delle conversazioni

2. Impostare il membro iamRoleArn del campo conversationLogs sull'Amazon Resource Name (ARN) di un ruolo IAM che dispone delle autorizzazioni necessarie per abilitare i log delle conversazioni sulle risorse specificate.

Per attivare i log audio utilizzando l'API

1. Chiamare l'operazione PutBotAlias (p. 383) con una voce nel membro logSettings del campo conversationLogs

• Impostare il membro destination su S3 • Impostare il membro logType su AUDIO • Impostare il membro resourceArn sull'ARN del bucket Amazon S3 in cui sono archiviati i log audio • Facoltativo. Per crittografare i log audio con una chiave AWS KMS specifica, impostare il membro kmsKeyArn dell'ARN della chiave utilizzata per la crittografia. 2. Impostare il membro iamRoleArn del campo conversationLogs sull'Amazon Resource Name (ARN) di un ruolo IAM che dispone delle autorizzazioni necessarie per abilitare i log delle conversazioni sulle risorse specificate.

Disabilitare i log delle conversazioni

Per disattivare i log utilizzando la console

1. Aprire la console Amazon Lex https://console.aws.amazon.com/lex. 2. Dall'elenco, scegliere un bot. 3. Scegliere la scheda Settings (Impostazioni) quindi scegliere Conversation logs (Log delle conversazioni) dal menu a sinistra. 4. Nell'elenco degli alias, scegliere l'icona delle impostazioni per l'alias per il quale si desidera configurare i log delle conversazioni. 5. Deselezionare la casella di controllo da testo, audio o entrambi per disattivare la registrazione. 6. Scegliere Save (Salva) per interrompere la registrazione delle conversazioni.

Per disattivare i log utilizzando l'API

• Chiamare l'operazione PutBotAlias senza il campo conversationLogs.

Per disattivare i log di testo utilizzando l'API

• • In caso di registrazione dell'audio • Chiamare l'operazione PutBotAlias (p. 383) con una voce logSettings solo per AUDIO. • La chiamata all'operazione PutBotAlias non deve avere una voce logSettings per TEXT. • Se non si sta registrando l'audio • Chiamare l'operazione PutBotAlias (p. 383) senza il campo conversationLogs.

Per disattivare i log audio utilizzando l'API

• • In caso di registrazione del testo • Chiamare l'operazione PutBotAlias (p. 383) con una voce logSettings solo per TEXT. • La chiamata all'operazione PutBotAlias non deve avere una voce logSettings per AUDIO. • Se non si sta registrando il testo • Chiamare l'operazione PutBotAlias (p. 383) senza il campo conversationLogs.

35 Amazon Lex Guida per gli sviluppatori Crittografare i log delle conversazioni

Crittografare i log delle conversazioni

È possibile utilizzare la crittografia per proteggere il contenuto dei log delle conversazioni. Per i log di testo e audio, è possibile utilizzare AWS KMS gestito dal cliente CMKs per crittografare i dati nel tuo CloudWatch Logs gruppo di log e bucket S3. Note

Amazon Lex supporta solo la simmetria CMKs. Non utilizzare una CMK asimmetrica per crittografare i dati.

La crittografia si abilita utilizzando una chiave AWS KMS nel gruppo di log CloudWatch Logs che Amazon Lex utilizza per i log di testo. Non è possibile fornire una chiave AWS KMS nelle impostazioni del log per abilitare la crittografia AWS KMS del gruppo di log. Per ulteriori informazioni, consulta la pagina relativa alla Crittografia dei dati di log in CloudWatch Logs tramite AWS KMS nella Guida per l'utente di Amazon CloudWatch Logs.

Per i log audio si utilizza la crittografia predefinita sul bucket S3 o si specifica una chiave AWS KMS per crittografare gli oggetti audio. Anche se il bucket S3 utilizza la crittografia predefinita, è comunque possibile specificare una chiave AWS KMS diversa per crittografare gli oggetti audio. Per ulteriori informazioni, consulta la pagina relativa alla Crittografia predefinita di Amazon S3 per i bucket S3 nella Guida per sviluppatori di Amazon Simple Storage Service.

Amazon Lex richiede le autorizzazioni di AWS KMS se si sceglie di crittografare i log audio. È necessario collegare ulteriori policy al ruolo IAM utilizzato per i log delle conversazioni. Se si utilizza la crittografia predefinita nel bucket S3, la policy deve concedere l'accesso alla chiave AWS KMS configurata per tale bucket. Se si specifica una chiave AWS KMS nelle impostazioni del log audio, è necessario concedere l'accesso a tale chiave.

Se non hai creato un ruolo per i log delle conversazioni, consulta Policy IAM per i log delle conversazioni (p. 31).

Per creare una policy IAM per l'utilizzo di una chiave AWS KMS per la crittografia dei log audio

1. Creare un documento nella directory corrente chiamato LexConversationLogsKMSPolicy.json, aggiungervi la seguente policy e salvarlo.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "kms:GenerateDataKey" ], "Resource": "kms-key-arn" } ] }

2. Nell'AWS CLI, creare la policy IAM che concede l'autorizzazione per utilizzare la chiave AWS KMS per crittografare i log audio.

aws iam create-policy \ --policy-name kms-policy-name \ --policy-document file://LexConversationLogsKMSPolicy.json

3. Collegare la policy al ruolo creato per i log delle conversazioni.

aws iam attach-role-policy \

36 Amazon Lex Guida per gli sviluppatori Visualizzare i log di testo in Amazon CloudWatch Logs

--policy-arn arn:aws:iam::account-id:policy/kms-policy-name \ --role-name role-name

Visualizzare i log di testo in Amazon CloudWatch Logs

Amazon Lex archivia i log di testo delle conversazioni in Amazon CloudWatch Logs. Per visualizzare i log, è possibile utilizzare la console CloudWatch Logs o l'API. Per ulteriori informazioni, consulta le sezioni Ricerca di dati di log utilizzando i modelli dei filtri e Sintassi delle queryCloudWatch Logs Insights nella Guida per l'utente di Amazon CloudWatch Logs.

Per visualizzare i log tramite la console Amazon Lex

1. Aprire la console Amazon Lex https://console.aws.amazon.com/lex. 2. Dall'elenco, scegliere un bot. 3. Scegliere la scheda Settings (Impostazioni), quindi scegliere Conversation logs (Log delle conversazioni) dal menu a sinistra. 4. Selezionare il collegamento in Text logs (Log di testo) per visualizzare i log dell'alias nella console CloudWatch.

È inoltre possibile utilizzare la console CloudWatch o l'API per visualizzare le voci del log. Per trovare le voci del log, passare al gruppo di log configurato per l'alias. È possibile trovare il prefisso del flusso di log nella console Amazon Lex o utilizzando l'operazione GetBotAlias (p. 307).

Le voci del log di un'enunciazione di un utente si trovano in più flussi di log. Un'enunciazione nella conversazione ha una voce in uno dei flussi di log con il prefisso specificato. Una voce nel flusso di log contiene le seguenti informazioni.

{ "messageVersion": "1.0", "botName": "bot name", "botAlias": "bot alias", "botVersion": "bot version", "inputTranscript": "text used to process the request", "botResponse": "response from the bot", "intent": "matched intent", "nluIntentConfidence": "number", "slots": { "slot name": "slot value", "slot name": null, "slot name": "slot value" ... }, "alternativeIntents": [ { "name": "intent name", "nluIntentConfidence": "number", "slots": { "slot name": slot value, "slot name": null, "slot name": slot value ... } }, { "name": "intent name", "nluIntentConfidence": number, "slots": {} } ],

37 Amazon Lex Guida per gli sviluppatori Visualizzare i log di testo in Amazon CloudWatch Logs

"developerOverride": "true" | "false", "missedUtterance": true | false, "inputDialogMode": "Text" | "Speech", "requestId": "request ID", "s3PathForAudio": "S3 path to audio file", "userId": "user ID", "sessionId": "session ID", "sentimentResponse": { "sentimentScore": "{Positive: number, Negative: number, Neutral: number, Mixed: number}", "sentimentLabel": "Positive" | "Negative" | "Neutral" | "Mixed" }, "slotToElicit": "slot name", "dialogState": "ElicitIntent" | "ConfirmIntent" | "ElicitSlot" | "Fulfilled" | "ReadyForFulfillment" | "Failed", "responseCard": { "genericAttachments": [ ... ], "contentType": "application/vnd.amazonaws.card.generic", "version": 1 }, "locale": "locale", "timestamp": "ISO 8601 UTC timestamp", "kendraResponse": { "totalNumberOfResults": number, "resultItems": [ { "id": "query ID", "type": "DOCUMENT" | "QUESTION_ANSWER" | "ANSWER", "additionalAttributes": [ { ... } ], "documentId": "document ID", "documentTitle": { "text": "title", "highlights": null }, "documentExcerpt": { "text": "text", "highlights": [ { "beginOffset": number, "endOffset": number, "topAnswer": true | false } ] }, "documentURI": "URI", "documentAttributes": [] } ], "facetResults": [], "sdkResponseMetadata": { "requestId": "request ID" }, "sdkHttpMetadata": { "httpHeaders": { "Content-Length": "number", "Content-Type": "application/x-amz-json-1.1", "Date": "date and time", "x-amzn-RequestId": "request ID" }, "httpStatusCode": 200

38 Amazon Lex Guida per gli sviluppatori Accesso ai log audio in Amazon S3

}, "queryId": "query ID" }, "sessionAttributes": { "attribute name": "attribute value" ... }, "requestAttributes": { "attribute name": "attribute value" ... } }

Il contenuto della voce di log dipende dal risultato di una transazione e dalla configurazione del bot e della richiesta.

• I campi intent, slots e slotToElicit non vengono visualizzati in una voce se il campo missedUtterance è true. • Il campo s3PathForAudio non compare se i log audio sono disabilitati o se il campo inputDialogMode è Text. • Il campo responseCard viene visualizzato solo quando è stata definita una scheda di risposta per il bot. • La mappa requestAttributes viene visualizzata solo se nella richiesta sono stati specificati attributi di richiesta. • Il kendraResponse è presente solo quando il campo AMAZON.KendraSearchIntent effettua una richiesta di ricerca di un Amazon Kendra indice. • Il developerOverride è vero quando è stato specificato un intento alternativo nel Lambda funzione. • La mappa sessionAttributes viene visualizzata solo se nella richiesta sono stati specificati attributi di sessione. • La mappa sentimentResponse viene visualizzata solo se si configura il bot per restituire i valori di sentiment.

Note

Il formato di input può cambiare senza una modifica corrispondente nel messageVersion. Il codice non deve generare un errore se sono presenti nuovi campi.

È necessario disporre di un ruolo e di una policy impostati per consentire a Amazon Lex di scrivere in CloudWatch Logs. Per ulteriori informazioni, consulta Policy IAM per i log delle conversazioni (p. 31). Accesso ai log audio in Amazon S3

Amazon Lex archivia i log audio per le conversazioni in un bucket S3.

Per accedere ai log audio tramite la console

1. Aprire la console Amazon Lex https://console.aws.amazon.com/lex. 2. Dall'elenco, scegliere un bot. 3. Scegliere la scheda Settings (Impostazioni), quindi scegliere Conversation logs (Log delle conversazioni) dal menu a sinistra. 4. Selezionare il collegamento in Audio logs (Log audio) per accedere ai log dell'alias nella console Amazon S3.

È inoltre possibile utilizzare la console Amazon S3 o l'API per accedere ai log audio. È possibile visualizzare il prefisso della chiave dell'oggetto S3 dei file audio nella console Amazon Lex o nel campo resourcePrefix della risposta all'operazione GetBotAlias.

39 Amazon Lex Guida per gli sviluppatori Monitorare lo stato del log delle conversazioni con i parametri CloudWatch Monitorare lo stato del log delle conversazioni con i parametri CloudWatch

Utilizza Amazon CloudWatch per monitorare i parametri di consegna dei log delle conversazioni. È possibile impostare allarmi sui parametri in modo da essere consapevoli dei problemi relativi alla registrazione, se dovessero verificarsi.

Amazon Lex fornisce quattro parametri nello spazio dei nomi AWS/Lex per i log delle conversazioni:

• ConversationLogsAudioDeliverySuccess • ConversationLogsAudioDeliveryFailure • ConversationLogsTextDeliverySuccess • ConversationLogsTextDeliveryFailure

Per ulteriori informazioni, vedi CloudWatchParametri per i log delle conversazioni (p. 253).

I parametri di riuscita mostrano che Amazon Lex ha scritto correttamente i log audio o di testo nelle loro destinazioni.

I parametri di errore mostrano che Amazon Lex non è stato in grado di consegnare i log audio o di testo alla destinazione specificata. In genere si tratta di un errore di configurazione. Quando i parametri di errore sono superiori a zero, controllare quanto segue:

• Verificare che Amazon Lex sia un'entità attendibile per il ruolo IAM. • Per la registrazione di testo, verificare l'esistenza del gruppo di log CloudWatch Logs. Per la registrazione dell'audio, verificare l'esistenza del bucket S3. • Verificare che il ruolo IAM utilizzato da Amazon Lex per accedere al gruppo di log CloudWatch Logs o al bucket S3 abbia l'autorizzazione di scrittura per il gruppo di log o per il bucket. • Verificare che il bucket S3 si trovi nella stessa regione del bot Amazon Lex e che appartenga all'account. • Se si utilizza una chiave AWS KMS per la crittografia S3, verificare che non vi siano policy che impediscano a Amazon Lex di utilizzare la chiave e verificare che il ruolo IAM fornito disponga delle autorizzazioni AWS KMS necessarie. Per ulteriori informazioni, vedi Policy IAM per i log delle conversazioni (p. 31).

Gestione di sessioni con l'API Amazon Lex

Quando un utente avvia una conversazione con il tuo bot, Amazon Lex crea una sessione. Le informazioni scambiate tra la tua applicazione e Amazon Lex costituiscono lo stato della sessione per la conversazione. Quando inoltri una richiesta, la sessione viene identificata dalla combinazione del nome del bot e di un identificatore utente specificato da te. Per ulteriori informazioni sull'identificatore utente, consulta il campo userId nell’operazione PostContent (p. 425) o PostText (p. 434).

La risposta ricevuta da un'operazione di sessione include un identificatore sessione univoco che identifica una sessione specifica con un utente. È possibile utilizzare questo identificatore durante le operazioni di test o di risoluzione dei problemi del bot.

È possibile modificare lo stato della sessione scambiato tra l'applicazione e il bot. Ad esempio, è possibile creare e modificare attributi della sessione personalizzati che contengono informazioni sulla sessione ed è possibile modificare il flusso della conversazione impostando il contesto del dialogo per interpretare l’enunciazione successiva.

È possibile aggiornare lo stato della sessione in due modi. Il primo è mediante una funzione Lambda con l’operazione PostContent o PostText che viene richiamata ad ogni scambio di conversazione. Per

40 Amazon Lex Guida per gli sviluppatori Cambiare intento ulteriori informazioni, consulta Utilizzo delle funzioni Lambda (p. 140). L'altro è utilizzando l'API di runtime Amazon Lex nell’applicazione per modificare lo stato della sessione.

L’API di runtime Amazon Lex fornisce operazioni che consentono di gestire le informazioni relative alla sessione per una conversazione con il bot. Le operazioni sono le seguenti: PutSession (p. 442) , GetSession (p. 421) e DeleteSession (p. 418). È possibile utilizzare queste operazioni per ottenere informazioni sullo stato della sessione dell’utente con il bot e avere il controllo granulare sullo stato.

Utilizza l'operazione GetSession quando desideri ottenere lo stato attuale della sessione. L'operazione restituisce lo stato attuale della sessione, incluso lo stato del dialogo con l'utente, gli attributi della sessione impostati e i valori di slot per gli ultimi tre intenti con cui l'utente ha interagito.

L'operazione PutSession consente di manipolare direttamente lo stato attuale della sessione. È possibile impostare il tipo della prossima operazione di dialogo che il bot eseguirà, in modo da avere il controllo sul flusso della conversazione con il bot. Imposta il campo type dell’operazione di dialogo su Delegate se desideri che Amazon Lex stabilisca l’operazione successiva del bot.

Puoi utilizzare l'operazione PutSession per creare una nuova sessione con un bot e impostare l'intento iniziale del bot. Puoi inoltre utilizzare l'operazione PutSession per passare da un intento a un altro. Quando crei una sessione o modifichi l’intento, puoi anche impostare lo stato della sessione, inclusi valori di slot e attributi della sessione. Quando il nuovo intento è terminato, puoi riavviare l’intento precedente. Puoi utilizzare l'operazione GetSession per ottenere lo stato del dialogo dell’intento precedente di Amazon Lex e utilizzare le informazioni per impostare lo stato del dialogo dell'intento.

La risposta ricevuta dall’operazione PutSession contiene le stesse informazioni dell’operazione PostContent. Puoi utilizzare queste informazioni per richiedere all'utente le informazioni successive, esattamente come faresti con la risposta ricevuta dall'operazione PostContent.

Utilizza l'operazione DeleteSession per rimuovere una sessione esistente e ricominciare con una nuova sessione. Ad esempio, quando esegui il test del bot, puoi utilizzare l'operazione DeleteSession per eliminare le sessioni di test dal bot.

Le operazioni di sessione operano in sinergia con le funzioni di adempimento di Lambda. Ad esempio, se la funzione Lambda restituisce Failed come stato dell’adempimento, puoi utilizzare l'operazione PutSession per impostare il tipo di operazione di dialogo su close e fulfillmentState su ReadyForFulfillment per riprovare la fase di adempimento.

Di seguito sono elencate alcune azioni che è possibile effettuare con le operazioni di sessione:

• Impostare il bot in modo che avvii una conversazione invece di attendere l'utente. • Cambiare intento durante una conversazione. • Tornare a un intento precedente. • Avviare o riavviare una conversazione durante un’interazione. • Convalidare i valori di slot e impostare il bot in modo che richieda nuovamente i valori non validi.

Ognuna di queste azioni è descritta di seguito. Cambiare intento

Puoi utilizzare l'operazione PutSession per passare da un intento a un altro e per tornare a un intento precedente. Puoi utilizzare l'operazione PutSession per impostare gli attributi di sessione o i valori di slot per il nuovo intento.

• Richiama l'operazione PutSession. Utilizza come nome dell’intento quello del nuovo intento e imposta l’operazione di dialogo su Delegate. Puoi inoltre impostare i valori di slot o gli attributi di sessione necessari per il nuovo intento.

41 Amazon Lex Guida per gli sviluppatori Riprendere un intento precedente

• Amazon Lex avvierà una conversazione con l'utente utilizzando il nuovo intento.

Riprendere un intento precedente

Per riprendere un intento precedente puoi utilizzare l'operazione GetSession per ottenere il riepilogo dell’intento e l’operazione PutSession per impostare l'intento sullo stato di dialogo precedente.

• Richiama l'operazione GetSession. La risposta ricevuta dall’operazione include un riepilogo dello stato del dialogo degli ultimi tre intenti con cui l'utente ha interagito. • Utilizza le informazioni del riepilogo dell’intento per richiamare l'operazione PutSession. In questo modo, l’utente tornerà all’intento precedente nella stessa posizione della conversazione.

In alcuni casi, può essere necessario riprendere la conversazione dell’utente con il bot. Ad esempio, immagina di aver creato un bot per il servizio clienti e che la tua applicazione stabilisca che l'utente deve parlare con un addetto per ricevere assistenza. Dopo la comunicazione con l'utente, l’addetto può aggiungere le informazioni raccolte alla conversazione con il bot.

Per riprendere una sessione, segui una procedura simile a questa:

• La tua applicazione stabilisce che l'utente deve parlare con un addetto del servizio clienti. • Utilizza l'operazione GetSession per ottenere lo stato di dialogo attuale dell’intento. • L’addetto del servizio clienti parla con l'utente e risolve il problema. • Utilizza l'operazione PutSession per impostare lo stato di dialogo dell’intento. Potresti dover impostare valori di slot e attributi o modificare l’intento. • Il bot riprende la conversazione con l'utente.

Puoi utilizzare il parametro checkpointLabel dell'operazione PutSession per etichettare un intento in modo da poterlo trovare in un secondo momento. Ad esempio, un bot che chiede informazioni a un cliente potrebbe entrare in un intento Waiting mentre il cliente raccoglie le informazioni. Il bot crea un'etichetta di checkpoint per l'intento corrente e quindi avvia l'intento Waiting. Quando il cliente restituisce il bot può trovare l'intento precedente utilizzando l'etichetta di checkpoint e tornare indietro.

L'intento deve essere presente nella struttura recentIntentSummaryView restituita dall'operazione GetSession. Se si specifica un'etichetta di checkpoint nella richiesta di operazione GetSession, verrà restituito un massimo di tre intenti con quell'etichetta di checkpoint.

• Utilizzare l'operazione GetSession per ottenere lo stato corrente della sessione. • Utilizzare l'operazione PutSession per aggiungere un'etichetta di checkpoint all'ultimo intento. Se necessario puoi utilizzare questa chiamata PutSession per passare a un intento diverso. • Quando è il momento di tornare all'intento etichettato, chiama l'operazione GetSession per ottenere un elenco di intenti recenti. È possibile utilizzare il parametro checkpointLabelFilter in modo che Amazon Lex restituisca solo gli intenti con l'etichetta di checkpoint specificata.

Avviare una nuova sessione

Se desideri che il bot avvii la conversazione con l'utente, puoi utilizzare l'operazione PutSession.

• Crea un intento di benvenuto senza slot e un messaggio conclusivo che richieda all'utente di dichiarare un intento. Ad esempio, "Cosa desideri ordinare? Puoi dire "Ordina una bevanda" oppure "Ordina una pizza"”. • Richiama l'operazione PutSession. Utilizza come nome dell’intento quello dell’intento di benvenuto e imposta l’operazione di dialogo su Delegate.

42 Amazon Lex Guida per gli sviluppatori Convalidare valori di slot

• Amazon Lex risponderà con la richiesta inclusa nell’intento di benvenuto per avviare la conversazione con l'utente.

Convalidare valori di slot

Puoi convalidare le risposte inviate al bot utilizzando l’applicazione client. Se la risposta non è valida, puoi utilizzare l'operazione PutSession per ricevere una nuova risposta dall'utente. Ad esempio, immagina che il bot per ordinare fiori possa vendere soltanto tulipani, rose e gigli. Se l'utente ordina garofani, la tua applicazione può:

• Esaminare il valore di slot restituito dalla risposta PostText o PostContent. • Se il valore di slot non è valido, può richiamare l'operazione PutSession. L'applicazione deve eliminare il valore di slot, impostare il campo slotToElicit e impostare il valore di dialogAction.type su elicitSlot. In via facoltativa, puoi impostare i campi message e messageFormat se desideri modificare il messaggio che Amazon Lex utilizza per ottenere il valore di slot.

Opzioni di distribuzione di bot

Attualmente, Amazon Lex fornisce le opzioni di distribuzione di bot seguenti:

• SDK AWS Mobile Puoi creare applicazioni mobili che comunicano con – utilizzando Amazon Lex AWS Mobile.SDKs • Facebook Messenger – Puoi integrare la tua pagina Facebook Messenger con il tuo bot di Amazon Lex in modo che gli utenti finali su Facebook possano comunicare con il bot. Nell'implementazione corrente, questa integrazione supporta solo messaggi di input di testo. • Slack – Puoi integrare il tuo bot di Amazon Lex con un'applicazione di messaggistica Slack. • Twilio – Puoi integrare il tuo bot di Amazon Lex con il Simple Messaging Service (SMS) di Twilio.

Per alcuni esempi, consulta Deploying Amazon Lex Bots (p. 151).

Intenti incorporati e tipi di slot

To make it easier to create bots, Amazon Lex allows you to use standard built-in intents and slot types.

Argomenti • Intenti incorporati (p. 43) • Tipi di slot integrati (p. 55)

Intenti incorporati

For common actions, you can use the standard built-in intents library. Per creare un intento a partire da un intento incorporato, scegli un intento incorporato nella console e assegnagli un nuovo nome. The new intent has the configuration of the base intent, such as the sample utterances.

Nell'implementazione corrente, non puoi effettuare le seguenti operazioni:

• Add or remove sample utterances from the base intent • Configurazione di slot per intenti incorporati

43 Amazon Lex Guida per gli sviluppatori Intenti incorporati

To add a built-in intent to a bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Choose the bot to add the built-in intent to. 3. Nel riquadro di navigazione scegliere il segno più (+) accanto a Intenti. 4. Per Aggiungi intento, scegliere Cerca intenti esistenti. 5. In the Search intents box, type the name of the built-in intent to add to your bot. 6. For Copy built-in intent, give the intent a name, and then choose Add. 7. Configure the intent as required for your bot.

Argomenti • AMAZON.CancelIntent (p. 44) • AMAZON.FallbackIntent (p. 44) • AMAZON.HelpIntent (p. 46) • AMAZON.KendraSearchIntent (p. 47) • AMAZON.PauseIntent (p. 53) • AMAZON.RepeatIntent (p. 54) • AMAZON.ResumeIntent (p. 54) • AMAZON.StartOverIntent (p. 54) • AMAZON.StopIntent (p. 54)

Note

For the English (US) (en-US) locale, Amazon Lex supports intents from the Alexa standard built- in intents. Per un elenco di intenti incorporati, consulta la sezione relativa agli intenti incorporati standard in Alexa Skills Kit. Amazon Lex non supporta i seguenti intenti:

• AMAZON.YesIntent • AMAZON.NoIntent • Gli intenti nella libreria di intenti incorporati in Alexa Skills Kit

AMAZON.CancelIntent

Responds to words and phrases that indicate the user wants to cancel the current interaction. Your application can use this intent to remove slot type values and other attributes before ending the interaction with the user.

Common utterances:

• cancel • never mind • forget it

AMAZON.FallbackIntent

Quando l'input di un utente a un intento non è quello previsto da un bot, puoi configurare Amazon Lex per invocare un intento di fallback. Ad esempio, se l'input utente "I like to order Candy" non corrisponde a un intento nel bot OrderFlowers, Amazon Lex richiama l'intento di fallback per gestire la risposta.

44 Amazon Lex Guida per gli sviluppatori Intenti incorporati

Puoi aggiungere un intento di fallback aggiungendo il tipo di intento AMAZON.FallbackIntent integrato al bot. Puoi specificare l'intento utilizzando l'operazione PutBot (p. 372) o scegliendo l'intento dall'elenco di intenti integrati nella console.

L'invocazione di un intento di fallback utilizza due fasi. Nella prima fase l'intento di fallback viene abbinato in base all'input dell'utente. Quando l'intento di fallback viene abbinato, il modo in cui il bot si comporta dipende dal numero di nuovi tentativi configurati per un prompt. Ad esempio, se il numero massimo di tentativi di determinare un intento è 2, il bot restituisce il prompt di chiarimento del bot due volte prima di richiamare l'intento di fallback.

Amazon Lex corrisponde all'intento di fallback in queste situazioni:

• L'input dell'utente a un intento non corrisponde all'input previsto dal bot • L'input audio è un rumore o l'input di testo non viene riconosciuto come parole. • L'input dell'utente è ambiguo e Amazon Lex non è in grado di determinare quale intento richiamare.

L'intento di fallback viene richiamato quando:

• Il bot non riconosce l'input utente come intento dopo il numero configurato di tentativi di chiarimento quando la conversazione viene avviata. • Un intento non riconosce l'input utente come valore di slot dopo il numero di tentativi configurato. • Un intento non riconosce l'input utente come risposta a un prompt di conferma dopo il numero di tentativi configurato.

Puoi utilizzare quanto segue con un intento di fallback:

• Una funzione Lambda di adempimento • Istruzione di conclusione • Un prompt di follow-up

Non puoi aggiungere quanto segue a un intento di fallback:

• Enunciazioni • Slot • Una funzione Lambda di inizializzazione e convalida • Prompt di conferma

If you have configured both a cancel statement and a fallback intent for a bot, Amazon Lex uses the fallback intent. If you need your bot to have a cancel statement, you can use the fulfillment function for the fallback intent to provide the same behavior as a cancel statement. Per ulteriori informazioni, consulta il parametro abortStatement dell'operazione PutBot (p. 372). Utilizzo dei prompt di chiarimento

Se fornisci al bot una richiesta di chiarimento, il prompt viene utilizzato per richiedere un intento valido all'utente. Il prompt di chiarimento verrà ripetuto per il numero di volte che hai configurato. Dopodiché verrà richiamato l'intento di fallback.

Se non imposti un prompt di chiarimento quando crei un bot e l'utente non avvia la conversazione con un intento valido, Amazon Lex chiama immediatamente l'intento di fallback.

Quando utilizzi un intento di fallback senza un prompt di chiarimento, Amazon Lex non chiama il fallback in questi casi:

45 Amazon Lex Guida per gli sviluppatori Intenti incorporati

• Quando l'utente risponde a un prompt di follow-up ma non fornisce un intento. For example, in response to a follow-up prompt that says "Would you like anything else today?", the user says "Yes." Amazon Lex returns a 400 Bad Request exception because it doesn't have a clarification prompt to send to the user to get an intent. • Quando si utilizza una funzione AWS Lambda, si restituisce un tipo di finestra di dialogo ElicitIntent. Poiché Amazon Lex non dispone di un prompt di chiarimento per ottenere un intento dall'utente, restituisce un'eccezione 400 Bad Request (Richiesta non valida). • Quando utilizzi l'operazione PutSession, invii un tipo di finestra di dialogo ElicitIntent. Poiché Amazon Lex non dispone di un prompt di chiarimento per ottenere un intento dall'utente, restituisce un'eccezione 400 Bad Request (Richiesta non valida).

Utilizzo di una funzione Lambda con un intento di fallback

Quando viene richiamato un intento di fallback, la risposta dipende dall'impostazione del parametro fulfillmentActivity per l'operazione PutIntent (p. 388). Il bot esegue una delle seguenti operazioni:

• Restituisce le informazioni sull'intento all'applicazione client. • Chiama la funzione Lambda di adempimento. Chiama la funzione con le variabili di sessione impostate per la sessione.

Per ulteriori informazioni sull'impostazione della risposta quando viene richiamato un intento di fallback, consulta il parametro fulfillmentActivity dell'operazione PutIntent (p. 388).

Se utilizzi la funzione Lambda di adempimento nel tuo intento di fallback, puoi utilizzare questa funzione per chiamare un altro intento o per stabilire una forma di comunicazione con l'utente, ad esempio la raccolta di un numero di callback o l'apertura di una sessione con un rappresentante del servizio clienti.

Puoi svolgere qualsiasi operazione in una funzione Lambda di intento di fallback che puoi eseguire nella funzione di adempimento per qualsiasi altro intento. Per ulteriori informazioni sulla creazione di una funzione di adempimento tramite AWS Lambda, consulta Utilizzo delle funzioni Lambda (p. 140).

Un intento di fallback può essere richiamato più volte nella stessa sessione. Ad esempio, supponiamo che la funzione Lambda utilizzi l'operazione della finestra di dialogo ElicitIntent per richiedere all'utente un intento diverso. Se Amazon Lex non è in grado di dedurre l'intento dell'utente dopo il numero di tentativi configurato, richiama di nuovo l'intento di fallback. Richiama inoltre l'intento di fallback quando l'utente non risponde con un valore di slot valido dopo il numero di tentativi configurato.

È possibile configurare una funzione Lambda per tenere traccia del numero di volte in cui l'intento di fallback viene chiamato utilizzando una variabile di sessione. La funzione Lambda può eseguire un'operazione diversa se viene chiamata più volte rispetto alla soglia impostata nella funzione Lambda. Per ulteriori informazioni sulle variabili di sessione, consulta Impostazione degli attributi di sessione (p. 23). AMAZON.HelpIntent

Responds to words or phrases that indicate the user needs help while interacting with your bot. When this intent is invoked, you can configure your Lambda function or application to provide information about the your bot's capabilities, ask follow up questions about areas of help, or hand the interaction over to a human agent.

Common utterances:

• help • help me • can you help me

46 Amazon Lex Guida per gli sviluppatori Intenti incorporati

AMAZON.KendraSearchIntent

Per cercare i documenti indicizzati con Amazon Kendra, utilizzare l'intento AMAZON.KendraSearchIntent. Quando Amazon Lex non riesce a determinare l'operazione successiva in una conversazione con l'utente, attiva l'intento di ricerca.

The AMAZON.KendraSearchIntent is available only in the English (US) (en-US) locale.

Amazon Kendra è un servizio di ricerca basato sul machine learning che indicizza documenti in linguaggio naturale come documenti PDF o file di Microsoft Word. Può ricercare documenti indicizzati e restituire i seguenti tipi di risposte a una domanda:

• Una risposta • Una voce da una domanda frequente che potrebbe rispondere alla domanda • Un documento correlato alla domanda

Per un esempio di utilizzo di AMAZON.KendraSearchIntent, consulta Esempio: creazione di un bot di domande frequenti per un indice Amazon Kendra (p. 52).

Se configuri un intento AMAZON.KendraSearchIntent per il bot, Amazon Lex richiama l'intento ogni volta che non è in grado di determinare l'enunciazione dell'utente per uno slot o un intento. Ad esempio, se il bot sta richiedendo una risposta per un tipo di slot chiamato "condimento per la pizza" e l'utente dice "Cos'è una pizza?", Amazon Lex richiama AMAZON.KendraSearchIntent per gestire la domanda. Se non c'è risposta da Amazon Kendra, la conversazione continua nel modo configurato nel bot.

Quando si utilizza sia AMAZON.KendraSearchIntent che AMAZON.FallbackIntent nello stesso bot, Amazon Lex utilizza gli intenti come segue:

1. Amazon Lex calls the AMAZON.KendraSearchIntent. L'intento richiama l'operazione Amazon Kendra Query 2. Se Amazon Kendra restituisce una risposta, Amazon Lex mostra il risultato all'utente. 3. Se non vi è alcuna risposta da Amazon Kendra, Amazon Lex ripete la richiesta all'utente. L'operazione successiva dipende dalla risposta dell'utente. • Se la risposta dell'utente contiene un'enunciazione che Amazon Lex riconosce, ad esempio il riempimento di un valore di slot o la conferma di un intento, la conversazione con l'utente procede nel modo configurato per il bot. • Se la risposta dell'utente non contiene un'enunciazione che Amazon Lex riconosce, Amazon Lex effettua un'altra chiamata all'operazione Query. 4. Se non vi è alcuna risposta dopo il numero di tentativi configurato, Amazon Lex richiama AMAZON.FallbackIntent e termina la conversazione con l'utente.

Esistono tre modi per utilizzare AMAZON.KendraSearchIntent per effettuare una richiesta a Amazon Kendra:

• Lasciare che l'intento di ricerca faccia la richiesta per conto dell'utente. Amazon Lex richiama Amazon Kendra con l'enunciazione dell'utente come stringa di ricerca. Quando si crea l'intento, è possibile definire una stringa di filtro di query che limita il numero di risposte restituite da Amazon Kendra. Amazon Lex utilizza il filtro nella richiesta di query. • Add additional query parameters to the request to narrow the search results using your dialog Lambda function. È possibile aggiungere un campo kendraQueryFilterString che contiene parametri di query Amazon Kendra all'operazione di dialogo delegate. Quando si aggiungono parametri di query alla richiesta con la funzione Lambda, questi hanno la precedenza sul filtro di query definito al momento della creazione dell'intento. • Creare una nuova query utilizzando la funzione Lambda di dialogo. È possibile creare una richiesta di query Amazon Kendra completa che viene inviata da Amazon Lex. È possibile specificare la

47 Amazon Lex Guida per gli sviluppatori Intenti incorporati

query nel campo kendraQueryRequestPayload dell'operazione di dialogo delegate. Il campo kendraQueryRequestPayload ha la precedenza sul campo kendraQueryFilterString.

Per specificare il parametro queryFilterString quando si crea un bot o per specificare il campo kendraQueryFilterString quando si chiama l'operazione delegate in una funzione Lambda di dialogo, è necessario specificare una stringa utilizzata come filtro di attributi per la query Amazon Kendra. Se la stringa non è un filtro di attributo valido, si otterrà un'eccezione InvalidBotConfigException in fase di runtime. Per ulteriori informazioni sui filtri degli attributi, consulta l'argomento relativo all'utilizzo degli attributi dei documenti per filtrare le query nella Guida per gli sviluppatori di Amazon Kendra.

Per avere il controllo sulla query che Amazon Lex invia a Amazon Kendra, è possibile specificare una query nel campo kendraQueryRequestPayload della funzione Lambda di dialogo. Se la query non è valida, Amazon Lex restituisce un'eccezione InvalidLambdaResponseException. Per ulteriori informazioni, vedere l' operazione Query nella GuidaAmazon Kendra per gli sviluppatori.

Per un esempio di come utilizzare AMAZON.KendraSearchIntent, consulta Esempio: creazione di un bot di domande frequenti per un indice Amazon Kendra (p. 52).

Policy IAM per la ricerca Amazon Kendra

Per utilizzare l'intento AMAZON.KendraSearchIntent, è necessario utilizzare un ruolo che fornisca le policy AWS Identity and Access Management (IAM) che consentano a Amazon Lex assumere un ruolo runtime che dispone dell'autorizzazione per richiamare l'intento Amazon Kendra Query. Le impostazioni IAM utilizzate dipendono dal fatto che si crei AMAZON.KendraSearchIntent mediante la console Amazon Lex o utilizzando un SDK AWS o l'AWS Command Line Interface (AWS CLI). Quando si utilizza la console, è possibile scegliere se aggiungere l'autorizzazione per richiamare Amazon Kendra al ruolo collegato ai servizi Amazon Lex o se utilizzare un ruolo specifico per richiamare l'operazione Amazon Kendra Query. Quando si utilizza l'AWS CLI o un SDK per creare l'intento, è necessario utilizzare un ruolo specifico per richiamare l'operazione Query.

Collegamento di autorizzazioni

È possibile utilizzare la console per collegare le autorizzazioni per accedere all'operazione Amazon Kendra Query al ruolo Amazon Lex collegato ai servizi predefinito. Quando si collegano autorizzazioni al ruolo collegato ai servizi, non è necessario creare e gestire un ruolo runtime specifico per connettersi all'indice Amazon Kendra.

L'utente, il ruolo o il gruppo utilizzato per accedere alla console Amazon Lex deve disporre delle autorizzazioni per gestire le policy dei ruoli. Collegare la seguente policy IAM al ruolo di accesso della console. Quando si concedono queste autorizzazioni, il ruolo dispone delle autorizzazioni necessarie per modificare la policy del ruolo collegato ai servizi esistente.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "iam:AttachRolePolicy", "iam:PutRolePolicy", "iam:GetRolePolicy" ], "Resource": "arn:aws:iam::*:role/aws-service-role/lex.amazonaws.com/ AWSServiceRoleForLexBots" }, { "Effect": "Allow", "Action": "iam:ListRoles", "Resource": "*"

48 Amazon Lex Guida per gli sviluppatori Intenti incorporati

} ] }

Specifica di un ruolo

È possibile utilizzare la console, l'AWS CLI o l'API per specificare un ruolo runtime da utilizzare quando si richiama l'operazione Amazon Kendra Query.

L'utente, il ruolo o il gruppo IAM utilizzato per specificare il ruolo runtime deve disporre dell'autorizzazione iam:PassRole. La policy seguente definisce l'autorizzazione. È possibile utilizzare le chiavi di contesto di condizione iam:AssociatedResourceArn e iam:PassedToService per limitare ulteriormente l'ambito delle autorizzazioni. Per ulteriori informazioni, consulta Chiavi del contesto di condizione IAM e AWS STS nella Guida per l'utente AWS Identity and Access Management.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::account:role/role" } ] }

Il ruolo runtime che Amazon Lex deve utilizzare per richiamare Amazon Kendra deve disporre delle autorizzazioni kendra:Query. Quando si utilizza un ruolo IAM esistente per l'autorizzazione a richiamare l'operazione Amazon Kendra Query, al ruolo deve essere collegata la policy seguente.

È possibile utilizzare la console IAM, l'API IAM o l'AWS CLI per creare una policy e collegarla a un ruolo. Queste istruzioni utilizzano l'AWS CLI per creare il ruolo e le policy. Note

Il codice seguente è formattato per Linux e MacOS. Per Windows, sostituire il carattere di continuazione della riga di Linux (\) con un accento circonflesso (^).

Per aggiungere l'autorizzazione per l'operazione Query a un ruolo

1. Creare un documento denominato KendraQueryPolicy.json nella directory corrente, aggiungervi il seguente codice e salvarlo

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "kendra:Query" ], "Resource": [ "arn:aws:kendra:region:account:index/index ID" ] } ] }

2. In AWS CLI, eseguire il comando seguente per creare la policy IAM per l'esecuzione dell'operazione Amazon Kendra Query.

49 Amazon Lex Guida per gli sviluppatori Intenti incorporati

aws iam create-policy \ --policy-name query-policy-name \ --policy-document file://KendraQueryPolicy.json

3. Collegare la policy al ruolo IAM utilizzato per richiamare l'operazione Query.

aws iam attach-role-policy \ --policy-arn arn:aws:iam::account-id:policy/query-policy-name --role-name role-name

È possibile scegliere di aggiornare il ruolo Amazon Lex collegato ai servizi o di utilizzare un ruolo creato al momento della creazione di AMAZON.KendraSearchIntent per il bot. Nella procedura seguente viene illustrato come scegliere il ruolo IAM da utilizzare.

Per specificare il ruolo runtime per AMAZON.KendraSearchIntent

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere il bot a cui si desidera aggiungere AMAZON.KendraSearchIntent. 3. Scegliete il segno più (+) accanto a Intenti. 4. In Aggiungi intento, scegliere Cerca intenti esistenti. 5. In Intenti di ricerca, immettere AMAZON.KendraSearchIntent e quindi scegliere Aggiungi. 6. In Copia intento integrato, immettere un nome per l'intento, ad esempio KendraSearchIntent, quindi scegliere Aggiungi. 7. Aprire la sezione Query Amazon Kendra. 8. In Ruolo IAM, scegliere una delle seguenti opzioni:

• Per aggiornare il ruolo Amazon Lex collegato ai servizi per consentire al bot di eseguire query sugli indici Amazon Kendra, scegliere Aggiungi autorizzazioni Amazon Kendra. • Per utilizzare un ruolo che dispone dell'autorizzazione per chiamare l'operazione Amazon Kendra Query, scegliere Utilizza un ruolo esistente.

Utilizzo degli attributi di richiesta e di sessione come filtri

Per filtrare la risposta da Amazon Kendra alle voci correlate alla conversazione corrente, usa gli attributi di sessione e di richiesta come filtri aggiungendo il parametro queryFilterString durante la creazione del bot. Quando si crea l'intento, è necessario specificare un segnaposto per l'attributo, quindi Amazon Lex sostituisce un valore prima di richiamare Amazon Kendra. Per ulteriori informazioni sugli attributi di richiesta, consulta Impostazione degli attributi di richiesta (p. 24). Per ulteriori informazioni sugli attributi di sessione, consulta Impostazione degli attributi di sessione (p. 23).

Di seguito è riportato un esempio di un parametro queryFilterString che utilizza un attributo di sessione denominato "DocumentType" per filtrare la query Amazon Kendra.

"{\"equalsTo\": {\"key\": \"Type\", \"value\": {\"stringValue\": \"[DocumentType]\"}}}"

Di seguito è riportato un esempio di un parametro queryFilterString che utilizza un attributo di richiesta denominato "DepartmentName" per filtrare la query Amazon Kendra.

"{\"equalsTo\": {\"key\": \"Department\", \"value\": {\"stringValue\": \"((DepartmentName))\"}}}"

50 Amazon Lex Guida per gli sviluppatori Intenti incorporati

Utilizzo della risposta di ricerca

Amazon Kendra restituisce la risposta a una ricerca nell'istruzione conclusion dell'intento. L'intento deve avere un'istruzione conclusion a meno che una funzione Lambda di adempimento non produca un messaggio di conclusione.

Amazon Kendra ha quattro tipi di risposte.

• x-amz-lex:kendra-search-response-question_answer-question- – The question from a FAQ that matches the search. • x-amz-lex:kendra-search-response-question_answer-answer- – The answer from a FAQ that matches the search. • x-amz-lex:kendra-search-response-document- – An excerpt from a document in the index that is related to the text of the utterance. • x-amz-lex:kendra-search-response-answer- – An excerpt from a document in the index that answers the question.

Le risposte vengono restituite in attributi request. Possono esserci fino a cinque risposte per ogni attributo, numerate da 1 a 5. Per ulteriori informazioni sulle risposte, consulta l'argomento relativo ai tipi di risposta nella Guida per gli sviluppatori di Amazon Kendra.

L'istruzione conclusion deve avere uno o più gruppi di messaggi. Ogni gruppo di messaggi contiene uno o più messaggi. Ogni messaggio può contenere una o più variabili segnaposto che vengono sostituite dagli attributi di richiesta nella risposta da Amazon Kendra. Nel gruppo di messaggi deve essere presente almeno un messaggio in cui tutte le variabili del messaggio vengono sostituite dai valori degli attributi di richiesta nella risposta runtime oppure nel gruppo deve essere presente un messaggio senza variabili segnaposto. Gli attributi della richiesta sono impostati con doppie parentesi ("((" "))"). I seguenti messaggi del gruppo di messaggi corrispondono a qualsiasi risposta da Amazon Kendra:

• "Ho trovato una domanda frequente per te: ((x-amz-lex:kendra-search-response-question_answer- question-1)), e la risposta è ((x-amz-lex:kendra-search-response-question_answer-answer er-1))" • "Ho trovato un estratto da un documento utile: ((x-amz-lex:kendra-search-response-document-1))" • "Penso che la risposta alle tue domande sia ((x-amz-lex:kendra-search-response-answer-1))"

Utilizzo di una funzione Lambda per gestire la richiesta e la risposta

L'intento AMAZON.KendraSearchIntent può utilizzare l'hook del codice di dialogo e l'hook del codice di adempimento per gestire la richiesta a Amazon Kendra e la risposta. Utilizzare la funzione Lambda di hook del codice di dialogo quando si desidera modificare la query inviata a Amazon Kendra e la funzione Lambda di hook del codice di adempimento quando si desidera modificare la risposta.

Creazione di una query con l'hook del codice di dialogo

È possibile utilizzare l'hook del codice di dialogo per creare una query da inviare a Amazon Kendra. L'utilizzo dell'hook del codice di dialogo è facoltativo. Se non si specifica un hook del codice di dialogo, Amazon Lex costruisce una query dall'enunciazione dell'utente e utilizza queryFilterString fornito al momento della configurazione dell'intento, se ne è stato fornito uno.

È possibile utilizzare due campi nella risposta dell'hook del codice di dialogo per modificare la richiesta a Amazon Kendra:

• kendraQueryFilterString – Use this string to specify attribute filters for the Amazon Kendra request. È possibile filtrare la query utilizzando uno qualsiasi dei campi di indice definiti nell'indice. Per informazioni sulla struttura della stringa del filtro, consulta l'argomento relativo all'utilizzo degli attributi del documento per filtrare le query nella Guida per gli sviluppatori di Amazon Kendra. Se la stringa del filtro specificata non è valida, si otterrà un'eccezione InvalidLambdaResponseException.

51 Amazon Lex Guida per gli sviluppatori Intenti incorporati

La stringa kendraQueryFilterString sovrascrive qualsiasi stringa di query specificata in queryFilterString configurato per l'intento. • kendraQueryRequestPayload – Use this string to specify an Amazon Kendra query. La query può utilizzare una qualsiasi delle caratteristiche di Amazon Kendra. Se non si specifica una query valida, si ottiene un'eccezione InvalidLambdaResponseException. Per ulteriori informazioni, consulta Query nella Guida per gli sviluppatori di Amazon Kendra.

Dopo aver creato il filtro o la stringa di query, inviare la risposta a Amazon Lex con il campo dialogAction della risposta impostato su delegate. Amazon Lex invia la query a Amazon Kendra e quindi restituisce la risposta alla query all'hook del codice di adempimento. Utilizzo dell'hook del codice di adempimento per la risposta

Dopo che Amazon Lex ha inviato una query a Amazon Kendra, la risposta alla query viene restituita alla funzione AMAZON.KendraSearchIntent di adempimento Lambda. L'evento di input per il codice hook contiene la risposta completa da Amazon Kendra. I dati della query si trovano nella stessa struttura restituita dall'operazione Amazon Kendra Query. Per ulteriori informazioni, consulta l'argomento relativo alla Sintassi delle risposte alle query nella Guida per gli sviluppatori di Amazon Kendra.

L'hook del codice di adempimento è facoltativo. Se non ne esiste uno o se il codice hook non restituisce un messaggio nella risposta, Amazon Lex utilizza l'istruzione conclusion per le risposte. Esempio: creazione di un bot di domande frequenti per un indice Amazon Kendra

In questo esempio viene creato un bot Amazon Lex che utilizza un indice Amazon Kendra per fornire risposte alle domande degli utenti. Il bot di domande frequenti gestisce la finestra di dialogo per l'utente. Esso utilizza l'intento AMAZON.KendraSearchIntent per eseguire query nell'indice e presentare la risposta all'utente. Per creare il bot:

1. Creare un bot con cui i clienti interagiranno per ottenere risposte dal bot. 2. Creare un intento personalizzato. Il bot richiede almeno un intento con almeno una enunciazione. Questo intento consente la c reazione del bot, ma non viene usato altrimenti. 3. Aggiungi l'intento KendraSearchIntent al bot e configuralo per funzionare con l'indice Amazon Kendra. 4. Esegui il test del bot ponendo domande a cui viene data risposta mediante documenti memorizzati nell'indice Amazon Kendra.

Prima di poter utilizzare questo esempio, è necessario creare un indice Amazon Kendra. Per ulteriori informazioni, consulta l'argomento relativo alle nozioni di base sul bucket S3 (console) nella Guida per gli sviluppatori di Amazon Kendra.

Per creare un bot di domande frequenti

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Nel riquadro di navigazione, scegliere Bot. 3. Selezionare Create (Crea). 4. Seleziona Custom bot (Bot personalizzato). Configurare il bot come segue:

• Bot name – Give the bot a name that indicates its purpose, such as KendraTestBot. • Output voice – Choose None. • Session timeout – Enter 5. • Sentiment analysis – Choose No. • COPPA – Choose No. • User utterance storage – Choose Do not store.

52 Amazon Lex Guida per gli sviluppatori Intenti incorporati

5. Selezionare Create (Crea).

Per creare correttamente un bot, è necessario creare almeno un intento con almeno un enunciazione di esempio. Questo intento è necessario per creare il bot Amazon Lex, ma non viene utilizzato per la risposta alle domande frequenti. L'enunciazione per l'intento non deve essere applicata a nessuna delle domande poste dal cliente.

Per creare l'intento richiesto

1. Nella pagina Nozioni di base sul bot scegli Crea intento. 2. Per Aggiungi intento, scegli Crea intento. 3. Nella finestra di dialogo Crea intento assegna un nome all'intento, ad esempio RequiredIntent. 4. Per Enunciazioni di esempio, digitare un'enunciazione, ad esempio Required utterance. 5. Scegliere Salva intento.

Ora, creare l'intento per eseguire ricerche in un indice Amazon Kendra e i messaggi di risposta che dovrebbe restituire.

Per creare un messaggio di intento e risposta AMAZON.KendraSearchIntent

1. Nel riquadro di navigazione scegliere il segno più (+) accanto a Intenti. 2. Per Aggiungi intento, scegliere Cerca intenti esistenti. 3. In the Search intents box, enter AMAZON.KendraSearchIntent, then choose it from the list. 4. Per Copia intento integrato, assegnare un nome all'intento, ad esempio KendraSearchIntent, quindi scegliere Aggiungi. 5. Nell'editor degli intenti, scegli Query Amazon Kendra per aprire le opzioni delle query. 6. Dal menu Indice Amazon Kendra scegli l'indice che desideri venga ricercato dall'intento. 7. Nella sezione Risposta aggiungere i seguenti tre messaggi:

I found a FAQ question for you: ((x-amz-lex:kendra-search-response-question_answer- question-1)) and the answer is ((x-amz-lex:kendra-search-response-question_answer- answer-1)). I found an excerpt from a helpful document: ((x-amz-lex:kendra-search-response- document-1)). I think the answer to your questions is ((x-amz-lex:kendra-search-response-answer-1)).

8. Selezionare Salva intento, quindi Crea per creare il bot.

Infine, usa la finestra di test della console per testare le risposte dal bot. Le domande dovrebbero trovarsi nel dominio supportato dall'indice.

Per testare il bot di domande frequenti

1. Nella finestra di test della console, digitare una domanda per l'indice. 2. Verificare la risposta nella sezione delle risposte della finestra di test. 3. Per reimpostare la finestra di test per un'altra domanda, scegli Cancella cronologia chat.

AMAZON.PauseIntent

Responds to words and phrases that enable the user to pause an interaction with a bot so that they can return to it later. Your Lambda function or application needs to save intent data in session variables, or

53 Amazon Lex Guida per gli sviluppatori Intenti incorporati you need to use the GetSession (p. 421) operation to retrieve intent data when you resume the current intent.

Common utterances:

• pause • pause that

AMAZON.RepeatIntent

Responds to words and phrases that enable the user to repeat the previous message. Your application needs to use a Lambda function to save the previous intent information in session variables, or you need to use the GetSession (p. 421) operation to get the previous intent information.

Common utterances:

• repeat • say that again • repeat that

AMAZON.ResumeIntent

Responds to words and phrases the enable the user to resume a previously paused intent. You Lambda function or application must manage the information required to resume the previous intent.

Common utterances:

• resume • continue • keep going

AMAZON.StartOverIntent

Responds to words and phrases that enable the user to stop processing the current intent and start over from the beginning. You can use your Lambda function or the PutSession operation to elicit the first slot value again.

Common utterances:

• start over • restart • start again

AMAZON.StopIntent

Responds to words and phrases that indicate that the user wants to stop processing the current intent and end the interaction with a bot. Your Lambda function or application should clear any existing attributes and slot type values and then end the interaction.

Common utterances:

• arresta

54 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

• off • shut up

Tipi di slot integrati

Amazon Lex supports built-in slot types that define how data in the slot is recognized and handled. Puoi creare slot di questi tipi nei tuoi intenti. In questo modo, si elimina la necessità di creare valori di enumerazione per dati di slot utilizzati più frequentemente come data, ora e posizione. I tipi di slot integrati non hanno versioni.

Tipo di slot Breve descrizione Impostazioni locali supportate

AMAZON.Airport (p. 56) Recognizes words that All locales represent an airport.

AMAZON.AlphaNumeric (p.Riconosce 56) parole All locales costituite da lettere e numeri.

AMAZON.City (p. 57) Recognizes words that All locales except represent a city. English (US)

AMAZON.Country (p. 58) Recognizes words that All locales represent a country.

AMAZON.DATE (p. 58) Recognizes words that All locales represent a date and converts them to a standard format.

AMAZON.DURATION (p. 58Recognizes) words that All locales represent duration and converts them to a standard format.

AMAZON.EmailAddress (p.Recognizes 58) words that All locales represent an email address and converts them into a standard email address.

AMAZON.FirstName (p. 59Recognizes) words that All locales except represent a first name. English (US)

AMAZON.LastName (p. 59Recognizes) words that All locales except represent a last name. English (US)

AMAZON.NUMBER (p. 59)Recognizes numeric All locales words and converts them into digits.

AMAZON.Percentage (p. 59Recognizes) words that All locales represent a percentage and converts them to a number and a percent sign (%).

55 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

Tipo di slot Breve descrizione Impostazioni locali supportate

AMAZON.PhoneNumber (p.Recognizes 60) words All locales that represent a phone number and converts them into a numeric string.

AMAZON.SpeedUnit (p. 60Recognizes) words that Inglese (Stati Uniti) represent a speed unit and converts them into a standard abbreviation.

AMAZON.State (p. 61) Recognizes words that All locales except represent a state. English (US)

AMAZON.StreetName (p. 61Recognizes) words that All locales except represent a street name. English (US)

AMAZON.TIME (p. 61) Recognizes words All locales that indicate times and converts them into a time format.

AMAZON.WeightUnit (p. 62Recognizes) words that Inglese (Stati Uniti) represent a weight unit and converts them into a standard abbreviation

Note

For the English (US) (en-US) locale, Amazon Lex supports slot types from the Alexa Skill Kit. Per un elenco dei tipi di slot integrati, consultare la sezione di riferimento ai tipi di slot nella documentazione dell'Alexa Skills Kit.

• Amazon Lex non supporta i tipi di slot integrati AMAZON.LITERAL o AMAZON.SearchQuery.

AMAZON.Airport

Provides a list of airports. Esempi includono:

• John F. Kennedy International Airport • Melbourne Airport

AMAZON.AlphaNumeric

Riconosce stringhe costituite da lettere e numeri, ad esempio APQ123.

È possibile utilizzare il tipo di slot AMAZON.AlphaNumeric per stringhe che contengono:

• Caratteri alfabetici, come ABC • Caratteri numerici, come 123 • Una combinazione di caratteri alfanumerici, come ABC123

56 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

È possibile aggiungere un'espressione regolare al tipo di slot AMAZON.AlphaNumeric per convalidare i valori inseriti per lo slot. Ad esempio, è possibile utilizzare un'espressione regolare per convalidare:

• Codici postali del Regno Unito o del Canada • Numeri della patente di guida • Numeri di identificazione del veicolo

Utilizzare un'espressione regolare standard. Amazon Lex supporta i seguenti caratteri nell'espressione regolare:

• A-Z, a-z • 0-9

Amazon Lex supporta anche i caratteri Unicode nelle espressioni regolari. La forma è \uUnicode. Utilizzare quattro cifre per rappresentare i caratteri Unicode. Ad esempio, [\u0041-\u005A] è uguale a [A-Z].

I seguenti operatori di espressioni regolari non sono supportati:

• Ripetitori infiniti: *, + o {x,} senza limite superiore. • Wild card (.)

La lunghezza massima dell'espressione regolare è di 100 caratteri. La lunghezza massima di una stringa memorizzata in un tipo di slot AMAZON.AlphaNumeric che utilizza un'espressione regolare è di 30 caratteri.

Di seguito sono riportate alcune espressioni regolari di esempio.

• Stringhe alfanumeriche, ad esempio APQ123 o APQ1: [A-Z]{3}[0-9]{1,3} o un più vincolate [A- DP-T]{3} [1-5]{1,3} • Formato US Postal Service Priority Mail International, quali CP123456789US: CP[0-9]{9}US • Numeri di routing bancari, quali 123456789: [0-9]{9}

Per impostare l'espressione regolare per un tipo di slot, utilizzare la console o l'operazione PutSlotType (p. 400). L'espressione regolare viene convalidata quando si salva il tipo di slot. Se l'espressione non è valida, Amazon Lex restituisce un messaggio di errore.

Quando si utilizza un'espressione regolare in un tipo di slot, Amazon Lex controlla l'input di slot di quel tipo rispetto all'espressione regolare. Se l'input corrisponde all'espressione, il valore viene accettato per lo slot. Se l'input non corrisponde, Amazon Lex richiede all'utente di ripetere l'input. AMAZON.City

Provides a list of local and world cities. The slot type recognizes common variations of city names. Amazon Lex doesn't convert from a variation to an official name.

This slot type is not available in the English (US) (en-US) locale.

Esempi:

• New York • Reykjavik • Tokyo • Versailles

57 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

AMAZON.Country

The names of countries around the world. Esempi:

• Australia • Germania • Giappone • Stati Uniti • Uruguay

AMAZON.DATE

Converts words that represent dates into a date format.

The date is provided to your intent in ISO-8601 date format. The date that your intent receives in the slot can vary depending on the specific phrase uttered by the user.

• Utterances that map to a specific date, such as "today," "now," or "November twenty-fifth," convert to a complete date: 2020-11-25. This defaults to dates on or after the current date. • Utterances that map to a specific week, such as "this week," or "next week," convert to the date of the first day of the week. In ISO-8601 format, the week starts on Monday and ends on Sunday. For example, if today is 2020-11-25, "next week" converts to 2020-11-30. • Utterances that map to a month, but not a specific day, such as "next month," convert to the last day of the month. For example, if today is 2020-11-25, "next month" converts to 2020-12-31. • Utterances that map to a year, but not a specific month or day, such as "next year," convert to the last day of the following year. For example, if today is 2020-11-25, "next year" converts to 2021-12-31.

AMAZON.DURATION

Converts words that indicate durations into a numeric duration.

The duration is resolved to a format based on the ISO-8601 duration format, PnYnMnWnDTnHnMnS. The P indicates that this is a duration, the n is a numeric value, and the capital letter following the n is the specific date or time element. For example, P3D means 3 days. A T is used to indicate that the remaining values represent time elements rather than date elements.

Esempi:

• "ten minutes": PT10M • "five hours": PT5H • "three days": P3D • "forty five seconds": PT45S • "eight weeks": P8W • "seven years": P7Y • "five hours ten minutes": PT5H10M • "two years three hours ten minutes": P2YT3H10M

AMAZON.EmailAddress

Riconosce parole che rappresentano un indirizzo e-mail fornito come nomeutente@dominio. Gli indirizzi possono includere i seguenti caratteri speciali in un nome utente: sottolineatura (_), trattino (-), punto (.) e il segno più (+).

58 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

AMAZON.FirstName

Commonly used first names. This slot type recognizes both formal names and informal nicknames. The name sent to your intent is the value sent by the user. Amazon Lex doesn't convert from the nick name to the formal name.

For first names that sound alike but are spelled differently, Amazon Lex sends your intent a single common form.

This slot type is not available in the English (US) (en-US) locale.

Esempi:

• Emily • John • Sophie

AMAZON.LastName

Commonly used last names. For names that sound alike that are spelled differently, Amazon Lex sends your intent a single common form.

This slot type is not available in the English (US) (en-US) locale.

Esempi:

• Brosky • Dasher • Evers • Parres • Welt

AMAZON.NUMBER

Converts words or numbers that express a number into digits, including decimal numbers. La tabella seguente mostra come il tipo di slot AMAZON.NUMBER acquisisce parole numeriche.

Input Risposta centoventitre punto quattro cinque 123.45 centoventitre punto quattro cinque 123.45 punto quattro due 0.42 punto quarantadue 0.42

232.998 232.998

50 50

AMAZON.Percentage

Converte parole e simboli che rappresentano una percentuale in un valore numerico con un segno di percentuale (%).

59 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

Se l'utente immette un numero senza un segno di percentuale o le parole "percent", il valore di slot è impostato sul numero. La tabella seguente mostra come il tipo di slot AMAZON.Percentage acquisisce le percentuali.

Input Risposta

50 per cento 50%

0.4 percent 0.4%

23.5% 23.5% twenty five percent 25%

AMAZON.PhoneNumber

Converte numeri o parole che rappresentano un numero di telefono in un formato stringa senza punteggiatura come segue.

Type (Tipo) Descrizione Input Risultato

Numero internazionale Numero di 11 cifre con +61 7 4445 1061 +61744431061 con un segno più (+) un segno più all'inizio. all'inizio +1 (509) 555-1212 +15095551212

Numero internazionale Numero a 11 cifre senza 1 (509) 555-1212 15095551212 senza un segno più (+) un segno più all'inizio all'inizio 61 7 4445 1061 61744451061

Numero nazionale Numero a 10 cifre senza (03) 5115 4444 0351154444 prefisso internazionale (509) 555-1212 5095551212

Numero locale Numero di telefono a 555-1212 5551212 7 cifre senza prefisso internazionale o indicativo di località

AMAZON.SpeedUnit

Converte parole che rappresentano unità di velocità in un'abbreviazione corrispondente. Ad esempio, "miles per hour" viene convertito in mph.

This slot type is available only in the English (US) (en-US) locale.

I seguenti esempi mostrano come il tipo di slot AMAZON.SpeedUnit acquisisce unità di velocità.

Unità di velocità Abbreviazione miglia orarie, mph, MPH, m/h mph chilometri orari, km orari, kmph, KMPH, km/h kmph metri al secondo, mps, MPS, m/s mps

60 Amazon Lex Guida per gli sviluppatori Tipi di slot integrati

Unità di velocità Abbreviazione miglia nautiche orarie, nodi, nodo nodo

AMAZON.State

The names of geographical and political regions within countries.

This slot type isn't available in the English (US) (en-US) locale.

Esempi:

• Bavaria • Fukushima Prefecture • Pacific Northwest • Queensland • Wales

AMAZON.StreetName

The names of streets within a typical street address. This includes just the street name, not the house number.

This slot type isn't available in the English (US) (en-US) locale.

Esempi:

• Canberra Avenue • Front Street • Market Road

AMAZON.TIME

Converte parole che rappresentano ore in valori orari. Includes resolutions for ambiguous times. Quando un utente immette un'orario ambiguo, Amazon Lex utilizza l'attributo slotDetails di un evento Lambda per trasmettere risoluzioni per gli orari ambigui alla funzione Lambda. Ad esempio, se il tuo bot richiede all'utente un'ora di consegna, l'utente può rispondere dicendo "10 o'clock". Questo orario è ambiguo, in quanto può intendere le 10 di mattina o le 10 di sera. In questo caso, il valore nella mappa slots è null e l'entità slotDetails contiene le due risoluzioni possibili dell'orario. Amazon Lex introduce quanto segue nella funzione Lambda:

"slots": { "deliveryTime": null }, "slotDetails": { "deliveryTime": { "resolutions": [ { "value": "10:00" }, { "value": "22:00" } ] }

61 Amazon Lex Guida per gli sviluppatori Tipi di slot personalizzati

}

Quando l'utente risponde con un orario non ambiguo, Amazon Lex invia l'orario alla funzione Lambda nell'attributo slots dell'evento Lambda e l'attributo slotDetails è vuoto. Ad esempio, se l'utente risponde "10:00 PM" alla richiesta di un orario di consegna, Amazon Lex introduce quanto segue nella funzione Lambda:

"slots": { "deliveryTime": "22:00" }

Per ulteriori informazioni sui dati inviati da Amazon Lex a una funzione Lambda, consulta Formato dell'evento di input (p. 140). AMAZON.WeightUnit

Converte parole che rappresentano un'unità di peso nell'abbreviazione corrispondente. Ad esempio, "kilogram" viene convertito in kg.

This slot type is available only in the English (US) (en-US) locale.

Gli esempi seguenti mostrano come il tipo di slot AMAZON.WeightUnit acquisisce unità di peso:

Unità di peso Abbreviazione

chilogrammi, chili, kgs, KGS kg

grammi, gms, gm, GMS, g g

milligrammi, mg, mgs mg

libbre, lbs, LBS lbs

once, oz, OZ oz

tonnellata, t t

chilotonnellata, kt kt

Tipi di slot personalizzati

Per ogni intento, puoi specificare i parametri che indicano le informazioni necessarie all'intento per adempiere alla richiesta dell'utente. Questi parametri o slot sono di diversi tipi. Un tipo di slot è un elenco di valori che Amazon Lex utilizza per addestrare il modello di machine learning a riconoscere i valori per uno slot. Ad esempio, puoi definire un tipo di slot denominato "Genres." Ogni valore nel tipo di slot è il nome di un genere, "commedia", "avventura", "documentario", ecc. Puoi definire un sinonimo per un valore del tipo di slot. Ad esempio, puoi definire i sinonimi "divertente" e "spiritoso" per il valore "commedia".

Puoi configurare il tipo di slot per limitare la risoluzione ai valori di slot. I valori di slot saranno utilizzati come un'enumerazione e il valore immesso dall'utente determinerà il valore di slot solo se è uguale a uno dei valori di slot o un sinonimo. Un sinonimo determina il valore di slot corrispondente. Ad esempio, se l'utente immette "divertente" determinerà il valore di slot "commedia".

In alternativa, puoi configurare il tipo di slot per espandere i valori. I valori di slot saranno utilizzati come dati di addestramento e lo slot determina il valore fornito dall'utente se è simile ai valori e sinonimi dello slot. Questo è il comportamento predefinito.

62 Amazon Lex Guida per gli sviluppatori Offuscamento degli slot

Amazon Lex gestisce un elenco di possibili risoluzioni per uno slot. Ogni voce presente nell'elenco fornisce un valore di risoluzione che Amazon Lex ha riconosciuto come possibilità aggiuntive per lo slot. Un valore di risoluzione è un best effort per la corrispondenza del valore di slot. L'elenco contiene fino a cinque valori.

Quando un valore immesso dall'utente è un sinonimo, la prima voce nell'elenco dei valori di risoluzione è il valore del tipo di slot. Ad esempio, se l'utente immette "divertente" il campo slots contiene "divertente" e la prima voce nel campo slotDetails è "commedia". Puoi configurare il valueSelectionStrategy quando crei o aggiorni un tipo di slot con l'operazione PutSlotType (p. 400) in modo che il valore di slot venga compilato con il primo valore dell'elenco di risoluzione.

Se si utilizza una funzione Lambda, l'evento di input per la funzione include un elenco di risoluzioni denominato slotDetails. L'esempio seguente mostra la sezione dello slot e dei dettagli dello slot dell'input per una funzione Lambda:

"slots": { "MovieGenre": "funny"; }, "slotDetails": { "Movie": { "resolutions": [ "value": "comedy" ] } }

Per ogni tipo di slot, si possono definire un massimo di 10.000 valori e sinonimi. Ogni bot può includere un numero totale di 50.000 sinonimi e valori di tipi di slot. Ad esempio, è possibile avere 5 tipi di slot, ognuno con 5.000 valori e 5.000 sinonimi, oppure 10 slot, ognuno con 2.500 valori e 2.500 sinonimi. Se si superano questi limiti, si riceverà un LimitExceededException richiamando l'operazione PutBot (p. 372).

Offuscamento degli slot

Amazon Lex consente di offuscare (nascondere) il contenuto degli slot in modo che non sia visibile. Per proteggere i dati sensibili acquisiti come valori di slot, puoi abilitare l'offuscamento dello slot per mascherare tali valori nei log delle conversazioni.

Quando si sceglie di offuscare i valori degli slot, Amazon Lex sostituisce il valore dello slot con il nome dello slot nei log delle conversazioni. Per uno slot chiamato full_name, il valore dello slot verrebbe offuscato nel seguente modo:

Before obfuscation: My name is John Stiles After obfuscation: My name is {full_name}

Se un'enunciazione contiene delle parentesi ({}), Amazon Lex li sostituisce con due barre rovesciate (\\). Ad esempio, il testo {John Stiles} viene offuscato come segue:

Before obfuscation: My name is {John Stiles} After obfuscation: My name is \\{{full_name}\\}

I valori degli slot vengono offuscati nei log delle conversazioni. I valori di slot sono ancora disponibili nella risposta proveniente dalle operazioni PostContent e PostText, nonché per le funzioni Lambda

63 Amazon Lex Guida per gli sviluppatori Analisi delle emozioni

di convalida e di adempimento. Se si utilizzano valori di slot nei prompt o nelle risposte, tali valori non vengono offuscati nei log delle conversazioni.

Nel primo turno di una conversazione, Amazon Lex offusca i valori di slot se riconosce uno slot e un valore di slot nell'enunciazione. Se non viene riconosciuto alcun valore di slot, Amazon Lex non offusca l'enunciazione.

Nel secondo turno e nei successivi, Amazon Lex conosce lo slot da ottenere e se il valore dello slot deve essere offuscato. Se Amazon Lex riconosce il valore dello slot, il valore viene offuscato. Se Amazon Lex non riconosce un valore, l'intera enunciazione viene offuscata. Qualsiasi valore di slot in enunciazioni perse non verrà offuscato.

Amazon LexInoltre non offusca i valori di slot archiviati negli attributi di richiesta o di sessione. Se si archiviano valori di slot che devono essere offuscati come attributo, è necessario crittografare o nascondere in altro modo il valore.

Amazon Lex non offusca il valore dello slot nell'audio. Offusca il valore dello slot nella trascrizione audio.

Non è necessario offuscare tutti gli slot in un bot. È possibile scegliere quali slot offuscare utilizzando la console o l'API Amazon Lex. Nella console, selezionare Slot obfuscation (Offuscamento dello slot) nelle impostazioni di uno slot. Se si utilizza l'API, impostare il campo obfuscationSetting dello slot su DEFAULT_OBFUSCATION quando si invoca l'operazione PutIntent (p. 388).

Analisi delle emozioni

È possibile utilizzare l'analisi del sentiment per determinare i sentimenti espressi in un enunciato utente. Con le informazioni sulle emozioni è possibile gestire il flusso di conversazione o eseguire l'analisi post- chiamata. Ad esempio, se l'emozione dell’utente è negativa, è possibile creare un flusso per passare una conversazione a un agente umano.

Amazon Lex si integra con Amazon Comprehend per rilevare le emozioni dell'utente. La risposta da Amazon Comprehend indica se il sentimento generale del testo è positivo, neutro, negativo o misto. La risposta contiene l'emozione più probabile per l'enunciato utente e i punteggi per ciascuna delle categorie di emozioni. Il punteggio rappresenta la probabilità che l'emozione sia stata rilevata correttamente.

Si abilita l'analisi delle emozioni per un bot utilizzando la console o utilizzando l'API Amazon Lex. Sulla console Amazon Lex, scegliere la scheda Settings (Impostazioni) per il bot, quindi impostare l'opzione Sentiment Analysis (Analisi sentiment) su Yes (Sì). Se si utilizza l'API, chiamare l'operazione PutBot (p. 372) con il campo detectSentiment impostato su true.

Quando l'analisi del sentiment è abilitata, la risposta delle operazioni PostContent (p. 425) e PostText (p. 434) restituisce un campo chiamato sentimentResponse nella risposta bot con altri metadati. Il campo sentimentResponse ha due campi, SentimentLabel e SentimentScore, che contengono il risultato dell'analisi dell'emozione. Se si utilizza una funzione Lambda, il campo sentimentResponse è incluso nei dati dell'evento inviati alla funzione.

Di seguito è riportato un esempio del campo sentimentResponse restituito come parte della risposta PostText o PostContent. Il campo SentimentScore è una stringa che contiene i punteggi per la risposta.

{ "SentimentScore": "{ Mixed: 0.030585512690246105, Positive: 0.94992071056365967, Neutral: 0.0141543131828308, Negative: 0.00893945890665054 }", "SentimentLabel": "POSITIVE"

64 Amazon Lex Guida per gli sviluppatori Tagging di risorse

}

Amazon Lex chiama Amazon Comprehend per conto dell'utente per determinare l'emozione in ogni enunciato elaborato dal bot. Abilitando l'analisi delle emozioni, l'utente accetta i termini e i contratti relativi al servizio Amazon Comprehend. Per ulteriori informazioni sui prezzi di Amazon Comprehend, consulta Prezzi di Amazon Comprehend.

Per ulteriori informazioni sul funzionamento dell'analisi delle emozioni Amazon Comprehend, consulta Determinazione delle emozioni nella Guida per gli sviluppatori di Amazon Comprehend.

Tagging delle risorse Amazon Lex

Per gestire i bot Amazon Lex, gli alias bot e i canali bot, puoi assegnare i metadati a ciascuna risorsa sotto forma di tag. Un tag è un'etichetta che assegni a una risorsa AWS. Ciascun tag è formato da una chiave e da un valore,

I tag ti consentono di categorizzare le tue risorse AWS in modi diversi, ad esempio, per scopo, proprietario o applicazione. I tag ti aiutano a:

• Identificare e organizzare le risorse AWS. Molte risorse AWS supportano il tagging, perciò è possibile assegnare lo stesso tag a risorse di diversi servizi per indicare che queste sono correlate. Ad esempio, puoi contrassegnare un bot e le funzioni Lambda che utilizza con lo stesso tag. • Assegnare i costi. I tag vengono attivati nel pannello di controllo AWS Billing and Cost Management. AWS usa i tag per categorizzare i costi e fornire un report di allocazione dei costi mensili. Per Amazon Lex, puoi allocare i costi per ogni alias utilizzando i tag specifici dell'alias, ad eccezione dell'alias $LATEST. Allochi i costi per l'alias $LATEST utilizzando i tag per il bot Amazon Lex. Per ulteriori informazioni, consulta la pagina sull'utilizzo dei tag per l'allocazione dei costi nella Guida per l'utente di AWS Billing and Cost Management. • Controllare l'accesso alle risorse. Puoi utilizzare i tag in Amazon Lex per creare policy e controllare l'accesso alle risorse Amazon Lex. Queste policy possono essere collegate a un ruolo o a un utente IAM per abilitare il controllo dell'accesso basato su tag. Per ulteriori informazioni, consulta Autorizzazione basata su tag Amazon Lex (p. 237). Per vedere un esempio di policy basata su identità per limitare l'accesso a una risorsa in base ai tag di tale risorsa, consulta Esempio: utilizzare un tag per accedere a una risorsa (p. 242).

Puoi lavorare con i tag utilizzando la AWS Management Console, l'AWS Command Line Interface o l'API Amazon Lex.

Tagging delle risorse

Se usi la console Amazon Lex, puoi contrassegnare le risorse durante la creazione oppure aggiungere i tag in un secondo momento. È inoltre possibile utilizzare la console per aggiornare o rimuovere i tag esistenti.

Se usi l'AWS CLI o l'API Amazon Lex, puoi utilizzare le seguenti operazioni per gestire i tag per le risorse:

• ListTagsForResource (p. 370) – visualizzare i tag associati a una risorsa. • PutBot (p. 372) e PutBotAlias (p. 383) – applicare i tag quando un bot o un alias bot viene creato. • TagResource (p. 414) – aggiungere e modificare i tag in una risorsa esistente. • UntagResource (p. 416) – rimuovere i tag da una risorsa.

Le seguenti risorse in Amazon Lex supportano il tagging:

• Bots: usa un Amazon Resource Name (ARN) simile al seguente:

65 Amazon Lex Guida per gli sviluppatori Restrizioni applicate ai tag

• arn:${partition}:lex:${region}:${account}:bot:${bot-name} • Alias bot: usa un ARN come il seguente: • arn:${partition}:lex:${region}:${account}:bot:${bot-name}:${bot-alias} • Canali bot: usa un ARN come il seguente: • arn:${partition}:lex:${region}:${account}:bot-channel:${bot-name}:${bot- alias}:${channel-name}

Restrizioni applicate ai tag

Le seguenti restrizioni di base si applicano ai tag per le risorse Amazon Lex:

• Numero massimo di tag - 50 • Lunghezza massima della chiave - 128 caratteri • Lunghezza massima del valore - 256 caratteri • Caratteri validi per la chiave e il valore: a–z, A–Z, 0–9, spazio e i seguenti caratteri: _ . : / = + - e @ • Per chiavi e valori viene fatta distinzione tra maiuscole e minuscole. • Non utilizzare aws: come prefisso per le chiavi; l'utilizzo di questo prefisso è esclusivo di AWS.

Tagging delle risorse (console)

Puoi utilizzare la console per gestire i tag per una risorsa bot, alias bot o canale bot. Puoi aggiungere i tag quando crei una risorsa oppure puoi aggiungere, modificare o rimuovere tag dalle risorse esistenti.

Per aggiungere un tag quando si crea un bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere Create (Crea) per creare un nuovo bot. 3. Nella parte inferiore della pagina Create your bot (Crea il tuo bot) scegliere Tags (Tag). 4. Scegliere Add tag (Aggiungi tag) e aggiungere uno o più tag al bot. Puoi aggiungere fino a 50 tag.

Per aggiungere un tag quando si crea un alias bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere il bot a cui si desidera aggiungere l'alias bot. 3. Seleziona Settings (Impostazioni). 4. Aggiungere il nome alias, scegliere la versione bot, quindi scegliere Add tags (Aggiungi tag). 5. Scegliere Add tag (Aggiungi tag) e aggiungere uno o più tag all'alias bot. Puoi aggiungere fino a 50 tag.

Per aggiungere un tag quando si crea un canale bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere il bot a cui si desidera aggiungere il canale bot. 3. Scegliere Channels (Canali) quindi scegliere il canale che si desidera aggiungere. 4. Aggiungere i dettagli per il canale bot, quindi scegliere Tags (Tag).

66 Amazon Lex Guida per gli sviluppatori Tagging delle risorse (AWS CLI)

5. Scegliere Add tag (Aggiungi tag) e aggiungere uno o più tag al canale bot. Puoi aggiungere fino a 50 tag.

Per aggiungere un tag quando si importa un bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere Actions (Operazioni), quindi Import (Importa). 3. Scegliere il file zip per importare il bot. 4. Scegliere Tags (Tag), quindi scegliere Add tag (Aggiungi tag) per aggiungere uno o più tag al bot. Puoi aggiungere fino a 50 tag.

Per aggiungere, rimuovere o modificare un tag per un bot esistente

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Dal menu a sinistra, scegliere Bot e selezionare il bot che si desidera modificare. 3. Scegliere Settings (Impostazioni) quindi dal menu a sinistra scegliere General (Generale). 4. Scegliere Tags (Tag) e quindi aggiungere, modificare o rimuovere i tag per il bot.

Per aggiungere, rimuovere o modificare un tag per un alias bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Dal menu a sinistra, scegliere Bot e selezionare il bot che si desidera modificare. 3. Scegliere Settings (Impostazioni) quindi dal menu a sinistra scegliere Aliases (Alias). 4. Scegliere Manage tags (Gestisci tag) per l'alias che si desidera modificare, quindi aggiungere, modificare o rimuovere i tag per l'alias bot.

Per aggiungere, rimuovere o modificare un tag per un canale bot esistente

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Dal menu a sinistra, scegliere Bot e selezionare il bot che si desidera modificare. 3. Seleziona Channels (Canali). 4. Scegliere Tags (Tag) e quindi aggiungere, modificare o rimuovere i tag per il canale bot.

Tagging delle risorse (AWS CLI)

Puoi utilizzare l'AWS CLI per gestire i tag per una risorsa bot, alias bot o canale bot. Puoi aggiungere i tag quando crei un bot o un alias bot oppure puoi aggiungere, modificare o rimuovere i tag da un bot, un alias bot o un canale bot.

Tutti gli esempi sono formattati per Linux e macOS. Per utilizzare il comando in Windows, sostituisci il carattere di continuazione Linux (\) con un accento circonflesso (^).

Per aggiungere un tag quando si crea un bot

• Il seguente comando abbreviato put-bot dell'AWS CLI mostra i parametri che devi utilizzare per aggiungere un tag quando crei un bot. Per creare effettivamente un bot, devi fornire altri parametri. Per ulteriori informazioni, consulta Step 4: Getting Started (AWS CLI) (p. 110).

67 Amazon Lex Guida per gli sviluppatori Tagging delle risorse (AWS CLI)

aws lex-models put-bot \ --tags '[{"key": "key1", "value": "value1"}, \ {"key": "key2", "value": "value2"}]'

Per aggiungere un tag quando si crea un alias bot

• Il seguente comando abbreviato put-bot-alias dell'AWS CLI mostra i parametri che devi utilizzare per aggiungere un tag quando crei un alias bot. Per creare effettivamente un alias bot, devi fornire altri parametri. Per ulteriori informazioni, consulta Exercise 5: Create an Alias (AWS CLI) (p. 133).

aws lex-models put-bot \ --tags '[{"key": "key1", "value": "value1"}, \ {"key": "key2", "value": "value2"}]"

Per elencare i tag per una risorsa

• Utilizzare il comando list-tags-for-resource dell'AWS CLI per mostrare le risorse associate a un bot, un alias bot, un canale bot.

aws lex-models list-tags-for-resource \ --resource-arn bot, bot alias, or bot channel ARN

Per aggiungere o modificare i tag in una risorsa

• Utilizzare il comando tag-resource dell'AWS CLI per aggiungere o modificare un bot, un alias bot o un canale bot.

aws lex-models tag-resource \ --resource-arn bot, bot alias, or bot channel ARN \ --tags '[{"key": "key1", "value": "value1"}, \ {"key": "key2", "value": "value2"}]'

Per rimuovere i tag da una risorsa

• Utilizzare il comando untag-resource dell'AWS CLI per rimuovere i tag da un bot, un alias bot o un canale bot.

aws lex-models untag-resource \ --resource-arn bot, bot alias, or bot channel ARN \ --tag-keys '["key1", "key2"]'

68 Amazon Lex Guida per gli sviluppatori Fase 1: impostazione di un account

Nozioni di base su Amazon Lex

Amazon Lex fornisce operazioni delle API che è possibile integrare con le applicazioni esistenti. Per un elenco delle operazioni supportate, consultare la Riferimento alle API (p. 266). È possibile utilizzare una qualsiasi delle seguenti opzioni:

• SDK AWS: quando utilizzi gli SDK, le richieste a Amazon Lex vengono automaticamente firmate e autenticate utilizzando le credenziali fornite. Questa è la soluzione consigliata per la creazione di applicazioni. • AWS CLI: puoi utilizzare AWS CLI per accedere a una delle caratteristiche di Amazon Lex senza dover scrivere codice. • Console AWS: la console costituisce il modo più semplice per iniziare a provare e utilizzare Amazon Lex.

Se è la prima volta che utilizzi Amazon Lex, ti consigliamo di leggere prima Amazon Lex: come funziona (p. 3).

Argomenti • Fase 1. Impostazione di un account AWS e creazione di un utente Amministratore (p. 69) • Fase 2: configurazione diAWS Command Line Interface (p. 70) • Fase 3: nozioni di base (console) (p. 71) • Step 4: Getting Started (AWS CLI) (p. 110)

Fase 1. Impostazione di un account AWS e creazione di un utente Amministratore

Prima di usare Amazon Lex per la prima volta, è necessario completare le seguenti operazioni:

1. Registrazione ad AWS (p. 69) 2. Creazione di un utente IAM (p. 70)

Registrazione ad AWS

Se disponi già di un account AWS, ignora questo passaggio.

Quando ti registri a Amazon Web Services (AWS), il tuo account AWS viene automaticamente registrato per tutti i servizi AWS, tra cui Amazon Lex. Ti vengono addebitati solo i servizi che utilizzi.

Con Amazon Lex, paghi solo le risorse che utilizzi. Se sei un nuovo cliente AWS, puoi iniziare a utilizzare Amazon Lex gratuitamente. Per ulteriori informazioni, consulta Piano di utilizzo gratuito AWS.

Se disponi già di un account AWS, passa all'operazione successiva. Se non disponi di un account AWS, utilizza la seguente procedura per crearne uno.

Per creare un account AWS

1. Aprire https://portal.aws.amazon.com/billing/signup.

69 Amazon Lex Guida per gli sviluppatori Creazione di un utente IAM

2. Seguire le istruzioni online.

Come parte della procedura di registrazione riceverai una telefonata, durante la quale dovrai inserire un codice di verifica sulla tastiera del telefono.

Prendi nota dell'ID del tuo account AWS, sarà necessario per l'operazione successiva. Creazione di un utente IAM

I servizi di AWS, ad esempio Amazon Lex, richiedono l'immissione di credenziali di accesso, in modo da consentire al servizio di stabilire se l'utente dispone delle autorizzazioni per accedere alle risorse presenti nel servizio. Per la console è necessaria la password. Per consentire all'account AWS di accedere a AWS CLI o all'API, è possibile creare chiavi di accesso.

È sconsigliabile tuttavia accedere ad AWS utilizzando le credenziali dell'account AWS. Consigliamo invece di effettuare queste operazioni:

• Utilizzare AWS Identity and Access Management (IAM) per creare un utente IAM • Aggiungere l'utente a un gruppo IAM con autorizzazioni amministrative. • Concedere autorizzazioni amministrative per l'utente IAM creato.

Potrai quindi accedere ad AWS utilizzando un URL speciale e le credenziali utente di IAM.

Per eseguire gli esercizi Nozioni di base di questa guida si presuppone che tu abbia creato un utente (adminuser) con privilegi di amministratore. Per creare un adminuser nel tuo account, utilizza la procedura indicata di seguito.

Per creare un utente amministratore e accedere alla console

1. Crea nel tuo account AWS un utente amministratore denominato adminuser. Per istruzioni, consulta l'articolo relativo alla Creazione del primo utente e gruppo di amministratori IAM nella Guida per l'utente di IAM. 2. Come utente, puoi accedere alla AWS Management Console tramite un URL speciale. Per ulteriori informazioni, consulta Modalità di accesso degli utenti al tuo account nella Guida per l'utente di IAM.

Per ulteriori informazioni su IAM, consulta:

• AWS Identity and Access Management (IAM) • Nozioni di base • Guida per l'utente di IAM

Fase successiva

Fase 2: configurazione diAWS Command Line Interface (p. 70)

Fase 2: configurazione diAWS Command Line Interface

Se preferisci utilizzare Amazon Lex con AWS Command Line Interface (AWS CLI), puoi scaricare e configurare l'interfaccia.

70 Amazon Lex Guida per gli sviluppatori

Important

AWS CLI non è necessario per eseguire le fasi degli esercizi delle nozioni di base. Tuttavia, alcuni esercizi successivi di questa guida si basano sull'utilizzo di AWS CLI. Se preferisci iniziare utilizzando la console, ignora questa fase e passa a Fase 3: nozioni di base (console) (p. 71). In seguito, quando necessario, potrai tornare a questa fase e configurare AWS CLI.

Per configurare AWS CLI

1. Scarica e configura AWS CLI. Per istruzioni, consulta i seguenti argomenti nella Guida per l'utente di AWS Command Line Interface:

• Come configurare l'AWS Command Line Interface • Configurazione di AWS Command Line Interface 2. Aggiungi un profilo denominato per l'utente amministratore al termine del file di configurazione di AWS CLI. Utilizzerai questo profilo quando esegui i comandi AWS CLI. Per ulteriori informazioni, consulta l'articolo relativo ai profili denominati nella Guida per l'utente di AWS Command Line Interface.

[profile adminuser] aws_access_key_id = adminuser access key ID aws_secret_access_key = adminuser secret access key region = aws-region

Per un elenco delle regioni AWS disponibili, consulta Regioni ed endpoint nel documento Riferimento generale Amazon Web Services. 3. Verifica la configurazione digitando il comando help al prompt dei comandi:

aws help

Fase 3: nozioni di base (console) (p. 71) Fase 3: nozioni di base (console)

Il modo più semplice per imparare a utilizzare Amazon Lex consiste nell'utilizzare la console. Per iniziare, abbiamo creato i seguenti esercizi, ognuno dei quali si basa sull'uso della console:

• Esercizio 1: creazione di un bot Amazon Lex utilizzando un piano, ovvero un bot predefinito che fornisce tutti gli elementi di configurazione necessari per il bot. Dovrai effettuare solo operazioni minime per eseguire il test della configurazione end-to-end.

Inoltre, utilizzerai il piano della funzione Lambda, fornito da AWS Lambda, per creare una funzione Lambda. Questa funzione rappresenta un hook di codice che utilizza codice predefinito compatibile con il bot. • Esercizio 2: creazione di un bot personalizzato mediante creazione e configurazione manuali. Viene creata anche una funzione Lambda come hook di codice. Viene fornito il codice di esempio. • Esercizio 3: pubblicazione di un bot e quindi creazione di una nuova versione del bot. Parte di questo esercizio consiste nella creazione di un alias che punta alla versione del bot.

Argomenti • Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72) • Esercizio 2: Creazione di un personalizzato Amazon Lex Bot (p. 98) • Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109)

71 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console)

In questo esercizio, devi effettuare le seguenti operazioni:

• Crea il tuo primo bot di Amazon Lex e testalo nella console Amazon Lex.

Per questo esercizio, utilizza il piano OrderFlowers. Per ulteriori informazioni sui piani, consulta l'argomento Amazon Lex e piani AWS Lambda (p. 150).

• Crea una funzione AWS Lambda e testala nella console Lambda. Durante l'elaborazione di una richiesta, il tuo bot chiama questa funzione Lambda. Per questo esercizio, utilizza un piano di Lambda (lex-order- flowers-python) fornito nella console AWS Lambda per creare la tua funzione Lambda. Il codice del piano indica il modo in cui puoi utilizzare la stessa funzione Lambda per eseguire l'inizializzazione e la convalida e per realizzare l'intento di OrderFlowers.

• Aggiorna il bot per aggiungere la funzione Lambda come hook di codice per realizzare l'intento. Esegui il test dell'esperienza end-to-end.

Le seguenti sezioni illustrano cosa fanno i piani. Amazon LexBot di : panoramica dei piani

Per creare un bot di , utilizza il piano OrderFlowersAmazon Lex. Per ulteriori informazioni sulla struttura di un bot, consulta l'argomento Amazon Lex: come funziona (p. 3). Il bot è preconfigurato come segue:

• Intent – OrderFlowers (Intenti OrderFlower) • Tipi di slot – Un tipo di slot personalizzato chiamato FlowerTypes con valori di enumerazione: roses lilies, e tulips. • Slot – L'intento richiede le seguenti informazioni (ovvero slot) prima che il bot possa realizzare l'intento. • PickupTime (tipo integrato AMAZON.TIME) • FlowerType (tipo FlowerTypes personalizzato) • PickupDate (tipo integrato AMAZON.DATE) • Enunciazione – Le seguenti enunciazioni di esempio indicano l'intento dell'utente: • "I would like to pick up flowers." • "I would like to order some flowers." • Prompt – Dopo che il bot identifica l'intento, utilizza i seguenti prompt per riempire gli slot: • Prompt per lo FlowerType slot – "What type of flowers would you like to order?" • Prompt per lo PickupDate slot – "What day do you want the {FlowerType} to be picked up?" • Prompt per lo PickupTime slot – "At what time do you want the {FlowerType} to be picked up?" • Istruzione di conferma – "Okay, your {FlowerType} will be ready for pickup by {PickupTime} on {PickupDate. Does this sound okay?"

AWS LambdaFunzione : riepilogo del piano

La funzione Lambda in questo esercizio esegue le operazioni di inizializzazione, convalida e adempimento. Pertanto, dopo aver creato la funzione Lambda, devi aggiornare la configurazione dell'intento specificando la medesima funzione Lambda come hook di codice per gestire inizializzazione, convalida e adempimento.

72 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

• In qualità di hook di codice dell'inizializzazione e la convalida, la funzione Lambda esegue la convalida di base. Ad esempio, se per il ritiro l'utente fornisce un orario che non rientra nelle normali ore lavorative, la funzione Lambda istruisce Amazon Lex di chiedere nuovamente all'utente un orario. • Come parte dell'hook di codice di adempimento, la funzione Lambda restituisce un messaggio di riepilogo a indicare che l'ordine dei fiori è stato collocato (ovvero che l'intento è stato realizzato).

Fase successiva

Fase 1. Creazione di un bot di Amazon Lex (console) (p. 73) Fase 1. Creazione di un bot di Amazon Lex (console)

Per questo esercizio, crea un bot per ordinare dei fiori, denominato OrderFlowersBot.

Per creare un bot di Amazon Lex (console)

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Se questo è il tuo primo bot, seleziona Get Started (Inizia); altrimenti, nella pagina Bots (Bot), scegli Crea. 3. Nella pagina Create your Lex bot (Crea bot di Lex), fornisci le seguenti informazioni, quindi scegli Create (Crea).

• Seleziona il piano OrderFlowers. • Lascia il nome di bot predefinito (OrderFlowers). • Per COPPA, scegliere No. • Per User utterance storage (Storage enunciazione utente), scegliere la risposta appropriata. 4. Selezionare Create (Crea). La console effettua le richieste necessarie ad Amazon Lex per salvare la configurazione. La console visualizza la finestra dell'editor il bot. 5. Attendere la conferma che il bot è stato creato. 6. Esegui il test del bot. Note

Puoi eseguire il test del bot digitando una parte di testo nella finestra di prova oppure, nei browser compatibili, scegliendo il pulsante del microfono nella finestra di prova e parlando.

Utilizza il seguente testo di esempio per avviare una conversazione con il bot per l'ordine dei fiori:

73 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Da questo input, il bot deduce l'intento OrderFlowers e richiede i dati dello slot. Una volta forniti tutti i dati di slot necessari, il bot realizza l'intento (OrderFlowers) restituendo tutte le informazioni all'applicazione client (in questo caso, la console). La console mostra le informazioni nella finestra di prova.

Nello specifico:

• Nell'istruzione "What day do you want the roses to be picked up?", il termine "roses" appare perché il prompt dello slot pickupDate viene configurato utilizzando delle sostituzioni, {FlowerType}. Verificare nella console. • L'istruzione "Okay, your roses will be ready..." è il prompt di conferma che hai configurato. • L'ultima istruzione ("FlowerType:roses...") indica semplicemente i dati dello slot restituiti al client, in questo caso, nella finestra di prova. Nel prossimo esercizio, utilizzerai una funzione Lambda per realizzare l'intento, nel qual caso otterrai un messaggio a indicare l'adempimento dell'ordine.

Fase successiva

Fase 2 (facoltativo): Revisione dei dettagli del flusso di informazioni (console) (p. 75)

74 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Fase 2 (facoltativo): Revisione dei dettagli del flusso di informazioni (console)

Questa sezione illustra il flusso di informazioni tra un client e Amazon Lex per ogni input utente nella conversazione di esempio.

L'esempio utilizza la finestra di test della console per la conversazione con il bot.

Per aprire la finestra Amazon Lex di test

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegli il bot da testare. 3. Dal lato destro della console , scegliere Test chatbot (Test chatbot).

Per visualizzare il flusso di informazioni relativo ai contenuti parlati o digitati, scegli l'argomento appropriato.

Argomenti • Fase 2a (facoltativo): Revisione dei dettagli del flusso di informazioni parlate (console) (p. 75) • Fase 2b (facoltativo): Revisione dei dettagli del flusso di informazioni digitate (console) (p. 80)

Fase 2a (facoltativo): Revisione dei dettagli del flusso di informazioni parlate (console)

Questa sezione illustra il flusso di informazioni tra il client e Amazon Lex quando il client utilizza il riconoscimento vocale per l'invio di richieste. Per ulteriori informazioni, consulta PostContent (p. 425).

1. L'utente afferma: Vorrei ordinare dei fiori.

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1" Accept: "audio/mpeg"

Request body input stream

L'URI e il corpo della richiesta forniscono informazioni a Amazon Lex:

• URI della richiesta – Fornisce il nome del bot (OrderFlowers), l'alias del bot ($LATEST) e il nome utente (una stringa casuale che identifica l'utente). content indica che si tratta di una richiesta API PostContent API (non una richiesta PostText). • Intestazioni della richiesta • x-amz-lex-session-attributes – Il valore con codifica base64 rappresenta "{}". Quando il client effettua la prima richiesta non vi sono attributi della sessione. • Content-Type – Riflette il formato audio. • Corpo della richiesta – Il flusso audio dell'input utente ("I would like to order some flowers.").

75 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Note

Se invece di usare la voce, l'utente sceglie di inviare una parte di testo ("I would like to order some flowers") all'API PostContent, il corpo della richiesta sarà l'input utente. L'intestazione Content-Type viene impostata di conseguenza:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/ content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "text/plain; charset=utf-8" Accept: accept

Request body input stream

b. Dal flusso di input, Amazon Lex rileva l'intento (OrderFlowers). Quindi, sceglie uno degli slot di intenti (in questo caso, FlowerType) e uno dei relativi prompt per l'ottenimento del valore, infine invia una risposta con le seguenti intestazioni:

x-amz-lex-dialog-state:ElicitSlot x-amz-lex-input-transcript:I would like to order some flowers. x-amz-lex-intent-name:OrderFlowers x-amz-lex-message:What type of flowers would you like to order? x-amz-lex-session-attributes:e30= x-amz-lex-slot-to-elicit:FlowerType x-amz-lex- slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjpudWxsLCJQaWNrdXBEYXRlIjpudWxsfQ==

I valori dell'intestazione forniscono le informazioni seguenti:

• x-amz-lex-input-transcript – Fornisce la trascrizione dell'audio (input utente) dalla richiesta • x-amz-lex-message – fornisce la trascrizione dell'audio restituito da Amazon Lex nella risposta • x-amz-lex-slots – La versione con codifica base64 degli slot e dei valori:

{"PickupTime":null,"FlowerType":null,"PickupDate":null}

• x-amz-lex-session-attributes – La versione con codifica base64 degli attributi della sessione ({})

Il client riproduce l'audio nel corpo della risposta. 2. L'utente pronuncia: rose

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1" Accept: "audio/mpeg"

Request body input stream ("roses")

76 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Il corpo della richiesta è il flusso audio dell'input utente (rose). sessionAttributes rimane vuoto. b. Amazon Lex interpreta il flusso di input nel contesto dell'intento corrente (ricorda che ha chiesto a questo utente le informazioni relative allo slot FlowerType). Amazon Lex aggiorna innanzitutto il valore dello slot dell'intento corrente. Quindi sceglie un altro slot (PickupDate), insieme a uno dei relativi messaggi di richiesta (Quando vuoi ritirare le rose?), e restituisce una risposta con le seguenti intestazioni:

x-amz-lex-dialog-state:ElicitSlot x-amz-lex-input-transcript:roses x-amz-lex-intent-name:OrderFlowers x-amz-lex-message:When do you want to pick up the roses? x-amz-lex-session-attributes:e30= x-amz-lex-slot-to-elicit:PickupDate x-amz-lex- slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6bnVsbH0=

I valori dell'intestazione forniscono le informazioni seguenti:

• x-amz-lex-slots – La versione con codifica base64 degli slot e dei valori:

{"PickupTime":null,"FlowerType":"roses","PickupDate":null}

• x-amz-lex-session-attributes – La versione con codifica base64 degli attributi della sessione ({})

Il client riproduce l'audio nel corpo della risposta. 3. L'utente pronuncia: domani

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1" Accept: "audio/mpeg"

Request body input stream ("tomorrow")

Il corpo della richiesta è il flusso audio dell'input utente ("tomorrow"). sessionAttributes rimane vuoto. b. Amazon Lex interpreta il flusso di input nel contesto dell'intento corrente (ricorda che ha chiesto a questo utente le informazioni relative allo slot PickupDate). Amazon Lex aggiorna innanzitutto il valore (PickupDate) dello slot dell'intento corrente. Quindi sceglie un altro slot per recuperare il valore di (PickupTime) e uno dei prompt di ottenimento del valore (Quando vuoi ritirare le rose il 18/03/2018?), infine restituisce una risposta con le seguenti intestazioni:

x-amz-lex-dialog-state:ElicitSlot x-amz-lex-input-transcript:tomorrow x-amz-lex-intent-name:OrderFlowers x-amz-lex-message:When do you want to pick up the roses on 2017-03-18? x-amz-lex-session-attributes:e30= x-amz-lex-slot-to-elicit:PickupTime

77 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

x-amz-lex- slots:eyJQaWNrdXBUaW1lIjpudWxsLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtMTgifQ== x-amzn-RequestId:3a205b70-0b69-11e7-b447-eb69face3e6f

I valori dell'intestazione forniscono le informazioni seguenti:

• x-amz-lex-slots – La versione con codifica base64 degli slot e dei valori:

{"PickupTime":null,"FlowerType":"roses","PickupDate":"2017-03-18"}

• x-amz-lex-session-attributes – La versione con codifica base64 degli attributi della sessione ({})

Il client riproduce l'audio nel corpo della risposta. 4. L'utente pronuncia: 18

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "text/plain; charset=utf-8" Accept: "audio/mpeg"

Request body input stream ("6 pm")

Il corpo della richiesta è il flusso audio dell'input utente ("6 pm"). sessionAttributes rimane vuoto. b. Amazon Lex interpreta il flusso di input nel contesto dell'intento corrente (ricorda che ha chiesto a questo utente le informazioni relative allo slot PickupTime). Innanzitutto aggiorna il valore dello slot dell'intento corrente.

A questo punto Amazon Lex rileva di avere le informazioni per tutti gli slot. Tuttavia, poiché l'intento OrderFlowers è configurato con un messaggio di conferma, Amazon Lex necessita di una conferma esplicita dell'utente prima di poter procedere e realizzare l'intento e pertanto invia una risposta con le intestazioni seguenti per richiedere una conferma prima di ordinare i fiori:

x-amz-lex-dialog-state:ConfirmIntent x-amz-lex-input-transcript:six p. m. x-amz-lex-intent-name:OrderFlowers x-amz-lex-message:Okay, your roses will be ready for pickup by 18:00 on 2017-03-18. Does this sound okay? x-amz-lex-session-attributes:e30= x-amz-lex- slots:eyJQaWNrdXBUaW1lIjoiMTg6MDAiLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtMTgifQ== x-amzn-RequestId:083ca360-0b6a-11e7-b447-eb69face3e6f

I valori dell'intestazione forniscono le informazioni seguenti:

• x-amz-lex-slots – La versione con codifica base64 degli slot e dei valori:

{"PickupTime":"18:00","FlowerType":"roses","PickupDate":"2017-03-18"}

• x-amz-lex-session-attributes – La versione con codifica base64 degli attributi della sessione ({})

78 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Il client riproduce l'audio nel corpo della risposta. 5. L'utente pronuncia: Sì

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/content HTTP/1.1 x-amz-lex-session-attributes: "e30=" Content-Type: "audio/x-l16; sample-rate=16000; channel-count=1" Accept: "audio/mpeg"

Request body input stream ("Yes")

Il corpo della richiesta è il flusso audio dell'input utente ("Yes"). sessionAttributes rimane vuoto. b. Amazon Lex; interpreta il flusso di input e comprende che l'utente desidera procedere con l'ordine. L'intento OrderFlowers è configurato con ReturnIntent come attività di l'attività di adempimento. Viene così indicato ad Amazon Lex di restituire tutti i dati dell'intento al client. Amazon Lex restituisce una risposta con i dati seguenti:

x-amz-lex-dialog-state:ReadyForFulfillment x-amz-lex-input-transcript:yes x-amz-lex-intent-name:OrderFlowers x-amz-lex-session-attributes:e30= x-amz-lex- slots:eyJQaWNrdXBUaW1lIjoiMTg6MDAiLCJGbG93ZXJUeXBlIjoicm9zaSdzIiwiUGlja3VwRGF0ZSI6IjIwMTctMDMtMTgifQ==

L'intestazione della risposta x-amz-lex-dialog-state è impostata su ReadyForFulfillment. Quindi il client può realizzare l'intento. 6. A questo punto, esegui nuovamente il test del bot. Per stabilire un nuovo contesto (utente), scegli il collegamento Clear (Cancella) nella console. Fornisci i dati per l'intento OrderFlowers e includi alcuni dati non validi. Ad esempio:

• Gelsomino come tipo di fiore (non è uno dei tipi di fiore supportati) • Ieri come giorno in cui si desidera ritirare i fiori

Nota che il bot accetta questi valori perché non disponi di alcun codice per inizializzare e convalidare i dati utente. Nella sezione successiva, aggiungerai una funzione Lambda per effettuare tale operazione. Tieni presente quanto segue in relazione alla funzione Lambda:

• Convalida i dati dello slot dopo ogni input utente. Soddisfa l'intento alla fine. Ciò significa che il bot elabora l'ordine di fiori e restituisce un messaggio all'utente invece che restituire semplicemente i dati dello slot al client. Per ulteriori informazioni, consulta Utilizzo delle funzioni Lambda (p. 140). • Inoltre, imposta gli attributi di sessione. Per ulteriori informazioni sugli attributi di sessione, consulta PostText (p. 434).

Al termine della sezione Nozioni di base, potrai eseguire gli esercizi aggiuntivi (Esempi aggiuntivi: Creazione Amazon Lex Bot (p. 173)). Prenota viaggio (p. 192) utilizza gli attributi di sessione per condividere le informazioni tra intenti per impegnarsi in una conversazione dinamica con l'utente.

Fase successiva

79 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Fase 3. Creazione di una funzione Lambda (console) (p. 84)

Fase 2b (facoltativo): Revisione dei dettagli del flusso di informazioni digitate (console)

Questa sezione illustra il flusso di informazioni tra il client e Amazon Lex in cui il client utilizza l'API PostText per inviare le richieste. Per ulteriori informazioni, consulta PostText (p. 434).

1. L'utente digita: Vorrei ordinare dei fiori

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "I would like to order some flowers", "sessionAttributes": {} }

L'URI e il corpo della richiesta forniscono informazioni a Amazon Lex:

• URI della richiesta – Fornisce il nome del bot (OrderFlowers), l'alias del bot ($LATEST) e il nome utente (una stringa casuale che identifica l'utente). Il codice text finale indica che si tratta di una richiesta API PostText (non PostContent).

• Corpo della richiesta – Include l'input utente (inputText) e sessionAttributesvuoto. Quando il client effettua la prima richiesta non vi sono attributi della sessione. La funzione Lambda li avvia in un secondo momento. b. A partire da inputText, Amazon Lex rileva l'intento (OrderFlowers). Questo intento non ha alcun hook di codice (ossia le funzioni Lambda) per l'inizializzazione e la convalida dell'input utente o l'adempimento.

Amazon Lex sceglie uno degli slot di intenti (FlowerType) per ottenere il valore. Inoltre, seleziona uno dei prompt per l'ottenimento del valore dello slot (tutti parte della configurazione dell'intento) e invia la seguente risposta al client. La console mostra il messaggio nella risposta all'utente.

Il client visualizza il messaggio nella risposta. 2. L'utente digita: rose

80 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "roses", "sessionAttributes": {} }

inputText nel corpo della richiesta fornisce l'input utente. sessionAttributes rimane vuoto. b. Amazon Lex innanzitutto interpreta inputText nel contesto dell'intento —corrente il servizio ricorda che ha richiesto all'utente specifico le informazioni sullo FlowerType slot. Amazon Lex innanzitutto aggiorna il valore dello slot per l'intento corrente e sceglie un altro slot (PickupDate) insieme a uno dei messaggi —di richiestaQuale giorno desideri che le rose vengano ritirate?— per lo slot.

Quindi, Amazon Lex restituisce la risposta seguente:

Il client visualizza il messaggio nella risposta. 3. L'utente digita: domani

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "tomorrow", "sessionAttributes": {} }

inputText nel corpo della richiesta fornisce l'input utente. sessionAttributes rimane vuoto. b. Amazon Lex innanzitutto interpreta inputText nel contesto dell'intento —corrente il servizio ricorda che ha richiesto all'utente specifico le informazioni sullo PickupDate slot. Amazon Lex aggiorna il valore dello slot (PickupDate) per l'intento corrente. e sceglie un altro slot per ottenere il valore di (PickupTime). Restituisce uno dei prompt —di emissione del valoreDeliver the roses at what time on 2017-01-05?—al client.

Amazon LexQuindi, restituisce la risposta seguente:

81 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Il client visualizza il messaggio nella risposta. 4. L'utente digita: 18:00

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "6 pm", "sessionAttributes": {} }

inputText nel corpo della richiesta fornisce l'input utente. sessionAttributes rimane vuoto. b. Amazon Lex innanzitutto interpreta inputText nel contesto dell'intento —corrente il servizio ricorda di aver richiesto all'utente specifico le informazioni sullo PickupTime slot. Amazon Lex aggiorna innanzitutto il valore dello slot per l'intento corrente. A questo punto Amazon Lex rileva di avere le informazioni per tutti gli slot.

Tuttavia, poiché l'intento OrderFlowers è configurato con un messaggio di conferma, Pertanto, Amazon Lex necessita di una conferma esplicita dell'utente prima di poter procedere e realizzare l'intento. Amazon Lex invia il seguente messaggio al client per richiedere una conferma prima di ordinare i fiori:

Il client visualizza il messaggio nella risposta. 5. L'utente digita: Sì

82 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/4o9wwdhx6nlheferh6a73fujd3118f5w/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "Yes", "sessionAttributes": {} }

inputText nel corpo della richiesta fornisce l'input utente. sessionAttributes rimane vuoto. b. Amazon Lex interpreta inputText nel contesto della conferma dell'intento corrente e comprende che l'utente desidera procedere con l'ordine. L'intento OrderFlowers è configurato con ReturnIntent come attività di adempimento (non è presente alcuna funzione Lambda per realizzare l'intento). Pertanto, Amazon Lex restituisce i dati dello slot al client.

Amazon Lex imposta dialogState su ReadyForFulfillment. Quindi il client può realizzare l'intento. 6. A questo punto, esegui nuovamente il test del bot. Per farlo, devi scegliere il collegamento Clear (Cancella) nella console per stabilire un nuovo contesto (utente). Ora, quando fornisci i dati per l'intento relativo all'ordine di fiori, prova a fornire dei dati non validi. Ad esempio:

• Gelsomino come tipo di fiore (non è uno dei tipi di fiore supportati). • Ieri come giorno in cui si desidera ritirare i fiori.

Nota che il bot accetta questi valori perché non disponi di alcun codice per inizializzare/convalidare i dati utente. Nella sezione successiva, aggiungerai una funzione Lambda per effettuare tale operazione. Tieni presente quanto segue in relazione alla funzione Lambda:

• La funzione Lambda convalida i dati dello slot dopo ogni input utente. Soddisfa l'intento alla fine. Ciò significa che il bot elabora l'ordine di fiori e restituisce un messaggio all'utente invece che restituire semplicemente i dati dello slot al client. Per ulteriori informazioni, consulta Utilizzo delle funzioni Lambda (p. 140). • La funzione Lambda imposta anche gli attributi di sessione. Per ulteriori informazioni sugli attributi di sessione, consulta PostText (p. 434).

Al termine della sezione Nozioni di base, potrai eseguire gli esercizi aggiuntivi (Esempi aggiuntivi: Creazione Amazon Lex Bot (p. 173)). Prenota viaggio (p. 192) utilizza gli attributi di sessione per condividere le informazioni tra intenti per impegnarsi in una conversazione dinamica con l'utente.

83 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Fase successiva

Fase 3. Creazione di una funzione Lambda (console) (p. 84) Fase 3. Creazione di una funzione Lambda (console)

Crea una funzione Lambda (tramite il piano lex-order-flowers-python) ed esegui l'invocazione del test utilizzando dati di evento di esempio nella console AWS Lambda.

Torna alla console Amazon Lex e aggiungi la funzione Lambda come hook di codice per realizzare l'intento OrderFlowers in OrderFlowersBot creato nella sezione precedente.

Per creare la funzione Lambda (console)

1. Accedi alla AWS Management Console e apri la console AWS Lambda all'indirizzo https:// console.aws.amazon.com/lambda/. 2. Selezionare Create function (Crea funzione). 3. Nella pagina Crea funzione scegliere Use a blueprint (Usa un piano). Digita lex- nella casella di testo di filtro, quindi premi Enter per trovare il piano e scegli il piano lex-order-flowers-python.

LambdaI piani della funzione sono forniti sia in Node.js sia in Python. Per questo esercizio, utilizza il piano basato su Python. 4. Nella pagina Basic information (Informazioni di base), procedere come segue:

• Digita il nome della funzione Lambda (OrderFlowersCodeHook). • Per il ruolo di esecuzione, scegli Create a new role with basic Lambda permissions (Crea un nuovo ruolo con le autorizzazioni di base Lambda. • Non modificare gli altri valori predefiniti. 5. Selezionare Create function (Crea funzione). 6. Se stai utilizzando un'impostazione locale diversa da English (US) (en-US), aggiorna i nomi degli intenti come descritto in Aggiornamento di un piano per un'impostazione locale specifica (p. 150). 7. Esegui il test della funzione Lambda.

a. Seleziona Select a test events (Seleziona eventi test), Configure test event (Configura evento test). b. Seleziona Amazon Lex Order Flowers nell'elenco Event template (Modello eventi). Questo evento di esempio corrisponde al modello di richiesta/risposta di Amazon Lex (consulta Utilizzo delle funzioni Lambda (p. 140)). Assegna un nome all'evento di test (LexOrderFlowersTest). c. Selezionare Create (Crea). d. Scegli Test per testare l'hook del codice. e. Verificare che la Lambda funzione sia stata eseguita correttamente. La risposta in questo caso corrisponde al modello di risposta di Amazon Lex.

Fase successiva

Fase 4. Aggiunta della funzione Lambda come hook di codice (console) (p. 84) Fase 4. Aggiunta della funzione Lambda come hook di codice (console)

In questa sezione aggiornerai la configurazione dell'intento OrderFlowers per utilizzare la funzione Lambda come segue:

84 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

• Innanzitutto, utilizza la funzione Lambda come hook di codice per realizzare l'intento OrderFlowers. Esegui il test del bot e verifica di avere ricevuto un messaggio di adempimento dalla funzione Lambda. Amazon Lex invoca la funzione Lambda solo dopo che avrai fornito i dati di tutti gli slot necessari a ordinare i fiori. • Configura la stessa funzione Lambda come hook di codice per eseguire l'inizializzazione e la convalida. Esegui il test e verifica che la funzione Lambda esegua la convalida (quando fornisci i dati dello slot).

Per aggiungere una funzione Lambda come hook di codice (console)

1. Nella console di Amazon Lex seleziona il bot OrderFlowers. La console visualizza l'intento OrderFlowers. Accertati che la versione dell'intento sia impostata su $LATEST poiché questa è l'unica versione che è possibile modificare. 2. Aggiungi la funzione Lambda come hook di codice di adempimento ed eseguine il test.

a. Nell'editor, scegli AWS Lambda function come Fulfillment (Adempimento), quindi seleziona la funzione Lambda che hai creato nella fase precedente (OrderFlowersCodeHook). Seleziona OK per assegnare ad Amazon Lex l'autorizzazione a invocare la funzione Lambda.

Stai configurando questa funzione Lambda come hook di codice per realizzare l'intento. Amazon Lex invoca questa funzione solo dopo avere ottenuto dall'utente tutti i dati necessari dello slot per realizzare l'intento. b. Specifica un messaggio di saluto (Goodbye message). c. Seleziona Build (Crea). d. Esegui il test del bot utilizzando la conversazione precedente.

L'ultima istruzione "Thanks, your order for roses...." è una risposta della funzione Lambda che indica che hai eseguito la configurazione come hook di codice. Nella sezione precedente, non era presente alcuna funzione Lambda. Adesso stai utilizzando una funzione Lambda per realizzare realmente l'intento OrderFlowers. 3. Aggiungi la funzione Lambda come hook di codice di inizializzazione e convalida ed eseguine il test.

Il codice di esempio della funzione Lambda che stai utilizzando può eseguire sia la convalida dell'input utente che l'adempimento. L'evento di input ricevuto dalla Lambda funzione ha un campo (invocationSource) che il codice utilizza per determinare quale parte del codice eseguire. Per ulteriori informazioni, consulta Formato di evento di input e di risposta della funzione Lambda (p. 140).

a. Seleziona la versione $LATEST dell'intento OrderFlowers. Questa è l'unica versione che puoi aggiornare. b. Nell'editor, scegli Initialization and validation (Inizializzazione e convalida) nella sezione Options (Opzioni). c. Di nuovo, seleziona la stessa funzione Lambda. d. Seleziona Build (Crea). e. Esegui il test del bot.

A questo punto sei pronto per conversare con Amazon Lex come segue. Per eseguire il test della porzione di convalida, scegli le 6 PM come orario in modo che la funzione Lambda restituisca una risposta ("Our business hours are from 10 AM to 5 PM.") e ti presenti nuovamente una richiesta. Dopo che avrai fornito tutti i dati dello slot validi, la funzione Lambda soddisferà l'ordine.

85 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Fase successiva

Fase 5 (facoltativo): Revisione dei dettagli del flusso di informazioni (console) (p. 86) Fase 5 (facoltativo): Revisione dei dettagli del flusso di informazioni (console)

Questa sezione illustra il flusso di informazioni tra il client e Amazon Lex per ogni input utente, inclusa l'integrazione della funzione Lambda. Note

La sezione presuppone che il client invii le richieste ad Amazon Lex utilizzando l'API di runtime PostText e mostra i dettagli di richiesta e risposta corrispondenti. Per un esempio di flusso di

86 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

informazioni tra client e Amazon Lex in cui il client utilizza l'API PostContent, consulta Fase 2a (facoltativo): Revisione dei dettagli del flusso di informazioni parlate (console) (p. 75).

Per ulteriori informazioni sull'API di runtime PostText e ulteriori dettagli sulle richieste e le risposte mostrate nelle fasi seguenti, consulta l'argomento PostText (p. 434).

1. Utente: Vorrei ordinare dei fiori.

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "I would like to order some flowers", "sessionAttributes": {} }

L'URI e il corpo della richiesta forniscono informazioni a Amazon Lex:

• URI della richiesta – Fornisce il nome del bot (OrderFlowers), l'alias del bot ($LATEST) e il nome utente (una stringa casuale che identifica l'utente). Il codice text finale indica che si tratta di una richiesta API PostText (non PostContent). • Corpo della richiesta – Include l'input utente (inputText) e sessionAttributesvuoto. Quando il client effettua la prima richiesta non vi sono attributi della sessione. La funzione Lambda li avvia in un secondo momento. b. A partire da inputText, Amazon Lex rileva l'intento (OrderFlowers). configurato con una funzione Lambda come hook di codice per l'inizializzazione e la convalida dei dati utente. Pertanto, Amazon Lex invoca tale funzione Lambda passando le informazioni seguenti come dati di evento:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "ignw84y6seypre4xly5rimopuri2xwnd", "sessionAttributes": {}, "bot": { "name": "OrderFlowers", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderFlowers", "slots": { "PickupTime": null, "FlowerType": null, "PickupDate": null }, "confirmationStatus": "None" } }

Per ulteriori informazioni, consulta Formato dell'evento di input (p. 140).

Oltre alle informazioni inviate dal client, Amazon Lex include anche i dati aggiuntivi seguenti:

• messageVersion – attualmente Amazon Lex supporta solo la versione 1.0.

87 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

• invocationSource – Indica lo scopo della chiamata della Lambda funzione. In questo caso, lo scopo è eseguire l'inizializzazione e la convalida dei dati utente. A questo punto Amazon Lex sa che l'utente non ha ancora fornito tutti i dati dello slot per realizzare l'intento. • currentIntentInformazioni su con tutti i valori dello slot impostati su null. c. Al momento, tutti i valori dello slot sono nulli. Non c'è alcunché da convalidare per la funzione Lambda. La funzione Lambda restituisce la risposta seguente ad Amazon Lex:

{ "sessionAttributes": {}, "dialogAction": { "type": "Delegate", "slots": { "PickupTime": null, "FlowerType": null, "PickupDate": null } } }

Per informazioni sul formato della risposta, consulta l'argomento Formato della risposta (p. 145).

Si noti quanto segue:

• dialogAction.type – Impostando questo valore su Delegate, la Lambda funzione delega a la responsabilità di decidere l'operazione Amazon Lexsuccessiva. Note

Se la funzione Lambda rileva qualcosa nella convalida dei dati utente, indica ad Amazon Lex come procedere, come illustrato nelle successive fasi. d. In base a dialogAction.type, Amazon Lex decide la successiva operazione da eseguire. Poiché nessuno slot è popolato, decide di ottenere il valore dello slot FlowerType Inoltre, seleziona uno dei messaggi di richiesta per l'ottenimento del valore ("What type of flowers would you like to order?") dello slot e invia la seguente risposta al client:

Il client visualizza il messaggio nella risposta. 2. Utente: rosa

a. Il client invia la seguente richiesta PostText (p. 434) a Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text "Content-Type":"application/json" 88 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

"Content-Encoding":"amz-1.0"

{ "inputText": "roses", "sessionAttributes": {} }

Nel corpo della richiesta, inputText fornisce l'input utente. sessionAttributes rimane vuoto. b. Amazon Lex interpreta innanzitutto inputText nel contesto dell'intento corrente. Il servizio ricorda che aveva richiesto all'utente specifico le informazioni sullo slot FlowerType e aggiorna il valore dello slot nell'intento corrente, quindi invoca la funzione Lambda con i seguenti dati di evento:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "ignw84y6seypre4xly5rimopuri2xwnd", "sessionAttributes": {}, "bot": { "name": "OrderFlowers", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderFlowers", "slots": { "PickupTime": null, "FlowerType": "roses", "PickupDate": null }, "confirmationStatus": "None" } }

Si noti quanto segue:

• invocationSource – continua a essere DialogCodeHook (stiamo semplicemente convalidando i dati utente). • currentIntent.slots – Amazon Lex ha aggiornato lo slot FlowerType con rose. c. Secondo il valore invocationSource di DialogCodeHook, la funzione Lambda esegue la convalida dei dati utente e riconosce roses come valore valido dello slot (e imposta Price come un attributo di sessione), quindi restituisce la seguente risposta ad Amazon Lex.

{ "sessionAttributes": { "Price": 25 }, "dialogAction": { "type": "Delegate", "slots": { "PickupTime": null, "FlowerType": "roses", "PickupDate": null } } }

Si noti quanto segue:

89 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

• sessionAttributes – Lambda La funzione ha aggiunto Price (delle rose) come attributo di sessione. • dialogAction.type – è impostato su Delegate. I dati utente erano validi, pertanto la funzione Lambda indica a Amazon Lex di scegliere la prossima operazione da eseguire.

d. In base a dialogAction.type, Amazon Lex sceglie la successiva operazione da eseguire. Amazon Lex sa di avere bisogno di più dati dello slot in modo che selezioni lo slot successivo non popolato (PickupDate) con la massima priorità in base alla configurazione dell'intento. Amazon Lex seleziona uno dei messaggi —di richiesta di emissione del valore "What day do you want the roses to be picked up?" —per questo slot in base alla configurazione dell'intento, quindi invia la seguente risposta al client:

Il client visualizza semplicemente il messaggio nella risposta – "What day do you want the roses to be picked up?" 3. Utente: domani

a. Il client invia la seguente richiesta PostText (p. 434) a Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "tomorrow", "sessionAttributes": { "Price": "25" } }

Nel corpo della richiesta, inputText fornisce l'input utente e il client trasferisce gli attributi di sessione al servizio. b. Amazon Lex ricorda il contesto —in cui stava richiedendo i dati per lo PickupDate slot. In questo contesto, sa che il valore inputText è per lo slot PickupDate. Amazon Lex invoca quindi la funzione Lambda inviando l'evento seguente:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "ignw84y6seypre4xly5rimopuri2xwnd", "sessionAttributes": {

90 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

"Price": "25" }, "bot": { "name": "OrderFlowersCustomWithRespCard", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderFlowers", "slots": { "PickupTime": null, "FlowerType": "roses", "PickupDate": "2017-01-05" }, "confirmationStatus": "None" } }

Amazon Lex ha aggiornato currentIntent.slots impostando il valore di PickupDate. Nota inoltre che il servizio trasferisce sessionAttributes così com'è alla funzione Lambda. c. Secondo il valore invocationSource di DialogCodeHook, la funzione Lambda esegue la convalida dei dati utente e riconosce che il valore dello slot PickupDate è valido, quindi restituisce la seguente risposta ad Amazon Lex:

{ "sessionAttributes": { "Price": 25 }, "dialogAction": { "type": "Delegate", "slots": { "PickupTime": null, "FlowerType": "roses", "PickupDate": "2017-01-05" } } }

Si noti quanto segue:

• sessionAttributesNessuna modifica –. • dialogAction.type – è impostato su Delegate. I dati utente erano validi, pertanto la funzione Lambda indica a Amazon Lex di scegliere la prossima operazione da eseguire. d. In base a dialogAction.type, Amazon Lex sceglie la successiva operazione da eseguire. Amazon Lex sa di avere bisogno di ulteriori dati dello slot, quindi si avvale del successivo slot non popolato (PickupTime) con la più alta priorità secondo la configurazione dell'intento. Amazon Lex seleziona uno dei messaggi di richiesta per l'ottenimento del valore ("Deliver the roses at what time on 2017-01-05?") per questo slot in base alla configurazione dell'intento, quindi invia la seguente risposta al client:

91 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Il client visualizza il messaggio nella risposta – "Deliver the roses at what time on 2017-01-05 4. Utente: 16:00

a. Il client invia la seguente richiesta PostText (p. 434) a Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "4 pm", "sessionAttributes": { "Price": "25" } }

Nel corpo della richiesta, inputText fornisce l'input utente. Il client trasferisce sessionAttributes nella richiesta. b. Amazon Lex comprende il contesto. Comprende inoltre che stava richiedendo i dati dello slot PickupTime. In questo contesto, sa che il valore inputText è per lo slot PickupTime. Amazon Lex invoca quindi la funzione Lambda inviando l'evento seguente:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "ignw84y6seypre4xly5rimopuri2xwnd", "sessionAttributes": { "Price": "25" }, "bot": { "name": "OrderFlowersCustomWithRespCard", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderFlowers", "slots": { "PickupTime": "16:00", "FlowerType": "roses", "PickupDate": "2017-01-05" }, "confirmationStatus": "None" }

92 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

}

Amazon Lex ha aggiornato currentIntent.slots impostando il valore di PickupTime. c. Secondo il valore invocationSource di DialogCodeHook, la funzione Lambda esegue la convalida dei dati utente e riconosce che il valore dello slot PickupDate è valido, quindi restituisce la seguente risposta ad Amazon Lex.

{ "sessionAttributes": { "Price": 25 }, "dialogAction": { "type": "Delegate", "slots": { "PickupTime": "16:00", "FlowerType": "roses", "PickupDate": "2017-01-05" } } }

Si noti quanto segue:

• sessionAttributes – Nessuna modifica nell'attributo di sessione. • dialogAction.type – è impostato su Delegate. I dati utente erano validi, pertanto la funzione Lambda indica a Amazon Lex di scegliere la prossima operazione da eseguire. d. A questo punto, Amazon Lex sa di avere tutti i dati dello slot. Tuttavia, poiché questo intento è configurato con un prompt di conferma, Amazon Lex invia la seguente risposta all'utente chiedendo conferma prima di realizzare l'intento:

Il client visualizza semplicemente il messaggio nella risposta e attende la risposta dell'utente. 5. Utente: Sì

a. Il client invia la seguente richiesta PostText (p. 434) a Amazon Lex:

POST /bot/OrderFlowers/alias/$LATEST/user/ignw84y6seypre4xly5rimopuri2xwnd/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "yes", "sessionAttributes": {

93 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

"Price": "25" } } b. Amazon Lex interpreta inputText nel contesto della conferma dell'intento corrente. Amazon Lex comprende che l'utente desidera procedere con l'ordine. Questa volta, Amazon Lex invoca la funzione Lambda per realizzare l'intento inviando l'evento seguente, che imposta invocationSource su FulfillmentCodeHook nell'evento che invia alla funzione Lambda. Amazon Lex imposta anche confirmationStatus su Confirmed.

{ "messageVersion": "1.0", "invocationSource": "FulfillmentCodeHook", "userId": "ignw84y6seypre4xly5rimopuri2xwnd", "sessionAttributes": { "Price": "25" }, "bot": { "name": "OrderFlowersCustomWithRespCard", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderFlowers", "slots": { "PickupTime": "16:00", "FlowerType": "roses", "PickupDate": "2017-01-05" }, "confirmationStatus": "Confirmed" } }

Si noti quanto segue:

• invocationSource – Questa volta Amazon Lex impostare questo valore su FulfillmentCodeHook, indicando alla Lambda funzione di realizzare l'intento. • confirmationStatus – è impostato su Confirmed. c. Questa volta, la funzione Lambda realizza l'intento OrderFlowers e restituisce la seguente risposta:

{ "sessionAttributes": { "Price": "25" }, "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Thanks, your order for roses has been placed and will be ready for pickup by 16:00 on 2017-01-05" } } }

Si noti quanto segue:

• Imposta la dialogAction.type – Lambda funzione : imposta questo valore su Close, indicando Amazon Lex a di non aspettarsi una risposta dell'utente.

94 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

• dialogAction.fulfillmentState – è impostato su Fulfilled (Soddisfatto) e include un elemento message appropriato da trasmettere all'utente. d. Amazon Lex esamina fulfillmentState e invia la seguente risposta al client.

Amazon Lex restituisce quindi quanto segue al client:

Nota:

• dialogState – Amazon Lex imposta questo valore su fulfilled. • message – è lo stesso messaggio fornito dalla Lambda funzione .

Il client visualizza il messaggio. 6. A questo punto, esegui nuovamente il test del bot. Per stabilire un nuovo contesto (utente), scegli il collegamento Clear (Cancella) nella finestra di prova. A questo punto, fornisci dei dati non validi dello slot per l'intento OrderFlowers. Questa volta, la funzione Lambda esegue la convalida dei dati, reimposta su null il valore dei dati dello slot e chiede ad Amazon Lex di richiedere all'utente dei dati validi. Ad esempio, prova quanto seguente:

• Gelsomino come tipo di fiore (non è uno dei tipi di fiore supportati). • Ieri come giorno in cui si desidera ritirare i fiori. • Dopo aver effettuato l'ordine, inserisci un altro tipo di fiore invece che rispondere "yes" per confermare l'ordine. In risposta, la funzione Lambda aggiorna Price nell'attributo di sessione, mantenendo un totale parziale degli ordini di fiori.

La funzione Lambda esegue inoltre l'operazione di adempimento.

Fase successiva

Fase 6: Aggiornamento della configurazione dell'intento per aggiungere un'enunciazione (console) (p. 95) Fase 6: Aggiornamento della configurazione dell'intento per aggiungere un'enunciazione (console)

Il bot OrderFlowers è configurato con due sole enunciazioni. Ciò fornisce informazioni limitate affinché Amazon Lex crei un modello di machine learning in grado di riconoscere e rispondere all'intento dell'utente. Prova digitando "I want to order flowers" nella finestra di prova. Amazon Lex non riconosce il testo e

95 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano risponde con "I didn't understand you, what would you like to do?" Puoi migliorare il modello di machine learning aggiungendo altre enunciazioni.

Ogni enunciazione che aggiungi fornisce ad Amazon Lex ulteriori informazioni su come rispondere ai tuoi utenti. Non è necessario che tu aggiunga un'enunciazione precisa, Amazon Lex generalizza usando gli esempi che fornisci per riconoscere sia le corrispondenze esatte che gli input simili.

Per aggiungere un'enunciazione (console)

1. Aggiungi l'enunciazione "I want flowers" all'intento digitando la frase nella sezione Sample utterances (Enunciazioni di esempio) dell'editor di intenti, quindi clicca l'icona con il simbolo più accanto alla nuova enunciazione.

2. Crea il tuo bot per ottenere la modifica. Seleziona Build (Crea), quindi di nuovo Build (Crea). 3. Esegui il test del bot per verificare che riconosca la nuova enunciazione. Nella finestra di prova, digita "I want to order flowers." Amazon Lex riconosce la frase e risponde con "What type of flowers would you like to order?".

96 Amazon Lex Guida per gli sviluppatori Esercizio 1: Creazione di un bot utilizzando un piano

Fase successiva

Fase 7 (facoltativo): Pulizia (Console) (p. 97) Fase 7 (facoltativo): Pulizia (Console)

Adesso, elimina le risorse che hai creato e pulisci il tuo account.

Puoi eliminare solo le risorse che non sono in uso. In generale, devi eliminare le risorse nell'ordine seguente:

• Elimina i bot per liberare risorse di intenti. • Elimina gli intenti per liberare risorse di tipo di slot. • Elimina i tipi di slot come ultima cosa.

Per pulire il tuo account (console)

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Dall'elenco di bot, scegli la casella di controllo accanto a OrderFlowers. 3. Per eliminare il bot, scegli Delete (Elimina), quindi scegli Continue (Continua) nella finestra di dialogo di conferma. 4. Nel riquadro a sinistra seleziona Intents (Intenti). 5. Nell'elenco di Intenti, scegli OrderFlowersIntent. 6. Per eliminare l'intento, scegli Delete (Elimina), quindi scegli Continue (Continua) nella finestra di dialogo di conferma. 7. Nel riquadro a sinistra seleziona Slot types (Tipi di slot). 8. Nell'elenco di tipi di slot, scegli Flowers (Fiori). 9. Per eliminare il tipo di slot, scegli Delete (Elimina), quindi scegli Continue (Continua) nella finestra di dialogo di conferma.

97 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

Hai rimosso tutte le risorse Amazon Lex che hai creato e hai pulito il tuo account. Se lo desideri, puoi utilizzare la console Lambda per eliminare la funzione Lambda utilizzata in questo esercizio. Esercizio 2: Creazione di un personalizzato Amazon Lex Bot

In questo esercizio verrà utilizzata la console Amazon Lex per creare un bot personalizzato che consente di ordinare la pizza (OrderPizzaBot). Il bot verrà configurato con l'aggiunta di un intento personalizzato (OrderPizza), la definizione di tipi di slot personalizzati e degli slot necessari per la realizzazione dell'ordine di una pizza (bordo della pizza, dimensioni e così via). Per ulteriori informazioni sui tipi di slot e sugli slot, consultare Amazon Lex: come funziona (p. 3).

Argomenti • Passaggio 1: Creare una funzione Lambda (p. 98) • Passaggio 2: Crea un bot (p. 100) • Passaggio 3: Creare ed eseguire il test del bot (p. 105) • Fase 4 (opzionale): Elimini (p. 108)

Passaggio 1: Creare una funzione Lambda

In primo luogo, è necessario creare una funzione Lambda per realizzare l'ordine di una pizza. Questa funzione deve essere specificata nel bot Amazon Lex, creato nella sezione successiva.

Per creare una funzione Lambda

1. Accedi alla AWS Management Console e apri la console AWS Lambda all'indirizzo https:// console.aws.amazon.com/lambda/. 2. Seleziona Create function (Crea funzione). 3. Nella pagina Create function (Crea funzione), scegli Author from scratch (Crea da zero).

Per creare una funzione Lambda si utilizzerà il codice personalizzato fornito in questo esercizio, pertanto è necessario selezionare la funzione di creazione da zero.

Eseguire questa operazione:

a. Digita il nome (PizzaOrderProcessor). b. Per il Runtime (Runtime), scegliere la versione più recente di Node.js. c. Seleziona Create new role from template(s) (Crea nuovo ruolo da modello/i) come Role (Ruolo). d. Immetti un nuovo nome ruolo (PizzaOrderProcessorRole). e. Seleziona Create function (Crea funzione). 4. Nella pagina della funzione esegui questi passaggi:

Nella sezione Function code (Codice funzione) seleziona Edit code inline (Modifica codice in linea) e quindi copia e incolla il seguente codice funzione Node.js nella finestra.

'use strict';

// Close dialog with the customer, reporting fulfillmentState of Failed or Fulfilled ("Thanks, your pizza will arrive in 20 minutes") function close(sessionAttributes, fulfillmentState, message) { return {

98 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

sessionAttributes, dialogAction: { type: 'Close', fulfillmentState, message, }, }; }

// ------Events ------

function dispatch(intentRequest, callback) { console.log(`request received for userId=${intentRequest.userId}, intentName= ${intentRequest.currentIntent.name}`); const sessionAttributes = intentRequest.sessionAttributes; const slots = intentRequest.currentIntent.slots; const crust = slots.crust; const size = slots.size; const pizzaKind = slots.pizzaKind;

callback(close(sessionAttributes, 'Fulfilled', {'contentType': 'PlainText', 'content': `Okay, I have ordered your ${size} ${pizzaKind} pizza on ${crust} crust`}));

}

// ------Main handler ------

// Route the incoming request based on intent. // The JSON body of the request is provided in the event slot. exports.handler = (event, context, callback) => { try { dispatch(event, (response) => { callback(null, response); }); } catch (err) { callback(err); } };

5. Seleziona Save (Salva).

Esecuzione del test della funzione Lambda utilizzando dati evento di esempio

Esegui il test della funzione Lambda nella console utilizzando i dati evento di esempio per chiamare la funzione in modo manuale.

Per testare la funzione Lambda:

1. Accedi alla AWS Management Console e apri la console AWS Lambda all'indirizzo https:// console.aws.amazon.com/lambda/. 2. Nella pagina Lambda function (Funzione ) seleziona la funzione Lambda (PizzaOrderProcessor).) 3. Nella pagina delle funzioni, nell'elenco degli eventi di test, seleziona Configure test events (Configura eventi di test). 4. Nella pagina Configure test event (Configura evento di test) segui la procedura riportata di seguito.

a. Seleziona Create new test event (Crea nuovo evento di test). b. Nel campo Event name (Nome evento) immetti il nome per l'evento (PizzaOrderProcessorTest). c. Copia il seguente evento Amazon Lex nella finestra.

99 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

{ "messageVersion": "1.0", "invocationSource": "FulfillmentCodeHook", "userId": "user-1", "sessionAttributes": {}, "bot": { "name": "PizzaOrderingApp", "alias": "$LATEST", "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "OrderPizza", "slots": { "size": "large", "pizzaKind": "meat", "crust": "thin" }, "confirmationStatus": "None" } }

5. Scegliere Create (Crea).

Dopo la creazione del test in AWS Lambda, torna alla pagina delle funzioni. Scegli Verifica e Lambda esegue il tuo Lambda funzione.

Nella casella dei risultati, seleziona Details (Dettagli). Il seguente output verrà visualizzato nel riquadro Execution result (Risultato esecuzione) della console.

{ "sessionAttributes": {}, "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Okay, I have ordered your large meat pizza on thin crust." } }

Approfondimenti

Passaggio 2: Crea un bot (p. 100) Passaggio 2: Crea un bot

In questa fase verrà creato un bot per la gestione degli ordini di pizza.

Argomenti • Creazione del bot (p. 101) • Creazione di un intento (p. 101) • Creazione dei tipi di slot (p. 102) • Configurazione dell'intento (p. 103) • Configurazione del bot (p. 104)

100 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

Creazione del bot

Crea il bot PizzaOrderingBot con le informazioni minime necessarie. In seguito, verrà aggiunto un intento, ovvero l'operazione che l'utente desidera eseguire.

Per creare il bot

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Crea un bot.

a. Se si tratta della tua prima creazione di un bot, seleziona Get Started (Inizia). In caso contrario, seleziona Bots, quindi Create (Crea). b. Nella pagina Create your Lex bot (Crea bot di Lex), seleziona Custom bot (Bot personalizzato) e fornisci le seguenti informazioni:

• Nome bot: PizzaOrderingBot • Linguaggio: Scegli la lingua e le impostazioni internazionali per il tuo bot. • Voce in uscita: Salli • Timeout di sessione: 5 minuti • Programma di protezione dei processi (COPPA): Scegliere la risposta appropriata. • Archiviazione enunciazione utente: Scegliere la risposta appropriata. c. Scegliere Create (Crea).

La console invia Amazon Lex una richiesta per creare un nuovo bot. Amazon Lex imposta la versione del bot su $LATEST. Dopo aver creato il bot, Amazon Lex mostra il bot Redattore scheda:

• La versione Latest (Più recente) del bot appare accanto al nome del bot nella console. Le nuove risorse di Amazon Lex hanno versione $LATEST. Per ulteriori informazioni, vedi Funzione Versioni multiple e alias (p. 136). • Poiché non è stato creato alcun tipo di intento o di slot, nell'elenco non è visualizzato alcun tipo. • Build (Crea) e Publish (Pubblica) sono attività a livello di bot. Dopo aver configurato l'intero bot, potrai scoprire ulteriori informazioni su queste attività.

Approfondimenti

Creazione di un intento (p. 101)

Creazione di un intento

A questo punto, con le informazioni minime necessarie, verrà creato l'intento OrderPizza, ovvero l'operazione che l'utente desidera eseguire. Verranno aggiunti i tipi di slot per l'intento e quindi configurato l'intento in un momento successivo.

101 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

Per creare un intento

1. Nella console di Amazon Lex, seleziona il segno più (+) accanto a Intents (Intenti), quindi Create new intent (Crea nuovo intento). 2. Nella finestra di dialogo Create intent (Crea intento) digita il nome dell'intento (OrderPizza) e quindi seleziona Add (Aggiungi).

La console invia una richiesta a Amazon Lex per la creazione dell'intento OrderPizza. In questo esempio si creano slot per l'intento dopo aver creato i tipi di slot.

Approfondimenti

Creazione dei tipi di slot (p. 102) Creazione dei tipi di slot

A questo punto è necessario creare i tipi di slot o i valori dei parametri utilizzati dall'intento OrderPizza.

Per creare i tipi di slot

1. Nel menu a sinistra, seleziona il segno più (+) accanto a Slot types (Tipi di slot). 2. Nella finestra di dialogo Add slot type (Aggiungi tipo di slot) aggiungi i seguenti elementi:

• Nome tipo di slot – Croste • Descrizione – Crosta disponibile • Seleziona l'opzione Restrict to Slot values and Synonyms (Limita a valori slot e sinonimi). • Valore – Tipo thick. Premere il tasto Tab e nel Sinonimo tipo di campo stuffed. Scegliere il segno più (+). Digita thin e quindi scegli di nuovo il segno più (+).

La finestra di dialogo dovrebbe essere simile alla seguente:

3. Seleziona Add slot to intent (Aggiungi slot a intento).

102 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

4. Nella pagina Intent (Intento) seleziona Required (Obbligatorio). Modificare il nome dello slot da slotOne a crust. Modificare il prompt in What kind of crust would you like? 5. Ripeti Step 1 a Step 4 utilizzando i valori della seguente tabella:

Name (Nome) Description Valori Nome slot Prompt (Descrizione)

Dimensioni Dimensioni small, medium, formato Quali dimensioni disponibili large per la pizza?

PizzaKind Pizze disponibili alle verdure, ai pizzaKind Desideri una formaggi pizza alle verdure o ai formaggi?

Approfondimenti

Configurazione dell'intento (p. 103)

Configurazione dell'intento

Configura l'intento OrderPizza per soddisfare la richiesta di un utente che desidera ordinare una pizza.

Per configurare un intento

• Nella pagina di configurazione OrderPizza configura l'intento come segue:

• Espressioni di esempio – Digitare le seguenti stringhe. I nomi degli slot sono racchiusi tra parentesi graffe {}. • Vorrei ordinare una pizza • Voglio ordinare una pizza • Voglio ordinare una pizza {pizzaKind} • Voglio ordinare una pizza {size} {pizzaKind} • Voglio ordinare una pizza {size} con bordo • È possibile ordinare una pizza? • È possibile ordinare una pizza {pizzaKind}? • È possibile ordinare una pizza {size} {pizzaKind}? • Inizializzazione e convalida Lambda – Lasciare l'impostazione predefinita. • Richiesta di conferma – Lasciare l'impostazione predefinita. • Adempimento – Eseguire le seguenti operazioni: • Scegli AWS Lambda function (Funzione ). • Scegli PizzaOrderProcessor. • Se viene visualizzata la finestra di dialogo Add permission to Lambda function (Aggiungi autorizzazione alla funzione ), scegli OK per fornire all'intento OrderPizza l'autorizzazione per la chiamata della funzione Lambda PizzaOrderProcessor. • Lascia selezionato il valore None (Nessuno).

L'intento sarà simile al seguente:

103 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

Approfondimenti

Configurazione del bot (p. 104)

Configurazione del bot

Configura la gestione degli errori per il bot PizzaOrderingBot.

1. Passa al bot PizzaOrderingBot. Scegli Editor, quindi seleziona Error Handling (Gestione degli errori).

104 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

2. Utilizza la scheda Editor per configurare la gestione degli errori del bot.

• Le informazioni fornite in Clarification Prompts(Prompt di chiarimento) eseguono la mappatura alla configurazione del clarificationPrompt del bot.

Quando Amazon Lex non è in grado di determinare l'intento dell'utente, il servizio restituisce una risposta utilizzando tale messaggio. • Le informazioni fornite nella frase di Hang-up (Sospensione) eseguono la mappatura alla configurazione di abortStatement del bot.

Se il servizio non è in grado di determinare l'intento dell'utente dopo un determinato numero di richieste consecutive, Amazon Lex restituisce una risposta utilizzando tale messaggio.

Mantieni le impostazioni predefinite.

Approfondimenti

Passaggio 3: Creare ed eseguire il test del bot (p. 105) Passaggio 3: Creare ed eseguire il test del bot

Assicurati che il bot funzioni creandolo ed eseguendo il test.

Per creare ed eseguire il test del bot

1. Per creare il bot PizzaOrderingBot seleziona Build (Crea).

Amazon Lex crea un modello di machine learning per il bot. Quando esegui il test del bot, la console utilizza l'API di runtime per inviare l'input utente a Amazon Lex. Amazon Lex utilizza quindi il modello di machine learning per interpretare l'input utente.

La creazione potrebbe richiedere un po' di tempo. 2. Per eseguire il test del bot, nella finestra Test Bot (Test del bot) avvia la comunicazione con il bot Amazon Lex.

• Ad esempio, potresti pronunciare o digitare quanto segue:

105 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

• Per eseguire il test del bot, utilizza le enunciazioni di esempio configurate nell'intento OrderPizza. Ad esempio, quanto segue è una delle enunciazioni di esempio configurata per l'intento PizzaOrder:

I want a {size} {crust} crust {pizzaKind} pizza

Per eseguire il test, digita quanto segue:

I want a large thin crust cheese pizza

Se digiti "I want to order a pizza", Amazon Lex rileva l'intento (OrderPizza). Quindi, Amazon Lex chiede informazioni sullo slot.

Dopo aver fornito tutte le informazioni sugli slot, Amazon Lex richiama la funzione Lambda configurata per l'intento.

La funzione Lambda restituisce un messaggio ("Okay, I have ordered your ...") ad Amazon Lex, che Amazon Lex restituisce all'utente.

Esame della risposta

Sotto la finestra della chat è presente un riquadro che consente di esaminare la risposta di Amazon Lex. Il riquadro fornisce informazioni complete sullo stato del bot con modifiche dinamiche che riflettono l'interazione in corso tra l'utente il bot.

Il contenuto del riquadro mostra lo stato corrente dell'operazione.

106 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

• Stato finestra di dialogo – Lo stato corrente della conversazione con l'utente. Può essere ElicitIntent, ElicitSlot, ConfirmIntent o Fulfilled.

• Riepilogo – Mostra una vista semplificata della finestra di dialogo che mostra i valori di slot per l'intento che viene soddisfatto in modo da poter tenere traccia del flusso di informazioni. Vengono mostrati il nome dell'intento, il numero di slot, il numero di slot popolati e un elenco di tutti gli slot e dei relativi valori associati.

• Dettaglio – Mostra la risposta JSON non elaborata dal chatbot per fornire una visione più approfondita dell'interazione bot e dello stato corrente della finestra di dialogo durante il test e il debug del chatbot. Se si digita nella finestra della chat, il riquadro di ispezione mostra la risposta JSON dell'operazione PostText (p. 434). Se si utilizza la comunicazione vocale nella finestra della chat, il riquadro di ispezione mostra le intestazioni della risposta dall'operazione PostContent (p. 425).

107 Amazon Lex Guida per gli sviluppatori Esercizio 2: Crea un bot personalizzato

Approfondimenti

Fase 4 (opzionale): Elimini (p. 108) Fase 4 (opzionale): Elimini

È possibile eliminare le risorse create ed effettuare la pulizia dell'account per evitare di incorrere in ulteriori costi per le risorse create.

Puoi eliminare solo le risorse che non sono in uso. Ad esempio, non è possibile eliminare un tipo di slot a cui fa riferimento un intento. Non è possibile eliminare un intento a cui fa riferimento un bot.

Per eliminare le risorse, procedere in questo ordine:

• Elimina i bot per liberare risorse di intenti. • Elimina gli intenti per liberare risorse di tipo di slot. • Elimina i tipi di slot come ultima cosa.

Per effettuare la pulizia dell'account:

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Nell'elenco dei bot seleziona PizzaOrderingBot. 3. Per eliminare il bot, seleziona Delete (Elimina) e quindi Continue (Continua). 4. Nel riquadro a sinistra seleziona Intents (Intenti).

108 Amazon Lex Guida per gli sviluppatori Esercizio 3. Pubblicazione di una versione e creazione di un alias

5. Nell'elenco di intenti seleziona OrderPizza. 6. Per eliminare l'intento, seleziona Delete (Elimina) e quindi Continue (Continua). 7. Nel menu a sinistra seleziona Slot types (Tipi di slot). 8. Nell'elenco di tipi di slot, seleziona Crusts (Bordi). 9. Per eliminare il tipo di bot seleziona Delete (Elimina) e quindi Continue (Continua). 10. Ripeti Step 8 e Step 9 per i tipi di slot Sizes e PizzaKind.

Hai rimosso tutte le risorse che hai creato e hai pulito il tuo account.

Fasi successive

• Pubblicazione di una versione e creazione di un alias • Creazione di un Amazon Lex con il AWS Command Line Interface

Esercizio 3. Pubblicazione di una versione e creazione di un alias

Negli esercizi introduttivi 1 e 2 hai creato un bot e ne hai eseguito il test. In questo esercizio, devi effettuare le seguenti operazioni:

• Pubblicazione di una nuova versione del bot. Amazon Lex esegue una copia snapshot della versione $LATEST per pubblicare una nuova versione. • Creazione di un alias che punta alla nuova versione.

Per ulteriori informazioni sulla funzione Versioni multiple e sugli alias, consulta Funzione Versioni multiple e alias (p. 136).

Per pubblicare una versione di un bot creato per questo esercizio, procedi come descritto di seguito:

1. Nella console di Amazon Lex, scegli uno dei bot che hai creato.

Verifica che la console visualizzi la versione $LATEST accanto al nome del bot. 2. Seleziona Publish (Pubblica). 3. Nella procedura guidata Publish (Pubblica) nome bot, specifica l'alias BETA, quindi scegli Publish (Pubblica). 4. Verifica che la console di Amazon Lex visualizzi la nuova versione accanto al nome del bot.

109 Amazon Lex Guida per gli sviluppatori Step 4: Getting Started (AWS CLI)

Ora che disponi di un bot con un alias e una versione pubblicata, puoi distribuirlo (nella tua applicazione per dispositivi mobili o integrarlo in Facebook Messenger). Per un esempio, consultare Integrating an Amazon Lex Bot with Facebook Messenger (p. 153).

Step 4: Getting Started (AWS CLI)

In questa fase, userai AWS CLI per creare, testare e modificare un bot di Amazon Lex. Per completare questi esercizi, dovrai acquisire familiarità con l'uso dell'interfaccia a riga di comando (CLI) e disporre di un editor di testo. Per ulteriori informazioni, consulta Fase 2: configurazione diAWS Command Line Interface (p. 70)

• Exercise 1 — Create and test an Amazon Lex bot. The exercise provides all of the JSON objects that you need to create a custom slot type, an intent, and a bot. For more information, see Amazon Lex: come funziona (p. 3) • Exercise 2 — Update the bot that you created in Exercise 1 to add an additional sample utterance. Amazon Lex uses sample utterances to build the machine learning model for your bot. • Exercise 3 — Update the bot that you created in Exercise 1 to add a Lambda function to validate user input and to fulfill the intent. • Exercise 4 — Publish a version of the slot type, intent, and bot resources that you created in Exercise 1. A version is a snapshot of a resource that can't be changed. • Exercise 5 — Create an alias for the bot that you created in Exercise 1. • Exercise 6 — Clean up your account by deleting the slot type, intent, and bot that you created in Exercise 1, and the alias that you created in Exercise 5.

Argomenti • Exercise 1: Create an Amazon Lex Bot (AWS CLI) (p. 110) • Exercise 2: Add a New Utterance (AWS CLI) (p. 122) • Exercise 3: Add a Lambda Function (AWS CLI) (p. 126) • Exercise 4: Publish a Version (AWS CLI) (p. 129) • Exercise 5: Create an Alias (AWS CLI) (p. 133) • Exercise 6: Clean Up (AWS CLI) (p. 134)

Exercise 1: Create an Amazon Lex Bot (AWS CLI)

In generale, quando crei bot:

1. Crei tipi di slot per definire le informazioni che verranno utilizzate dal tuo bot. 2. Crei intenti che definiscano le operazioni dell'utente supportate dal bot. Usa i tipi di slot personalizzati che hai creato in precedenza per definire gli slot, o parametri, richiesti dal tuo intento. 3. Crei un bot che utilizzi gli intenti da te definiti.

In questo esercizio devi creare e testare un nuovo bot di Amazon Lex utilizzando l'interfaccia a riga di comando. Usa le strutture JSON fornite per creare il bot. Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Argomenti • Step 1: Create a Service-Linked Role (AWS CLI) (p. 111)

110 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

• Step 2: Create a Custom Slot Type (AWS CLI) (p. 111) • Step 3: Create an Intent (AWS CLI) (p. 113) • Step 4: Create a Bot (AWS CLI) (p. 116) • Step 5: Test a Bot (AWS CLI) (p. 118)

Step 1: Create a Service-Linked Role (AWS CLI)

Amazon Lex assume i ruoli collegati ai servizi di AWS Identity and Access Management per chiamare i servizi AWS per conto dei tuoi bot. I ruoli presenti nel tuo account sono collegati ai casi d'uso di Amazon Lex e dispongono di autorizzazioni predefinite. Per ulteriori informazioni, vedi Using Service-Linked Roles for Amazon Lex (p. 245).

Se hai già creato un bot di Amazon Lex utilizzando la console, il ruolo collegato ai servizi è stato creato automaticamente. Passa a Step 2: Create a Custom Slot Type (AWS CLI) (p. 111).

Per creare un ruolo collegato ai servizi (AWS CLI)

1. In AWS CLI, digita il comando seguente:

aws iam create-service-linked-role --aws-service-name lex.amazonaws.com

2. Controlla la policy utilizzando il comando seguente:

aws iam get-role --role-name AWSServiceRoleForLexBots

La risposta è:

{ "Role": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "lex.amazonaws.com" } } ] }, "RoleName": "AWSServiceRoleForLexBots", "Path": "/aws-service-role/lex.amazonaws.com/", "Arn": "arn:aws:iam::account-id:role/aws-service-role/lex.amazonaws.com/ AWSServiceRoleForLexBots" }

Next Step

Step 2: Create a Custom Slot Type (AWS CLI) (p. 111) Step 2: Create a Custom Slot Type (AWS CLI)

Crea un tipo di slot personalizzato con i valori di enumerazione dei fiori che è possibile ordinare. Userai questo tipo nella fase successiva per creare l'intento OrderFlowers. A slot type definisce i valori possibili per uno slot o un parametro dell'intento.

111 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Per creare un tipo di slot personalizzato (AWS CLI)

1. Creare un file di testo denominato FlowerTypes.json. Copiare il codice JSON da FlowerTypes.json (p. 112) nel file di testo. 2. Chiama l'operazione PutSlotType (p. 400) utilizzando AWS CLI per creare il tipo di slot. L'esempio è formattato per Unix, Linux e macOS. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws lex-models put-slot-type \ --region region \ --name FlowerTypes \ --cli-input-json file://FlowerTypes.json

La risposta del server è:

{ "enumerationValues": [ { "value": "tulips" }, { "value": "lilies" }, { "value": "roses" } ], "name": "FlowerTypes", "checksum": "checksum", "version": "$LATEST", "lastUpdatedDate": timestamp, "createdDate": timestamp, "description": "Types of flowers to pick up" }

Next Step

Step 3: Create an Intent (AWS CLI) (p. 113) FlowerTypes.json

Il codice seguente rappresenta i dati JSON necessari per creare il tipo di slot personalizzato FlowerTypes:

{ "enumerationValues": [ { "value": "tulips" }, { "value": "lilies" }, { "value": "roses" } ], "name": "FlowerTypes",

112 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

"description": "Types of flowers to pick up" }

Step 3: Create an Intent (AWS CLI)

Crea un intento per il bot OrderFlowersBot e fornisci tre slot, o parametri. Gli slot consentono al bot di realizzare l'intento:

• FlowerType is a custom slot type that specifies which types of flowers can be ordered. • AMAZON.DATE and AMAZON.TIME are built-in slot types used for getting the date and time to deliver the flowers from the user.

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Per creare l'intento OrderFlowers (AWS CLI)

1. Creare un file di testo denominato OrderFlowers.json. Copiare il codice JSON da OrderFlowers.json (p. 115) nel file di testo. 2. In AWS CLI, chiama l'operazione PutIntent (p. 388) per creare l'intento. L'esempio è formattato per Unix, Linux e macOS. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws lex-models put-intent \ --region region \ --name OrderFlowers \ --cli-input-json file://OrderFlowers.json

Il server risponde come segue:

{ "confirmationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Okay, your {FlowerType} will be ready for pickup by {PickupTime} on {PickupDate}. Does this sound okay?", "contentType": "PlainText" } ] }, "name": "OrderFlowers", "checksum": "checksum", "version": "$LATEST", "rejectionStatement": { "messages": [ { "content": "Okay, I will not place your order.", "contentType": "PlainText" } ] }, "createdDate": timestamp, "lastUpdatedDate": timestamp, "sampleUtterances": [ "I would like to pick up flowers", "I would like to order some flowers" ],

113 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

"slots": [ { "slotType": "AMAZON.TIME", "name": "PickupTime", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Pick up the {FlowerType} at what time on {PickupDate}?", "contentType": "PlainText" } ] }, "priority": 3, "description": "The time to pick up the flowers" }, { "slotType": "FlowerTypes", "name": "FlowerType", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What type of flowers would you like to order?", "contentType": "PlainText" } ] }, "priority": 1, "slotTypeVersion": "$LATEST", "sampleUtterances": [ "I would like to order {FlowerType}" ], "description": "The type of flowers to pick up" }, { "slotType": "AMAZON.DATE", "name": "PickupDate", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What day do you want the {FlowerType} to be picked up?", "contentType": "PlainText" } ] }, "priority": 2, "description": "The date to pick up the flowers" } ], "fulfillmentActivity": { "type": "ReturnIntent" }, "description": "Intent to order a bouquet of flowers for pick up" }

114 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

Next Step

Step 4: Create a Bot (AWS CLI) (p. 116) OrderFlowers.json

Il codice seguente rappresenta i dati JSON necessari per creare l'intento OrderFlowers:

{ "confirmationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Okay, your {FlowerType} will be ready for pickup by {PickupTime} on {PickupDate}. Does this sound okay?", "contentType": "PlainText" } ] }, "name": "OrderFlowers", "rejectionStatement": { "messages": [ { "content": "Okay, I will not place your order.", "contentType": "PlainText" } ] }, "sampleUtterances": [ "I would like to pick up flowers", "I would like to order some flowers" ], "slots": [ { "slotType": "FlowerTypes", "name": "FlowerType", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What type of flowers would you like to order?", "contentType": "PlainText" } ] }, "priority": 1, "slotTypeVersion": "$LATEST", "sampleUtterances": [ "I would like to order {FlowerType}" ], "description": "The type of flowers to pick up" }, { "slotType": "AMAZON.DATE", "name": "PickupDate", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What day do you want the {FlowerType} to be picked up?", "contentType": "PlainText" }

115 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

] }, "priority": 2, "description": "The date to pick up the flowers" }, { "slotType": "AMAZON.TIME", "name": "PickupTime", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Pick up the {FlowerType} at what time on {PickupDate}?", "contentType": "PlainText" } ] }, "priority": 3, "description": "The time to pick up the flowers" } ], "fulfillmentActivity": { "type": "ReturnIntent" }, "description": "Intent to order a bouquet of flowers for pick up" }

Step 4: Create a Bot (AWS CLI)

Il bot OrderFlowersBot include l'intento OrderFlowers creato nella fase precedente. Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262). Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\ $LATEST" in $LATEST.

Per creare il bot OrderFlowersBot (AWS CLI)

1. Creare un file di testo denominato OrderFlowersBot.json. Copiare il codice JSON da OrderFlowersBot.json (p. 117) nel file di testo. 2. In AWS CLI, chiama l'operazione PutBot (p. 372) per creare il bot. L'esempio è formattato per Unix, Linux e macOS. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws lex-models put-bot \ --region region \ --name OrderFlowersBot \ --cli-input-json file://OrderFlowersBot.json

La risposta del server è riportata di seguito. Quando crei o aggiorni bot, il status il campo è impostato su BUILDING. Ciò indica che il bot non è pronto all'uso. Usa l'operazione GetBot (p. 302) della fase successiva per determinare quando il bot è pronto all'uso.

{ "status": "BUILDING", "intents": [ {

116 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

"intentVersion": "$LATEST", "intentName": "OrderFlowers" } ], "name": "OrderFlowersBot", "locale": "en-US", "checksum": "checksum", "abortStatement": { "messages": [ { "content": "Sorry, I'm not able to assist at this time", "contentType": "PlainText" } ] }, "version": "$LATEST", "lastUpdatedDate": timestamp, "createdDate": timestamp, "clarificationPrompt": { "maxAttempts": 2, "messages": [ { "content": "I didn't understand you, what would you like to do?", "contentType": "PlainText" } ] }, "voiceId": "Salli", "childDirected": false, "idleSessionTTLInSeconds": 600, "processBehavior": "BUILD", "description": "Bot to order flowers on the behalf of a user" }

3. Per determinare se il tuo nuovo bot è pronto all'uso, esegui il comando riportato di seguito. Ripetere questo comando fino a status resi sul campo READY. L'esempio è formattato per Unix, Linux e macos. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws lex-models get-bot \ --region region \ --name OrderFlowersBot \ --version-or-alias "\$LATEST"

Individua il campo status nella risposta:

{ "status": "READY",

...

}

Next Step

Step 5: Test a Bot (AWS CLI) (p. 118) OrderFlowersBot.json

Il codice seguente fornisce i dati JSON necessari per creare il bot di OrderFlowers Amazon Lex:

117 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

{ "intents": [ { "intentVersion": "$LATEST", "intentName": "OrderFlowers" } ], "name": "OrderFlowersBot", "locale": "en-US", "abortStatement": { "messages": [ { "content": "Sorry, I'm not able to assist at this time", "contentType": "PlainText" } ] }, "clarificationPrompt": { "maxAttempts": 2, "messages": [ { "content": "I didn't understand you, what would you like to do?", "contentType": "PlainText" } ] }, "voiceId": "Salli", "childDirected": false, "idleSessionTTLInSeconds": 600, "description": "Bot to order flowers on the behalf of a user" }

Step 5: Test a Bot (AWS CLI)

Per testare il bot, puoi utilizzare un test basato sull'input vocale o di testo.

Argomenti • Test the Bot Using Text Input (AWS CLI) (p. 118) • Test the Bot Using Speech Input (AWS CLI) (p. 120)

Test the Bot Using Text Input (AWS CLI)

Per verificare che il bot funzioni correttamente con l'input di testo, usa l'operazione PostText (p. 434). Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Runtime Service Quotas (p. 261). Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per testare il bot utilizzando l'input di testo (AWS CLI)

1. In AWS CLI, avvia una conversazione con il bot OrderFlowersBot. L'esempio è formattato per Unix, Linux e macOS. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws lex-runtime post-text \ --region region \

118 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

--bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --input-text "i would like to order flowers"

Amazon Lex riconosce l'intento dell'utente e avvia una conversazione restituendo la risposta seguente:

{ "slotToElicit": "FlowerType", "slots": { "PickupDate": null, "PickupTime": null, "FlowerType": null }, "dialogState": "ElicitSlot", "message": "What type of flowers would you like to order?", "intentName": "OrderFlowers" }

2. Esegui i comandi riportati di seguito per completare la conversazione con il bot.

aws lex-runtime post-text \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --input-text "roses"

aws lex-runtime post-text \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --input-text "tuesday"

aws lex-runtime post-text \ --region region \ --bot-name OrderFlowersBot --bot-alias "\$LATEST" \ --user-id UserOne \ --input-text "10:00 a.m."

aws lex-runtime post-text \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --input-text "yes"

Una volta confermato l'ordine, Amazon Lex invia una risposta di soddisfazione per completare la conversazione:

{ "slots": { "PickupDate": "2017-05-16", "PickupTime": "10:00", "FlowerType": "roses" }, "dialogState": "ReadyForFulfillment", "intentName": "OrderFlowers"

119 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

}

Next Step

Test the Bot Using Speech Input (AWS CLI) (p. 120) Test the Bot Using Speech Input (AWS CLI)

Per testare il bot utilizzando file audio, usa l'operazione PostContent (p. 425). Genera i file audio utilizzando le operazioni di sintesi vocale di .

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi di Amazon Lex e Amazon Polly. Per l'elenco delle regioni relative ad Amazon Lex, consulta Runtime Service Quotas (p. 261). Per un elenco di regioni per Amazon Polly vedere AWS Regioni ed endpoint nella Amazon Web Services General Reference. Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per testare il bot utilizzando l'input vocale (AWS CLI)

1. In AWS CLI, crea un file audio utilizzando Amazon Polly. L'esempio è formattato per Unix, Linux e macOS. Per Windows, sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

aws polly synthesize-speech \ --region region \ --output-format pcm \ --text "i would like to order flowers" \ --voice-id "Salli" \ IntentSpeech.mpg

2. Pe inviare il file audio a Amazon Lex, esegui il seguente comando. Amazon Lex salva l'audio della risposta nel file di output specificato.

aws lex-runtime post-content \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --content-type "audio/l16; rate=16000; channels=1" \ --input-stream IntentSpeech.mpg \ IntentOutputSpeech.mpg

Amazon Lex risponde con una richiesta per il primo slot, quindi salva l'audio della risposta nel file di output specificato.

{ "contentType": "audio/mpeg", "slotToElicit": "FlowerType", "dialogState": "ElicitSlot", "intentName": "OrderFlowers", "inputTranscript": "i would like to order some flowers", "slots": { "PickupDate": null, "PickupTime": null,

120 Amazon Lex Guida per gli sviluppatori Exercise 1: Create a Bot

"FlowerType": null }, "message": "What type of flowers would you like to order?" }

3. Per ordinare rose, crea i file audio seguenti e inviali ad Amazon Lex:

aws polly synthesize-speech \ --region region \ --output-format pcm \ --text "roses" \ --voice-id "Salli" \ FlowerTypeSpeech.mpg

aws lex-runtime post-content \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --content-type "audio/l16; rate=16000; channels=1" \ --input-stream FlowerTypeSpeech.mpg \ FlowerTypeOutputSpeech.mpg

4. Per impostare la data di consegna, crea i file audio seguenti e inviali ad Amazon Lex:

aws polly synthesize-speech \ --region region \ --output-format pcm \ --text "tuesday" \ --voice-id "Salli" \ DateSpeech.mpg

aws lex-runtime post-content \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --content-type "audio/l16; rate=16000; channels=1" \ --input-stream DateSpeech.mpg \ DateOutputSpeech.mpg

5. Per impostare l'orario di consegna, crea i file audio seguenti e inviali ad Amazon Lex:

aws polly synthesize-speech \ --region region \ --output-format pcm \ --text "10:00 a.m." \ --voice-id "Salli" \ TimeSpeech.mpg

aws lex-runtime post-content \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --content-type "audio/l16; rate=16000; channels=1" \ --input-stream TimeSpeech.mpg \ TimeOutputSpeech.mpg

6. Per confermare la consegna, crea i file audio seguenti e inviali ad Amazon Lex:

121 Amazon Lex Guida per gli sviluppatori Exercise 2: Add a New Utterance

aws polly synthesize-speech \ --region region \ --output-format pcm \ --text "yes" \ --voice-id "Salli" \ ConfirmSpeech.mpg

aws lex-runtime post-content \ --region region \ --bot-name OrderFlowersBot \ --bot-alias "\$LATEST" \ --user-id UserOne \ --content-type "audio/l16; rate=16000; channels=1" \ --input-stream ConfirmSpeech.mpg \ ConfirmOutputSpeech.mpg

Una volta confermata la consegna, Amazon Lex invia una risposta che conferma la realizzazione dell'intento:

{ "contentType": "text/plain;charset=utf-8", "dialogState": "ReadyForFulfillment", "intentName": "OrderFlowers", "inputTranscript": "yes", "slots": { "PickupDate": "2017-05-16", "PickupTime": "10:00", "FlowerType": "roses" } }

Next Step

Exercise 2: Add a New Utterance (AWS CLI) (p. 122) Exercise 2: Add a New Utterance (AWS CLI)

Per migliorare il modello di machine learning utilizzato da Amazon Lex per riconoscere le richieste da parte degli utenti, aggiungi un'altra enunciazione di esempio al bot.

L'aggiunta di una nuova enunciazione è un processo diviso in quattro fasi.

1. Usa l'operazione GetIntent (p. 338) per ottenere un intento da Amazon Lex. 2. Aggiorna l'intento. 3. Usa l'operazione PutIntent (p. 388) per inviare l'intento aggiornato nuovamente ad Amazon Lex. 4. Usa le operazioni GetBot (p. 302) e PutBot (p. 372) per ricreare qualsiasi bot che utilizza l'intento.

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

La risposta dell'operazione GetIntent contiene un campo denominato checksum che identifica una specifica revisione dell'intento. È necessario fornire il valore checksum quando si utilizza l'operazione PutIntent (p. 388) per aggiornare un intento. In caso contrario, verrà visualizzato il messaggio di errore seguente:

122 Amazon Lex Guida per gli sviluppatori Exercise 2: Add a New Utterance

An error occurred (PreconditionFailedException) when calling the PutIntent operation: Intent intent name already exists. If you are trying to update intent name you must specify the checksum.

Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per aggiornare l'intento OrderFlowers (AWS CLI)

1. In AWS CLI, ottieni l'intento da Amazon Lex. Amazon Lex invia l'output a un file denominato OrderFlowers-V2.json.

aws lex-models get-intent \ --region region \ --name OrderFlowers \ --intent-version "\$LATEST" > OrderFlowers-V2.json

2. Apri OrderFlowers-V2.json in un editor di testo.

1. Individua e cancella i campi createdDate, lastUpdatedDate e version. 2. Aggiungi il testo seguente nel campo sampleUtterances:

I want to order flowers

3. Salvare il file . 3. Invia l'intento aggiornato ad Amazon Lex con il comando seguente:

aws lex-models put-intent \ --region region \ --name OrderFlowers \ --cli-input-json file://OrderFlowers-V2.json

Amazon Lex invia la risposta seguente:

{ "confirmationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Okay, your {FlowerType} will be ready for pickup by {PickupTime} on {PickupDate}. Does this sound okay?", "contentType": "PlainText" } ] }, "name": "OrderFlowers", "checksum": "checksum", "version": "$LATEST", "rejectionStatement": { "messages": [ { "content": "Okay, I will not place your order.", "contentType": "PlainText"

123 Amazon Lex Guida per gli sviluppatori Exercise 2: Add a New Utterance

} ] }, "createdDate": timestamp, "lastUpdatedDate": timestamp, "sampleUtterances": [ "I would like to pick up flowers", "I would like to order some flowers", "I want to order flowers" ], "slots": [ { "slotType": "AMAZON.TIME", "name": "PickupTime", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "Pick up the {FlowerType} at what time on {PickupDate}?", "contentType": "PlainText" } ] }, "priority": 3, "description": "The time to pick up the flowers" }, { "slotType": "FlowerTypes", "name": "FlowerType", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What type of flowers would you like to order?", "contentType": "PlainText" } ] }, "priority": 1, "slotTypeVersion": "$LATEST", "sampleUtterances": [ "I would like to order {FlowerType}" ], "description": "The type of flowers to pick up" }, { "slotType": "AMAZON.DATE", "name": "PickupDate", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What day do you want the {FlowerType} to be picked up?", "contentType": "PlainText" } ] }, "priority": 2, "description": "The date to pick up the flowers" } ],

124 Amazon Lex Guida per gli sviluppatori Exercise 2: Add a New Utterance

"fulfillmentActivity": { "type": "ReturnIntent" }, "description": "Intent to order a bouquet of flowers for pick up" }

Ora che l'intento è stato aggiornato, ricrea qualsiasi bot che lo utilizza.

Per ricreare il bot OrderFlowersBot (AWS CLI)

1. In AWS CLI, ottieni la definizione del bot OrderFlowersBot e salvala in un file con il comando seguente:

aws lex-models get-bot \ --region region \ --name OrderFlowersBot \ --version-or-alias "\$LATEST" > OrderFlowersBot-V2.json

2. In un editor di testo, aprire OrderFlowersBot-V2.json. Rimuovere il createdDate, lastUpdatedDate, status e version campi. 3. In un editor di testo, aggiungi la seguente riga alla definizione del bot:

"processBehavior": "BUILD",

4. In AWS CLI, crea una nuova revisione del bot eseguendo il comando riportato di seguito:

aws lex-models put-bot \ --region region \ --name OrderFlowersBot \ --cli-input-json file://OrderFlowersBot-V2.json

La risposta del server è:

{ "status": "BUILDING", "intents": [ { "intentVersion": "$LATEST", "intentName": "OrderFlowers" } ], "name": "OrderFlowersBot", "locale": "en-US", "checksum": "checksum", "abortStatement": { "messages": [ { "content": "Sorry, I'm not able to assist at this time", "contentType": "PlainText" } ] }, "version": "$LATEST", "lastUpdatedDate": timestamp, "createdDate": timestamp "clarificationPrompt": { "maxAttempts": 2, "messages": [ { "content": "I didn't understand you, what would you like to do?",

125 Amazon Lex Guida per gli sviluppatori Exercise 3: Add a Lambda Function

"contentType": "PlainText" } ] }, "voiceId": "Salli", "childDirected": false, "idleSessionTTLInSeconds": 600, "description": "Bot to order flowers on the behalf of a user" }

Next Step

Exercise 3: Add a Lambda Function (AWS CLI) (p. 126) Exercise 3: Add a Lambda Function (AWS CLI)

Aggiungi una funzione Lambda che convalidi l'input dell'utente e realizzi l'intento dell'utente per il bot.

L'aggiunta di un'espressione Lambda è un processo diviso in cinque fasi.

1. Usa la funzione AddPermission di Lambda per consentire all'intento OrderFlowers di chiamare l'operazione Lambda Invoke. 2. Usa l'operazione GetIntent (p. 338) per ottenere l'intento da Amazon Lex. 3. Aggiorna l'intento per aggiungere la funzione Lambda. 4. Usa l'operazione PutIntent (p. 388) per inviare l'intento aggiornato nuovamente ad Amazon Lex. 5. Usa le operazioni GetBot (p. 302) e PutBot (p. 372) per ricreare qualsiasi bot che utilizza l'intento.

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Se aggiungi una funzione Lambda a un intento prima di aggiungere l'autorizzazione InvokeFunction, verrà visualizzato il messaggio di errore seguente:

An error occurred (BadRequestException) when calling the PutIntent operation: Lex is unable to access the Lambda function Lambda function ARN in the context of intent intent ARN. Please check the resource-based policy on the function.

La risposta dell'operazione GetIntent contiene un campo denominato checksum che identifica una specifica revisione dell'intento. È necessario fornire il valore checksum quando si utilizza l'operazione PutIntent (p. 388) per aggiornare un intento. In caso contrario, verrà visualizzato il messaggio di errore seguente:

An error occurred (PreconditionFailedException) when calling the PutIntent operation: Intent intent name already exists. If you are trying to update intent name you must specify the checksum.

Questo esercizio utilizza la funzione Lambda creata in Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). Per istruzioni su come creare una funzione Lambda, consulta Fase 3. Creazione di una funzione Lambda (console) (p. 84).

126 Amazon Lex Guida per gli sviluppatori Exercise 3: Add a Lambda Function

Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\ $LATEST" in $LATEST.

Per aggiungere una funzione Lambda a un intento

1. In AWS CLI, aggiungi l'autorizzazione InvokeFunction per l'intento OrderFlowers:

add-permission \ --region region \ --function-name OrderFlowersCodeHook \ --statement-id LexGettingStarted-OrderFlowersBot \ --action lambda:InvokeFunction \ --principal lex.amazonaws.com \ --source-arn "arn:aws:lex:region:account ID:intent:OrderFlowers:*"

Lambda invia la risposta seguente:

{ "Statement": "{\"Sid\":\"LexGettingStarted-OrderFlowersBot\", \"Resource\":\"arn:aws:lambda:region:account ID:function:OrderFlowersCodeHook\", \"Effect\":\"Allow\", \"Principal\":{\"Service\":\"lex.amazonaws.com\"}, \"Action\":[\"lambda:InvokeFunction\"], \"Condition\":{\"ArnLike\": {\"AWS:SourceArn\": \"arn:aws:lex:region:account ID:intent:OrderFlowers:*\"}}}" }

2. Ottieni l'intento da Amazon Lex. Amazon Lex invia l'output a un file denominato OrderFlowers- V3.json.

aws lex-models get-intent \ --region region \ --name OrderFlowers \ --intent-version "\$LATEST" > OrderFlowers-V3.json

3. In un editor di testo aprire il file OrderFlowers-V3.json.

1. Individua e cancella i campi createdDate, lastUpdatedDate e version. 2. Aggiorna il campo fulfillmentActivity:

"fulfillmentActivity": { "type": "CodeHook", "codeHook": { "uri": "arn:aws:lambda:region:account ID:function:OrderFlowersCodeHook", "messageVersion": "1.0" } }

3. Salvare il file . 4. In AWS CLI, invia l'intento aggiornato a Amazon Lex:

aws lex-models put-intent \ --region region \ --name OrderFlowers \ --cli-input-json file://OrderFlowers-V3.json

127 Amazon Lex Guida per gli sviluppatori Exercise 3: Add a Lambda Function

Ora che l'intento è stato aggiornato, ricrea il bot.

Per ricreare il bot OrderFlowersBot

1. In AWS CLI, ottieni la definizione del bot OrderFlowersBot e salvala in un file:

aws lex-models get-bot \ --region region \ --name OrderFlowersBot \ --version-or-alias "\$LATEST" > OrderFlowersBot-V3.json

2. In un editor di testo, aprire OrderFlowersBot-V3.json. Rimuovere il createdDate, lastUpdatedDate, status, e version campi. 3. Nell'editor di testo, aggiungi la seguente riga alla definizione del bot:

"processBehavior": "BUILD",

4. In AWS CLI, crea una nuova revisione del bot:

aws lex-models put-bot \ --region region \ --name OrderFlowersBot \ --cli-input-json file://OrderFlowersBot-V3.json

La risposta del server è:

{ "status": "READY", "intents": [ { "intentVersion": "$LATEST", "intentName": "OrderFlowers" } ], "name": "OrderFlowersBot", "locale": "en-US", "checksum": "checksum", "abortStatement": { "messages": [ { "content": "Sorry, I'm not able to assist at this time", "contentType": "PlainText" } ] }, "version": "$LATEST", "lastUpdatedDate": timestamp, "createdDate": timestamp, "clarificationPrompt": { "maxAttempts": 2, "messages": [ { "content": "I didn't understand you, what would you like to do?", "contentType": "PlainText" } ] }, "voiceId": "Salli", "childDirected": false, "idleSessionTTLInSeconds": 600, "description": "Bot to order flowers on the behalf of a user"

128 Amazon Lex Guida per gli sviluppatori Exercise 4: Publish a Version

}

Next Step

Exercise 4: Publish a Version (AWS CLI) (p. 129) Exercise 4: Publish a Version (AWS CLI)

A questo punto, crea una versione del bot creato nell'esercizio 1. A version è una snapshot del bot. Una volta creata la versione, non potrai modificarla. L'unica versione di un bot che è possibile aggiornare è la versione $LATEST. Per ulteriori informazioni sulle versioni, consulta Funzione Versioni multiple e alias (p. 136).

Prima di pubblicare una versione di un bot, è necessario pubblicare i relativi intenti. Analogamente, è necessario pubblicare i tipi di slot cui fanno riferimento tali intenti. In generale, per pubblicare una versione di un bot:

1. Pubblichi una versione di un tipo di slot con l'operazione CreateSlotTypeVersion (p. 280). 2. Pubblichi una versione di un intento con l'operazione CreateIntentVersion (p. 274). 3. Pubblichi una versione di un bot con l'operazione CreateBotVersion (p. 269).

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Argomenti • Step 1: Publish the Slot Type (AWS CLI) (p. 129) • Step 2: Publish the Intent (AWS CLI) (p. 130) • Step 3: Publish the Bot (AWS CLI) (p. 132)

Step 1: Publish the Slot Type (AWS CLI)

Prima di pubblicare una versione di qualsiasi intento che utilizza un tipo di slot, è necessario pubblicare una versione di tale tipo di slot. In questo caso, dovrai pubblicare il tipo di slot FlowerTypes. Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per pubblicare un tipo di slot (AWS CLI)

1. In AWS CLI, ottieni la versione più recente del tipo di slot:

aws lex-models get-slot-type \ --region region \ --name FlowerTypes \ --slot-type-version "\$LATEST"

La risposta di Amazon Lex è riportata di seguito. Registra il checksum per l'attuale revisione della versione $LATEST.

129 Amazon Lex Guida per gli sviluppatori Exercise 4: Publish a Version

{ "enumerationValues": [ { "value": "tulips" }, { "value": "lilies" }, { "value": "roses" } ], "name": "FlowerTypes", "checksum": "checksum", "version": "$LATEST", "lastUpdatedDate": timestamp, "createdDate": timestamp, "description": "Types of flowers to pick up" }

2. Pubblica una versione del tipo di slot. Usa il checksum registrato nella fase precedente.

aws lex-models create-slot-type-version \ --region region \ --name FlowerTypes \ --checksum "checksum"

La risposta di Amazon Lex è riportata di seguito. Registra il numero di versione per la fase successiva.

{ "version": "1", "enumerationValues": [ { "value": "tulips" }, { "value": "lilies" }, { "value": "roses" } ], "name": "FlowerTypes", "createdDate": timestamp, "lastUpdatedDate": timestamp, "description": "Types of flowers to pick up" }

Next Step

Step 2: Publish the Intent (AWS CLI) (p. 130) Step 2: Publish the Intent (AWS CLI)

Prima di pubblicare un intento, è necessario pubblicare tutti i tipi di slot cui fa riferimento l'intento. I tipi di slot devono essere versioni numerate, anziché la versione $LATEST.

Innanzitutto, aggiorna l'intento OrderFlowers per usare la versione del tipo di slot FlowerTypes pubblicata nella fase precedente. Quindi pubblica una nuova versione dell'intento OrderFlowers.

130 Amazon Lex Guida per gli sviluppatori Exercise 4: Publish a Version

Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per pubblicare una versione di un intento (AWS CLI)

1. In AWS CLI, ottieni la versione $LATEST dell'intento OrderFlowers e salvala in un file:

aws lex-models get-intent \ --region region \ --name OrderFlowers \ --intent-version "\$LATEST" > OrderFlowers_V4.json

2. In un editor di testo, aprire il file OrderFlowers_V4.json. Elimina il createdDate, lastUpdatedDate, e version campi. Individua il tipo di slot FlowerTypes e modifica la versione nel numero di versione registrato nella fase precedente. Il seguente frammento del file OrderFlowers_V4.json mostra la posizione della modifica:

{ "slotType": "FlowerTypes", "name": "FlowerType", "slotConstraint": "Required", "valueElicitationPrompt": { "maxAttempts": 2, "messages": [ { "content": "What type of flowers?", "contentType": "PlainText" } ] }, "priority": 1, "slotTypeVersion": "version", "sampleUtterances": [] },

3. In AWS CLI, salva la revisione dell'intento:

aws lex-models put-intent \ --name OrderFlowers \ --cli-input-json file://OrderFlowers_V4.json

4. Ottieni il checksum della versione più recente dell'intento:

aws lex-models get-intent \ --region region \ --name OrderFlowers \ --intent-version "\$LATEST" > OrderFlowers_V4a.json

Il seguente frammento della risposta mostra il checksum dell'intento. Registra questo valore per la fase successiva.

"name": "OrderFlowers", "checksum": "checksum", "version": "$LATEST",

5. Pubblica una nuova versione dell'intento:

131 Amazon Lex Guida per gli sviluppatori Exercise 4: Publish a Version

aws lex-models create-intent-version \ --region region \ --name OrderFlowers \ --checksum "checksum"

Il seguente frammento della risposta mostra la nuova versione dell'intento. Registra il numero di versione per la fase successiva.

"name": "OrderFlowers", "checksum": "checksum", "version": "version",

Next Step

Step 3: Publish the Bot (AWS CLI) (p. 132) Step 3: Publish the Bot (AWS CLI)

Dopo aver pubblicato tutti i tipi di slot e gli intenti utilizzati dal tuo bot, potrai pubblicare il bot.

Aggiorna il bot OrderFlowersBot per utilizzare l'intento OrderFlowers aggiornato nella fase precedente. Quindi pubblica una nuova versione del bot OrderFlowersBot. Note

L'esempio seguente di AWS CLI è formattato per Unix, Linux e macOS. Per Windows, modifica "\$LATEST" in $LATEST e sostituisci il carattere di continuazione UNIX barra rovesciata (\) al termine di ogni riga con un accento circonflesso (^).

Per pubblicare una versione di un bot (AWS CLI)

1. In AWS CLI, ottieni la versione $LATEST del bot OrderFlowersBot e salvala in un file:

aws lex-models get-bot \ --region region \ --name OrderFlowersBot \ --version-or-alias "\$LATEST" > OrderFlowersBot_V4.json

2. In un editor di testo, aprire il file OrderFlowersBot_V4.json. Elimina il createdDate, lastUpdatedDate, status e version campi. Individua l'intento OrderFlowers e modifica la versione nel numero di versione registrato nella fase precedente. Il seguente frammento di OrderFlowersBot_V4.json mostra la posizione della modifica.

"intents": [ { "intentVersion": "version", "intentName": "OrderFlowers" }

3. In AWS CLI, salva la nuova revisione del bot: Prendere nota del numero di versione restituito dalla chiamata a put-bot.

aws lex-models put-bot \ --name OrderFlowersBot \ --cli-input-json file://OrderFlowersBot_V4.json

132 Amazon Lex Guida per gli sviluppatori Exercise 5: Create an Alias

4. Ottieni il checksum della versione più recente del bot: Utilizzare il numero di versione restituito al passaggio 3.

aws lex-models get-bot \ --region region \ --version-or-alias version \ --name OrderFlowersBot > OrderFlowersBot_V4a.json

Il seguente frammento della risposta mostra il checksum del bot. Registra questo valore per la fase successiva.

"name": "OrderFlowersBot", "locale": "en-US", "checksum": "checksum",

5. Pubblica una nuova versione del bot:

aws lex-models create-bot-version \ --region region \ --name OrderFlowersBot \ --checksum "checksum"

Il seguente frammento della risposta mostra la nuova versione del bot.

"checksum": "checksum", "abortStatement": { ... }, "version": "1", "lastUpdatedDate": timestamp,

Next Step

Exercise 5: Create an Alias (AWS CLI) (p. 133) Exercise 5: Create an Alias (AWS CLI)

Un alias è un puntatore a una specifica versione di un bot Con un alias è possibile aggiornare facilmente la versione utilizzata dalle applicazioni client. Per ulteriori informazioni, consulta Funzione Versioni multiple e alias (p. 136). Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Per creare un alias (AWS CLI)

1. In AWS CLI, ottieni la versione del bot OrderFlowersBot creato in Exercise 4: Publish a Version (AWS CLI) (p. 129).

aws lex-models get-bot \ --region region \ --name OrderFlowersBot \ --version-or-alias version > OrderFlowersBot_V5.json

2. In un editor di testo, aprire OrderFlowersBot_v5.json. Trovare e registrare il numero della versione. 3. In AWS CLI, crea l'alias del bot:

133 Amazon Lex Guida per gli sviluppatori Exercise 6: Clean Up

aws lex-models put-bot-alias \ --region region \ --name PROD \ --bot-name OrderFlowersBot \ --bot-version version

Di seguito è riportata la risposta del server:

{ "name": "PROD", "createdDate": timestamp, "checksum": "checksum", "lastUpdatedDate": timestamp, "botName": "OrderFlowersBot", "botVersion": "1" }}

Next Step

Exercise 6: Clean Up (AWS CLI) (p. 134) Exercise 6: Clean Up (AWS CLI)

Elimina le risorse che hai creato e pulisci il tuo account.

Puoi eliminare solo le risorse che non sono in uso. In generale, devi eliminare le risorse nell'ordine seguente:

1. Elimina gli alias per liberare risorse di bot. 2. Elimina i bot per liberare risorse di intenti. 3. Elimina gli intenti per liberare risorse di tipo di slot. 4. Elimina i tipi di slot.

Per eseguire i comandi di questo esercizio, devi conoscere la regione in cui verranno eseguiti i comandi. Per l'elenco delle regioni, consulta Model Building Quotas (p. 262).

Per effettuare la pulizia dell'account (AWS CLI)

1. Dalla riga di comando di AWS CLI, elimina l'alias:

aws lex-models delete-bot-alias \ --region region \ --name PROD \ --bot-name OrderFlowersBot

2. Dalla riga di comando di AWS CLI, elimina il bot:

aws lex-models delete-bot \ --region region \ --name OrderFlowersBot

3. Dalla riga di comando di AWS CLI, elimina l'intento:

aws lex-models delete-intent \

134 Amazon Lex Guida per gli sviluppatori Exercise 6: Clean Up

--region region \ --name OrderFlowers

4. Dalla riga di comando di AWS CLI, elimina il tipo di slot:

aws lex-models delete-slot-type \ --region region \ --name FlowerTypes

Hai rimosso tutte le risorse che hai creato e pulito il tuo account.

135 Amazon Lex Guida per gli sviluppatori Controllo delle versioni

Funzione Versioni multiple e alias

Amazon Lex supporta la pubblicazione di versioni di bot, intenti e tipi di slot per controllare l'implementazione utilizzata dalle applicazioni client. Una versione è una snapshot numerata del lavoro dell'utente che è possibile pubblicare per l'utilizzo in diverse parti del flusso di lavoro, quali lo sviluppo, la distribuzione beta e la produzione.

I bot di Amazon Lex supportano anche gli alias. Un alias è un puntatore a una specifica versione di un bot Con un alias è possibile aggiornare facilmente la versione utilizzata dalle applicazioni client. Ad esempio, si potrebbe associare un alias alla versione 1 di un bot. Quando si è pronti per aggiornare il bot, è possibile pubblicare la versione 2 del bot e modificare l'alias in modo che punti alla nuova versione. Poiché le applicazioni utilizzano l'alias anziché una versione specifica, tutti i client otterranno la nuova funzionalità senza necessità di un aggiornamento.

Argomenti • Controllo delle versioni (p. 136) • Alias (p. 138)

Controllo delle versioni

Quando si esegue la versione di una risorsa Amazon Lex, viene creata una snapshot della risorsa in modo che sia possibile utilizzare la risorsa esistente al momento della creazione della versione. Una volta creata una versione, mentre si continua a lavorare sull'applicazione questa versione rimarrà invariata. La versione $LATEST

Quando si crea un bot, un intento o un tipo di slot di Amazon Lex è disponibile una sola versione, la versione $LATEST.

La versione $LATEST è la copia di lavoro della risorsa. Fino a quando non si pubblica la prima versione della risorsa, è possibile aggiornare solo la versione $LATEST. La versione $LATEST è l'unica versione della risorsa disponibile.

Solo la versione $LATEST di una risorsa può utilizzare la versione $LATEST di un'altra risorsa. Ad esempio, la versione $LATEST di un bot può utilizzare la versione $LATEST di un intento e la versione $LATEST di un intento può utilizzare la versione $LATEST di un tipo di slot.

La versione $LATEST del bot deve essere utilizzata solo per i test manuali. Amazon Lex limita il numero di richieste di runtime che è possibile effettuare per la versione $LATEST del bot.

136 Amazon Lex Guida per gli sviluppatori Pubblicazione di una versione di una risorsa di Amazon Lex

Pubblicazione di una versione di una risorsa di Amazon Lex

Quando si pubblica una risorsa, Amazon Lex crea una copia della versione $LATEST e la salva come versione numerata. La versione pubblicata non può essere modificata.

È possibile creare e pubblicare versioni tramite la console Amazon Lex o l'operazione CreateBotVersion (p. 269). Per un esempio, consultare Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109).

Quando si modifica la versione $LATEST di una risorsa, è possibile pubblicare la nuova versione per rendere disponibili le modifiche per le applicazioni client. Ogni volta che si pubblica una versione, Amazon Lex copia la versione $LATEST per creare la nuova versione e incrementa il numero della versione di 1 numero. I numeri di versione non vengono mai riutilizzati. Ad esempio, se si elimina una versione con numero di risorsa 10 e quindi la si ricrea, il numero della nuova versione assegnato da Amazon Lex sarà 11.

Prima di poter pubblicare un bot, è necessario farlo puntare a una versione numerata di qualsiasi evento utilizzato. Se si tenta di pubblicare una nuova versione di un bot che utilizza la versione $LATEST di un intento, Amazon Lex restituisce un'eccezione di richiesta non valida HTTP 400. Prima di poter pubblicare una versione numerata dell'intento, è necessario far puntare l'intento a una versione numerata di qualsiasi tipo di slot utilizzato. In caso contrario, verrà restituita un'eccezione di richiesta non valida 400 HTTP.

Note

Amazon Lex pubblica una nuova versione solo se l'ultima versione pubblicata è diversa dalla versione $LATEST. Se si tenta di pubblicare la versione $LATEST senza modificarla, Amazon Lex non crea né pubblica una nuova versione. Aggiornamento di una risorsa Amazon Lex

È possibile aggiornare solo la versione $LATEST di un bot, intento o tipo di slot di Amazon Lex. Non è possibile modificare le versioni pubblicate. È possibile pubblicare una nuova versione in qualsiasi

137 Amazon Lex Guida per gli sviluppatori Eliminazione di una risorsa o versione di Amazon Lex

momento dopo aver aggiornato una risorsa tramite la console o le operazioni CreateBotVersion (p. 269), CreateIntentVersion (p. 274) o CreateSlotTypeVersion (p. 280). Eliminazione di una risorsa o versione di Amazon Lex

Amazon Lex supporta l'eliminazione di una risorsa o versione tramite la console o una delle operazioni API:

• DeleteBot (p. 284) • DeleteBotVersion (p. 290) • DeleteBotAlias (p. 286) • DeleteBotChannelAssociation (p. 288) • DeleteIntent (p. 292) • DeleteIntentVersion (p. 294) • DeleteSlotType (p. 296) • DeleteSlotTypeVersion (p. 298)

Alias

Un alias è un puntatore a una specifica versione di un bot Amazon Lex. È possibile utilizzare un alias per consentire alle applicazioni client di utilizzare una versione specifica del bot senza richiedere all'applicazione di tenere traccia di quale versione sia.

L'esempio seguente mostra due versioni di un bot Amazon Lex: la versione 1 e la versione 2. A ciascuna di queste versioni di bot è associato un alias: rispettivamente BETA e PROD. Le applicazioni client utilizzano l'alias PROD per accedere al bot.

Quando si crea una seconda versione del bot, è possibile aggiornare l'alias utilizzando la console o l'operazione PutBot (p. 372) per fare in modo che punti alla nuova versione del bot. Se si modifica l'alias, tutte le applicazioni client utilizzeranno la nuova versione. Se si verifica un problema relativo alla nuova

138 Amazon Lex Guida per gli sviluppatori Alias versione, è possibile tornare alla versione precedente semplicemente modificando l'alias in modo che punti a tale versione.

Note

Sebbene sia possibile effettuare un test della versione $LATEST di un bot nella console, quando si integra un bot con l'applicazione client si consiglia di pubblicare prima una versione e creare un alias che punta a tale versione. Utilizzare l'alias nell'applicazione client per i motivi illustrati in questa sezione. Quando si aggiorna un alias, prima di iniziare a utilizzare la nuova versione Amazon Lex attenderà fino allo scadere del timeout di sessione per tutte le sessioni correnti. Per ulteriori informazioni sul timeout di sessione, consultare the section called “Impostazione del timeout di sessione” (p. 26).

139 Amazon Lex Guida per gli sviluppatori Formato di evento di input e di risposta della funzione Lambda Utilizzo delle funzioni Lambda

Puoi creare funzioni AWS Lambda da utilizzare come hook di codice per il bot di Amazon Lex. Nella configurazione dell'intento, puoi identificare le funzioni Lambda per eseguire operazioni di inizializzazione e convalida, di adempimento o entrambi.

Ti consigliamo di utilizzare una funzione Lambda come hook di codice per il bot. Senza una funzione Lambda, il bot restituisce l'informazione sull'intento all'applicazione client per l'adempimento.

Argomenti • Formato di evento di input e di risposta della funzione Lambda (p. 140) • Amazon Lex e piani AWS Lambda (p. 150)

Formato di evento di input e di risposta della funzione Lambda

Questa sezione descrive la struttura dei dati dell'evento che Amazon Lex fornisce a una funzione Lambda. Utilizza queste informazioni per analizzare l'input nel codice Lambda. Illustra inoltre il formato della risposta che Amazon Lex prevede di ricevere in restituzione dalla funzione Lambda.

Argomenti • Formato dell'evento di input (p. 140) • Formato della risposta (p. 145)

Formato dell'evento di input

Di seguito è riportato il formato generale di un evento Amazon Lex passato a una funzione Lambda. Fai riferimento a queste informazioni quando scrivi la tua funzione Lambda. Note

Il formato di input potrebbe cambiare senza che corrisponda una modifica in messageVersion. Il codice non deve generare un errore se sono presenti nuovi campi.

{ "currentIntent": { "name": "intent-name", "nluIntentConfidenceScore": score, "slots": { "slot name": "value", "slot name": "value" }, "slotDetails": { "slot name": { "resolutions" : [ { "value": "resolved value" }, { "value": "resolved value" } ], "originalValue": "original text" }, "slot name": { "resolutions" : [

140 Amazon Lex Guida per gli sviluppatori Formato dell'evento di input

{ "value": "resolved value" }, { "value": "resolved value" } ], "originalValue": "original text" } }, "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)" }, "alternativeIntents": [ { "name": "intent-name", "nluIntentConfidenceScore": score, "slots": { "slot name": "value", "slot name": "value" }, "slotDetails": { "slot name": { "resolutions" : [ { "value": "resolved value" }, { "value": "resolved value" } ], "originalValue": "original text" }, "slot name": { "resolutions" : [ { "value": "resolved value" }, { "value": "resolved value" } ], "originalValue": "original text" } }, "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)" } ], "bot": { "name": "bot name", "alias": "bot alias", "version": "bot version" }, "userId": "User ID specified in the POST request to Amazon Lex.", "inputTranscript": "Text used to process the request", "invocationSource": "FulfillmentCodeHook or DialogCodeHook", "outputDialogMode": "Text or Voice, based on ContentType request header in runtime API request", "messageVersion": "1.0", "sessionAttributes": { "key": "value", "key": "value" }, "requestAttributes": { "key": "value", "key": "value" }, "recentIntentSummaryView": [ { "intentName": "Name", "checkpointLabel": Label, "slots": { "slot name": "value", "slot name": "value" }, "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)", "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close",

141 Amazon Lex Guida per gli sviluppatori Formato dell'evento di input

"fulfillmentState": "Fulfilled or Failed", "slotToElicit": "Next slot to elicit" } ], "sentimentResponse": { "sentimentLabel": "sentiment", "sentimentScore": "score" }, "kendraResponse": { Complete query response from Amazon Kendra }, "activeContexts": [ { "timeToLive": { "timeToLiveInSeconds": seconds, "turnsToLive": turns }, "name": "name", "parameters": { "key name": "value" } } ] }

Tieni conto delle ulteriori informazioni seguenti sui campi di evento:

• currentIntent – Fornisce i campi name, slots, slotDetails e confirmationStatus dell'intento.

nluIntentConfidenceScore è la certezza che Amazon Lex abbia l'intento corrente che corrisponde al meglio all'intento corrente dell'utente.

slots è una mappa di nomi di slot, configurati per l'intento, per i valori degli slot che Amazon Lex ha riconosciuto nella conversazione con l'utente. Un valore di slot rimane null fino a quando l'utente non fornisca un valore.

Il valore dello slot nell'evento di input potrebbe non corrispondere a uno dei valori configurati per lo slot. Ad esempio, se l'utente risponde al prompt "Quale colore preferisci per l'auto?" con "pizza", Amazon Lex restituirà "pizza" come valore dello slot. La funzione dovrebbe convalidare i valori per assicurare che questi abbiano senso nel contesto.

slotDetails fornisce ulteriori informazioni su un valore dello slot. La matrice resolutions contiene un elenco di valori aggiuntivi riconosciuti per lo slot. Ciascuno slot può avere un massimo di cinque valori.

Il campo originalValue contiene il valore che l'utente ha inserito per lo slot. Quando il tipo di slot è configurato per restituire il valore di risoluzione superiore come valore dello slot, originalValue potrebbe essere diverso dal valore del campo slots.

confirmationStatus fornisce la risposta dell'utente a un messaggio di richiesta di conferma, se disponibile. Ad esempio, se Amazon Lex chiede "Vuoi ordinare una pizza grande al caffè?", in base alla 142 Amazon Lex Guida per gli sviluppatori Formato dell'evento di input

risposta dell'utente, il valore di questo campo può essere Confirmed o Denied. In caso contrario, il valore di questo campo è None.

Se l'utente conferma l'intento, Amazon Lex imposta questo campo su Confirmed. Se l'utente nega l'intento, Amazon Lex imposta questo valore su Denied.

Nella risposta di conferma, un'enunciazione utente potrebbe fornire aggiornamenti dello slot. Ad esempio, l'utente potrebbe dire "Sì, modifica dimensione a media". In questo caso, l'evento Lambda successivo presenterà il valore dello slot aggiornato PizzaSize impostato su medium. Amazon Lex imposta confirmationStatus su None, in quanto l'utente ha modificato alcuni dati dello slot, richiedendo alla funzione Lambda di eseguire la convalida dei dati utente.

• alternativeIntents – Se si abilitano i punteggi di attendibilità, Amazon Lex restituisce fino a quattro intenti alternativi. Ciascun intento include un punteggio che indica il livello di affidabilità di Amazon Lex circa il fatto che l'intento sia corretto in base all'enunciazione dell'utente.

Il contenuto degli intenti alternativi è uguale al contenuto del campo currentIntent. Per ulteriori informazioni, consulta Using Confidence Scores (p. 28).

• bot Informazioni sul bot che ha elaborato la richiesta.– • name – Il nome del bot che ha elaborato la richiesta. • alias – L'alias della versione del bot che ha elaborato la richiesta. • version – La versione del bot che ha elaborato la richiesta.

• userId – Questo valore viene fornito dall'applicazione client. Amazon Lex lo passa alla funzione Lambda.

• inputTranscript – Il testo utilizzato per elaborare la richiesta.

Se si tratta di un input di testo, il campo inputTranscript contiene il testo inserito dall'utente.

In caso di input di flusso audio, il campo inputTranscript contiene il testo estratto dal flusso audio. Questo è il testo che viene effettivamente elaborato per riconoscere gli intenti e i valori dello slot.

• invocationSource – Per indicare perché Amazon Lex richiama la funzione Lambda imposta uno dei seguenti valori: • DialogCodeHook – Amazon Lex imposta questo valore per indirizzare la funzione Lambda all'inizializzazione della funzione e alla convalida dell'input di dati dell'utente.

Quando l'intento è configurato per invocare una funzione Lambda come hook di codice di inizializzazione e di convalida, Amazon Lex invoca la funzione Lambda specificata su ciascun input dell'utente (enunciazione) dopo che Amazon Lex ha compreso l'intento. 143 Amazon Lex Guida per gli sviluppatori Formato dell'evento di input

Note

Se l'intento non è chiaro, Amazon Lex non sarà in grado di invocare la funzione Lambda.

• FulfillmentCodeHook – Amazon Lex imposta questo valore per indirizzare la funzione Lambda all'adempimento di un intento.

Se l'intento è configurato per invocare una funzione Lambda come hook di codice di adempimento, Amazon Lex imposta invocationSource su questo valore solo quando dispone di tutti i dati dello slot necessari per adempiere l'intento.

Nella configurazione dell'intento, puoi avere due funzioni Lambda separate per inizializzare e convalidare i dati utente e adempiere l'intento. Puoi inoltre utilizzare una funzione Lambda per entrambe le operazioni. In questo caso, la funzione Lambda può utilizzare il valore di invocationSource per seguire il percorso corretto del codice.

• outputDialogMode – Per ogni input utente, il client invia la richiesta a Amazon Lex utilizzando una delle operazioni API di runtime, PostContent (p. 425) o PostText (p. 434). Amazon Lex utilizza i parametri della richiesta per determinare se la risposta al client è testo o vocale, quindi imposta il campo di conseguenza.

La funzione Lambda può utilizzare queste informazioni per generare un messaggio appropriato. Ad esempio, se il client prevede una risposta vocale, la funzione Lambda può restituire Speech Synthesis Markup Language (SSML) al posto del testo.

• messageVersion – La versione del messaggio che identifica il formato dei dati di evento che giungono alla funzione Lambda e il formato previsto della risposta da parte di una funzione Lambda. Note

Puoi configurare questo valore quando definisci un intento. Nell'implementazione corrente, è supportata solo la versione 1.0 dei messaggi. Pertanto, la console presuppone il valore predefinito di 1.0 e non mostra la versione del messaggio. • sessionAttributes – Attributi di sessione specifici dell'applicazione che il client invia nella richiesta. Se vuoi che Amazon Lex li includa nella risposta al client, la funzione Lambda deve inviarli a Amazon Lex nella risposta. Per ulteriori informazioni, consulta Impostazione degli attributi di sessione (p. 23)

• requestAttributes – Attributi specifici della richiesta che il client invia nella richiesta. Utilizza gli attributi di richiesta per inviare informazioni che non devono essere conservate per l'intera sessione. Se non ci sono attributi della richiesta, il valore sarà null. Per ulteriori informazioni, consulta Impostazione degli attributi di richiesta (p. 24)

• recentIntentSummaryView – Informazioni sullo stato di un intento. È possibile visualizzare informazioni sugli ultimi tre intenti utilizzati. Queste informazioni possono essere usate per impostare i valori nell'intento o per tornare a un intento precedente. Per ulteriori informazioni, consulta Gestione di sessioni con l'API Amazon Lex (p. 40). 144 Amazon Lex Guida per gli sviluppatori Formato della risposta

• sentimentResponse – Il risultato di un'analisi del sentiment Amazon Comprehend dell'ultima enunciazione. È possibile utilizzare queste informazioni per gestire il flusso di conversazione del bot in base all'emozione espressa dall'utente. Per ulteriori informazioni, consulta Analisi delle emozioni (p. 64).

• kendraResponse – Il risultato di una query a un indice Amazon Kendra. Presente solo nell'input a un hook di codice di adempimento e solo quando l'intento estende l'intento integrato AMAZON.KendraSearchIntent. Il campo contiene l'intera risposta della ricerca Amazon Kendra. Per ulteriori informazioni, consulta AMAZON.KendraSearchIntent (p. 47).

• activeContexts – Uno o più contesti attivi durante il turno di una conversazione con l'utente. • timeToLive – L'intervallo di tempo o il numero di turni nella conversazione con l'utente in cui il contesto rimane attivo. • name (nome) – il nome del contesto. • Parametri Un elenco di coppie chiave/valore che contiene il nome e il valore degli slot dall'intento che ha attivato il contesto.

Per ulteriori informazioni, consulta Impostazione del contesto dell'intento (p. 20).

Formato della risposta

Amazon Lex prevede una risposta da una funzione Lambda nel formato seguente:

{ "sessionAttributes": { "key1": "value1", "key2": "value2" ... }, "recentIntentSummaryView": [ { "intentName": "Name", "checkpointLabel": "Label", "slots": { "slot name": "value", "slot name": "value" }, "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)", "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close", "fulfillmentState": "Fulfilled or Failed", "slotToElicit": "Next slot to elicit" } ], "activeContexts": [ { "timeToLive": { "timeToLiveInSeconds": seconds, "turnsToLive": turns }, "name": "name", "parameters": { "key name": "value" } } ],

145 Amazon Lex Guida per gli sviluppatori Formato della risposta

"dialogAction": { "type": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close", Full structure based on the type field. See below for details. } }

La risposta è composta da quattro campi. I campi sessionAttributes, recentIntentSummaryView e activeContexts sono facoltativi, il campo dialogAction è obbligatorio. Il contenuto del campo dialogAction dipende dal valore del campo type. Per informazioni dettagliate, consulta dialogAction (p. 147). sessionAttributes

Facoltativo. Se includi il campo sessionAttributes, questo può essere vuoto. Se la funzione Lambda non restituisce gli attributi di sessione, rimangono gli ultimi sessionAttributes noti trasmessi tramite l'API o la funzione Lambda. Per maggiori informazioni, consulta le operazioni PostContent (p. 425) e PostText (p. 434).

"sessionAttributes": { "key1": "value1", "key2": "value2" } recentIntentSummaryView

Facoltativo. Se incluso, imposta i valori per uno o più intenti recenti. È possibile includere informazioni per un massimo di tre intenti. Ad esempio, puoi impostare i valori per gli intenti precedenti in base alle informazioni raccolte dall'intento corrente. Le informazioni contenute nel riepilogo devono essere valide per l'intento. Ad esempio, il nome dell'intento deve essere un intento nel bot. Se includi un valore di slot nella visualizzazione riepilogo, lo slot deve essere presente nell'intento. Se non includi la recentIntentSummaryView nella risposta, tutti i valori degli intenti recenti rimangono invariati. Per ulteriori informazioni, vedere l'operazione PutSession (p. 442) o il tipo di dati IntentSummary (p. 503).

"recentIntentSummaryView": [ { "intentName": "Name", "checkpointLabel": "Label", "slots": { "slot name": "value", "slot name": "value" }, "confirmationStatus": "None, Confirmed, or Denied (intent confirmation, if configured)", "dialogActionType": "ElicitIntent, ElicitSlot, ConfirmIntent, Delegate, or Close", "fulfillmentState": "Fulfilled or Failed", "slotToElicit": "Next slot to elicit" } ]

activeContexts

Facoltativo. Se incluso, imposta il valore per uno o più contesti. Ad esempio, è possibile includere un contesto per fare in modo che uno o più intenti abbiano tale contesto come input idoneo per il riconoscimento al successivo turno della conversazione.

I valori time-to-live di tutti i contesti attivi che non sono inclusi nella risposta diminuiscono e potrebbero essere ancora attivi nella richiesta successiva.

146 Amazon Lex Guida per gli sviluppatori Formato della risposta

Se specifichi un time-to-live 0 per un contesto che è stato incluso nell'evento di input, sarà inattivo nella richiesta successiva.

Per ulteriori informazioni, consulta Impostazione del contesto dell'intento (p. 20). dialogAction

Campo obbligatorio. Il campo dialogAction indirizza Amazon Lex verso l'operazione successiva e descrive cosa prevedere da parte dell'utente dopo che Amazon Lex ha restituito una risposta al client.

Il campo type indica l'operazione successiva. Determina inoltre gli altri campi che la funzione Lambda deve fornire come parte del valore dialogAction.

• Close — Informa Amazon Lex di non attendere una risposta da parte dell'utente. Ad esempio, "L'ordine della tua pizza è stato registrato" non richiede una risposta.

Il campo fulfillmentState è obbligatorio. Amazon Lex utilizza questo valore per impostare il campo dialogState nelle risposte PostContent (p. 425) o PostText (p. 434) all'applicazione client. I campi message e responseCard sono facoltativi. Se non specifichi un messaggio, Amazon Lex utilizza il messaggio di saluto o il messaggio di prosecuzione configurato per l'intento.

"dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled or Failed", "message": { "contentType": "PlainText or SSML or CustomPayload", "content": "Message to convey to the user. For example, Thanks, your pizza has been ordered." }, "responseCard": { "version": integer-value, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [ { "title":"card-title", "subTitle":"card-sub-title", "imageUrl":"URL of the image to be shown", "attachmentLinkUrl":"URL of the attachment to be associated with the card", "buttons":[ { "text":"button-text", "value":"Value sent to server on button click" } ] } ] } }

• ConfirmIntent — Informa Amazon Lex che l'utente deve fornire una risposta affermativa o negativa per confermare o rifiutare l'intento corrente.

È necessario includere i campi intentName e slots. Il campo slots deve contenere una voce per ciascuno slot riempito per l'intento specificato. Non è necessario includere una voce nel campo slots per gli slot che non vengono riempiti. È necessario includere il campo message se il campo intento confirmationPrompt è nullo. Il contenuto del campo message restituito dalla funzione Lambda ha la precedenza rispetto al confirmationPrompt specificato nell'intento. Il campo responseCard è facoltativo.

147 Amazon Lex Guida per gli sviluppatori Formato della risposta

"dialogAction": { "type": "ConfirmIntent", "message": { "contentType": "PlainText or SSML or CustomPayload", "content": "Message to convey to the user. For example, Are you sure you want a large pizza?" }, "intentName": "intent-name", "slots": { "slot-name": "value", "slot-name": "value", "slot-name": "value" }, "responseCard": { "version": integer-value, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [ { "title":"card-title", "subTitle":"card-sub-title", "imageUrl":"URL of the image to be shown", "attachmentLinkUrl":"URL of the attachment to be associated with the card", "buttons":[ { "text":"button-text", "value":"Value sent to server on button click" } ] } ] } }

• Delegate — indica a Amazon Lex di scegliere la successiva operazione in base alla configurazione del bot. Se la risposta non include alcun attributo di sessione, Amazon Lex mantiene gli attributi esistenti. Per ottenere un valore null di uno slot, non occorre includere il campo slot nella richiesta. Si riceverà un'eccezione DependencyFailedException se la funzione di adempimento restituisce l'operazione di dialogo Delegate senza rimuovere alcuno slot.

I campi kendraQueryRequestPayload e kendraQueryFilterString sono facoltativi e utilizzati solo quando l'intento è derivato dall'intento integrato AMAZON.KendraSearchIntent. Per ulteriori informazioni, consulta AMAZON.KendraSearchIntent (p. 47).

"dialogAction": { "type": "Delegate", "slots": { "slot-name": "value", "slot-name": "value", "slot-name": "value" }, "kendraQueryRequestPayload": "Amazon Kendra query", "kendraQueryFilterString": "Amazon Kendra attribute filters" }

• ElicitIntent — Indica a Amazon Lex che l'utente deve rispondere con un'enunciazione che include un intento. Ad esempio, "Voglio una pizza grande", che indica OrderPizzaIntent. L'enunciazione "grande", invece, non è sufficiente affinché Amazon Lex deduca l'intento dell'utente.

148 Amazon Lex Guida per gli sviluppatori Formato della risposta

I campi message e responseCard sono facoltativi. Se non fornisci un messaggio, Amazon Lex utilizza uno dei messaggi di richiesta di chiarimento del bot. Se non viene definito alcun prompt di chiarimento, Amazon Lex restituisce un’eccezione 400 Bad Request (Richiesta non valida).

{ "dialogAction": { "type": "ElicitIntent", "message": { "contentType": "PlainText or SSML or CustomPayload", "content": "Message to convey to the user. For example, What can I help you with?" }, "responseCard": { "version": integer-value, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [ { "title":"card-title", "subTitle":"card-sub-title", "imageUrl":"URL of the image to be shown", "attachmentLinkUrl":"URL of the attachment to be associated with the card", "buttons":[ { "text":"button-text", "value":"Value sent to server on button click" } ] } ] } }

• ElicitSlot — Indica a Amazon Lex che è previsto che l'utente fornisca un valore dello slot nella risposta.

I campi intentName, slotToElicit e slots sono obbligatori. I campi message e responseCard sono facoltativi. Se non specifichi un messaggio, Amazon Lex utilizza uno dei messaggi di richiesta di sollecitazione dello slot configurati per lo slot.

"dialogAction": { "type": "ElicitSlot", "message": { "contentType": "PlainText or SSML or CustomPayload", "content": "Message to convey to the user. For example, What size pizza would you like?" }, "intentName": "intent-name", "slots": { "slot-name": "value", "slot-name": "value", "slot-name": "value" }, "slotToElicit" : "slot-name", "responseCard": { "version": integer-value, "contentType": "application/vnd.amazonaws.card.generic", "genericAttachments": [ { "title":"card-title", "subTitle":"card-sub-title",

149 Amazon Lex Guida per gli sviluppatori Amazon Lex e piani AWS Lambda

"imageUrl":"URL of the image to be shown", "attachmentLinkUrl":"URL of the attachment to be associated with the card", "buttons":[ { "text":"button-text", "value":"Value sent to server on button click" } ] } ] } }

Amazon Lex e piani AWS Lambda

La console di Amazon Lex offre bot di esempio (chiamati piani di bot) preconfigurati in modo da poter creare e testare rapidamente un bot nella console. Per ciascuno di questi piani di bot, sono offerti anche piani della funzione Lambda. Questi piani forniscono il codice di esempio funzionante con i bot corrispondenti. Puoi utilizzare questi piani per creare rapidamente un bot configurato con una funzione Lambda come hook di codice, oltre a testare la configurazione end-to-end, senza scrivere codice.

Puoi utilizzare i piani di bot di Amazon Lex seguenti e i piani della funzione AWS Lambda corrispondenti come hook di codice per bot:

• Amazon Lex Piano di — OrderFlowers • AWS Lambda Piano di — lex-order-flowers-python • Amazon Lex Piano di — ScheduleAppointment • AWS Lambda Piano di — lex-make-appointment-python • Amazon Lex Piano di — BookTrip • AWS Lambda Piano di — lex-book-trip-python

Per creare un bot utilizzando un piano e configurarlo affinché utilizzi una funzione Lambda come hook di codice, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). Per esempi di utilizzo di altri piani, consulta Esempi aggiuntivi: Creazione Amazon Lex Bot (p. 173). Aggiornamento di un piano per un'impostazione locale specifica

Se stai usando un piano in una lingua locale diversa dall'inglese (Stati Uniti), devi aggiornare il nome di tutti gli intenti in modo da includere le impostazioni locali. Ad esempio, se stai utilizzando il piano OrderFlowers, devi procedere come segue.

• Trovare la funzione dispatch vicino alla fine del codice della funzione Lambda. • Nella funzione dispatch aggiornare il nome dell'intento per includere le impostazioni locali in uso. Ad esempio, se stai utilizzando la lingua locale inglese (Australiana) (en-AU), modifica la riga:

if intent_name == 'OrderFlowers':

to

if intent_name == 'OrderFlowers_enAU':

Gli altri piani utilizzano altri nomi di intenti, devono essere aggiornati come prima di utilizzarli.

150 Amazon Lex Guida per gli sviluppatori Deploying an Amazon Lex Bot on a Messaging Platform

Deploying Amazon Lex Bots

Questa sezione fornisce esempi di distribuzione di bot di Amazon Lex su differenti piattaforme di messaggistica e in applicazioni per dispositivi mobili.

Argomenti • Deploying an Amazon Lex Bot on a Messaging Platform (p. 151) • Deploying an Amazon Lex Bot in Mobile Applications (p. 165)

Deploying an Amazon Lex Bot on a Messaging Platform

Questa sezione descrive come distribuire bot di Amazon Lex sulle piattaforme di messaggistica Facebook, Slack e Twilio. Note

Per l'archiviazione delle configurazioni di Facebook, Slack o Twilio, Amazon Lex utilizza le chiavi master del cliente (CMK) di AWS Key Management Service per crittografare le informazioni. La prima volta che crei un canale a una di queste piattaforme di messaggistica, Amazon Lex crea una chiave CMK predefinita (aws/lex). In alternativa, puoi creare la tua chiave CMK con AWS KMS. Questa opzione ti offre una maggiore flessibilità, tra cui la possibilità di creare, ruotare e disabilitare le chiavi. Puoi anche definire controlli di accesso e controllare le chiavi di crittografia utilizzate per proteggere i dati. Per ulteriori informazioni, vedere la Guida per gli sviluppatori di AWS Key Management Service.

Quando una piattaforma di messaggistica invia una richiesta a Amazon Lex, include informazioni specifiche della piattaforma come attributo di richiesta per la funzione Lambda. Utilizza questi attributi per personalizzare il comportamento del bot. Per ulteriori informazioni, vedi Impostazione degli attributi di richiesta (p. 24).

Tutti gli attributi acquisiscono il nomespace x-amz-lex: come prefisso. Ad esempio, il user-id si chiama attributo x-amz-lex:user-id. Sono presenti attributi comuni inviati da tutte le piattaforme di messaggistica in aggiunta agli attributi specifici per una particolare piattaforma. La tabella seguente elenca gli attributi di richiesta che le piattaforme di messaggistica inviano alla funzione Lambda del tuo bot.

Attributi di richiesta comuni

Attributo Descrizione:

channel-id L'identificatore dell'endpoint del canale di Amazon Lex.

channel-name Il nome di canale di Amazon Lex.

channel-type Uno dei seguenti valori:

• Facebook • Kik • Slack • Twilio-SMS

151 Amazon Lex Guida per gli sviluppatori Deploying an Amazon Lex Bot on a Messaging Platform

Attributo Descrizione: webhook-endpoint-url L'endpoint di Amazon Lex per il canale.

Attributi di richiesta di Facebook

Attributo Descrizione: user-id L'identificatore Facebook del mittente. Consulta https:// developers.facebook.com/docs/messenger-platform/webhook-reference/ message-received. facebook-page-id L'identificatore di pagina Facebook del destinatario. Consulta https:// developers.facebook.com/docs/messenger-platform/webhook-reference/ message-received.

Attributi di richiesta di Kik

Attributo Descrizione: kik-chat-id Identificatore della conversazione in cui è coinvolto il tuo bot. Per ulteriori informazioni, consulta https://dev.kik.com/#/docs/messaging#message- formats. kik-chat-type Il tipo di conversazione da cui è stato creato il messaggio. Per ulteriori informazioni, consulta https://dev.kik.com/#/docs/messaging#message- formats. kik-message-id Un UUID che identifica il messaggio. Per ulteriori informazioni, consulta https://dev.kik.com/#/docs/messaging#message-formats. kik-message-type Il tipo di messaggio. Per ulteriori informazioni, consulta https://dev.kik.com/ #/docs/messaging#message-types.

Attributi di richiesta di Twilio

Attributo Descrizione: user-id Il numero di telefono del mittente ("From"). Consulta https:// www.twilio.com/docs/api/rest/message. twilio-target-phone- Il numero di telefono del destinatario ("To"). Consulta https:// number www.twilio.com/docs/api/rest/message.

Attributi di richiesta di Slack

Attributo Descrizione: user-id L'identificatore utente di Slack. Consulta https://api.slack.com/types/user. slack-team-id L'identificatore del team che ha inviato il messaggio. Consulta https:// api.slack.com/methods/team.info. slack-bot-token Il token dello sviluppatore che fornisce al bot l'accesso alle API di Slack. Consulta https://api.slack.com/docs/token-types.

152 Amazon Lex Guida per gli sviluppatori Integrating with Facebook

Integrating an Amazon Lex Bot with Facebook Messenger

Questo esercizio mostra come integrare Facebook Messenger con il tuo bot di Amazon Lex. Completa la seguente procedura:

1. Creare un bot Amazon Lex 2. Creazione di un'applicazione Facebook 3. Per integrare Facebook Messenger con il tuo bot Amazon Lex 4. Convalida dell'integrazione

Argomenti • Step 1: Create an Amazon Lex Bot (p. 153) • Step 2: Create a Facebook Application (p. 153) • Step 3: Integrate Facebook Messenger with the Amazon Lex Bot (p. 153) • Step 4: Test the Integration (p. 155)

Step 1: Create an Amazon Lex Bot

Se non hai già un bot di Amazon Lex, crealo e distribuiscilo. In questo argomento si presuppone che tu stia utilizzando il bot creato nell'esercizio 1 "Nozioni di base". Tuttavia, puoi utilizzare uno qualsiasi dei bot di esempio forniti in questa guida. Per l'esercizio 1 "Nozioni di base", consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72).

1. Creare un bot Amazon Lex Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Distribuisci il bot e crea un alias. Per istruzioni, consulta Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109).

Step 2: Create a Facebook Application

Sul portale per gli sviluppatori di Facebook, crea un'applicazione e una pagina Facebook. Per istruzioni, consulta il documento Quick Start nella documentazione della piattaforma di Facebook Messenger. Prendi nota dei dati seguenti:

• The App Secret for the Facebook App • The Page Access Token for the Facebook page

Step 3: Integrate Facebook Messenger with the Amazon Lex Bot

In questa sezione integrerai Facebook Messenger con il tuo bot di Amazon Lex.

Una volta completata questa operazione, la console offre un URL di callback. Prendi nota di questo URL.

To integrate Facebook Messenger with your bot

1. a. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. b. Seleziona il tuo bot di Amazon Lex.

153 Amazon Lex Guida per gli sviluppatori Integrating with Facebook

c. Seleziona Channels (Canali). d. Seleziona Facebook nella sezione Chatbots (Chatbot). La console visualizza la pagina di integrazione di Facebook. e. In questa pagina, effettua quanto segue:

• Type the following name: BotFacebookAssociation. • For KMS key, choose aws/lex . • For Alias, choose the bot alias. • For Verify token, type a token. This can be any string you choose (for example, ExampleToken). You use this token later in the Facebook developer portal when you set up the webhook. • For Page access token, type the token that you obtained from Facebook in Step 2. • For App secret key, type the key that you obtained from Facebook in Step 2.

f. Seleziona Activate (Attiva).

La console crea l'associazione del canale del bot e restituisce un URL di callback. Prendi nota di questo URL. 2. Sul portale per gli sviluppatori di Facebook, scegli la tua applicazione. 3. Seleziona il prodotto Messenger, quindi Setup webhooks (Webhook di configurazione) nella sezione Webhooks (Webhook) della pagina.

Per istruzioni, consulta il documento Quick Start nella documentazione della piattaforma di Facebook Messenger. 4. Nella pagina webhook della procedura guidata per la registrazione, effettua quanto segue:

• For Callback URL, type the callback URL provided in the Amazon Lex console earlier in the procedure. • For Verify Token, type the same token that you used in Amazon Lex. • Choose Subscription Fields (messages, messaging_postbacks, and messaging_optins). • Choose Verify and Save. This initiates a handshake between Facebook and Amazon Lex.

154 Amazon Lex Guida per gli sviluppatori Integrating with Kik

5. Abilita l'integrazione degli webhook. Seleziona la pagina creata, quindi scegli subscribe (effettua registrazione). Note

Se aggiorni o crei nuovamente un webhook, annulla la registrazione ed eseguila nuovamente per la pagina.

Step 4: Test the Integration

A questo punto puoi iniziare una conversazione da Facebook Messenger con il tuo bot di Amazon Lex.

1. Apri la tua pagina Facebook e scegli Messaggio. 2. Nella finestra di Messenger, utilizza le stesse enunciazioni di prova fornite in Fase 1. Creazione di un bot di Amazon Lex (console) (p. 73).

Integrating an Amazon Lex Bot with Kik

Questo esercizio fornisce istruzioni per l'integrazione di un bot di Amazon Lex con l'applicazione di messaggistica Kik. Completa la seguente procedura:

1. Creare un bot Amazon Lex 2. Crea un bot di Kik utilizzando l'app e il sito Web di Kik. 3. Integra il bot di Amazon Lex con il bot di Kik tramite la console di Amazon Lex. 4. Svolgi una conversazione con il bot di Amazon Lex utilizzando Kik per testare l'associazione tra il bot di Amazon Lex e Kik.

Argomenti • Step 1: Create an Amazon Lex Bot (p. 155) • Step 2: Create a Kik Bot (p. 156) • Step 3: Integrate the Kik Bot with the Amazon Lex Bot (p. 156) • Step 4: Test the Integration (p. 157)

Step 1: Create an Amazon Lex Bot

Se non hai già un bot di Amazon Lex, crealo e distribuiscilo. In questo argomento si presuppone che tu stia utilizzando il bot creato nell'esercizio 1 "Nozioni di base". Tuttavia, puoi utilizzare uno qualsiasi dei bot di esempio forniti in questa guida. Per l'esercizio 1 "Nozioni di base", consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72)

1. Creare un bot Amazon Lex Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Distribuisci il bot e crea un alias. Per istruzioni, consulta Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109).

Fase successiva

Step 2: Create a Kik Bot (p. 156)

155 Amazon Lex Guida per gli sviluppatori Integrating with Kik

Step 2: Create a Kik Bot

In questa fase puoi utilizzare l'interfaccia utente di Kik per creare un bot di Kik. Puoi utilizzare le informazioni generate durante la creazione del bot per connetterlo al bot di Amazon Lex.

1. Se non lo hai già fatto, scarica e installa l'app di Kik e crea un account di Kik. Se disponi di un account, effettua l'accesso. 2. Apri il sito Web di Kik all'indirizzo https://dev.kik.com/. Lascia la finestra del browser aperta. 3. Nell'app di Kik, seleziona l'icona a forma di ingranaggio per aprire le impostazioni, quindi seleziona Your Kik Code (Il tuo codice di Kik). 4. Scansiona il codice di Kik sul sito Web di Kit per aprire la chatbot di Botsworth. Seleziona Yes (Sì) per aprire il pannello di controllo del bot. 5. Nell'app di Kik, seleziona Create a Bot (Crea un bot). Segui le istruzioni per creare il bot di Kik. 6. Una volta creato il bot, seleziona Configuration (Configurazione) nel browser. Assicurati che sia selezionato il nuovo bot. 7. Annota il nome del bot e la chiave API per la sezione successiva.

Fase successiva

Step 3: Integrate the Kik Bot with the Amazon Lex Bot (p. 156) Step 3: Integrate the Kik Bot with the Amazon Lex Bot

Dopo aver creato un bot di Amazon Lex e un bot di Kik, sei pronto per creare un'associazione di canale che li colleghi in Amazon Lex. Quando l'associazione è attiva, Amazon Lex configura in modo automatico un URL di callback con Kik.

1. Accedi alla Console di gestione AWS, quindi apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Seleziona il bot di Amazon Lex che hai creato nella Fase 1. 3. Seleziona la scheda Channels (Canali). 4. Nella sezione Channels (Canali), seleziona Kik. 5. Nella pagina di Kik, inserisci quanto segue:

• Type a name. For example, BotKikIntegration. • Type a description. • Choose "aws/lex" from the KMS key drop-down. • For Alias, choose an alias from the drop-down. • For Kik bot user name, type the name that you gave the bot on Kik. • For Kik API key, type the API key that was assigned to the bot on Kik. • For User greeting, type the greeting that you would like your bot to send the first time that a user chats with it. • For Error message, enter an error message that is shown to the user when part of the conversation is not understood. • For Group chat behavior, choose one of the options: • Enable – Enables the entire chat group to interact with your bot in a single conversation. • Disable – Restricts the conversation to one user in the chat group.

156 Amazon Lex Guida per gli sviluppatori Integrating with Kik

• Choose Activate to create the association and link it to the Kik bot.

Fase successiva

Step 4: Test the Integration (p. 157) Step 4: Test the Integration

Ora che hai creato un'associazione tra il bot di Amazon Lex e Kik, puoi utilizzare l'app di Kik per testare l'associazione.

1. Avvia l'app di Kik ed effettua l'accesso. Seleziona il bot creato. 2. Puoi testare il bot come riportato di seguito:

157 Amazon Lex Guida per gli sviluppatori Integrating with Slack

Appeni digiti ciascuna frase, il bot di Amazon Lex risponderà tramite Kik con il messaggio di richiesta creato per ciascuno slot.

Integrating an Amazon Lex Bot with Slack

Questo esercizio fornisce istruzioni per l'integrazione di un bot di Amazon Lex con l'applicazione di messaggistica Slack. Completa la seguente procedura:

1. Creare un bot Amazon Lex 2. Crea un'applicazione di messaggistica Slack. 3. Integra l'applicazione Slack con il tuo bot di Amazon Lex. 4. Verifica l'integrazione avviando una conversazione con il tuo bot di Amazon Lex. Invia messaggi con l'applicazione Slack e completa una verifica in una finestra del browser.

Argomenti • Step 1: Create an Amazon Lex Bot (p. 159) • Step 2: Sign Up for Slack and Create a Slack Team (p. 159)

158 Amazon Lex Guida per gli sviluppatori Integrating with Slack

• Step 3: Create a Slack Application (p. 159) • Step 4: Integrate the Slack Application with the Amazon Lex Bot (p. 160) • Step 5: Complete Slack Integration (p. 161) • Step 6: Test the Integration (p. 162)

Step 1: Create an Amazon Lex Bot

Se non hai già un bot di Amazon Lex, crealo e distribuiscilo. In questo argomento si presuppone che tu stia utilizzando il bot creato nell'esercizio 1 "Nozioni di base". Tuttavia, puoi utilizzare uno qualsiasi dei bot di esempio forniti in questa guida. Per l'esercizio 1 "Nozioni di base", consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72)

1. Creare un bot Amazon Lex Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Distribuisci il bot e crea un alias. Per istruzioni, consulta Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109).

Fase successiva

Step 2: Sign Up for Slack and Create a Slack Team (p. 159) Step 2: Sign Up for Slack and Create a Slack Team

Registra un account Slack e crea un team Slack. Per istruzioni, consulta Utilizzo di Slack. Nella prossima sezione dovrai creare un'applicazione Slack che tutto il team Slack possa installare.

Fase successiva

Step 3: Create a Slack Application (p. 159) Step 3: Create a Slack Application

In questa sezione, vengono effettuate le operazioni seguenti:

1. Crea un'applicazione di Slack nella console API Slack 2. Configura l'applicazione per aggiungere messaggi interattivi al tuo bot:

Al termine della sessione riceverai le credenziali dell'applicazione (ID client, Client Secret e token di verifica). Nella sezione successiva ti servirai di queste informazioni per configurare l'associazione di canali del bot nella console Amazon Lex.

1. Accedi alla console API Slack su http://api.slack.com . 2. Creazione di un'applicazione

Dopo aver creato correttamente l'applicazione, Slack visualizza la pagina delle informazioni di base per l'applicazione. 3. Configura le funzioni dell'applicazione nel modo seguente:

• Nel menu a sinistra, scegliere Interattività e collegamenti.

• Choose the toggle to turn interactive components on. • In the Request URL box, specify any valid URL. For example, you can use https:// slack.com.

159 Amazon Lex Guida per gli sviluppatori Integrating with Slack

Note

For now, enter any valid URL to get the verification token that you need in the next step. You will update this URL after you add the bot channel association in the Amazon Lex console. • Choose Save Changes. 4. Nel menu a sinistra, in Settings (Impostazioni), seleziona Basic Information (Informazioni di base). Prendi nota delle seguenti credenziali dell'applicazione:

• Client ID • Client Secret • Verification Token

Fase successiva

Step 4: Integrate the Slack Application with the Amazon Lex Bot (p. 160) Step 4: Integrate the Slack Application with the Amazon Lex Bot

Adesso che disponi delle credenziali dell'applicazione Slack, puoi integrare l'applicazione con il tuo bot di Amazon Lex. Per associare l'applicazione Slack con il tuo bot, aggiungi l'associazione di canali in Amazon Lex.

Nella console Amazon Lex, attiva un'associazione di canali del bot per associare il bot alla tua applicazione Slack. Quando l'associazione di canali bot è attivata, Amazon Lex restituisce due URL (URL Postback e URL OAuth). Prendi nota di questi URL perché ti serviranno più avanti.

Per integrare l'applicazione Slack con il tuo bot di Amazon Lex

1. Accedi alla Console di gestione AWS, quindi apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Seleziona il bot di Amazon Lex che hai creato nella Fase 1. 3. Seleziona la scheda Channels (Canali). 4. Nel menu a sinistra seleziona Slack. 5. Nella pagina Slack fornisci i seguenti dati:

• Type a name. For example, BotSlackIntegration. • Choose "aws/lex" from the KMS key drop-down. • For Alias, choose the bot alias. • Type the Client Id, Client secret, and Verification Token, which you recorded in the preceding step. These are the credentials of the Slack application.

160 Amazon Lex Guida per gli sviluppatori Integrating with Slack

6. Seleziona Activate (Attiva).

La console crea l'associazione di canali del bot e restituisce due URL (l'URL Postback e l'URL OAuth). Prendine nota. Nella sezione successiva, aggiorna la configurazione dell'applicazione Slack per utilizzare questi endpoint nel modo seguente:

• The Postback URL is the Amazon Lex bot's endpoint that listens to Slack events. You use this URL: • As the request URL in the Event Subscriptions feature of the Slack application. • To replace the placeholder value for the request URL in the Interactive Messages feature of the Slack application. • The OAuth URL is your Amazon Lex bot's endpoint for an OAuth handshake with Slack.

Fase successiva

Step 5: Complete Slack Integration (p. 161) Step 5: Complete Slack Integration

In questa sezione, utilizza la console API Slack per completare l'integrazione dell'applicazione Slack.

161 Amazon Lex Guida per gli sviluppatori Integrating with Twilio SMS

1. Accedi alla console API Slack su http://api.slack.com. Seleziona l'app che hai creato in Step 3: Create a Slack Application (p. 159). 2. Aggiorna la funzione OAuth & Permissions (OAuth e autorizzazioni) nel modo seguente:

a. Nel menu a sinistra, seleziona OAuth & Permissions (OAuth e autorizzazioni). b. Nella sezione Redirect URLs (URL di reindirizzamento), aggiungi l'URL OAuth fornito da Amazon Lex nella fase precedente. Seleziona Add a new Redirect URL (Aggiungi un nuovo URL di reindirizzamento), quindi Save URLs (Salva URL). c. Nella Ambiti token Bot , aggiungere due autorizzazioni con il Aggiungi un ambito oauth pulsante. Filtra l'elenco con il seguente testo:

• chat:write • team:read 3. Aggiorna il Interattività e collegamenti funzionalità aggiornando il URL richiesta valore all'URL postback che Amazon Lex fornito nel passaggio precedente. Inserire l'URL del postback; salvato nella fase 4, quindi scegliere Save Changes (Salva cambiamenti). 4. Iscriviti alla funzione Event Subscriptions (Abbonamenti a eventi) nel modo seguente:

• Enable events by choosing the On option. • Set the Request URL value to the Postback URL that Amazon Lex provided in the preceding step. • In the Subscribe to Bot Events section, subscribe to the message.im bot event to enable direct messaging between the end user and the Slack bot. • Save the changes.

Fase successiva

Step 6: Test the Integration (p. 162) Step 6: Test the Integration

Utilizza adesso una finestra del browser per verificare l'integrazione di Slack con il tuo bot di Amazon Lex.

1. Seleziona Manage Distribution (Gestisci la distribuzione) in Settings (Impostazioni). Seleziona Add to Slack (Aggiungi a Slack) per installare l'applicazione. Autorizza il bot a rispondere ai messaggi. 2. Sarai reindirizzato al team Slack. Nel menu a sinistra, nella sezione Direct Messages (Messaggi diretti), seleziona il tuo bot. Se non lo trovi, seleziona il simbolo "più" (+) accanto all'opzione Direct Messages (Messaggi diretti) per cercarlo. 3. Avvia una chat con la tua applicazione Slack collegata al bot di Amazon Lex. Adesso il tuo bot risponderà ai messaggi.

Se hai creato il bot utilizzando l'esercizio 1 "Nozioni di base", puoi utilizzare le conversazioni di esempio che trovi nell'esercizio. Per ulteriori informazioni, vedi Fase 4. Aggiunta della funzione Lambda come hook di codice (console) (p. 84).

Integrating an Amazon Lex Bot with Twilio Programmable SMS

Questo esercizio fornisce istruzioni per l'integrazione di un bot di Amazon Lex con il servizio di messaggistica semplice (SMS) di Twilio. Completa la seguente procedura:

1. Creare un bot Amazon Lex 2. Integrazione di Twilio programmable SMS con il bot di Amazon Lex

162 Amazon Lex Guida per gli sviluppatori Integrating with Twilio SMS

3. Esecuzione di un'interazione con il bot di Amazon Lex testando la configurazione tramite il servizio SMS sul cellulare 4. Verificare l'integrazione.

Argomenti • Step 1: Create an Amazon Lex Bot (p. 163) • Step 2: Create a Twilio SMS Account (p. 163) • Step 3: Integrate the Twilio Messaging Service Endpoint with the Amazon Lex Bot (p. 163) • Step 4: Test the Integration (p. 164)

Step 1: Create an Amazon Lex Bot

Se non hai già un bot di Amazon Lex, crealo e distribuiscilo. In questo argomento si presuppone che tu stia utilizzando il bot creato nell'esercizio 1 "Nozioni di base". Tuttavia, puoi utilizzare uno qualsiasi dei bot di esempio forniti in questa guida. Per l'esercizio 1 "Nozioni di base", consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72).

1. Creare un bot Amazon Lex Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Distribuisci il bot e crea un alias. Per istruzioni, consulta Esercizio 3. Pubblicazione di una versione e creazione di un alias (p. 109).

Step 2: Create a Twilio SMS Account

Effettua la registrazione di un account Twilio e registra le seguenti informazioni relative all'account:

• ACCOUNT SID • AUTH TOKEN

Per le istruzioni sulla registrazione, consulta la pagina https://www.twilio.com/console. Step 3: Integrate the Twilio Messaging Service Endpoint with the Amazon Lex Bot

Per integrare Twilio con il bot di Amazon Lex

1. Per associare il bot di Amazon Lex con l'endpoint di Twilio programmable SMS, attiva un'associazione del canale del bot nella console di Amazon Lex. Quando l'associazione del canale del bot è stato attivata, Amazon Lex restituisce un URL di callback. Registra questo URL di callback poiché ne avrai bisogno in un secondo momento.

a. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. b. Seleziona il bot di Amazon Lex che hai creato nella Fase 1. c. Seleziona la scheda Channels (Canali). d. Nella sezione Chatbots (Chatbot), seleziona Twilio SMS. e. Nella pagina Twilio SMS, fornisci le seguenti informazioni:

• Type a name. For example, BotTwilioAssociation. • Choose "aws/lex" from KMS key.

163 Amazon Lex Guida per gli sviluppatori Integrating with Twilio SMS

• For Alias, choose the bot alias. • For Authentication Token, type the AUTH TOKEN for your Twilio account. • For Account SID, type the ACCOUNT SID for your Twilio account.

f. Seleziona Activate (Attiva).

La console crea l'associazione del canale del bot e restituisce un URL di callback. Registra l'URL. 2. Nella console di Twilio, connetti l'endpoint di Twilio SMS al bot di Amazon Lex.

a. Accedi alla console di Twilio all'indirizzo https://www.twilio.com/console. b. Se non disponi di un endpoint di Twilio SMS, crealo. c. Aggiorna la configurazione Inbound Settings (Impostazioni In entrata) del servizio di messaggistica impostando il valore REQUEST URL (URL RICHIESTA) sull'URL di callback che Amazon Lex ha fornito nella fase precedente.

Step 4: Test the Integration

Utilizza il tuo cellulare per testare l'integrazione tra Twilio SMS e il tuo bot.

Per eseguire il test dell'integrazione

1. Accedi alla console di Twilio all'indirizzo https://www.twilio.com/console ed effettua quanto segue:

a. Verificare di avere un numero Twilio associato al servizio di messaggistica nella sezione Manage Numbers (Gestione numeri).

Puoi inviare messaggi a questo numero e avviare interazioni SMS con il bot di Amazon Lex dal tuo cellulare. b. Verificare che il telefono cellulare sia elencato come ID chiamante verificato.

164 Amazon Lex Guida per gli sviluppatori Deploying an Amazon Lex Bot in Mobile Applications

In caso contrario, seguire le istruzioni sulla console Twilio per abilitare il cellulare che si intende utilizzare per il test.

A questo punto puoi usare il tuo cellulare per inviare messaggi all'endpoint di Twilio SMS, che è mappato al bot di Amazon Lex. 2. Utilizzando il tuo cellulare, invia messaggi al numero Twilio.

Il bot di Amazon Lex risponde. Se hai creato il bot utilizzando l'esercizio 1 "Nozioni di base", puoi utilizzare le conversazioni di esempio che trovi nell'esercizio. Per ulteriori informazioni, vedi Fase 4. Aggiunta della funzione Lambda come hook di codice (console) (p. 84).

Deploying an Amazon Lex Bot in Mobile Applications

Uso AWS Amplify, puoi integrare il tuo Amazon Lex bot con applicazioni mobili o web. Per ulteriori informazioni, vedere Interazioni – Iniziare nella AWS Amplify Docs.

165 Amazon Lex Guida per gli sviluppatori Exporting and Importing in Amazon Lex Format

Importing and Exporting Amazon Lex Bots, Intents, and Slot Types

Puoi importare o esportare un bot, un intento o un tipo di slot. Ad esempio, se vuoi condividere un bot con un collega di un altro account AWS, puoi esportarlo e poi inviarlo. Se desideri aggiungere più enunciazioni a un bot, puoi esportarlo, aggiungere le enunciazioni, quindi importarlo di nuovo nel tuo account.

Puoi export bot, intenti e tipi di slot in Amazon Lex (per condividerli o modificarli) o un formato di competenza Alexa. Puoi import solo in Amazon Lex formato.

Quando esegui l'esportazione di una risorsa, devi esportarla in un formato compatibile con il servizio selezionato per l'esportazione, Amazon Lex o il kit di competenze Alexa. Se esporti un bot nel formato Amazon Lex, puoi reimportarlo nel tuo account, o un utente Amazon Lex in un altro account può importarlo nel proprio account. Puoi anche esportare un bot in un formato compatibile con una competenza di Alexa. Quindi puoi importare il bot utilizzando il kit di competenze di Alexa per rendere il tuo bot disponibile con Alexa. Per ulteriori informazioni, vedi Exporting to an Alexa Skill (p. 171).

Quando esporti un bot, un intento o un tipo di slot, le risorse vengono scritte su un file JSON. Per esportare un bot, un intento o un tipo di slot, puoi utilizzare la console Amazon Lex o l'operazione GetExport (p. 332). Importazione di un bot, un intento o un tipo di slot tramite StartImport (p. 406).

Argomenti • Exporting and Importing in Amazon Lex Format (p. 166) • Exporting to an Alexa Skill (p. 171)

Exporting and Importing in Amazon Lex Format

Per esportare bot, intenti e tipi di slot da Amazon Lex con l'intenzione di importarli in Amazon Lex, dovrai creare un file JSON in formato Amazon Lex. Puoi modificare le tue risorse in questo file e importarle di nuovo in Amazon Lex. Ad esempio, puoi aggiungere enunciazioni a un intento, quindi importare l'intento modificato nel tuo account. Puoi inoltre utilizzare il formato JSON per condividere una risorsa. Ad esempio, puoi esportare un bot da una regione AWS e poi importarlo in un'altra regione. In alternativa, puoi inviare il file JSON a un collega per condividere un bot.

Argomenti • Exporting in Amazon Lex Format (p. 166) • Importing in Amazon Lex Format (p. 167) • JSON Format for Importing and Exporting (p. 168)

Exporting in Amazon Lex Format

Esporta i tuoi bot, intenti e tipi di slot Amazon Lex in un formato che puoi importare su un account AWS. Puoi esportare le seguenti risorse:

• A bot, including all of the intents and custom slot types used by the bot • An intent, including all of the custom slot types used by the intent

166 Amazon Lex Guida per gli sviluppatori Importing in Amazon Lex Format

• A custom slot type, including all of values for the slot type

Puoi esportare solo una versione numerata di una risorsa. Non è possibile esportare una versione $LATEST di una risorsa.

L'esportazione è un processo asincrono. Una volta completata l'esportazione, otteni un URL prefirmato Amazon S3. L'URL fornisce il percorso di un archivio .zip che contiene la risorsa esportata in formato JSON.

Per esportare bot, intenti o tipi di slot personalizzati, puoi utilizzare la console o l'operazione GetExport (p. 332).

Il processo di esportazione di un bot, di un intento o di un tipo di slot è lo stesso. Nelle seguenti procedure, sostituisci l'intento o il tipo di slot al bot. Exporting a Bot

Per esportare un bot

1. Accedi alla Console di gestione AWS, quindi apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegli Bots (Bot), quindi seleziona il bot da esportare. 3. Nel menu Actions (Operazioni), scegli Export (Esporta). 4. Nella finestra di dialogo Export Bot (Esporta Bot), scegli la versione del bot da esportare. Per Platform (Piattaforma), seleziona Amazon Lex. 5. Scegli Export (Esporta). 6. Scarica e salva l'archivio .zip.

Amazon Lex esporta il bot su un file JSON contenuto nell'archivio .zip. Per aggiornare il bot, modifica il testo in formato JSON, quindi importalo di nuovo in Amazon Lex.

Approfondimenti

Importing in Amazon Lex Format (p. 167) Importing in Amazon Lex Format

Dopo aver esportato una risorsa su un file JSON in formato Amazon Lex puoi importare il file JSON contenente la risorsa in uno o più account AWS. Ad esempio, puoi esportare un bot e poi importarlo in un'altra regione AWS. In alternativa, puoi inviare il bot a un collega in modo che possa importarlo nel proprio account.

Quando importi un bot, un intento o un tipo di slot, devi decidere se desideri sovrascrivere la versione $LATEST di una risorsa, ad esempio un intento o un tipo di slot, durante l'importazione, oppure se desideri che l'importazione non vada a buon fine, per mantenere la risorsa presente nel tuo account. Ad esempio, se stai caricando una versione modificata di una risorsa sul tuo account, puoi scegliere di sovrascrivere la versione $LATEST. Se stai caricando una risorsa ricevuta da un collega, puoi scegliere di far fallire l'importazione se ci sono conflitti di risorse, in modo che le tue risorse non vengano sostituite.

Durante l'importazione di una risorsa, si applicano le autorizzazioni assegnate all'utente che effettua la richiesta di importazione. L'utente deve avere le autorizzazioni per tutte le risorse nell'account su cui avrà effetto l'importazione. L'utente deve anche disporre delle autorizzazioni per le operazioni GetBot (p. 302) PutBot (p. 372), GetIntent (p. 338), PutIntent (p. 388), GetSlotType (p. 357), PutSlotType (p. 400). Per ulteriori informazioni sulle autorizzazioni, consultare Come funziona Amazon Lex con IAM (p. 235).

167 Amazon Lex Guida per gli sviluppatori JSON Format for Importing and Exporting

L'importazione consente di registrare gli errori che si verificano durante l'elaborazione. Alcuni errori sono riportati prima che l'importazione abbia inizio, altri vengono riportati durante il processo di importazione. Ad esempio, se l'account che sta importando un intento non ha l'autorizzazione per chiamare una funzione Lambda utilizzata dall'intento, l'importazione avrà esito negativo prima che le modifiche vengano apportate ai tipi di slot o agli intenti. Se l'importazione ha esito negativo durante il processo, viene modificata la versione $LATEST di qualsiasi intento o tipo di slot importati prima del fallimento del processo. Non è possibile eseguire il rollback delle modifiche apportate alla versione $LATEST.

Quando importi una risorsa, tutte le risorse dipendenti vengono importate nella versione $LATEST della risorsa e ricevono poi una versione numerata. Ad esempio, se un bot impiega un intento, all'intento viene assegnata una versione numerata. Se un intento utilizza un tipo di slot personalizzato, al tipo di slot viene assegnata una versione numerata.

Una risorsa viene importata solo una volta. Ad esempio, se il bot contiene un intento OrderPizza e un intento OrderDrink ed entrambi si basano sul tipo di slot personalizzato Size, il tipo di slot Size viene importato una volta e utilizzato per entrambi gli intenti. Note

Se hai esportato il tuo bot con il enableModelImprovements parametro impostato su false, è necessario aprire il file.zip contenente la definizione bot e modificare il enableModelImprovements parametro a true nelle seguenti regioni:

• Asia Pacific (Singapore) (ap-southeast-1) • Asia Pacific (Tokyo) (ap-northeast-1) • EU (Frankfurt) (eu-central-1) • EU (London) (eu-west-2)

Il processo di importazione di un bot, di un intento o di un tipo di slot personalizzato è lo stesso. Nelle seguenti procedure, sostituisci l'intento o il tipo di slot, secondo quanto richiesto. Importing a Bot

Per importare un bot

1. Accedi alla Console di gestione AWS, quindi apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegli Bots (Bot), quindi seleziona il bot da importare. Per importare un nuovo bot, salta questa fase. 3. In Actions (Operazioni), seleziona Import (Importa). 4. Per Import Bot (Importa bot), scegli l'archivio .zip che contiene il file JSON in cui si trova il bot da importare. Se desideri visualizzare i conflitti di unione prima che avvenga l'unione, scegli Notify me of merge conflicts (Inviami una notifica per i conflitti di unione). Se disattivi la verifica dei conflitti, la versione $LATEST di tutte le risorse utilizzate dal bot viene sovrascritta. 5. Seleziona Import (Importa). Se hai scelto di ricevere una notifica in caso di conflitti di unione, al loro verificarsi, apparirà una finestra di dialogo che li elenca. Per sovrascrivere la versione $LATEST di tutte le risorse in conflitto, scegli Sovrascrivi e continua. Per interrompere l'importazione, scegli Cancel (Annulla).

Ora puoi testare il bot nel tuo account. JSON Format for Importing and Exporting

I seguenti esempi mostrano la struttura JSON per l'esportazione e l'importazione di tipi di slot, intenti e bot in formato Amazon Lex.

168 Amazon Lex Guida per gli sviluppatori JSON Format for Importing and Exporting

Slot Type structure

La seguente è la struttura JSON per i tipi di slot personalizzati. Utilizza questa struttura per importare o esportare i tipi di slot e quando esporti gli intenti che dipendono da tipi di slot personalizzati.

{ "metadata": { "schemaVersion": "1.0", "importType": "LEX", "importFormat": "JSON" }, "resource": { "name": "slot type name", "version": "version number", "enumerationValues": [ { "value": "enumeration value", "synonyms": [] }, { "value": "enumeration value", "synonyms": [] } ], "valueSelectionStrategy": "ORIGINAL_VALUE or TOP_RESOLUTION" } }

Intent structure

La seguente è la struttura JSON per gli intenti. Utilizza questa struttura per importare o esportare intenti e bot che dipendono da un intento.

{ "metadata": { "schemaVersion": "1.0", "importType": "LEX", "importFormat": "JSON" }, "resource": { "description": "intent description", "rejectionStatement": { "messages": [ { "contentType": "PlainText or SSML or CustomPayload", "content": "string" } ] }, "name": "intent name", "version": "version number", "fulfillmentActivity": { "type": "ReturnIntent or CodeHook" }, "sampleUtterances": [ "string", "string" ], "slots": [ { "name": "slot name", "description": "slot description",

169 Amazon Lex Guida per gli sviluppatori JSON Format for Importing and Exporting

"slotConstraint": "Required or Optional", "slotType": "slot type", "valueElicitationPrompt": { "messages": [ { "contentType": "PlainText or SSML or CustomPayload", "content": "string" } ], "maxAttempts": value }, "priority": value, "sampleUtterances": [] } ], "confirmationPrompt": { "messages": [ { "contentType": "PlainText or SSML or CustomPayload", "content": "string" }, { "contentType": "PlainText or SSML or CustomPayload", "content": "string" } ], "maxAttempts": value }, "slotTypes": [ List of slot type JSON structures. For more information, see Slot Type structure. ] } }

Bot structure

La seguente è la struttura JSON per i bot. Utilizza questa struttura durante l'importazione o l'esportazione di bot.

{ "metadata": { "schemaVersion": "1.0", "importType": "LEX", "importFormat": "JSON" }, "resource": { "name": "bot name", "version": "version number",, "nluIntentConfidenceThreshold": 0.00-1.00, "enableModelImprovements": true | false, "intents": [ List of intent JSON structures. For more information, see Intent structure. ], "slotTypes": [ List of slot type JSON structures. For more information, see Slot Type structure. ], "voiceId": "output voice ID", "childDirected": boolean, "locale": "en-US", "idleSessionTTLInSeconds": timeout, "description": "bot description",

170 Amazon Lex Guida per gli sviluppatori Exporting to an Alexa Skill

"clarificationPrompt": { "messages": [ { "contentType": "PlainText or SSML or CustomPayload", "content": "string" } ], "maxAttempts": value }, "abortStatement": { "messages": [ { "contentType": "PlainText or SSML or CustomPayload", "content": "string" } ] } } }

Exporting to an Alexa Skill

Puoi esportare lo schema del bot in un formato compatibile con una competenza di Alexa. Dopo aver esportato il bot su un file JSON, puoi caricarlo su Alexa utilizzando Alexa Skill Builder.

Per esportare un bot e i relativi schemi (modello di interazione)

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Scegliere il bot da esportare. 3. In Actions (Operazioni), seleziona Export (Esporta). 4. Scegliere la versione del bot che si desidera esportare. Per il formato, seleziona Alexa Skills Kit (Kit competenze Alexa), quindi scegli Export (Esporta). 5. Se viene visualizzata una finestra di dialogo di download, scegliere una posizione in cui salvare il file, quindi Save (Salva).

Il file scaricato è un archivio .zip contenente un file con il nome del bot esportato. Contiene le informazioni necessarie per importare il bot come competenza Alexa. Note

Amazon Lex e il Kit di competenze di Alexa differiscono nei seguenti modi:

• Session attributes, denoted by square brackets ([]), are not supported by the Alexa Skills Kit. You need to update prompts that use session attributes. • Punctuation marks are not supported by the Alexa Skills Kit. You need to update utterances that use punctuation.

Per caricare il bot su una competenza Alexa

1. Accedi al portale per gli sviluppatori all'indirizzo https://developer.amazon.com/. 2. Nella pagina Alexa Skills (Competenze di Alexa), scegliere Create Skill (Crea competenza). 3. Nella pagina Create a new skill (Crea una nuova competenza), immettere un nome di competenza e il linguaggio predefinito per essa. Accertarsi che per il modello di competenza sia selezionato Custom (Personalizzato), quindi scegliere Create skill (Crea competenza).

171 Amazon Lex Guida per gli sviluppatori Exporting to an Alexa Skill

4. Accertarsi che sia selezionato Start from scratch (Inizia da zero), quindi scegliere Choose (Scegli). 5. Nel menu a sinistra, scegliere JSON Editor (Editor JSON) . Trascinare il file JSON esportato da Amazon Lex nell'editor JSON. 6. Scegliere Save Model (Salva modello) per salvare il modello di interazione.

Una volta caricato lo schema nella competenza Alexa, puoi apportare tutte le modifiche necessarie per eseguire la competenza con Alexa. Per ulteriori informazioni sulla creazione di una competenza Alexa, vedere Utilizzare il Costruttore delle competenze (Beta) nella Alexa Skills Kit.

172 Amazon Lex Guida per gli sviluppatori Pianifica appuntamento

Esempi aggiuntivi: Creazione Amazon Lex Bot

Le sezioni seguenti forniscono ulteriori esercizi di Amazon Lex con istruzioni dettagliate.

Argomenti • Pianifica appuntamento (p. 173) • Prenota viaggio (p. 192) • Utilizzo di una scheda di risposta (p. 216) • Aggiornamento delle enunciazioni (p. 220) • Integrazione con un sito Web (p. 221) • Assistente agente del call center (p. 221)

Pianifica appuntamento

L'esempio di bot in questo esercizio consente di pianificare gli appuntamenti per uno studio dentistico. L'esempio illustra inoltre l'utilizzo di schede di risposta per ottenere l'input utente mediante pulsanti. Più precisamente, l'esempio illustra la generazione dinamica di schede di risposta durante la fase di runtime.

Puoi configurare le schede di risposta durante la creazione (definite anche schede di risposta statiche) oppure generarle dinamicamente in una funzione AWS Lambda. In questo esempio, il bot utilizza le seguenti schede di risposta:

• Una scheda di risposta che elenca i pulsanti per tipo di appuntamento. Ad esempio:

• Una scheda di risposta che elenca i pulsanti per data dell'appuntamento. Ad esempio:

173 Amazon Lex Guida per gli sviluppatori Pianifica appuntamento

• Una scheda di risposta che elenca i pulsanti per confermare l'ora suggerita per l'appuntamento. Ad esempio:

Le date e gli orari disponibili per l'appuntamento variano, di conseguenza è necessario generare schede di risposta in fase di runtime. Puoi utilizzare una funzione AWS Lambda per generare queste schede di risposta in modo dinamico. La funzione Lambda restituisce schede di risposta nella sua risposta a Amazon Lex. Amazon Lex include la scheda di risposta nella sua risposta al client.

Se un client (ad esempio, Facebook Messenger) supporta le schede di risposta, l'utente può scegliere uno dei pulsanti oppure digitare la risposta. In caso contrario, l'utente digita semplicemente la risposta.

Oltre al pulsante illustrato nell'esempio precedente, è anche possibile includere immagini, allegati e altre informazioni utili da visualizzare sulle schede di risposta. Per informazioni sulle schede di risposta, consulta Schede di risposta (p. 16).

In questo esercizio, devi effettuare le seguenti operazioni:

• Creare e testare un bot (utilizzando ScheduleAppointment progetto). Per questo esercizio, utilizzi un piano di bot per configurare ed eseguire il test del bot in tempi brevi. Per un elenco dei piani disponibili, consulta Amazon Lex e piani AWS Lambda (p. 150). Questo bot è preconfigurato con un intento (MakeAppointment).

• Creazione e test di una funzione Lambda (utilizzando il piano lex-make-appointment-python fornito da Lambda). L'intento MakeAppointment viene configurato per utilizzare questa funzione Lambda come hook di codice con cui eseguire le attività di inizializzazione, convalida e realizzazione.

174 Amazon Lex Guida per gli sviluppatori Panoramica del piano di bot (ScheduleAppointment)

Note

La funzione Lambda di esempio fornita mostra una conversazione dinamica basata sulla disponibilità simulata di un appuntamento dal dentista. In un'applicazione reale, puoi utilizzare un calendario reale per impostare un appuntamento. • Aggiornamento della configurazione dell'intento MakeAppointment per utilizzare la funzione Lambda come hook di codice e test dell'intera esperienza. • Pubblicazione del bot di pianificazione di appuntamenti su Facebook Messenger per vedere le schede di risposta in azione (il client nella console di Amazon Lex non supporta attualmente le schede di risposta).

Le sezioni seguenti forniscono informazioni di riepilogo sui piani utilizzati in questo esercizio.

Argomenti • Panoramica del piano di bot (ScheduleAppointment) (p. 175) • Panoramica del piano della funzione Lambda (lex-make-appointment-python) (p. 176) • Passaggio 1: Creare un bot Amazon Lex (p. 176) • Passaggio 2: Creare una funzione Lambda (p. 178) • Passaggio 3: Aggiornare l'intento: Configurazione di un hook di codice (p. 179) • Passaggio 4: Distribuisci il bot sulla piattaforma Facebook Messenger (p. 180) • Dettagli del flusso di informazioni (p. 180)

Panoramica del piano di bot (ScheduleAppointment)

Il ScheduleAppointment che utilizzi per creare un bot per questo esercizio è preconfigurato con quanto segue:

• Tipi di slot: un tipo di slot personalizzato denominato AppointmentTypeValue, con i valori di enumerazione root canal, cleaning e whitening. • Intento un intento (MakeAppointment), preconfigurato come segue: • Slot machine – L'intento è configurato con i seguenti slot: • Slot AppointmentType, del tipo personalizzato AppointmentTypes . • Slot Date del tipo integrato AMAZON.DATE. • Slot Time del tipo integrato AMAZON.TIME. • Enunciazioni – L'intento è preconfigurato con le seguenti enunciazioni: • "I would like to book an appointment" • "Book an appointment" • "Book a {AppointmentType}"

Se l'utente utilizza una di queste enunciazioni, Amazon Lex determina che MakeAppointment è l'intento, quindi utilizza i messaggi di richiesta per ottenere i dati dello slot. • Richieste – L'intento è preconfigurato con i seguenti prompt: • Messaggio di richiesta per lo slot AppointmentType: "What type of appointment would you like to schedule?" • Messaggio di richiesta per lo slot Date: "When should I schedule your {AppointmentType}?" • Richiesta di Time alloggiamento – "A che ora si desidera pianificare {AppointmentType}?" e

"At what time on {Date}?" • Messaggio di richiesta di conferma: "{Time} is available, should I go ahead and book your appointment?"

175 Amazon Lex Guida per gli sviluppatori Panoramica del piano della funzione Lambda (lex-make-appointment-python)

• Messaggio di annullamento: "Okay, I will not schedule an appointment."

Panoramica del piano della funzione Lambda (lex- make-appointment-python)

Il Lambda Il piano della funzione (lex-make-appointment-python) è un hook di codice per i bot creati utilizzando la ScheduleAppointment piano del bot.

Il codice del piano della funzione Lambda è in grado di eseguire le attività di inizializzazione/convalida e di realizzazione.

• Il codice della funzione Lambda mostra una conversazione dinamica basata su un esempio di disponibilità per un appuntamento dal dentista (nelle applicazioni reali, puoi utilizzare un calendario). Per il giorno o la data che l'utente specifica, il codice viene configurato come segue: • Se non ci sono appuntamenti disponibili, il Lambda La funzione restituisce una risposta che indica Amazon Lex per richiedere all'utente un altro giorno o una data (impostando dialogAction tipo a ElicitSlot). Per ulteriori informazioni, consulta Formato della risposta (p. 145). • Se è disponibile un solo appuntamento nel giorno o nella data specificati, il Lambda suggerisce il tempo disponibile nella risposta e Amazon Lex per ottenere la conferma dell'utente impostando il dialogAction nella risposta a ConfirmIntent. Questo illustra come migliorare l'esperienza utente suggerendo in modo proattivo il tempo disponibile per un appuntamento. • Se sono disponibili più appuntamenti, la funzione Lambda restituisce un elenco di ore disponibili nella risposta a Amazon Lex. Amazon Lex restituisce una risposta al client con il messaggio generato dalla funzione Lambda. • Come l'hook di codice di realizzazione, la funzione Lambda restituisce un messaggio di riepilogo indicante che un appuntamento è fissato (ovvero che l'intento è realizzato).

Note

In questo esempio, viene descritto come utilizzare le schede di risposta. La funzione Lambda crea e restituisce una scheda di risposta a Amazon Lex. La scheda di risposta elenca i giorni e le ore disponibili come pulsanti tra cui scegliere. Quando esegui il test del bot utilizzando il client fornito dalla console di Amazon Lex, non puoi visualizzare la scheda di risposta. Per visualizzarla, devi integrare il bot in una piattaforma di messaggistica come Facebook Messenger. Per istruzioni, consulta Integrating an Amazon Lex Bot with Facebook Messenger (p. 153). Per ulteriori informazioni sulle schede di risposta, consultare Gestione dei messaggi (p. 10).

Quando Amazon Lex richiama la funzione Lambda, passa i dati di evento come input. Uno dei campi di evento è invocationSource, che viene utilizzato dalla funzione Lambda per scegliere tra un'attività di convalida dell'input e di realizzazione. Per ulteriori informazioni, vedi Formato dell'evento di input (p. 140).

Approfondimenti

Passaggio 1: Creare un bot Amazon Lex (p. 176) Passaggio 1: Creare un bot Amazon Lex

In questa sezione, si crea un Amazon Lex tramite il bot di ScheduleAppointment , che è fornito nella Amazon Lex console di.

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/.

176 Amazon Lex Guida per gli sviluppatori Passaggio 1: Creare un bot Amazon Lex

2. Nella pagina Bots (Bot) scegli Create (Crea). 3. Nella pagina Create your Lex bot (Crea bot Lex), procedi come descritto di seguito:

• Seleziona il piano ScheduleAppointment. • Lascia il nome di bot predefinito (ScheduleAppointment). 4. Scegliere Create (Crea).

Questa fase salva e crea il bot. La console invia le seguenti richieste a Amazon Lex durante il processo di creazione:

• Creazione di una nuova versione dei tipi di slot (a partire dalla versione $LATEST). Per informazioni sui tipi di slot definiti in questo piano di bot, consulta Panoramica del piano di bot (ScheduleAppointment) (p. 175). • Creazione di una versione dell'intento MakeAppointment (a partire dalla versione $LATEST). In alcuni casi, la console invia una richiesta per l'operazione API update prima di creare una nuova versione. • Aggiornamento della versione $LATEST del bot.

A questo punto, Amazon Lex crea un modello di machine learning per il bot. Quando esegui il test del bot nella console, la console utilizza l'API di runtime per inviare l'input utente a Amazon Lex. Amazon Lex utilizza quindi il modello di machine learning per interpretare l'input utente. 5. La console mostra ScheduleAppointment bot di. Nella scheda Editor, esamina i dettagli relativi all'intento preconfigurato (MakeAppointment). 6. Esegui il test del bot nella finestra di prova. Utilizza la seguente schermata per iniziare una conversazione di prova con il bot:

Tieni presente quanto segue:

177 Amazon Lex Guida per gli sviluppatori Passaggio 2: Creare una funzione Lambda

• A partire dall'input utente iniziale ("Book an appointment"), il bot deduce l'intento (MakeAppointment). • Il bot utilizza quindi i messaggi di richiesta configurati per ottenere i dati dello slot dall'utente. • Il piano di bot include l'intento MakeAppointment configurato con il seguente messaggio di richiesta di conferma:

{Time} is available, should I go ahead and book your appointment?

Dopo che l'utente ha fornito tutti i dati dello slot, Amazon Lex restituisce una risposta al client con una richiesta di conferma come messaggio. Il client visualizza il messaggio per l'utente:

16:00 is available, should I go ahead and book your appointment?

Nota che il bot accetta qualsiasi valore di data e ora per l'appuntamento poiché non disponi di alcun codice per inizializzare o convalidare i dati utente. Nella sezione successiva, aggiungerai una funzione Lambda per effettuare tale operazione.

Approfondimenti

Passaggio 2: Creare una funzione Lambda (p. 178) Passaggio 2: Creare una funzione Lambda

In questa sezione, crei una funzione Lambda utilizzando un piano (lex-make-appointment-python) fornito nella console di Lambda. Esegui inoltre il test della funzione Lambda dopo averla richiamata mediante esempi di dati di evento di Amazon Lex forniti dalla console.

1. Accedi alla AWS Management Console e apri la console AWS Lambda all'indirizzo https:// console.aws.amazon.com/lambda/. 2. Seleziona Create a Lambda function (Crea una funzione . 3. In Select blueprint (Seleziona piano), digita lex per trovare il piano e scegli il piano lex-make- appointment-python. 4. Configurazione di Lambda funzionano come segue.

• Digita il nome della funzione Lambda (MakeAppointmentCodeHook). • Per il ruolo, scegli Create a new role from template(s) (Crea un nuovo ruolo da modello), quindi digita un nome di ruolo. • Non modificare gli altri valori predefiniti. 5. Selezionare Create function (Crea funzione). 6. Se si utilizza un'impostazione locale diversa da English (US) (en-US), aggiornare i nomi degli intenti come descritto in Aggiornamento di un piano per un'impostazione locale specifica (p. 150). 7. Esegui il test della funzione Lambda.

a. Seleziona Actions (Operazioni), quindi Configure test event (Configura evento test). b. Dall'elenco Sample event template (Modello evento di esempio), scegli Lex-Make Appointment (preview) (Lex-Crea appuntamento (anteprima)). Questo esempio di evento utilizza il modello di richiesta/risposta di Amazon Lex, con valori impostati per soddisfare una richiesta del tuo bot di Amazon Lex. Per informazioni sul modello di richiesta/risposta di Amazon Lex, consulta Utilizzo delle funzioni Lambda (p. 140). c. Scegliere Save and test (Salva ed esegui test).

178 Amazon Lex Guida per gli sviluppatori Passaggio 3: Aggiornare l'intento: Configurazione di un hook di codice

d. Verificare che il Lambda La funzione è stata eseguita correttamente. La risposta in questo caso corrisponde al modello di risposta di Amazon Lex.

Approfondimenti

Passaggio 3: Aggiornare l'intento: Configurazione di un hook di codice (p. 179) Passaggio 3: Aggiornare l'intento: Configurazione di un hook di codice

In questa sezione, aggiorni la configurazione dell'intento MakeAppointment per utilizzare la funzione Lambda come hook di codice per le attività di convalida e realizzazione.

1. Nella finestra Amazon Lex console, selezionare il pulsante ScheduleAppointment bot di. La console visualizza l'intento MakeAppointment. Modifica la configurazione dell'intento come segue. Note

Puoi aggiornare solo le versioni $LATEST di qualsiasi risorsa di Amazon Lex, inclusi gli intenti. Assicurati che la versione dell'intento sia impostata su $LATEST. Non hai ancora pubblicato una versione del bot, di conseguenza dovrebbe essere ancora la versione $LATEST nella console.

a. Nella sezione Options (Opzioni), scegli Initialization and validation code hook (Hook di codice inizializzazione e convalida), quindi scegli la funzione Lambda dall'elenco. b. Nella sezione Fulfillment (Realizzazione), scegli AWS Lambda function (Funzione AWS Lambda), quindi scegli la funzione Lambda dall'elenco. c. Seleziona Goodbye message (Messaggio di saluto). 2. Seleziona Save (Salva), quindi Build (Crea). 3. Esegui il test del bot.

179 Amazon Lex Guida per gli sviluppatori Passaggio 4: Distribuisci il bot sulla piattaforma Facebook Messenger

Approfondimenti

Passaggio 4: Distribuisci il bot sulla piattaforma Facebook Messenger (p. 180) Passaggio 4: Distribuisci il bot sulla piattaforma Facebook Messenger

Nella sezione precedente, hai testato il ScheduleAppointment bot utilizzando il client nella Amazon Lex console di. Al momento, la console di Amazon Lex non supporta le schede di risposta. Per eseguire il test delle schede di risposta generate dinamicamente che il bot supporta, distribuisci il bot sulla piattaforma Facebook Messenger ed eseguine il test.

Per istruzioni, consulta Integrating an Amazon Lex Bot with Facebook Messenger (p. 153).

Approfondimenti

Dettagli del flusso di informazioni (p. 180) Dettagli del flusso di informazioni

Il piano di bot ScheduleAppointment mostra principalmente l'utilizzo di carte di risposta generate dinamicamente. La funzione Lambda in questo esercizio include schede di risposta nella sua risposta a Amazon Lex. Amazon Lex include le schede di risposta nella sua risposta al client. Questa sezione descrive quanto segue:

• Il flusso di dati tra il client e Amazon Lex.

180 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

La sezione presuppone che il client invii le richieste a Amazon Lex utilizzando l'API di runtime PostText e mostra i dettagli di richiesta/risposta corrispondenti. Per ulteriori informazioni sull'API di runtime PostText, consulta PostText (p. 434). Note

Per un esempio di flusso di informazioni tra client e Amazon Lex in cui il client utilizza l'API PostContent, consulta Fase 2a (facoltativo): Revisione dei dettagli del flusso di informazioni parlate (console) (p. 75).

• Il flusso di dati tra Amazon Lex e la funzione Lamba. Per ulteriori informazioni, vedi Formato di evento di input e di risposta della funzione Lambda (p. 140).

Note

L'esempio presuppone l'utilizzo del client di Facebook Messenger, il quale non include gli attributi di sessione nella richiesta a Amazon Lex. Di conseguenza, le richieste di esempio mostrate in questa sezione sono vuote sessionAttributes. Se esegui il test del bot utilizzando il client fornito nella Amazon Lex console , il client include gli attributi di sessione.

Questa sezione descrive cosa accade dopo ogni input utente.

1. Utente: Tipi Book an appointment.

a. Il client (console) invia la seguente richiesta PostContent (p. 425) ad Amazon Lex:

POST /bot/ScheduleAppointment/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/ text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"book appointment", "sessionAttributes":{} }

L'URI e il corpo della richiesta forniscono informazioni a Amazon Lex:

• URI della richiesta: fornisce il nome del bot (ScheduleAppointment), l'alias del bot ($LATEST) e l'ID del nome utente. Il codice text di fine indica che si tratta di una richiesta API PostText (non PostContent). • Corpo della richiesta: include l'input utente (inputText) e il campo sessionAttributes vuoto. b. A partire da inputText, Amazon Lex rileva l'intento (MakeAppointment). Il servizio richiama la funzione Lambda, configurata come hook di codice, per eseguire l'inizializzazione e la convalida trasmettendo l'evento seguente. Per informazioni dettagliate, consulta Formato dell'evento di input (p. 140).

{ "currentIntent": { "slots": { "AppointmentType": null, "Date": null, "Time": null },

181 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

"name": "MakeAppointment", "confirmationStatus": "None" }, "bot": { "alias": null, "version": "$LATEST", "name": "ScheduleAppointment" }, "userId": "bijt6rovckwecnzesbthrr1d7lv3ja3n", "invocationSource": "DialogCodeHook", "outputDialogMode": "Text", "messageVersion": "1.0", "sessionAttributes": {} }

Oltre alle informazioni inviate dal client, Amazon Lex include anche i seguenti dati:

• currentIntent: fornisce informazioni sull'intento corrente. • invocationSource: indica lo scopo della chiamata della funzione Lambda. In questo caso, lo scopo è eseguire l'inizializzazione e la convalida dei dati utente (Amazon Lex sa che l'utente non ha ancora fornito tutti i dati dello slot per realizzare l'intento). • messageVersion: Amazon Lex supporta attualmente solo la versione 1.0. c. A questo punto, tutti i valori di slot sono null (non c'è nulla da convalidare). La funzione Lambda restituisce la seguente risposta a Amazon Lex, indicando al servizio di ottenere informazioni per lo slot AppointmentType. Per informazioni sul formato della risposta, consulta l'argomento Formato della risposta (p. 145).

{ "dialogAction": { "slotToElicit": "AppointmentType", "intentName": "MakeAppointment", "responseCard": { "genericAttachments": [ { "buttons": [ { "text": "cleaning (30 min)", "value": "cleaning" }, { "text": "root canal (60 min)", "value": "root canal" }, { "text": "whitening (30 min)", "value": "whitening" } ], "subTitle": "What type of appointment would you like to schedule?", "title": "Specify Appointment Type" } ], "version": 1, "contentType": "application/vnd.amazonaws.card.generic" }, "slots": { "AppointmentType": null, "Date": null, "Time": null }, "type": "ElicitSlot",

182 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

"message": { "content": "What type of appointment would you like to schedule?", "contentType": "PlainText" } }, "sessionAttributes": {} }

La risposta include i campi dialogAction e sessionAttributes. Il campo dialogAction restituisce inoltre i seguenti campi:

• type: impostando questo campo su ElicitSlot, la funzione Lambda indica a Amazon Lex di ottenere il valore per lo slot specificato nel campo slotToElicit. La funzione Lambda fornisce inoltre un message da distribuire all'utente. • responseCard: identifica un elenco di possibili valori per lo slot AppointmentType. Un client che supporta le schede di risposta (ad esempio, Facebook Messenger) visualizza una scheda di risposta per consentire all'utente di scegliere un tipo di appuntamento, come segue:

d. Come indicato da dialogAction.type nella risposta della funzioneLambda, Amazon Lex invia la seguente risposta al client:

Il client legge la risposta, quindi visualizza il messaggio: "Che tipo di appuntamento vorresti fissare?" e la scheda di risposta (se il client supporta le schede di risposta). 2. Utente: A seconda del client, l'utente ha due opzioni:

• Se la scheda di risposta è visualizzata, scegli devitalizzazione (60 min) o digita root canal. • Se il client non supporta le schede di risposta, digita root canal.

183 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni a. Il client invia la seguente richiesta PostText a Amazon Lex (delle interruzioni di riga sono state aggiunte per facilitare la lettura):

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "root canal", "sessionAttributes": {} } b. Amazon Lex richiama la funzione Lambda per la convalida dei dati utente inviando il seguente evento come parametro:

{ "currentIntent": { "slots": { "AppointmentType": "root canal", "Date": null, "Time": null }, "name": "MakeAppointment", "confirmationStatus": "None" }, "bot": { "alias": null, "version": "$LATEST", "name": "ScheduleAppointment" }, "userId": "bijt6rovckwecnzesbthrr1d7lv3ja3n", "invocationSource": "DialogCodeHook", "outputDialogMode": "Text", "messageVersion": "1.0", "sessionAttributes": {} }

Nei dati di evento, nota quanto segue:

• invocationSource continua a essere DialogCodeHook. In questa fase, stiamo solo convalidando i dati utente. • Amazon Lex imposta il campo AppointmentType nello slot currentIntent.slots su root canal. • Amazon Lex trasferisce semplicemente il campo sessionAttributes tra il client e la funzione Lambda. c. La funzione Lambda convalida l'input utente e restituisce la risposta seguente a Amazon Lex, indicando al servizio di ottenere un valore per la data dell'appuntamento.

{ "dialogAction": { "slotToElicit": "Date", "intentName": "MakeAppointment", "responseCard": { "genericAttachments": [ { "buttons": [ { "text": "2-15 (Wed)", "value": "Wednesday, February 15, 2017"

184 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

}, { "text": "2-16 (Thu)", "value": "Thursday, February 16, 2017" }, { "text": "2-17 (Fri)", "value": "Friday, February 17, 2017" }, { "text": "2-20 (Mon)", "value": "Monday, February 20, 2017" }, { "text": "2-21 (Tue)", "value": "Tuesday, February 21, 2017" } ], "subTitle": "When would you like to schedule your root canal?", "title": "Specify Date" } ], "version": 1, "contentType": "application/vnd.amazonaws.card.generic" }, "slots": { "AppointmentType": "root canal", "Date": null, "Time": null }, "type": "ElicitSlot", "message": { "content": "When would you like to schedule your root canal?", "contentType": "PlainText" } }, "sessionAttributes": {} }

La risposta include di nuovo i campi dialogAction e sessionAttributes. Il campo dialogAction restituisce inoltre i seguenti campi:

• type: impostando questo campo su ElicitSlot, la funzione Lambda indica a Amazon Lex di ottenere il valore per lo slot specificato nel campo slotToElicit. La funzione Lambda fornisce inoltre un message da distribuire all'utente. • responseCard: identifica un elenco di possibili valori per lo slot Date. Un client che supporta le schede di risposta (ad esempio, Facebook Messenger) visualizza una scheda di risposta che consente all'utente di scegliere una data per l'appuntamento:

185 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Sebbene la funzione Lambda abbia restituito cinque date, il client (Facebook Messenger) è limitato a tre pulsanti per una scheda di risposta. Pertanto, nello screenshot sono visualizzati solo i primi tre valori.

Queste date sono impostate come codificato nella funzione Lambda. In un'applicazione di produzione, puoi utilizzare un calendario per ottenere le date disponibili in tempo reale. Poiché le date sono dinamiche, devi generare la scheda di risposta dinamicamente nella funzione Lambda. d. Amazon Lex rileva dialogAction.type e restituisce una risposta al client che include informazioni presenti nella risposta della funzione Lambda.

Il client visualizza il messaggio: Quando vorresti programmare il tuo canale radicolare? e la scheda di risposta (se il client supporta le schede di risposta). 3. Utente: Tipi Thursday.

a. Il client invia la seguente richiesta PostText a Amazon Lex (delle interruzioni di riga sono state aggiunte per facilitare la lettura):

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "Thursday", "sessionAttributes": {}

186 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

} b. Amazon Lex richiama la funzione Lambda per la convalida dei dati utente inviando il seguente evento come parametro:

{ "currentIntent": { "slots": { "AppointmentType": "root canal", "Date": "2017-02-16", "Time": null }, "name": "MakeAppointment", "confirmationStatus": "None" }, "bot": { "alias": null, "version": "$LATEST", "name": "ScheduleAppointment" }, "userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy", "invocationSource": "DialogCodeHook", "outputDialogMode": "Text", "messageVersion": "1.0", "sessionAttributes": {} }

Nei dati di evento, nota quanto segue:

• invocationSource continua a essere DialogCodeHook. In questa fase, stiamo solo convalidando i dati utente. • Amazon Lex imposta il campo Date nello slot currentIntent.slots su 2017-02-16. • Amazon Lex trasferisce semplicemente il campo sessionAttributes tra il client e la funzione Lambda. c. La funzione Lambda convalida l'input utente. In questo caso, la funzione Lambda determina che non ci sono appuntamenti disponibili nella data specificata e restituisce la seguente risposta a Amazon Lex, indicando al servizio di ottenere di nuovo un valore per la data dell'appuntamento.

{ "dialogAction": { "slotToElicit": "Date", "intentName": "MakeAppointment", "responseCard": { "genericAttachments": [ { "buttons": [ { "text": "2-15 (Wed)", "value": "Wednesday, February 15, 2017" }, { "text": "2-17 (Fri)", "value": "Friday, February 17, 2017" }, { "text": "2-20 (Mon)", "value": "Monday, February 20, 2017" }, { "text": "2-21 (Tue)", "value": "Tuesday, February 21, 2017"

187 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

} ], "subTitle": "When would you like to schedule your root canal?", "title": "Specify Date" } ], "version": 1, "contentType": "application/vnd.amazonaws.card.generic" }, "slots": { "AppointmentType": "root canal", "Date": null, "Time": null }, "type": "ElicitSlot", "message": { "content": "We do not have any availability on that date, is there another day which works for you?", "contentType": "PlainText" } }, "sessionAttributes": { "bookingMap": "{\"2017-02-16\": []}" } }

La risposta include di nuovo i campi dialogAction e sessionAttributes. Il campo dialogAction restituisce inoltre i seguenti campi:

• Campo dialogAction: • type – Il Lambda imposta questo valore su ElicitSlot e resetta il slotToElicit campo a Date. Il Lambda fornisce anche un’adeguata message per trasmettere all'utente. • responseCard: restituisce un elenco di valori per lo slot Date. • sessionAttributes: questa volta la funzione Lambda include l'attributo di sessione bookingMap. Il relativo valore è la data richiesta dell'appuntamento e gli appuntamenti disponibili (un oggetto vuoto indica che non vi sono appuntamenti disponibili). d. Amazon Lex rileva dialogAction.type e restituisce una risposta al client che include informazioni presenti nella risposta della funzione Lambda.

188 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Il client visualizza il messaggio: Non abbiamo alcuna disponibilità in quella data, c’è un altro giorno che funziona per te? e la scheda di risposta (se il client supporta le schede di risposta). 4. Utente: A seconda del client, l'utente ha due opzioni:

• Se la scheda di risposta viene visualizzata, scegli 15-2 (mer.) o digita Wednesday. • Se il client non supporta le schede di risposta, digita Wednesday.

a. Il client invia la seguente richiesta PostText a Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/bijt6rovckwecnzesbthrr1d7lv3ja3n/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText": "Wednesday", "sessionAttributes": { } }

Note

Il client di Facebook Messenger non imposta alcun attributo di sessione. Se desideri conservare gli stati di sessione tra le richieste, devi farlo nella funzione Lambda. In un'applicazione reale, puoi avere la necessità di conservare questi attributi di sessione in un database back-end. b. Amazon Lex richiama la funzione Lambda per la convalida dei dati utente inviando il seguente evento come parametro:

{ "currentIntent": { "slots": { "AppointmentType": "root canal", "Date": "2017-02-15", "Time": null }, "name": "MakeAppointment", "confirmationStatus": "None" }, "bot": { "alias": null, "version": "$LATEST", "name": "ScheduleAppointment" }, "userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy", "invocationSource": "DialogCodeHook", "outputDialogMode": "Text", "messageVersion": "1.0", "sessionAttributes": { } }

Amazon Lex ha aggiornato currentIntent.slots impostando lo slot Date su 2017-02-15. c. La funzione Lambda convalida l'input utente e restituisce la risposta seguente a Amazon Lex affinché ottenga il valore per l'ora dell'appuntamento.

{ "dialogAction": {

189 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

"slots": { "AppointmentType": "root canal", "Date": "2017-02-15", "Time": "16:00" }, "message": { "content": "What time on 2017-02-15 works for you? 4:00 p.m. is our only availability, does that work for you?", "contentType": "PlainText" }, "type": "ConfirmIntent", "intentName": "MakeAppointment", "responseCard": { "genericAttachments": [ { "buttons": [ { "text": "yes", "value": "yes" }, { "text": "no", "value": "no" } ], "subTitle": "Is 4:00 p.m. on 2017-02-15 okay?", "title": "Confirm Appointment" } ], "version": 1, "contentType": "application/vnd.amazonaws.card.generic" } }, "sessionAttributes": { "bookingMap": "{\"2017-02-15\": [\"10:00\", \"16:00\", \"16:30\"]}" } }

La risposta include di nuovo i campi dialogAction e sessionAttributes. Il campo dialogAction restituisce inoltre i seguenti campi:

• Campo dialogAction: • type: la funzione Lambda imposta questo valore su ConfirmIntent, indicando a Amazon Lex di ottenere la conferma dell'utente per l'ora dell'appuntamento suggerita nel message. • responseCard: restituisce un elenco di valori sì/no tra cui l'utente deve scegliere. Se il client supporta le schede di risposta, visualizza la scheda di risposta, come mostrato nel seguente esempio:

• sessionAttributes: la funzione Lambda imposta l'attributo di sessione bookingMap con il relativo valore impostato sulla data dell'appuntamento e sugli appuntamenti disponibili in quella

190 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

data. In questo esempio, si tratta di appuntamenti di 30 minuti. Per una devitalizzazione che richieda un'ora, è possibile scegliere solo le 16:00.

d. Come indicato nel campo dialogAction.type della risposta della funzione Lambda, Amazon Lex restituisce la seguente risposta al client:

Il client visualizza il messaggio: A che ora è il 2017-02-15? 16.00 è la nostra unica disponibilità, funziona per te?

5. Utente: Scegli yes.

Amazon Lex richiama la funzione Lambda con i seguenti dati di evento. Perché l'utente ha risposto yes, Amazon Lex imposta il confirmationStatus a Confirmede imposta il Time campo in currentIntent.slots a 4 p.m.

{ "currentIntent": { "slots": { "AppointmentType": "root canal", "Date": "2017-02-15", "Time": "16:00" }, "name": "MakeAppointment", "confirmationStatus": "Confirmed" }, "bot": { "alias": null, "version": "$LATEST", "name": "ScheduleAppointment" }, "userId": "u3fpr9gghj02zts7y5tpq5mm4din2xqy", "invocationSource": "FulfillmentCodeHook", "outputDialogMode": "Text", "messageVersion": "1.0", "sessionAttributes": { } }

Poiché il campo confirmationStatus viene confermato, la funzione Lambda elabora l'intento (prenota un appuntamento dal dentista) e restituisce la seguente risposta a Amazon Lex:

191 Amazon Lex Guida per gli sviluppatori Prenota viaggio

{ "dialogAction": { "message": { "content": "Okay, I have booked your appointment. We will see you at 4:00 p.m. on 2017-02-15", "contentType": "PlainText" }, "type": "Close", "fulfillmentState": "Fulfilled" }, "sessionAttributes": { "formattedTime": "4:00 p.m.", "bookingMap": "{\"2017-02-15\": [\"10:00\"]}" } }

Tieni presente quanto segue:

• La funzione Lambda ha aggiornato sessionAttributes. • dialogAction.type è impostato su Close, di modo che Amazon Lex non preveda una risposta dell'utente. • dialogAction.fulfillmentState è impostato su Fulfilled, a indicare che l'intento è stato realizzato.

Il client visualizza il messaggio: Ok, ho prenotato il tuo appuntamento. Ci vediamo alle 16:00 del 2017-02-15.

Prenota viaggio

Nell'esempio seguente viene illustrata la creazione di un bot configurato per supportare più intenti. L'esempio illustra inoltre come utilizzare gli attributi di sessione per la condivisione di informazioni tra più intenti. Dopo aver creato il bot, potrai utilizzare un client di test nella console di Amazon Lex per eseguire il test del bot (BookTrip). Il client utilizza l'operazione API di runtime PostText (p. 434) per inviare le richieste ad Amazon Lex per ogni input utente.

Il BookTrip in questo esempio è configurato con due intenti (BookHotel e BookCar). Supponiamo ad esempio che un utente prenoti in primo luogo un hotel. Durante l'interazione, l'utente fornisce informazioni quali date di check-in, località e il numero di notti. Dopo che l'intento è realizzato, il client può conservare queste informazioni tramite gli attributi di sessione. Per ulteriori informazioni sugli attributi di sessione, consulta PostText (p. 434).

Supponiamo a questo punto che l'utente continui con la prenotazione di un'automobile. Utilizzare le informazioni fornite dall'utente nel precedente BookHotel (ovvero città di destinazione, date di check-in e check-out), il codice hook (funzione Lambda) configurato per inizializzare e convalidare BookCar intento, inizializza i dati dello slot per BookCar (ovvero, destinazione, città di ritiro, data di ritiro e data di ritorno). Questo illustra come la condivisione di informazioni tra più intenti consenta di creare bot in grado di iniziare una conversazione dinamica con l'utente.

In questo esempio vengono utilizzati gli attributi di sessione riportati di seguito. Gli attributi di sessione possono essere impostati e aggiornati solo dal client e dalla funzione Lambda. Amazon Lex può solo passare tali attributi dal client alla funzione Lambda. Amazon Lex non gestisce né modifica gli attributi di sessione.

192 Amazon Lex Guida per gli sviluppatori Passaggio 1: Revisione del progetto

• currentReservation: contiene dati dello slot per una prenotazione in corso e altre informazioni rilevanti. Di seguito è riportata una richiesta di esempio dal client ad Amazon Lex, con l'attributo di sessione currentReservation mostrato nel corpo della richiesta.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"Chicago", "sessionAttributes":{ "currentReservation":"{\"ReservationType\":\"Hotel\", \"Location\":\"Moscow\", \"RoomType\":null, \"CheckInDate\":null, \"Nights\":null}" } }

• lastConfirmedReservation: contiene informazioni simili relative a un eventuale intento precedente. Ad esempio, se l'utente ha prenotato un hotel e poi sta prenotando un'auto, questo attributo di sessione memorizza i dati dello slot per il precedente BookHotel intento.

• confirmationContext: la funzione Lambda imposta questo attributo su AutoPopulate quando precompila alcuni dati dello slot in base ai dati dello slot di una prenotazione precedente (se disponibile). Ciò consente la condivisione delle informazioni tra più intenti. Ad esempio, se l'utente ha in precedenza prenotato un hotel e ora desidera prenotare un'automobile, Amazon Lex può richiedere di confermare (o rifiutare) che l'automobile venga prenotata per la stessa città e per le stesse date di prenotazione dell'hotel.

In questo esercizio si utilizzano piani per creare un bot Amazon Lex e una funzione Lambda. Per ulteriori informazioni sui piani, consulta Amazon Lex e piani AWS Lambda (p. 150).

Approfondimenti

Passaggio 1: Rivedi i progetti utilizzati in questo esercizio (p. 193) Passaggio 1: Rivedi i progetti utilizzati in questo esercizio

Argomenti • Panoramica del piano di bot (BookTrip) (p. 193) • Panoramica del piano della funzione Lambda (lex-book-trip-python) (p. 195)

Panoramica del piano di bot (BookTrip)

Il piano (BookTrip) utilizzato per creare un bot offre la seguente preconfigurazione:

• Tipi di slot – Due tipi di slot personalizzati: • RoomTypes con valori di enumerazione: king, queen, e deluxe, per l'uso nel BookHotel intento.

193 Amazon Lex Guida per gli sviluppatori Passaggio 1: Revisione del progetto

• CarTypes con valori di enumerazione: economy, standard, midsize, full size, luxury, e minivan, per l'uso nel BookCar intento.

• Intento 1 (BookHotel) – È preconfigurato come segue: • Slot preconfigurati • RoomType, del tipo di slot personalizzato RoomTypes • Location, del tipo di slot integrato AMAZON.US_CITY • CheckInDate, del tipo di slot integrato AMAZON.DATE • Nights, del tipo di slot integrato AMAZON.NUMBER • Enunciazioni preconfigurate • "Book a hotel" • "I want to make hotel reservations" • "Book a {Nights} stay in {Location}"

Se l'utente utilizza una di queste enunciazioni, Amazon Lex determina che BookHotel è l'intento, quindi richiede all'utente i dati dello slot. • Messaggi di richiesta preconfigurati • Messaggio di richiesta per lo slot Location: "What city will you be staying in?" • Messaggio di richiesta per lo slot CheckInDate: "What day do you want to check in?" • Messaggio di richiesta per lo slot Nights: "How many nights will you be staying?" • Messaggio di richiesta per lo slot RoomType: "What type of room would you like, queen, king, or deluxe?" • Affermazione di conferma: "Okay, I have you down for a {Nights} night stay in {Location} starting {CheckInDate}. Shall I book the reservation?" • Rifiuto: "Okay, I have cancelled your reservation in progress."

• Intento 2 (BookCar) – È preconfigurato come segue: • Slot preconfigurati • PickUpCity, del tipo integrato AMAZON.US_CITY • PickUpDate, del tipo integrato AMAZON.DATE • ReturnDate, del tipo integrato AMAZON.DATE • DriverAge, del tipo integrato AMAZON.NUMBER • CarType, del tipo personalizzato CarTypes • Enunciazioni preconfigurate • "Book a car" • "Reserve a car" • "Make a car reservation"

Se l'utente pronuncia una di queste domande, Amazon Lex determina BookCar è l'intento e quindi richiede all'utente i dati dello slot. • Messaggi di richiesta preconfigurati • Messaggio di richiesta per lo slot PickUpCity: "In what city do you need to rent a car?" • Messaggio di richiesta per lo slot PickUpDate: "What day do you want to start your rental?"" • Messaggio di richiesta per lo slot ReturnDate: "What day do you want to return this car?"

• Messaggio di richiesta per lo slot DriverAge194 : "How old is the driver for this rental?" • Messaggio di richiesta per lo slot CarType: "What type of car would you like to rent? Le nostre opzioni più richieste sono: economica, media e di lusso" Amazon Lex Guida per gli sviluppatori Passaggio 2: Creare un bot Amazon Lex

• Affermazione di conferma: "Okay, I have you down for a {CarType} rental in {PickUpCity} from {PickUpDate} to {ReturnDate}. Should I book the reservation?" • Rifiuto: "Okay, I have cancelled your reservation in progress."

Panoramica del piano della funzione Lambda (lex-book-trip- python)

Oltre al piano di bot, AWS Lambda fornisce un piano (lex-book-trip-python) che è possibile utilizzare come hook di codice con il piano di bot. Per un elenco dei piani di bot e dei corrispondenti piani delle funzioni Lambda, consulta Amazon Lex e piani AWS Lambda (p. 150).

Quando crei un bot utilizzando la BookTrip , si aggiorna la configurazione di entrambi gli intenti (BookCar e BookHotel) aggiungendo questo Lambda fungono da hook di codice sia per l'inizializzazione/convalida dell'input di dati utente che per l'adempimento degli intenti.

Il codice di funzione Lambda fornito mostra una conversazione dinamica che utilizza le informazioni precedentemente note (conservate negli attributi di sessione) relative a un utente per inizializzare i valori di slot per un intento. Per ulteriori informazioni, vedi Gestione del contesto di una conversazione (p. 20).

Approfondimenti

Passaggio 2: Creare un bot Amazon Lex (p. 195) Passaggio 2: Creare un bot Amazon Lex

In questa sezione creerai un bot Amazon Lex (BookTrip).

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Nella pagina Bots (Bot) scegli Create (Crea). 3. Nella pagina Create your Lex bot (Crea bot di Lex):

• Seleziona il piano BookTrip. • Lascia il nome di bot di default (BookTrip). 4. Scegliere Create (Crea). La console invia a Amazon Lex una serie di richieste per creare il bot. Tieni presente quanto segue: 5. La console mostra BookTrip bot di. Nella pagina Redattore rivedere i dettagli degli intenti preconfigurati (BookCar e BookHotel). 6. Esegui il test del bot nella finestra di prova. Utilizza quanto segue per iniziare una conversazione di test con il bot:

195 Amazon Lex Guida per gli sviluppatori Passaggio 2: Creare un bot Amazon Lex

Dall'input utente iniziale ("Book a hotel") Amazon Lex deduce l'intento (BookHotel). Il bot utilizza quindi i prompt preconfigurati nell'intento per ottenere i dati dello slot dall'utente. Dopo che l'utente ha fornito tutti i dati dello slot, Amazon Lex restituisce una risposta al client con un messaggio che include l'intero input utente come messaggio. Il client visualizza il messaggio nella risposta, come mostrato.

CheckInDate:2016-12-18 Location:Chicago Nights:5 RoomType:queen

Continua ora la conversazione e prova a prenotare un'automobile.

196 Amazon Lex Guida per gli sviluppatori Passaggio 2: Creare un bot Amazon Lex

Nota,

• Non è attiva alcuna convalida dei dati utente in questo momento. Puoi ad esempio specificare qualsiasi città per prenotare un hotel. • Alcune delle informazioni fornite per prenotare un'automobile corrispondono a quelle specificate in precedenza (destinazione, città di ritiro, data di ritiro e data di riconsegna). In una conversazione dinamica il bot deve inizializzare alcune di queste informazioni in base all'input utente precedente specificato per la prenotazione dell'hotel.

In questa sezione successiva creerai una funzione Lambda per eseguire alcune attività di convalida e inizializzazione dei dati utente, utilizzando la condivisione delle informazioni tra più intenti tramite gli attributi di sessione. Aggiornerai quindi la configurazione degli intenti aggiungendo la funzione Lambda come un hook di codice per eseguire l'inizializzazione/la convalida dell'input utente e realizzare l'intento.

Approfondimenti

197 Amazon Lex Guida per gli sviluppatori Passaggio 3: Creazione di una funzione Lambda

Passaggio 3: Creazione di una funzione Lambda (p. 198) Passaggio 3: Creazione di una funzione Lambda

In questa sezione creerai una funzione Lambda utilizzando un piano (lex-book-trip-python) fornito nella console AWS Lambda. Eseguirai inoltre il test della funzione Lambda dopo averla richiamata mediante dati di evento di esempio forniti dalla console.

Questa funzione Lambda è scritta in Python.

1. Accedi alla AWS Management Console e apri la console AWS Lambda all'indirizzo https:// console.aws.amazon.com/lambda/. 2. Seleziona Create function (Crea funzione). 3. Scegliere Use a blueprint (Usa un piano). Digitare lex per individuare il piano e scegliere il piano lex- book-trip-python. 4. Scegli Configura il Lambda funzionano come segue.

• Digita il nome della funzione Lambda (BookTripCodeHook). • Per il ruolo, scegli Create a new role from template(s) (Crea un nuovo ruolo da modello), quindi digita un nome di ruolo. • Non modificare gli altri valori predefiniti. 5. Seleziona Create function (Crea funzione). 6. Se si utilizza un'impostazione locale diversa da English (US) (en-US), aggiornare i nomi degli intenti come descritto in Aggiornamento di un piano per un'impostazione locale specifica (p. 150). 7. Esegui il test della funzione Lambda. Richiama la funzione Lambda due volte, utilizzando i dati di esempio sia per prenotare un'automobile sia per prenotare un hotel.

a. Scegliere Configura evento di test dal menu a discesa Seleziona un evento di test. b. Seleziona Amazon Lex-Book Hotel nell'elenco Modello evento di esempio.

Questo evento di esempio corrisponde al modello di richiesta/risposta di Amazon Lex. Per ulteriori informazioni, vedi Utilizzo delle funzioni Lambda (p. 140). c. Scegliere Save and test (Salva ed esegui test). d. Verificare che il Lambda La funzione è stata eseguita correttamente. La risposta in questo caso corrisponde al modello di risposta di Amazon Lex. e. Ripeti la fase. Questa volta scegli Amazon Lex-Book Car (Lex-Book Car nell'elenco Modello evento di esempio. La funzione Lambda elabora la prenotazione dell'automobile.

Approfondimenti

Passaggio 4: Aggiungi il Lambda Fungere da hook di codice (p. 198) Passaggio 4: Aggiungi il Lambda Fungere da hook di codice

In questa sezione, è possibile aggiornare le configurazioni di entrambi i BookCar e BookHotel aggiungendo il Lambda fungono da hook di codice per le attività di inizializzazione/convalida e di esecuzione. Assicurati di scegliere la versione $LATEST degli intenti perché è possibile aggiornare solo la versione $LATEST delle risorse di Amazon Lex.

198 Amazon Lex Guida per gli sviluppatori Passaggio 4: Aggiungi il Lambda Fungere da hook di codice

1. Nella console di Amazon Lex, scegli il bot BookTrip. 2. Nella scheda Editor scegli l'intento BookHotel. Aggiorna la configurazione dell'intento come segue:

a. Assicurati che la versione dell'intento (accanto al nome dell'intento) sia $LATEST. b. Aggiungi la funzione Lambda come un hook di codice di inizializzazione e di convalida, come segue:

• In Options (Opzioni) scegli Initialization and validation code hook (Hook di codice di inizializzazione e di convalida). • Seleziona la funzione Lambda nell'elenco. c. Aggiungi la funzione Lambda come hook di codice di soddisfazione, come segue:

• In Fulfillment (Soddisfazione) scegli AWS Lambda function (Funzione AWS Lambda). • Seleziona la funzione Lambda nell'elenco. • Seleziona Goodbye message (Messaggio di saluto). d. Seleziona Save (Salva). 3. Nella pagina Redattore , scegliere la scheda BookCar intento. Segui la fase precedente per aggiungere la funzione Lambda come hook di codice di convalida e soddisfazione.

4. Seleziona Build (Crea). La console invia una serie di richieste ad Amazon Lex per salvare le configurazioni. 5. Esegui il test del bot. Ora che disponi di una funzione Lambda per l'esecuzione delle attività di inizializzazione, convalida dati utente e soddisfazione, puoi vedere la differenza nell'interazione dell'utente.

199 Amazon Lex Guida per gli sviluppatori Passaggio 4: Aggiungi il Lambda Fungere da hook di codice

Per ulteriori informazioni sul flusso di dati dal client (console) ad Amazon Lex e da Amazon Lex alla funzione Lambda, consulta Flusso di dati: Prenotare l'intento dell'hotel (p. 202). 6. Continua la conversazione e prenota un'automobile, come mostrato di seguito:

200 Amazon Lex Guida per gli sviluppatori Passaggio 4: Aggiungi il Lambda Fungere da hook di codice

Quando scegli di prenotare un'auto, il client (console) invia una richiesta a Amazon Lex che include gli attributi di sessione (dalla conversazione precedente, BookHotel). Amazon Lex trasferisce queste informazioni al Lambda , che quindi inizializza (ovvero precompila) alcune delle BookCar dati di slot (ovvero, PickUpDate, ReturnDate, e PickUpCity). Note

Viene illustrato come possono essere utilizzati gli attributi di sessione per mantenere il contesto tra gli intenti. Nella finestra di test del client della console è disponibile il collegamento Clear (Cancella), che consente all'utente di cancellare gli attributi di sessione precedenti.

Per ulteriori informazioni sul flusso di dati dal client (console) ad Amazon Lex e da Amazon Lex alla funzione Lambda, consulta Flusso di dati: Prenotare l'intento dell'auto (p. 211).

201 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Dettagli del flusso di informazioni

In questo esercizio, hai intrapreso una conversazione con il Amazon Lex BookTrip utilizzando il client della finestra di test fornito nella Amazon Lex console di. Questa sezione descrive quanto segue:

• Flusso di dati tra il client e Amazon Lex.

La sezione presuppone che il client invii le richieste ad Amazon Lex utilizzando l'API di runtime PostText e mostra i dettagli di richiesta e risposta corrispondenti. Per ulteriori informazioni sull'API di runtime PostText, consulta PostText (p. 434). Note

Per un esempio di flusso di informazioni tra client e Amazon Lex in cui il client utilizza l'API PostContent, consulta Fase 2a (facoltativo): Revisione dei dettagli del flusso di informazioni parlate (console) (p. 75).

• Flusso di dati tra Amazon Lex e la funzione Lambda. Per ulteriori informazioni, vedi Formato di evento di input e di risposta della funzione Lambda (p. 140).

Argomenti • Flusso di dati: Prenotare l'intento dell'hotel (p. 202) • Flusso di dati: Prenotare l'intento dell'auto (p. 211)

Flusso di dati: Prenotare l'intento dell'hotel

Questa sezione spiega cosa accade dopo ogni input utente.

1. Utente: "book a hotel"

a. Il client (console) invia la seguente richiesta PostText (p. 434) ad Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"book a hotel", "sessionAttributes":{} }

L'URI e il corpo della richiesta forniscono informazioni ad Amazon Lex:

• URI della richiesta: fornisce il nome del bot (BookTrip), l'alias del bot ($LATEST) e il nome utente. Il codice text finale indica che si tratta di una richiesta API PostText (non PostContent). • Corpo della richiesta – Include l'input dell'utente (inputText) e vuoto sessionAttributes. Inizialmente, si tratta di un oggetto vuoto e Lambda La funzione imposta prima gli attributi di sessione.

b. A partire da inputText, Amazon Lex rileva l'intento (BookHotel), configurato con una funzione Lambda come hook di codice per l'inizializzazione/la convalida dei dati utente. Amazon Lex invoca

202 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

quindi tale funzione Lambda passando le informazioni seguenti come parametro di evento (vedi Formato dell'evento di input (p. 140)):

{ "messageVersion":"1.0", "invocationSource":"DialogCodeHook", "userId":"wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes":{ }, "bot":{ "name":"BookTrip", "alias":null, "version":"$LATEST" }, "outputDialogMode":"Text", "currentIntent":{ "name":"BookHotel", "slots":{ "RoomType":null, "CheckInDate":null, "Nights":null, "Location":null }, "confirmationStatus":"None" } }

Oltre alle informazioni inviate dal client, Amazon Lex include anche i dati aggiuntivi seguenti:

• messageVersion: Amazon Lex supporta attualmente solo la versione 1.0. • invocationSource: indica lo scopo della chiamata della funzione Lambda. In questo caso, consente di eseguire l'inizializzazione e la convalida dei dati utente (in questo momento Amazon Lex sa che l'utente non ha ancora fornito tutti i dati dello slot per realizzare l'intento). • currentIntent: tutti i valori di slot sono impostati su null. c. Al momento, tutti i valori dello slot sono nulli. Non c'è alcunché da convalidare per la funzione Lambda. La funzione Lambda restituisce la risposta seguente ad Amazon Lex. Per informazioni sul formato della risposta, consulta Formato della risposta (p. 145).

{ "sessionAttributes":{ "currentReservation":"{\"ReservationType\":\"Hotel\",\"Location\":null, \"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}" }, "dialogAction":{ "type":"Delegate", "slots":{ "RoomType":null, "CheckInDate":null, "Nights":null, "Location":null } } }

Note

• currentReservation: la funzione Lambda include questo attributo di sessione. Il relativo valore è una copia delle informazioni sullo slot e del tipo di prenotazione correnti.

203 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Questi attributi di sessione possono essere aggiornati solo dal client e dalla funzione Lambda semplicemente passando i valori. • dialogAction.type: impostando questo valore su Delegate, la funzione Lambda delega a Amazon Lex la responsabilità dell'operazione successiva.

Se la funzione Lambda rileva qualcosa nella convalida dei dati utente, indica a Amazon Lex come procedere. d. In base a dialogAction.type, Amazon Lex decide la successiva operazione da eseguire: ottenere dati dall'utente per lo slot Location. Seleziona uno dei messaggi di richiesta ("What city will you be staying in?") per questo slot in base alla configurazione dell'intento, quindi invia la seguente risposta all'utente:

Gli attributi di sessione vengono passati al client.

Il client legge la risposta e quindi visualizza il messaggio: "In quale città soggiornerai?" 2. Utente: "Mosca"

a. Il client invia la seguente richiesta PostText a Amazon Lex (interruzioni di riga aggiunte per facilitare la lettura):

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"Moscow", "sessionAttributes":{ "currentReservation":"{\"ReservationType\":\"Hotel\", \"Location\":null, \"RoomType\":null, \"CheckInDate\":null, \"Nights\":null}" } }

Oltre a inputText, il client include gli stessi attributi di sessione currentReservation ricevuti. b. Amazon Lex innanzitutto interpreta inputText nel contesto dell'intento corrente (il servizio ricorda di avere richiesto all'utente specifico le informazioni sullo slot Location) e aggiorna

204 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

il valore dello slot per l'intento corrente, quindi invoca la funzione Lambda tramite il seguente evento:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":null, \"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}" }, "bot": { "name": "BookTrip", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "BookHotel", "slots": { "RoomType": null, "CheckInDate": null, "Nights": null, "Location": "Moscow" }, "confirmationStatus": "None" } }

Note

• invocationSource continua a essere DialogCodeHook. In questa fase, stiamo solo convalidando i dati utente. • Amazon Lex passa solo l'attributo di sessione alla funzione Lambda. • Per currentIntent.slots, Amazon Lex ha aggiornato lo slot Location in Moscow. c. La funzione Lambda esegue la convalida dei dati dell'utente e determina che Moscow è una località non valida. Note

La funzione Lambda in questo esercizio è un semplice elenco di città valide e Moscow non è presente nell'elenco. In un'applicazione di produzione, è possibile utilizzare un database di back-end per ottenere queste informazioni.

Reimposta il valore di slot su null e indica a Amazon Lex di richiedere un altro valore all'utente, inviando la seguente risposta:

{ "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":\"Moscow \",\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}" }, "dialogAction": { "type": "ElicitSlot", "intentName": "BookHotel", "slots": { "RoomType": null, "CheckInDate": null, "Nights": null, "Location": null 205 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

}, "slotToElicit": "Location", "message": { "contentType": "PlainText", "content": "We currently do not support Moscow as a valid destination. Can you try a different city?" } } }

Note

• currentIntent.slots.Location viene reimpostato su null. • dialogAction.type è impostato su ElicitSlot, che indica a Amazon Lex di richiedere quanto segue all'utente: • dialogAction.slotToElicit: slot per il quale ottenere i dati dall'utente. • dialogAction.message: un message da trasmettere all'utente. d. Amazon Lex rileva dialogAction.type e passa le informazioni al client nella seguente risposta:

Il client visualizza semplicemente il messaggio: "Attualmente non supportiamo Mosca come destinazione valida. Can you try a different city?" 3. Utente: "Chicago"

a. Il client invia la seguente richiesta PostText a Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"Chicago", "sessionAttributes":{ "currentReservation":"{\"ReservationType\":\"Hotel\", \"Location\":\"Moscow\", \"RoomType\":null, \"CheckInDate\":null, \"Nights\":null}" } }

206 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni b. Amazon Lex riconosce il contesto, ossia che stava richiedendo i dati dello slot Location. In questo contesto, sa che il valore inputText è per lo slot Location. Invoca quindi la funzione Lambda inviando l'evento seguente:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\":Moscow, \"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}" }, "bot": { "name": "BookTrip", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "BookHotel", "slots": { "RoomType": null, "CheckInDate": null, "Nights": null, "Location": "Chicago" }, "confirmationStatus": "None" } }

Amazon Lex ha aggiornato currentIntent.slots impostando lo slot Location su Chicago. c. Secondo il valore invocationSource di DialogCodeHook, la funzione Lambda esegue la convalida dei dati utente e riconosce Chicago come valore di slot valido, aggiorna l'attributo di sessione in modo appropriato, quindi restituisce la seguente risposta ad Amazon Lex.

{ "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\": \"Chicago\",\"RoomType\":null,\"CheckInDate\":null,\"Nights\":null}" }, "dialogAction": { "type": "Delegate", "slots": { "RoomType": null, "CheckInDate": null, "Nights": null, "Location": "Chicago" } } }

Note

• currentReservation: la funzione Lambda aggiorna questo attributo di sessione impostando Location su Chicago. • dialogAction.type – È impostato su Delegate. I dati utente erano validi e il Lambda funzione dirige Amazon Lex per scegliere la successiva azione.

207 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

d. In base a dialogAction.type, Amazon Lex sceglie la successiva operazione da eseguire. Amazon Lex sa di avere bisogno di ulteriori dati dello slot, quindi si avvale del successivo slot non popolato (CheckInDate) con la più alta priorità secondo la configurazione dell'intento. Seleziona uno dei messaggi di richiesta ("What day do you want to check in?") per questo slot in base alla configurazione dell'intento, quindi invia la seguente risposta al client:

Il client visualizza il messaggio: "In che giorno vuoi effettuare il check-in?"

4. L'interazione utente prosegue: l'utente fornisce i dati, la funzione Lambda convalida i dati, quindi delega ad Amazon Lex la successiva operazione da eseguire. Alla fine l'utente fornisce tutti i dati dello slot, la funzione Lambda convalida tutto l'input utente, quindi Amazon Lex riconosce di avere tutti i dati dello slot. Note

In questo esercizio, dopo che l'utente fornisce tutti i dati dello slot, la funzione Lambda calcola il prezzo della prenotazione dell'hotel e lo restituisce sotto forma di un altro attributo di sessione (currentReservationPrice).

A questo punto, l'intento è pronto per essere realizzato, ma il BookHotel è configurato con un prompt di conferma che richiede la conferma dell'utente prima Amazon Lex è in grado di soddisfare l'intento. Amazon Lex invia pertanto il seguente messaggio al client per richiedere una conferma prima di prenotare l'hotel:

208 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Il client visualizza il messaggio: “Ok, ti ho fatto perdere una notte a Chicago a partire dal 2016-12-18. Shall I book the reservation?" 5. Utente: "yes"

a. Il client invia la seguente richiesta PostText a Amazon Lex:

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"Yes", "sessionAttributes":{ "currentReservation":"{\"ReservationType\":\"Hotel\", \"Location\":\"Chicago\", \"RoomType\":\"queen\", \"CheckInDate\":\"2016-12-18\", \"Nights\":\"5\"}", "currentReservationPrice":"1195" } }

b. Amazon Lex interpreta inputText nel contesto della conferma dell'intento corrente e comprende che l'utente desidera procedere con la prenotazione. Questa volta Amazon Lex invoca la funzione Lambda per realizzare l'intento inviando il seguente evento. Impostando invocationSource su FulfillmentCodeHook nell'evento, esegue l'invio alla funzione Lambda. Amazon Lex imposta inoltre confirmationStatus su Confirmed.

{ "messageVersion": "1.0", "invocationSource": "FulfillmentCodeHook", "userId": "wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Hotel\",\"Location\": \"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}", "currentReservationPrice": "956" }, "bot": { "name": "BookTrip", "alias": null, "version": "$LATEST"

209 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

}, "outputDialogMode": "Text", "currentIntent": { "name": "BookHotel", "slots": { "RoomType": "queen", "CheckInDate": "2016-12-18", "Nights": "5", "Location": "Chicago" }, "confirmationStatus": "Confirmed" } }

Note

• invocationSource: questa volta Amazon Lex imposta questo valore su FulfillmentCodeHook, indicando alla funzione Lambda di realizzare l'intento. • confirmationStatus – È impostato su Confirmed. c. Questa volta, il Lambda funzione soddisfa il BookHotel intento, Amazon Lex completa la prenotazione, quindi restituisce la seguente risposta:

{ "sessionAttributes": { "lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location \":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}" }, "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": "Thanks, I have placed your reservation. Please let me know if you would like to book a car rental, or another hotel." } } }

Note

• lastConfirmedReservation: è un nuovo attributo di sessione aggiunto dalla funzione Lambda (anziché currentReservation, currentReservationPrice). • dialogAction.type: la funzione Lambda imposta questo valore su Close, indicando a Amazon Lex di non attendere alcuna risposta da parte dell'utente. • dialogAction.fulfillmentState: è impostato su Fulfilled e include un elemento message appropriato da trasmettere all'utente.

d. Amazon Lex esamina fulfillmentState e invia la seguente risposta al client:

210 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Note

• dialogState: Amazon Lex imposta questo valore su Fulfilled. • message: è lo stesso messaggio che ha fornito la funzione Lambda.

Il client visualizza il messaggio.

Flusso di dati: Prenotare l'intento dell'auto

Il BookTrip in questo esercizio supporta due intenti (BookHotel e BookCar). Dopo aver prenotato un hotel, l'utente può continuare la conversazione per prenotare un'automobile. Purché non si sia verificato il timeout della sessione, in ogni richiesta successiva il client continua a inviare gli attributi di sessione (in questo esempio, lastConfirmedReservation). Il Lambda può utilizzare queste informazioni per inizializzare i dati dello slot per BookCar intento. Ciò illustra come utilizzare gli attributi di sessione nella condivisione dei dati tra più intenti.

In particolare, quando l'utente sceglie BookCar intento, il Lambda La funzione utilizza le informazioni rilevanti nell'attributo di sessione per precompilare gli slot (PickUpDate, ReturnDate, e PickUpCity) per il BookCar intento. Note

Nella console di Amazon Lex è disponibile il collegamento Clear (Cancella), che consente di cancellare gli attributi di sessione precedenti.

Seguire le fasi di questa procedura per continuare la conversazione.

1. Utente: "also book a car"

a. Il client invia la seguente richiesta PostText a Amazon Lex.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"also book a car", "sessionAttributes":{ "lastConfirmedReservation":""{\"ReservationType\":\"Hotel\", \"Location\":\"Chicago\", \"RoomType\":\"queen\",

211 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

\"CheckInDate\":\"2016-12-18\", \"Nights\":\"5\"}" } }

Il client include l'attributo di sessione lastConfirmedReservation. b. Amazon Lex rileva l'intento (BookCar) dal inputText. Questo intento è configurato anche per richiamare Lambda per eseguire l'inizializzazione e la convalida dei dati utente. Amazon Lex richiama il Lambda con il seguente evento:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes": { "lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location \":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}" }, "bot": { "name": "BookTrip", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "BookCar", "slots": { "PickUpDate": null, "ReturnDate": null, "DriverAge": null, "CarType": null, "PickUpCity": null }, "confirmationStatus": "None" } }

Note

• messageVersion: Amazon Lex supporta attualmente solo la versione 1.0. • invocationSource: indica che lo scopo dell'invocazione è quello di eseguire l'inizializzazione e la convalida dei dati utente. • currentIntent: include il nome dell'intento e gli slot. A questo punto, tutti i valori di slot sono null. c. La funzione Lambda rileva tutti i valori di slot null, senza dati da convalidare. Utilizza tuttavia gli attributi di sessione per inizializzare alcuni valori di slot (PickUpDateReturnDate e PickUpCity) e restituisce la seguente risposta:

{ "sessionAttributes": { "lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location \":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}", "currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\":null, \"PickUpDate\":null,\"ReturnDate\":null,\"CarType\":null}", "confirmationContext": "AutoPopulate" },

212 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

"dialogAction": { "type": "ConfirmIntent", "intentName": "BookCar", "slots": { "PickUpCity": "Chicago", "PickUpDate": "2016-12-18", "ReturnDate": "2016-12-22", "CarType": null, "DriverAge": null }, "message": { "contentType": "PlainText", "content": "Is this car rental for your 5 night stay in Chicago on 2016-12-18?" } } }

Note

• Oltre a lastConfirmedReservation, la funzione Lambda include più attributi di sessione (currentReservation e confirmationContext). • dialogAction.type è impostato su ConfirmIntent, che informa Amazon Lex che si prevede che l'utente non risponda (il confirmationContext impostato su AutoPopulate, la funzione Lambda sa che la risposta dell'utente sì/no è per ottenere la conferma dell'utente dell'inizializzazione Lambda funzione eseguita (dati dello slot popolati automaticamente).

La funzione Lambda include nella risposta anche un messaggio informativo in dialogAction.message che Amazon Lex deve restituire al client. Note

Il termine ConfirmIntent (valore di dialogAction.type) non è correlato ad alcun intento di bot. Nell'esempio la funzione Lambda utilizza questo termine per indicare a Amazon Lex di ottenere dall'utente una risposta affermativa/negativa. d. In base a dialogAction.type, Amazon Lex restituisce la seguente risposta al client:

213 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Il client visualizza il messaggio: “Questa auto a noleggio è per il tuo soggiorno di 5 notti a Chicago il 2016-12-18?” 2. Utente: "yes"

a. Il client invia la seguente richiesta PostText a Amazon Lex.

POST /bot/BookTrip/alias/$LATEST/user/wch89kjqcpkds8seny7dly5x3otq68j3/text "Content-Type":"application/json" "Content-Encoding":"amz-1.0"

{ "inputText":"yes", "sessionAttributes":{ "confirmationContext":"AutoPopulate", "currentReservation":"{\"ReservationType\":\"Car\", \"PickUpCity\":null, \"PickUpDate\":null, \"ReturnDate\":null, \"CarType\":null}", "lastConfirmedReservation":"{\"ReservationType\":\"Hotel\", \"Location\":\"Chicago\", \"RoomType\":\"queen\", \"CheckInDate\":\"2016-12-18\", \"Nights\":\"5\"}" } }

b. Amazon Lex legge inputText e viene a conoscenza del contesto (ha richiesto all'utente di confermare la compilazione automatica). Amazon Lex invoca quindi la funzione Lambda inviando l'evento seguente:

{ "messageVersion": "1.0", "invocationSource": "DialogCodeHook", "userId": "wch89kjqcpkds8seny7dly5x3otq68j3", "sessionAttributes": { "confirmationContext": "AutoPopulate", "currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\":null, \"PickUpDate\":null,\"ReturnDate\":null,\"CarType\":null}", "lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location \":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}" }, "bot": { "name": "BookTrip", "alias": null, "version": "$LATEST" }, "outputDialogMode": "Text", "currentIntent": { "name": "BookCar", "slots": { "PickUpDate": "2016-12-18", "ReturnDate": "2016-12-22", "DriverAge": null, "CarType": null, "PickUpCity": "Chicago" }, "confirmationStatus": "Confirmed" } }

214 Amazon Lex Guida per gli sviluppatori Dettagli del flusso di informazioni

Poiché l'utente ha risposto in modo affermativo, Amazon Lex imposta confirmationStatus su Confirmed. c. confirmationStatus indica alla funzione Lambda che i valori precompilati sono corretti. La funzione Lambda svolge le operazioni seguenti:

• Aggiorna l'attributo di sessione currentReservation con il valore di slot precompilato. • Imposta il dialogAction.type a ElicitSlot • Imposta il valore slotToElicit su DriverAge.

Viene inviata la seguente risposta:

{ "sessionAttributes": { "currentReservation": "{\"ReservationType\":\"Car\",\"PickUpCity\": \"Chicago\",\"PickUpDate\":\"2016-12-18\",\"ReturnDate\":\"2016-12-22\",\"CarType \":null}", "lastConfirmedReservation": "{\"ReservationType\":\"Hotel\",\"Location \":\"Chicago\",\"RoomType\":\"queen\",\"CheckInDate\":\"2016-12-18\",\"Nights\": \"5\"}" }, "dialogAction": { "type": "ElicitSlot", "intentName": "BookCar", "slots": { "PickUpDate": "2016-12-18", "ReturnDate": "2016-12-22", "DriverAge": null, "CarType": null, "PickUpCity": "Chicago" }, "slotToElicit": "DriverAge", "message": { "contentType": "PlainText", "content": "How old is the driver of this car rental?" } } } d. Amazon Lex restituisce la risposta seguente:

215 Amazon Lex Guida per gli sviluppatori Esempio: Utilizzo di una scheda di risposta

Il cliente visualizza il messaggio "Quanto tempo ha il conducente di questo autonoleggio?" e la conversazione continua.

Utilizzo di una scheda di risposta

Questo esercizio è un'estensione dell'esercizio 1 delle Nozioni di base e comporta l'aggiunta di una scheda di risposta. Puoi creare un bot che supporti OrderFlowers , quindi aggiornare l'intento aggiungendo una scheda di risposta per FlowerType alloggiamento. In aggiunta al seguente prompt per lo slot FlowerType, l'utente potrà scegliere il tipo di fiori dalla scheda di risposta:

What type of flowers would you like to order?

La scheda di risposta è la seguente:

216 Amazon Lex Guida per gli sviluppatori Esempio: Utilizzo di una scheda di risposta

L'utente bot può digitare il testo o effettuare una scelta dall'elenco dei tipi di fiori. La scheda di risposta è configurata con un'immagine, che appare nel client come mostrato. Per ulteriori informazioni sulle schede di risposta, consultare Schede di risposta (p. 16).

Per creare ed eseguire il test di un bot con una scheda di risposta:

1. Seguire l'Esercizio 1 sulle nozioni di base per creare e testare un OrderFlowers bot di. È necessario completare le fasi 1, 2 e 3. Per eseguire il test della scheda di risposta, non è necessario aggiungere una funzione Lambda. Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Aggiorna il bot aggiungendo la scheda di risposta, quindi pubblica una versione. Quando pubblichi una versione, specifica un alias (BETA) a cui puntare.

a. Seleziona il bot nella console di Amazon Lex. b. Seleziona l'intento OrderFlowers. c. Seleziona l'icona a forma di ingranaggio delle impostazioni accanto al Prompt "What type of flowers" per configurare una scheda di risposta per FlowerType.

217 Amazon Lex Guida per gli sviluppatori Esempio: Utilizzo di una scheda di risposta

d. Assegna un titolo alla scheda e configura tre pulsanti come mostrato nella schermata che segue. Facoltativamente, puoi anche aggiungere alla scheda di risposta un'immagine, purché tu disponga di un URL dell'immagine. Se stai distribuendo il bot tramite Twilio SMS, devi fornire un URL immagine.

218 Amazon Lex Guida per gli sviluppatori Esempio: Utilizzo di una scheda di risposta

e. Seleziona Save (Salva) per salvare la scheda di risposta. f. Seleziona Save intent (Salva intento) per salvare la configurazione dell'intento. g. Per creare il bot, seleziona Build (Crea). h. Per pubblicare una versione di bot, seleziona Publish (Pubblica). Specifica BETA come un alias che punta alla versione del bot. Per informazioni sulla funzione Versioni multiple, consultare Funzione Versioni multiple e alias (p. 136). 3. Distribuisci il bot su una piattaforma di messaggistica:

• Distribuisci il bot sulla piattaforma Facebook Messenger ed esegui il test dell'integrazione. Per istruzioni, consulta Integrating an Amazon Lex Bot with Facebook Messenger (p. 153). Quando l'utente ordina dei fiori, la finestra dei messaggi mostra la scheda di risposta che consente di scegliere un tipo di fiore. • Distribuisci il bot sulla piattaforma Slack ed esegui il test dell'integrazione. Per istruzioni, consulta Integrating an Amazon Lex Bot with Slack (p. 158). Quando l'utente ordina dei fiori, la finestra dei messaggi mostra la scheda di risposta che consente di scegliere un tipo di fiore. • Distribuisci il bot sulla piattaforma Twilio SMS: Per istruzioni, consulta Integrating an Amazon Lex Bot with Twilio Programmable SMS (p. 162). Quando l'utente ordina dei fiori, il messaggio di Twilio mostra l'immagine dalla scheda di risposta. Twilio SMS non supporta i pulsanti nella risposta.

219 Amazon Lex Guida per gli sviluppatori Aggiornamento delle enunciazioni

Aggiornamento delle enunciazioni

In questo esercizio, aggiungerai ulteriori enunciazioni a quelle create nell'esercizio 1 delle Nozioni di base. Puoi utilizzare la scheda Monitoring (Monitoraggio) nella console di Amazon Lex per visualizzare le enunciazioni che il tuo bot non ha riconosciuto. Per migliorare l'esperienza dei tuoi utenti, puoi aggiungere tali enunciazioni al bot. Note

Una volta al giorno vengono create le statistiche delle enunciazioni. Puoi visualizzare l'enunciazione che non è stata riconosciuta, quante volte è stata ascoltata e l'ultimo giorno e l'ora in cui è stata ascoltata. Potrebbero essere necessarie fino a 24 ore prima che le enunciazioni mancanti vengano visualizzate nella console.

È possibile visualizzare le espressioni per diverse versioni del tuo bot. Per modificare la versione del bot di cui visualizzi le espressioni, scegliere una versione diversa dall'elenco a discesa accanto al nome del bot.

Per visualizzare e aggiungere le enunciazioni mancanti a un bot:

1. Segui il primo passaggio dell'esercizio 1 nelle Nozioni di base per creare e testare un bot OrderFlowers. Per istruzioni, consulta Esercizio 1: Creazione di un bot di Amazon Lex utilizzando un piano (console) (p. 72). 2. Esegui il test del bot digitando le seguenti enunciazioni nella finestra Test Bot (Esegui test del bot). Digita ogni enunciazione più volte. Il bot di esempio non riconosce le seguenti enunciazioni:

• Ordina dei fiori • Prendimi dei fiori • Per favore, ordina dei fiori • Prendimi qualche fiore 3. Attendi che Amazon Lex raccolga i dati relativi all'utilizzo delle enunciazioni mancanti. I dati sulle enunciazioni vengono generati una volta al giorno, solitamente di notte. 4. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 5. Seleziona il bot OrderFlowers. 6. Seleziona la scheda Monitoring (Monitoraggio), quindi Utterances (Enunciazioni) nel menu a sinistra, infine scegli il pulsante Missed (Mancanti). Il riquadro mostra un massimo di 100 enunciazioni mancanti.

220 Amazon Lex Guida per gli sviluppatori Integrazione con un sito Web

7. Per scegliere le enunciazioni mancanti che vuoi aggiungere al bot, seleziona la casella di controllo accanto ad esse. Per aggiungere l'enunciazione alla versione $LATEST dell'intento, scegli la freccia verso il basso accanto all'elenco a discesa Add utterance to intent (Aggiungi enunciazione a intento), quindi scegli l'intento. 8. Per ricreare il tuo bot, scegli Build (Crea), quindi nuovamente Build (Crea). 9. Per verificare se il tuo bot riconosce le nuove enunciazioni, usa il riquadro Test Bot (Esegui test del bot).

Integrazione con un sito Web

In questo esempio si integra un bot in un sito Web utilizzando testo e voce. Si utilizza JavaScript e AWS per creare un'esperienza interattiva per i visitatori del sito Web. È possibile scegliere tra questi esempi documentati nel Blog AWS sull'intelligenza artificiale:

• Distribuisci un'interfaccia Web per il tuo Chatbot: mostra un'interfaccia utente Web completa che offre un client Web per i chatbot Amazon Lex. È possibile utilizzare questi esempi per apprendere informazioni sui client Web o per usarli come elementi di base nelle tue applicazioni.

• "Buongiorno, visitatore!"—Coinvolgi gli utenti Web con Amazon Lex—Dimostra di utilizzare Amazon Lex, l'SDK AWS per JavaScript nel Browser, e Amazon Cognito per creare un'esperienza di conversazione sul sito Web.

• Acquisizione di input vocali in un browser e invio a Amazon Lex—Illustra l'integrazione di un chatbot basato su voce in un sito Web utilizzando l'SDK per JavaScript nel browser. L'applicazione registra l'audio, lo invia a Amazon Lex e riproduce la risposta.

Assistente agente del call center

In questo tutorial, utilizzerai Amazon Lex con Amazon Kendra per creare un bot di assistenza agente che assista gli agenti dell'assistenza clienti e pubblicarlo come applicazione Web. Amazon Kendra è un servizio

221 Amazon Lex Guida per gli sviluppatori Assistente agente del call center di ricerca aziendale che utilizza il machine learning per cercare tra i documenti e trovare risposte. Per ulteriori informazioni su Amazon Kendra, vedere il Amazon Kendra Guida per gli sviluppatori.

Amazon Lex I bot sono ampiamente utilizzati nei call center come primo punto di contatto per i clienti. Un bot è spesso in grado di risolvere le domande dei clienti. Quando un bot non è in grado di rispondere a una domanda, trasferisce la conversazione a un dipendente dell'assistenza clienti.

In questo tutorial, creeremo un Amazon Lex che gli agenti utilizzano per rispondere alle richieste dei clienti in tempo reale. Leggendo le risposte fornite dal bot, l'agente non può cercare manualmente le risposte.

Il bot e l'applicazione Web creati in questo tutorial aiutano gli agenti a rispondere ai clienti in modo efficiente e accurato fornendo rapidamente le risorse giuste. Il diagramma seguente mostra il funzionamento dell'applicazione Web.

Come mostra il diagramma, il Amazon Kendra di documenti è archiviato in un Amazon Simple Storage Service (Amazon S3). Se non disponi già di un bucket S3, puoi configurarne uno al momento della creazione del Amazon Kendra indice. Oltre a Amazon S3, utilizzerai Amazon Cognito per questo tutorial. Amazon Cognito gestisce le autorizzazioni per distribuire il bot come applicazione Web.

In questo tutorial, si crea un Amazon Kendra che fornisce risposte alle domande del cliente, crea il bot e aggiunge intenti che gli consentono di suggerire risposte basate sulla conversazione con il cliente, imposta Amazon Cognito per gestire le autorizzazioni di accesso e distribuire il bot come applicazione Web.

Tempo previsto: 75 minuti

Costo stimato: 2,50 USD all'ora per un Amazon Kendra e 0,75 USD per 1000 Amazon Lex richiede. Il tuo Amazon Kendra L'indice continua a essere eseguito al termine di questo esercizio. Assicurati di eliminarlo per evitare costi non necessari.

Nota: Assicurati di scegliere la stessa regione AWS per tutti i servizi utilizzati in questo tutorial.

Argomenti • Passaggio 1: Creazione di un Amazon Kendra Indice (p. 223) • Passaggio 2: Creare un bot Amazon Lex (p. 223) • Passaggio 3: Aggiungi un intento personalizzato e integrato (p. 224) • Passaggio 4: Configurazione di Amazon Cognito (p. 225)

222 Amazon Lex Guida per gli sviluppatori Passaggio 1: Creazione di un Amazon Kendra Indice

• Passaggio 5: Distribuisci il tuo bot come applicazione Web (p. 226) • Passaggio 6: Usa il bot (p. 226)

Passaggio 1: Creazione di un Amazon Kendra Indice

Iniziare creando un Amazon Kendra indice dei documenti che rispondono alle domande dei clienti. Un indice fornisce un'API di ricerca per le query del client. Puoi creare l'indice dai documenti di origine. Amazon Kendra restituisce le risposte che trova nei documenti indicizzati al bot, che le visualizza all'agente.

La qualità e l’accuratezza delle risposte suggerite da Amazon Kendra dipende dai documenti che indicizzi. I documenti devono includere file a cui l'agente accede frequentemente e che devono essere archiviati in un bucket S3. È possibile indicizzare i dati non strutturati e semistrutturati in formato.html, Microsoft Office (.doc,.ppt), PDF e testo.

Per creare un Amazon Kendra indice, vedere Nozioni di base su un bucket S3 (console) nella Amazon Kendra Guida per gli sviluppatori.

Per aggiungere domande e risposte (FAQ) che aiutino a rispondere alle domande dei clienti, vedere Aggiunta di domande e risposte nella Amazon Kendra Guida per gli sviluppatori. Per questo tutorial, utilizza la File ML_FAQ.csv su GitHub. Approfondimenti

Passaggio 2: Creare un bot Amazon Lex (p. 223) Passaggio 2: Creare un bot Amazon Lex

Amazon Lex fornisce un'interfaccia tra l'agente del call center e Amazon Kendra indice. Tiene traccia della conversazione tra l'agente e il cliente e chiama il AMAZON.KendraSearchIntent basato sulle domande che il cliente pone. Un intento è un'operazione che l'utente desidera eseguire.

Amazon Kendra cerca i documenti indicizzati e restituisce una risposta a Amazon Lex che viene visualizzato nel bot. Questa risposta è visibile solo all'agente.

Per creare un bot assistente agente

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Nel riquadro di navigazione, scegliere Bot. 3. Scegliere Create (Crea). 4. Scegli Bot personalizzato e configurare il bot.

a. Nome bot – Inserisci un nome che indichi lo scopo del bot, ad esempio AgentAssistBot. b. Voce di output: scegliere Nessuna. c. Timeout della sessione: immettere 5. d. COPPA: scegliere No. 5. Scegliere Create (Crea). Dopo aver creato il bot, Amazon Lex visualizza la scheda dell'editor del bot.

Approfondimenti

Passaggio 3: Aggiungi un intento personalizzato e integrato (p. 224)

223 Amazon Lex Guida per gli sviluppatori Passaggio 3: Aggiungi un intento personalizzato e integrato

Passaggio 3: Aggiungi un intento personalizzato e integrato

Un intento rappresenta un'operazione che l'agente del call center desidera che il bot esegua. In questo caso, l'agente desidera che il bot suggerisca risposte e risorse utili in base alla conversazione dell'agente con il cliente.

Amazon Lex ha due tipi di intenti: intenti personalizzati e intenti integrati. AMAZON.KendraSearchIntent è un intento integrato. Il bot utilizza la AMAZON.KendraSearchIntent per eseguire query sull'indice e visualizzare le risposte suggerite da Amazon Kendra.

Il bot in questo esempio non richiede un intento personalizzato. Tuttavia, per creare il bot, è necessario creare almeno un intento personalizzato con almeno un esempio di enunciazione. Questo intento è necessario solo per creare il bot assistente agente. Non esegue nessun'altra funzione. L'enunciazione per l'intento non deve rispondere ad alcuna delle domande che il cliente potrebbe porre. In questo modo si garantisce che il AMAZON.KendraSearchIntent viene chiamato per rispondere alle richieste dei clienti. Per ulteriori informazioni, vedi AMAZON.KendraSearchIntent (p. 47).

Per creare l'intento personalizzato richiesto

1. Nella pagina Nozioni di base sul bot scegli Crea intento. 2. Per Aggiungi intento, scegli Crea intento. 3. Nella finestra Crea intento immettere un nome descrittivo per l'intento, ad esempio RequiredIntent. 4. Per Espressioni di esempio, immettere un'enunciazione descrittiva, ad esempio Required utterance. 5. Scegliere Salva intento.

Per aggiungere il messaggio di intento e di risposta AMAZON.KendraSearchIntent

1. Nel riquadro di navigazione, scegliere il segno più (+) accanto a Intenzioni. 2. Scegli Cerca intenti esistenti. 3. Nella finestra Intenzioni di ricerca inserisci AMAZON.KendraSearchIntent, quindi sceglierlo dall'elenco. 4. Assegnare all'intento un nome descrittivo, ad esempio AgentAssistSearchIntent, quindi scegliere Aggiungi. 5. Nell'editor di intenti, scegliere Amazon Kendra query per aprire le opzioni di query. 6. Scegliere l'indice che si desidera cercare, 7. Nella finestra Risposta aggiungi i seguenti tre messaggi a un gruppo di messaggi.

I found an answer for the customer query: ((x-amz-lex:kendra-search-response- question_answer-question-1)) and the answer is ((x-amz-lex:kendra-search-response- question_answer-answer-1)). I found an excerpt from a helpful document: ((x-amz-lex:kendra-search-response- document-1)). I think this answer will help the customer: ((x-amz-lex:kendra-search-response- answer-1)).

8. Scegliere Salva intento. 9. Scegli Costruisci per creare il bot.

Approfondimenti

Passaggio 4: Configurazione di Amazon Cognito (p. 225)

224 Amazon Lex Guida per gli sviluppatori Passaggio 4: Configurazione di Amazon Cognito

Passaggio 4: Configurazione di Amazon Cognito

Per gestire le autorizzazioni e gli utenti per l'applicazione Web, è necessario configurare Amazon Cognito. Amazon Cognito garantisce che l'applicazione Web sia sicura e abbia il controllo degli accessi. Amazon Cognito utilizza i pool di identità per fornire AWS credenziali che concedono agli utenti l'accesso ad altri AWS servizi. Per questo tutorial, fornisce l'accesso a Amazon Lex.

Quando si crea un pool di identità, Amazon Cognito ti fornisce AWS Identity and Access Management (IAM) per gli utenti autenticati e non autenticati. Si modifica il IAM ruoli aggiungendo policy che concedono l'accesso a Amazon Lex.

Per impostare Amazon Cognito

1. Accedi alla AWS Management Console e aprire il Amazon Cognito console all'indirizzo https:// console.aws.amazon.com/cognito/. 2. Scegliere Manage Identity Pools (Gestisci pool di identità). 3. Scegliere Create new identity pool (Crea un nuovo pool di identità). 4. Configurare il pool di identità.

a. Nome pool di identità – Immettere un nome che indichi lo scopo del pool, ad esempio BotPool. b. Nella finestra Identità non autenticate scegliere Abilitare l'accesso a identità non autenticate. 5. Selezionare Create Pool (Crea pool). 6. Nella pagina Identificare il IAM Ruoli da utilizzare con il nuovo pool di identità , scegliere Visualizza dettagli. 7. Registrare il IAM Nomi dei ruoli. Verranno modificati in seguito. 8. Scegliere Allow (Permetti). 9. Nella pagina Nozioni di base su Amazon Cognito pagina, per Piattaforma, scegli JavaScript. 10. Nella finestra Ottieni AWS Credenziali , trovare e registrare il ID pool di identità. 11. Per consentire l'accesso a Amazon Lex, modifica il autenticato e non autenticato IAM ruoli.

a. Accedi alla AWS Management Console e apri la console IAM all'indirizzo https:// console.aws.amazon.com/iam/. b. Nel riquadro di navigazione, in Gestione degli accessi, scegli Ruoli. c. Nella casella di ricerca, immettere il nome del ruolo IAM autenticato e scegliere la casella di controllo accanto ad esso.

i. Scegliere Collega policy. ii. Nella casella di ricerca, immettere AmazonLexRunBotsOnly e scegliere la casella di controllo accanto ad esso. iii. Scegliere Attach policy (Collega policy). d. Inserire il nome del non autenticato IAM nella casella di ricerca e scegliere la casella di controllo accanto ad essa.

i. Scegliere Collega policy. ii. Nella casella di ricerca, immettere AmazonLexRunBotsOnly e scegliere la casella di controllo accanto ad esso. iii. Scegliere Attach policy (Collega policy).

Approfondimenti

Passaggio 5: Distribuisci il tuo bot come applicazione Web (p. 226)

225 Amazon Lex Guida per gli sviluppatori Passaggio 5: Distribuisci il tuo bot come applicazione Web

Passaggio 5: Distribuisci il tuo bot come applicazione Web

Per distribuire il bot come applicazione Web

1. Scarica il repository all'indirizzo https://github.com/awsdocs/amazon-lex-developer-guide/blob/master/ example_apps/agent_assistance_bot/ al tuo computer. 2. Accedere al repository scaricato e aprire il file index.html in un editor. 3. Apportare le seguenti modifiche:

a. Nella finestra AWS.config.credentials immettere il nome della regione e l'ID del pool di identità. b. Nella finestra Amazon Lex runtime parameters inserisci il nome del bot. c. Salvare il file.

Passaggio 6: Usa il bot

Ai fini della demo, fornisci input al bot come cliente e come agente. Per differenziare le due, le domande poste dal cliente iniziano con “Cliente:” e le risposte fornite dall'agente iniziano con "Agente:". Puoi scegliere da un menu di input suggeriti.

Esegui la tua applicazione web aprendo index.html per impegnarti in una copertura con il tuo bot in questo modo:.

226 Amazon Lex Guida per gli sviluppatori Passaggio 6: Usa il bot

Il pushChat() La funzione nel file index.html è spiegata di seguito.

var endConversationStatement = "Customer: I have no more questions. Thank you." // If the agent has to send a message, start the message with 'Agent' var inputText = document.getElementById('input'); if (inputText && inputText.value && inputText.value.trim().length > 0 && inputText.value[0]=='Agent') { showMessage(inputText.value, 'agentRequest','conversation'); inputText.value = ""; } // If the customer has to send a message, start the message with 'Customer' if(inputText && inputText.value && inputText.value.trim().length > 0 && inputText.value[0]=='Customer') { // disable input to show we're sending it var input = inputText.value.trim(); inputText.value = '...'; inputText.locked = true; customerInput = input.substring(2);

// Send it to the Lex runtime var params = { botAlias: '$LATEST', botName: 'KendraTestBot',

227 Amazon Lex Guida per gli sviluppatori Passaggio 6: Usa il bot

inputText: customerInput, userId: lexUserId, sessionAttributes: sessionAttributes };

showMessage(input, 'customerRequest', 'conversation'); if(input== endConversationStatement){ showMessage('Conversation Ended.','conversationEndRequest','conversation'); } lexruntime.postText(params, function(err, data) { if (err) { console.log(err, err.stack); showMessage('Error: ' + err.message + ' (see console for details)', 'lexError', 'conversation1') }

if (data &&input!=endConversationStatement) { // capture the sessionAttributes for the next cycle sessionAttributes = data.sessionAttributes;

showMessage(data, 'lexResponse', 'conversation1'); } // re-enable input inputText.value = ''; inputText.locked = false; }); } // we always cancel form submission return false;

Quando fornisci input come cliente, il Amazon Lex L'API di runtime la invia a Amazon Lex.

Il showMessage(daText, senderRequest, displayWindow) visualizza la conversazione tra l'agente e il cliente nella finestra della chat. Risposte suggerite da Amazon Kendra sono mostrati in una finestra adiacente. La conversazione termina quando il cliente dice “I have no more questions. Thank you.”

Nota: Elimina il tuo Amazon Kendra indice quando non in uso.

228 Amazon Lex Guida per gli sviluppatori Protezione dei dati

Sicurezza in Amazon Lex

Per AWS, la sicurezza della cloud ha la massima priorità. In quanto cliente AWS, puoi trarre vantaggio da un'architettura di data center e di rete progettata per soddisfare i requisiti delle aziende più esigenti a livello di sicurezza.

La sicurezza è una responsabilità condivisa tra AWS e l'utente. Il modello di responsabilità condivisa descrive questo come sicurezza del cloud e sicurezza nel cloud:

• Sicurezza del cloud – AWS è responsabile della protezione dell'infrastruttura che esegue i servizi AWS nel cloud AWS. AWS fornisce inoltre i servizi che è possibile utilizzare in modo sicuro. L'efficacia della nostra sicurezza è regolarmente testata e verificata da revisori di terze parti come parte dei programmi di conformità AWS. Per ulteriori informazioni sui programmi di conformità che si applicano a Amazon Lex, consulta Servizi coperti dal programma di conformitàAWS. • Sicurezza nel cloud – La tua responsabilità è determinata dal servizio AWS che utilizzi. L'utente è anche responsabile per altri fattori, tra cui la riservatezza dei dati, i requisiti dell'azienda e leggi e normative applicabili.

Questa documentazione consente di comprendere come applicare il modello di responsabilità condivisa quando si usa Amazon Lex. I seguenti argomenti illustrano come configurare Amazon Lex per soddisfare gli obiettivi di sicurezza e conformità. È inoltre illustrato come utilizzare altri servizi AWS che consentono di monitorare e proteggere le risorse Amazon Lex

Argomenti • Protezione dei dati in Amazon Lex (p. 229) • Identity and Access Management per Amazon Lex (p. 231) • Using Service-Linked Roles for Amazon Lex (p. 245) • Monitoraggio in Amazon Lex (p. 246) • Convalida della conformità per Amazon Lex (p. 257) • Resilienza in Amazon Lex (p. 258) • Sicurezza dell'infrastruttura in Amazon Lex (p. 258)

Protezione dei dati in Amazon Lex

Amazon Lex raccoglie i contenuti del cliente per la risoluzione dei problemi e per aiutare a migliorare il servizio. I contenuti dei clienti sono protetti per impostazione predefinita. Puoi eliminare i contenuti di singoli clienti utilizzando l'API Amazon Lex

Amazon Lex memorizza quattro tipi di contenuto:

• Esempi di espressioni che sono usate per costruire e addestrare un bot • Espressioni dei clienti dagli utenti che interagiscono con il bot • Gli attributi di sessione che forniscono informazioni specifiche dell'applicazione per tutta la durata dell'interazione di un utente con un bot • Gli attributi di richiesta che contengono informazioni che si applicano a una singola richiesta a un bot

Qualsiasi bot Amazon Lex che è stato progettato per l'uso da parte di bambini è regolato dal Children's Online Privacy Protection Act (COPPA). Per indicare a Amazon Lex che il bot è soggetto a COPPA utilizzando la console o Amazon Lex l'API , imposta il childDirected campo su true. Quando il childDirected campo è impostato su true, non vengono archiviate espressioni dell'utente.

229 Amazon Lex Guida per gli sviluppatori Crittografia dei dati inattivi

Argomenti • Crittografia dei dati inattivi (p. 230) • Crittografia in transito (p. 231) • Gestione delle chiavi (p. 231)

Crittografia dei dati inattivi

Amazon Lex crittografa le espressioni degli utenti che memorizza.

Argomenti • Espressioni di esempio (p. 230) • Espressioni del cliente (p. 230) • Attributi di sessione (p. 230) • Attributi di richiesta (p. 230)

Espressioni di esempio

Quando sviluppi un bot, puoi fornire le espressioni di esempio per ogni intento e slot. È anche possibile fornire valori personalizzati e sinonimi per le slot. Queste informazioni vengono crittografate mentre sono inattive e vengono utilizzate per creare il bot e per creare l'esperienza utente. Espressioni del cliente

Amazon Lex crittografa le espressioni che gli utenti inviano al bot a meno che il campo childDirected non sia impostato su true.

Quando il campo childDirected è impostato su true, non vengono archiviati espressioni degli utenti.

Quando il campo childDirected è impostato su false (predefinito), le espressioni degli utenti sono crittografate e memorizzate per 15 giorni per l'uso con l'operazione GetUtterancesView (p. 367) Per eliminare le espressioni archiviate per un determinato utente, utilizza l'operazione DeleteUtterances (p. 300)

Quando il bot accetta l'input vocale, l'input viene memorizzato in modo indefinito. Amazon Lex lo utilizza per migliorare la capacità del bot di rispondere all'input dell'utente.

Utilizza l'operazione DeleteUtterances (p. 300) per eliminare le espressioni archiviate per un determinato utente. Attributi di sessione

Gli attributi di sessione contengono informazioni specifiche sull'applicazione che vengono scambiate tra Amazon Lex e le applicazioni client. Amazon Lex invia gli attributi di sessione a tutte le funzioni di AWS Lambda configurate per un bot. Se una funzione di Lambda aggiunge o aggiorna gli attributi di sessione, Amazon Lex invia le nuove informazioni all'applicazione client.

Gli attributi di sessione persistono in un archivio crittografato per tutta la durata della sessione. È possibile configurare la sessione in modo che rimanga attiva per un minimo di 1 minuto e fino a 24 ore dopo l'ultima espressione dell'utente. La durata predefinita della sessione è di 5 minuti. Attributi di richiesta

Gli attributi di richiesta contengono informazioni specifiche sulla richiesta e si applicano solo alla richiesta corrente. Un'applicazione client utilizza gli attributi di richiesta per inviare informazioni a Amazon Lex in fase di runtime.

230 Amazon Lex Guida per gli sviluppatori Crittografia in transito

Utilizza gli attributi di richiesta per inviare informazioni che non devono essere conservate per l'intera sessione. Poiché gli attributi di richiesta non persistono tra le richieste, non vengono archiviati. Crittografia in transito

Amazon Lex usa il protocollo HTTPS per comunicare con l'applicazione client. Utilizza le firme HTTPS e AWS per comunicare con altri servizi, ad esempio Amazon Polly e AWS Lambda per conto della tua applicazione. Gestione delle chiavi

Amazon Lex protegge i contenuti dall'uso non autorizzato con le chiavi interne.

Identity and Access Management per Amazon Lex

AWS Identity and Access Management (IAM) è un servizio AWS che consente a un amministratore di controllare in modo sicuro l'accesso alle risorse AWS. Gli amministratori IAM controllano chi può essere autenticato (connesso) e autorizzato (dotato di autorizzazioni) a utilizzare risorse Amazon Lex. IAM è un servizio AWS che non prevede costi aggiuntivi.

Argomenti • Audience (p. 231) • Autenticazione con identità (p. 232) • Gestione dell'accesso tramite policy (p. 233) • Ulteriori informazioni (p. 235) • Come funziona Amazon Lex con IAM (p. 235) • Amazon LexEsempi di policy basate su identità (p. 240) • Risoluzione dei problemi di identità e accesso di Amazon Lex (p. 243)

Audience

Come utilizzi AWS Identity and Access Management (IAM) cambia in base a quali operazioni esegui in Amazon Lex.

Utente del servizio – Se utilizzi il Amazon Lex servizio per eseguire il tuo lavoro, l'amministratore ti fornisce le credenziali e le autorizzazioni necessarie. All'aumentare del numero di funzionalità Amazon Lex utilizzate per il lavoro, potrebbero essere necessarie ulteriori autorizzazioni. La comprensione della gestione dell'accesso consente di richiedere le autorizzazioni corrette all'amministratore. Se non riesci ad accedere a una funzionalità di Amazon Lex, consulta Risoluzione dei problemi di identità e accesso di Amazon Lex (p. 243).

Amministratore del servizio – Se sei il responsabile delle risorse Amazon Lex presso la tua azienda, probabilmente disponi dell'accesso completo a Amazon Lex. Il tuo compito è determinare le caratteristiche e le risorse Amazon Lex a cui i dipendenti devono accedere. Devi inviare le richieste all'amministratore IAM per cambiare le autorizzazioni degli utenti del servizio. Esamina le informazioni contenute in questa pagina per comprendere le nozioni di base di IAM. Per ulteriori informazioni su come la tua azienda può utilizzare IAM con Amazon Lex, consulta Come funziona Amazon Lex con IAM (p. 235).

Amministratore IAM – Se sei un amministratore IAM, potresti essere interessato a ottenere informazioni su come puoi scrivere policy per gestire l’accesso a Amazon Lex. Per visualizzare policy basate su identità

231 Amazon Lex Guida per gli sviluppatori Autenticazione con identità

Amazon Lex di esempio che puoi utilizzare in IAM, consulta Amazon LexEsempi di policy basate su identità (p. 240). Autenticazione con identità

L'autenticazione è la procedura di accesso ad AWS utilizzando le credenziali di identità. Per ulteriori informazioni sull'accesso utilizzando la AWS Management Console,consulta La console IAM e la pagina di accesso nella Guida per l'utente di IAM.

È necessario essere autenticati (connessi ad AWS) come Utente root Account AWS , un utente IAM o mediante l'assunzione del ruolo IAM. È anche possibile utilizzare l’autenticazione Single Sign-On (SSO) della propria azienda oppure collegarsi utilizzando Google o Facebook. In questi casi, l’amministratore ha configurato in precedenza la federazione delle identità utilizzando i ruoli IAM. Quando si accede ad AWS utilizzando le credenziali di un’altra azienda, si assume indirettamente un ruolo.

Per accedere direttamente alla AWS Management Console, utilizza la tua password con l’e-mail utente root o il nome utente IAM. Puoi effettuare l'accesso ad AWS a livello di programmazione utilizzando le chiavi di accesso utente root o IAM. AWS fornisce SDK e strumenti a riga di comando per firmare in maniera crittografica la richiesta utilizzando le tue credenziali. Se non utilizzi gli strumenti AWS, devi firmare la richiesta personalmente. A questo scopo, utilizza Signature Version 4, un protocollo per l'autenticazione di richieste API in entrata. Per ulteriori informazioni sulle richieste di autenticazione, consulta la pagina relativa al processo di firma Signature Version 4 nella AWS General Reference.

Indipendentemente dal metodo di autenticazione utilizzato, potrebbe essere necessario specificare ulteriori informazioni sulla sicurezza. AWS consiglia ad esempio di utilizzare la multi-factor authentication (MFA) per aumentare la sicurezza del tuo account. Per ulteriori informazioni, consulta Utilizzo dell'autenticazione a più fattori (MFA) in AWS nella Guida per l'utente di IAM. Utente root Account AWS

Quando si crea un Account AWS , si inizia con una singola identità di accesso che ha accesso completo a tutti i servizi AWS e le risorse nell'account. Tale identità è chiamata Account AWS utente root ed è possibile accedervi con l'indirizzo e-mail e la password utilizzati per creare l'account. È vivamente consigliato di non utilizzare utente root per le attività quotidiane, anche quelle amministrative. Attieniti alla best practice per utilizzare la utente root soltanto per creare il tuo primo utente IAM. Quindi conserva al sicuro le credenziali utente root e utilizzale per eseguire solo alcune attività di gestione dell'account e del servizio. IAMUtenti e gruppi

Un utente IAM è un'identità all'interno dell'account AWS che dispone di autorizzazioni specifiche per un singolo utente o applicazione. Un utente IAM può disporre di credenziali a lungo termine, ad esempio un nome utente e una password oppure un set di chiavi di accesso. Per informazioni su come generare le chiavi di accesso, consulta Gestione delle chiavi di accesso per gli utenti IAM nella Guida per l'utente di IAM. Quando generi le chiavi di accesso per un utente IAM, assicurarti di visualizzare e salvare la coppia di chiavi in modo sicuro. Non puoi recuperare la chiave di accesso segreta in futuro. Al contrario, sarà necessario generare una nuova coppia di chiavi di accesso.

Un gruppo IAM è un’identità che specifica una raccolta di utenti IAM. Non è possibile eseguire l’accesso come gruppo. Puoi utilizzare gruppi per specificare le autorizzazioni per più utenti alla volta. I gruppi semplificano la gestione delle autorizzazioni per set di utenti di grandi dimensioni. Ad esempio, puoi avere un gruppo denominato Amministratori IAM e concedere a tale gruppo le autorizzazioni per amministrare le risorse IAM.

Gli utenti sono diversi dai ruoli. Un utente è associato in modo univoco a una persona o un'applicazione, mentre un ruolo è destinato a essere assunto da chiunque ne abbia bisogno. Gli utenti dispongono di credenziali a lungo termine permanenti, mentre i ruoli forniscono credenziali temporanee. Per ulteriori informazioni, consulta Quando creare un utente IAM invece di un ruolo nella Guida per l'utente di IAM.

232 Amazon Lex Guida per gli sviluppatori Gestione dell'accesso tramite policy

IAMRuoli

Un ruolo IAM è un'identità all'interno dell'account AWS che dispone di autorizzazioni specifiche. È simile a un utente IAM ma non è associato a una persona specifica. È possibile assumere temporaneamente un ruolo IAM nella AWS Management Console mediante lo scambio di ruoli. Puoi assumere un ruolo chiamando un'operazione AWS CLI o API AWS oppure utilizzando un URL personalizzato. Per ulteriori informazioni sui metodi per l'utilizzo di ruoli, consulta Utilizzo di ruoli IAM nella Guida per l'utente di IAM.

IAMI ruoli con credenziali temporanee sono utili nelle seguenti situazioni:

• Autorizzazioni utente IAM temporanee– Un utente IAM può assumere un ruolo IAM per ottenere temporaneamente autorizzazioni diverse per un'attività specifica. • Accesso utente federato – Invece di creare un utente IAM, puoi utilizzare identità esistenti da AWS Directory Service, dalla tua directory di utente aziendale o da un provider di identità Web. Sono noti come utenti federati. AWS assegna un ruolo a un utente federato quando è richiesto l'accesso tramite un provider di identità. Per ulteriori informazioni sugli utenti federati, consulta la pagina relativa a utenti federati e ruoli nella Guida per l'utente di IAM. • Accesso tra account – Puoi utilizzare un ruolo IAM per permettere a un utente (principale attendibile) con un account diverso di accedere alle risorse nel tuo account. I ruoli sono lo strumento principale per concedere l'accesso tra account. Tuttavia, con alcuni dei servizi AWS, puoi collegare una policy direttamente a una risorsa (anziché utilizzare un ruolo come un proxy). Per informazioni sulle differenze tra ruoli e policy basate su risorse per l'accesso tra account, consulta Differenza tra i ruoli IAM e le policy basate su risorse nella Guida per l'utente di IAM. • AWS Accesso al servizio –Un ruolo del servizio è un ruolo IAM assunto dal servizio AWS per eseguire operazioni per tuo conto. Un amministratore di IAM può creare, modificare ed eliminare un ruolo di servizio da IAM. Per ulteriori informazioni, consulta Creazione di un ruolo per delegare le autorizzazioni a un servizio AWS nella Guida per l'utente di IAM. • Applicazioni in esecuzione su Amazon EC2 –Puoi utilizzare un ruolo IAM per gestire credenziali temporanee per le applicazioni in esecuzione su un'istanza EC2 e inviare richieste AWS CLI o API AWS. Ciò è preferibile all'archiviazione delle chiavi di accesso nell'istanza EC2. Per assegnare un ruolo AWS a un'istanza EC2, affinché sia disponibile per tutte le relative applicazioni, puoi creare un profilo di istanza collegato all'istanza. Un profilo di istanza contiene il ruolo e consente ai programmi in esecuzione sull'istanza EC2 di ottenere le credenziali temporanee. Per ulteriori informazioni, consulta Utilizzo di un ruolo IAM per concedere autorizzazioni ad applicazioni in esecuzione su istanze Amazon EC2 nella Guida per l'utente di IAM.

Per informazioni sull'utilizzo di ruoli IAM, consulta Quando creare un ruolo IAM invece di un utente nella Guida per l'utente di IAM. Gestione dell'accesso tramite policy

Per controllare l'accesso ad AWS è possibile creare policy e collegarle a identità IAM o risorse AWS. Una policy è un oggetto in AWS che, quando viene associato a un'identità o a una risorsa, ne definisce le autorizzazioni. AWS valuta queste policy quando un'entità (utente root, utente IAM o ruolo IAM) effettua una richiesta. Le autorizzazioni nella policy determinano l'approvazione o il rifiuto della richiesta. La maggior parte delle policy viene memorizzata in AWS sotto forma di documenti JSON. Per ulteriori informazioni sulla struttura e sui contenuti dei documenti delle policy JSON, consulta Panoramica delle policy JSON nella Guida per l'utente di IAM.

Un amministratore IAM può utilizzare le policy per specificare quali utenti hanno accesso alle risorse AWS e quali operazioni possono eseguire su tali risorse. Ogni entità IAM (utente o ruolo) inizialmente non dispone di autorizzazioni. Ovvero, per impostazione predefinita, gli utenti non possono eseguire alcuna operazione, neppure modificare la propria password. Per autorizzare un utente a eseguire operazioni, un amministratore deve collegare una policy di autorizzazioni a tale utente. In alternativa, l'amministratore può

233 Amazon Lex Guida per gli sviluppatori Gestione dell'accesso tramite policy aggiungere l'utente a un gruppo che dispone delle autorizzazioni desiderate. Quando un amministratore fornisce le autorizzazioni a un gruppo, le autorizzazioni vengono concesse a tutti gli utenti in tale gruppo.

IAMLe policy definiscono le autorizzazioni relative a un'operazione, indipendentemente dal metodo utilizzato per eseguirla. Ad esempio, supponiamo di disporre di una policy che consente l'operazione iam:GetRole. Un utente con tale policy può ottenere informazioni sul ruolo dalla AWS Management Console, la AWS CLI o l'API AWS. Policy basate sulle identità

Le policy basate su identità sono documenti di policy di autorizzazione JSON che è possibile collegare a un'identità, ad esempio un utente, un ruolo o un gruppo IAM. Tali policy definiscono le operazioni autorizzate per l'identità, nonché le risorse e le condizioni in cui possono essere eseguite. Per informazioni su come creare una policy basata su identità, consulta Creazione di policy IAM nella Guida per l'utente di IAM.

Le policy basate su identità possono essere ulteriormente classificate come policy inline o policy gestite. Le policy inline sono incorporate direttamente in un singolo utente, gruppo o ruolo. Le policy gestite sono policy standalone che possono essere collegate a più utenti, gruppi e ruoli nell'account AWS. Le policy gestite includono le policy gestite da AWS e le policy gestite dal cliente. Per informazioni su come scegliere tra una policy gestita o una policy inline, consulta Scelta fra policy gestite e policy inline nella Guida per l'utente di IAM. Altri tipi di policy

AWS supporta tipi di policy meno comuni aggiuntivi. Questi tipi di policy possono impostare il numero massimo di autorizzazioni concesse dai tipi di policy più comuni.

• Limiti delle autorizzazioni – Un limite delle autorizzazioni è una funzione avanzata nella quale si imposta il numero massimo di autorizzazioni che una policy basata su identità può concedere a un'entità IAM (utente o ruolo IAM). È possibile impostare un limite delle autorizzazioni per un'entità. Le autorizzazioni risultanti sono l’intersezione delle policy basate su identità dell’entità e i suoi limiti delle autorizzazioni. Le policy basate su risorse che specificano l'utente o il ruolo nel campo Principal sono limitate dal limite delle autorizzazioni. Un rifiuto esplicito in una qualsiasi di queste policy sostituisce l'autorizzazione. Per ulteriori informazioni sui limiti delle autorizzazioni, consulta Limiti delle autorizzazioni per le entità IAM nella Guida per l'utente di IAM. • Policy di controllo dei servizi (SCP)– Le SCP sono policy JSON che specificano il numero massimo di autorizzazioni per un'organizzazione o unità organizzativa (OU) in AWS Organizations. AWS Organizations è un servizio per il raggruppamento e la gestione centralizzata degli account AWS multipli di proprietà dell'azienda. Se si abilitano tutte le caratteristiche in un'organizzazione, è possibile applicare le policy di controllo dei servizi (SCP) a uno o tutti i propri account. L'SCP limita le autorizzazioni per le entità negli account membri, compreso ogni Utente root Account AWS . Per ulteriori informazioni su Organizations e SCP, consultare Come funzionano le SCP nella Guida per l'utente di AWS Organizations. • Policy di sessione – Le policy di sessione sono policy avanzate che si passano come parametro quando si crea in modo programmatico una sessione temporanea per un ruolo o un utente federato. Le autorizzazioni della sessione risultante sono l’intersezione delle policy basate sull’identità del ruolo o dell’utente e le policy di sessione. Le autorizzazioni possono anche provenire da una policy basata su risorse. Un rifiuto esplicito in una qualsiasi di queste policy sostituisce l'autorizzazione. Per ulteriori informazioni, consulta Policy di sessione nella Guida per l'utente di IAM.

Più tipi di policy

Quando più tipi di policy si applicano a una richiesta, le autorizzazioni risultanti sono più complicate da comprendere. Per informazioni su come AWS determina se consentire una richiesta quando sono coinvolti più tipi di policy, consulta Logica di valutazione delle policy nella Guida per l'utente di IAM.

234 Amazon Lex Guida per gli sviluppatori Ulteriori informazioni

Ulteriori informazioni

Per ulteriori informazioni su Identity and Access Management per Amazon Lex, consulta le pagine seguenti:

• Come funziona Amazon Lex con IAM (p. 235) • Risoluzione dei problemi di identità e accesso di Amazon Lex (p. 243)

Come funziona Amazon Lex con IAM

Prima di utilizzare AWS Identity and Access Management (IAM) per gestire l'accesso ad Amazon Lex, è necessario comprendere quali caratteristiche IAM sono disponibili per l'uso con Amazon Lex. Per una panoramica generale del funzionamento di Amazon Lex e altri AWS servizi con IAM, consulta AWS Servizi supportati da IAM nella Guida per l'utente di IAM.

Argomenti • Amazon LexPolicy basate su identità (p. 235) • Amazon LexPolicy basate su risorse (p. 237) • Autorizzazione basata su tag Amazon Lex (p. 237) • Ruoli Amazon Lex di IAM (p. 239)

Amazon LexPolicy basate su identità

Per specificare operazioni e risorse consentite o rifiutate, nonché le condizioni in base alle quali le operazioni sono consentite o rifiutate, puoi utilizzare le policy basate su identità IAM. Amazon Lex supporta operazioni, risorse e chiavi di condizione specifiche. Per informazioni su tutti gli elementi utilizzati in una policy JSON, consulta Documentazione di riferimento degli elementi delle policy JSON IAM nella Guida per l'utente di IAM.

Actions

L'elemento Action di una policy basata su identità IAM descrive l'operazione o le operazioni specifiche che saranno concesse o rifiutate dalla policy. Le operazioni della policy hanno spesso lo stesso nome dell’operazione API AWS. L’operazione viene utilizzata in una policy per concedere le autorizzazioni di eseguire l’operazione associata.

Le operazioni delle policy in Amazon Lex utilizzano il seguente prefisso prima dell'operazione: lex:. Ad esempio, per concedere a qualcuno l'autorizzazione per chiamare un bot Amazon Lex con l’operazione PostContent, includi l'operazione lex:PostContent nella policy. Le istruzioni delle policy devono includere un elemento Action o NotAction. Amazon Lex definisce le operazioni che descrivono le attività che puoi eseguire con questo servizio. Per visualizzare un elenco delle operazioni Amazon Lex, consulta Actions Defined by Amazon Lex nella Guida per l'utente di IAM.

Per specificare più operazioni in una sola dichiarazione, separa ciascuna di esse con una virgola come mostrato di seguito.

"Action": [ "lex:action1", "lex:action2"

Puoi specificare più operazioni tramite caratteri jolly (*). Ad esempio, per specificare tutte le operazioni che iniziano con la parola Put, includi la seguente operazione.

235 Amazon Lex Guida per gli sviluppatori Come funziona Amazon Lex con IAM

"Action": "lex:Put*"

Resources

L'elemento Resource specifica l'oggetto o gli oggetti a cui si applica l'operazione. Le istruzioni devono includere un elemento Resource o un elemento NotResource. Specifica una risorsa utilizzando un ARN o il carattere jolly (*) per indicare che l'istruzione si applica a tutte le risorse.

Un ARN di risorsa bot Amazon Lex ha il formato seguente. arn:aws:lex:${Region}:${Account}:bot:${Bot-Name}

Per ulteriori informazioni sul formato degli ARN, consulta Amazon Resource Name (ARN) e spazi dei nomi del servizio AWS.

Ad esempio, per specificare il bot OrderFlowers nell'istruzione, utilizza il seguente ARN.

"Resource": "arn:aws:lex:us-east-2:123456789012:bot:OrderFlowers"

Per specificare tutti i bot che appartengono ad un account specifico, utilizza il carattere jolly (*).

"Resource": "arn:aws:lex:us-east-2:123456789012:bot:*"

Alcune operazioni Amazon Lex, ad esempio quelle per la creazione di risorse, non possono essere eseguite su una risorsa specifica. In questi casi, è necessario utilizzare il carattere jolly (*).

"Resource": "*"

Per un elenco di tipi di risorse Amazon Lex e i relativi ARN, consulta Resources Defined by Amazon Lex nella Guida per l'utente di IAM. Per informazioni sulle operazioni con cui è possibile specificare l'ARN di ogni risorsa, consulta Actions Defined by Amazon Lex. Chiavi di condizione

Utilizza Condition l'elemento (o un Condition blocco) per specificare le condizioni in cui è applicata un'istruzione. L'elemento Condition è facoltativo. Puoi compilare espressioni condizionali che utilizzano operatori di condizione, ad esempio uguale a o minore di, per soddisfare la condizione nella policy con i valori nella richiesta.

Se specifichi più elementi Condition in un'istruzione o più chiavi in un singolo elemento Condition, questi vengono valutati da AWS utilizzando un'operazione AND logica. Se specifichi più valori per una singola chiave di condizione, AWS valuta la condizione utilizzando un'operazione OR logica. Tutte le condizioni devono essere soddisfatte prima che le autorizzazioni dell'istruzione vengano concesse.

Puoi anche utilizzare variabili segnaposto quando specifichi le condizioni. Ad esempio, puoi concedere a un utente IAM l'autorizzazione per accedere a una risorsa solo se è stata taggata con il nome utente IAM. Per ulteriori informazioni, consulta Elementi delle policy IAM: variabili e tag nella Guida per l'utente di IAM.

Amazon Lex definisce il proprio set di chiavi di condizione e, inoltre, supporta l'uso di alcune chiavi di condizione globali. Per un elenco di tutte le chiavi di condizione globali AWS, consulta Chiavi di contesto delle condizioni globali AWS nella Guida per l'utente di IAM.

La tabella seguente elenca le chiavi di condizione Amazon Lex che si applicano alle risorse Amazon Lex. È possibile includere tali chiavi negli elementi Condition di una policy di autorizzazioni IAM.

236 Amazon Lex Guida per gli sviluppatori Come funziona Amazon Lex con IAM

Examples

Per esempi di policy basate su identità Amazon Lex, consulta Amazon LexEsempi di policy basate su identità (p. 240). Amazon LexPolicy basate su risorse

Le policy basate su risorse sono documenti di policy JSON che specificano le operazioni che possono essere eseguite da un'entità principale specificata sulla Amazon Lex risorsa e in base a quali condizioni. Amazon Lex non supporta le policy basate su risorse. Autorizzazione basata su tag Amazon Lex

Puoi associare i tag a determinati tipi di risorse Amazon Lex per l'autorizzazione. Per controllare l'accesso basato su tag, fornisci le informazioni sui tag nell'elemento condizione di una policy utilizzando le chiavi di condizione lex:ResourceTag/${TagKey}, aws:RequestTag/${TagKey} o aws:TagKeys.

Per informazioni sul tagging delle risorse Amazon Lex, consulta Tagging delle risorse Amazon Lex (p. 65). Per un esempio di policy basata su identità che limita l'accesso a una risorsa in base ai tag delle risorse, consulta Esempio: utilizzare un tag per accedere a una risorsa (p. 242). Per ulteriori informazioni sull'utilizzo dei tag per limitare l'accesso alle risorse, consulta Controllo degli accessi tramite tag nella Guida per l'utente di IAM.

Nella tabella seguente sono elencate le azioni e i tipi di risorse corrispondenti per il controllo dell'accesso basato su tag. Ogni azione è autorizzata in base ai tag associati al tipo di risorsa corrispondente.

Operazione Tipo di risorsa Chiavi di condizione Note

CreateBotVersion bot lex:ResourceTag (p. 269)

DeleteBot (p. 284) bot lex:ResourceTag

DeleteBotAlias alias lex:ResourceTag (p. 286)

DeleteBotChannelAssociationcanale lex:ResourceTag (p. 288)

DeleteBotVersion bot lex:ResourceTag (p. 290)

DeleteSession bot o alias lex:ResourceTag Utilizza i tag associati (p. 418) al bot quando l'alias è impostato su $LATEST. Utilizza i tag associati all'alias specificato quando usati con altri alias.

DeleteUtterances bot lex:ResourceTag (p. 300)

GetBot (p. 302) bot o alias lex:ResourceTag Utilizza i tag associati al bot quando versionOrAlias è impostato su $LATEST o su una versione

237 Amazon Lex Guida per gli sviluppatori Come funziona Amazon Lex con IAM

Operazione Tipo di risorsa Chiavi di condizione Note numerica. Utilizza i tag associati all'alias specificato quando usati con alias

GetBotAlias (p. 307) alias lex:ResourceTag

GetBotChannelAssociationcanale lex:ResourceTag (p. 313)

GetBotChannelAssociationscanale lex:ResourceTag Utilizza i tag associati (p. 317) al bot quando l'alias è impostato su "-". Utilizza i tag associati all'alias specificato quando viene specificato un alias bot

GetBotVersions bot lex:ResourceTag (p. 323)

GetExport (p. 332) bot lex:ResourceTag

GetSession (p. 421) bot o alias lex:ResourceTag Utilizza i tag associati al bot quando l'alias è impostato su $LATEST. Utilizza i tag associati all'alias specificato quando usati con altri alias.

GetUtterancesView bot lex:ResourceTag (p. 367)

ListTagsForResource bot, alias o canale lex:ResourceTag (p. 370)

PostContent (p. 425) bot o alias lex:ResourceTag Utilizza i tag associati al bot quando l'alias è impostato su $LATEST. Utilizza i tag associati all'alias specificato quando usati con altri alias.

PostText (p. 434) bot o alias lex:ResourceTag Utilizza i tag associati al bot quando l'alias è impostato su $LATEST. Utilizza i tag associati all'alias specificato quando usati con altri alias.

PutBot (p. 372) bot lex:ResourceTag, aws:RequestTag, aws:TagKeys

238 Amazon Lex Guida per gli sviluppatori Come funziona Amazon Lex con IAM

Operazione Tipo di risorsa Chiavi di condizione Note

PutBotAlias (p. 383) alias lex:ResourceTag, aws:RequestTag, aws:TagKeys

PutSession (p. 442) bot o alias lex:ResourceTag Utilizza i tag associati al bot quando l'alias è impostato su $LATEST. Utilizza i tag associati all'alias specificato quando usati con altri alias.

StartImport (p. 406) bot lex:ResourceTag Si basa sulla policy di accesso per l'operazione PutBot. I tag e le autorizzazioni specifiche per l'operazione StartImport vengono ignorati.

TagResource bot, alias o canale lex:ResourceTag, (p. 414) aws:RequestTag, aws:TagKeys

UntagResource bot, alias o canale lex:ResourceTag, (p. 416) aws:RequestTag, aws:TagKeys

Ruoli Amazon Lex di IAM

Un ruolo IAM è un'entità all'interno dell'account AWS che dispone di autorizzazioni specifiche. Utilizzo di credenziali temporanee con Amazon Lex

Puoi utilizzare credenziali temporanee per effettuare l'accesso utilizzando la federazione, assumere un ruolo IAM o assumere un ruolo tra account. Per ottenere le credenziali di sicurezza temporanee, eseguire una chiamata a operazioni API AWS STS quali, ad esempio, AssumeRole o GetFederationToken.

Amazon Lex supporta l'utilizzo di credenziali temporanee. Ruoli collegati al servizio

Ruoli collegati al servizio consentono ai servizi AWS di accedere a risorse in altri servizi per completare un'operazione a tuo nome. I ruoli collegati ai servizi sono visualizzati nell'account IAM e sono di proprietà del servizio. Un amministratore IAM può visualizzare, ma non modificare le autorizzazioni dei ruoli collegati ai servizi.

Amazon Lex supporta i ruoli collegati ai servizi. Per ulteriori informazioni su come creare e gestire i ruoli collegati ai servizi Amazon Lex, consulta Step 1: Create a Service-Linked Role (AWS CLI) (p. 111). Ruoli dei servizi

Un servizio può assumere un ruolo del servizio a tuo nome. Questo ruolo consente al servizio di accedere alle risorse in altri servizi per completare un'operazione per conto dell'utente. I ruoli del servizio sono

239 Amazon Lex Guida per gli sviluppatori Esempi di policy basate su identità visualizzati nell'account IAM e sono di proprietà dell'account. Ciò significa che un amministratore IAM può modificare le autorizzazioni per questo ruolo. Tuttavia, in questo modo il servizio potrebbe non funzionare correttamente.

Amazon Lex supporta i ruoli del servizio. Scelta di un ruolo IAM in Amazon Lex

Amazon Lex utilizza ruoli collegati al servizio per chiamare Amazon Comprehend e Amazon Polly. Utilizza le autorizzazioni a livello di risorse sulle tue funzioni AWS Lambda per richiamarle.

È necessario fornire un ruolo IAM per abilitare il tagging delle conversazioni. Per ulteriori informazioni, consulta Creazione di un ruolo IAM e delle policy per i log delle conversazioni (p. 31). Amazon LexEsempi di policy basate su identità

Per impostazione predefinita, gli utenti e i ruoli IAM non dispongono dell'autorizzazione per creare o modificare risorse Amazon Lex. Inoltre, non sono in grado di eseguire attività utilizzando la AWS Management Console, AWS CLI o un'API AWS. Un amministratore IAM deve creare policy IAM che concedono a utenti e ruoli l'autorizzazione per eseguire operazioni API specifiche sulle risorse specificate di cui hanno bisogno. L'amministratore devi quindi collegare queste policy a utenti o gruppi IAM che richiedono tali autorizzazioni.

Per informazioni su come creare una policy basata su identità IAM utilizzando i documenti di policy JSON di esempio, consulta Creazione di policy nella scheda JSON nella Guida per l'utente di IAM.

Argomenti • Best practice delle policy (p. 240) • AWS Policy gestite da (predefinite) per Amazon Lex (p. 241) • Esempio: consentire agli utenti di visualizzare le loro autorizzazioni (p. 241) • Esempio: eliminare tutti i bot Amazon Lex (p. 242) • Esempio: utilizzare un tag per accedere a una risorsa (p. 242)

Best practice delle policy

Le policy basate su identità sono molto potenti. Determinano se qualcuno può creare, accedere o eliminare risorse Amazon Lex nell'account. Queste operazioni possono comportare costi aggiuntivi per l'account AWS. Quando crei o modifichi policy basate su identità, segui queste linee guida e raccomandazioni:

• Nozioni di base sull'utilizzo di policy AWS gestite – Per iniziare a utilizzare Amazon Lex rapidamente, utilizza policy AWS gestite per fornire ai dipendenti le autorizzazioni necessarie. Queste policy sono già disponibili nel tuo account e sono gestite e aggiornate da AWS. Per ulteriori informazioni, consulta Nozioni di base sull'utilizzo delle autorizzazioni con le policy gestite da AWS nella Guida per l'utente di IAM. • Assegnare il privilegio minimo – Quando si creano policy personalizzate, concedere solo le autorizzazioni richieste per eseguire un'attività. Iniziare con un set di autorizzazioni minimo e concedere autorizzazioni aggiuntive quando necessario. In questo modo, è più sicuro che iniziare con autorizzazioni che sono troppo permissive e cercare di limitarle in un secondo momento. Per ulteriori informazioni, consulta Assegnare il privilegio minimo nella Guida per l'utente di IAM. • Abilitare MFA per operazioni sensibili– Per una maggiore sicurezza, richiedere agli utenti IAM di utilizzare l'autenticazione a più fattori (MFA) per accedere a risorse sensibili o operazioni API. Per ulteriori informazioni, consulta il documento sull'Utilizzo dell'autenticazione a più fattori (MFA) in AWS nella Guida per l'utente di IAM. • Utilizzare le condizioni della policy per ulteriore sicurezza – Per quanto possibile, definire le condizioni in cui le policy basate su identità consentono l'accesso a una risorsa. Ad esempio, è possibile scrivere

240 Amazon Lex Guida per gli sviluppatori Esempi di policy basate su identità

condizioni per specificare un intervallo di indirizzi IP consentiti dai quali deve provenire una richiesta. È anche possibile scrivere condizioni per consentire solo le richieste all'interno di un intervallo di date o ore specificato oppure per richiedere l'utilizzo di SSL o MFA. Per ulteriori informazioni, consulta Elementi delle policy JSON IAM: condizione nella Guida per l'utente di IAM.

AWS Policy gestite da (predefinite) per Amazon Lex

AWS gestisce molti casi di utilizzo comuni fornendo policy IAM autonome create e amministrate da AWS. Queste policy sono denominate policy gestite da AWS. Le policy gestite da AWS rendono più semplice l'assegnazione di autorizzazioni appropriate a utenti, gruppi e ruoli rispetto a come avverrebbe se le policy si dovessero scrivere. Per ulteriori informazioni, consulta Policy gestite AWS nella Guida per IAM l'utente di .

Le seguenti policy gestite da AWS che puoi collegare a gruppi e ruoli nel tuo account, sono specifiche di Amazon Lex:

• AmazonLexReadOnly — Concede l'accesso in sola lettura alle Amazon Lex risorse . • AmazonLexRunBotsOnly — Concede l'accesso per eseguire Amazon Lex chatbot. • AmazonLexFullAccess — Concede l'accesso completo per creare, leggere, aggiornare, eliminare ed eseguire tutte le Amazon Lex risorse. Inoltre concede la possibilità di associare le funzioni Lambda i cui nomi iniziano con AmazonLex con gli intenti Amazon Lex.

Note

Per esaminare queste policy delle autorizzazioni, accedi alla console IAM ed esegui la ricerca delle policy specifiche.

La policy AmazonLexFullAccess non concede all'utente l'autorizzazione per utilizzare KendraSearchIntent l'intento per eseguire query su un Amazon Kendra indice. Per eseguire query su un indice, è necessario aggiungere ulteriori autorizzazioni alla policy. Per le autorizzazioni richieste, consulta Policy IAM per la ricerca Amazon Kendra (p. 48).

Puoi anche creare le tue policy IAM personalizzate per consentire autorizzazioni per operazioni API di Amazon Lex. Puoi collegare queste policy personalizzate ai ruoli o ai gruppi IAM che richiedono le autorizzazioni. Esempio: consentire agli utenti di visualizzare le loro autorizzazioni

Questa policy di esempio consente agli utenti IAM di visualizzare le policy gestite e inline che sono collegate all'identità dell'utente. Questa policy include le autorizzazioni per completare questa operazione sulla console o a livello di codice utilizzando AWS CLI o l'API AWS.

{ "Version": "2012-10-17", "Statement": [ { "Sid": "ViewOwnUserInfo", "Effect": "Allow", "Action": [ "iam:GetUserPolicy", "iam:ListGroupsForUser", "iam:ListAttachedUserPolicies", "iam:ListUserPolicies", "iam:GetUser" ],

241 Amazon Lex Guida per gli sviluppatori Esempi di policy basate su identità

"Resource": [ "arn:aws:iam::*:user/${aws:username}" ] }, { "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" } ] }

Esempio: eliminare tutti i bot Amazon Lex

Questa policy di esempio concede a un utente IAM nell'account AWS l'autorizzazione per eliminare qualsiasi bot nell'account.

{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "lex:DeleteBot" ], "Resource": [ "*" ] } ] }

Esempio: utilizzare un tag per accedere a una risorsa

Questa policy di esempio concede a un utente o a un ruolo IAM nell'account AWS l'autorizzazione per utilizzare l'operazione PostText con qualsiasi risorsa contrassegnata con la chiave Department e il valore Support.

{ "Version": "2012-10-17", "Statement": [ { "Action": "lex:PostText", "Effect": "Allow", "Resource": "*", "Condition": { "StringEquals": { "lex:ResourceTag/Department": "Support" } } }

242 Amazon Lex Guida per gli sviluppatori Risoluzione dei problemi

] }

Risoluzione dei problemi di identità e accesso di Amazon Lex

Utilizza le informazioni seguenti per diagnosticare e risolvere i problemi comuni che possono verificarsi durante l'utilizzo di Amazon Lex e AWS Identity and Access Management (IAM.)

Argomenti • Non sono autorizzato a eseguire un'operazione in Amazon Lex (p. 243) • Non sono autorizzato a eseguire iam:PassRole (p. 243) • Desidero visualizzare le mie chiavi di accesso (p. 244) • Sono un amministratore e desidero consentire ad altri utenti di accedere a Amazon Lex (p. 244) • Voglio consentire alle persone esterne al mio account AWS di accedere alle mie risorse Amazon Lex (p. 244)

Non sono autorizzato a eseguire un'operazione in Amazon Lex

Se AWS Management Console indica che non sei autorizzato a eseguire un'operazione, contatta l'amministratore per assistenza. L'amministratore è la persona che ti ha fornito il nome utente e la password.

L'errore seguente si verifica ad esempio quando l'utente mateojackson IAM cerca di utilizzare la console per visualizzare i dettagli relativi a un bot ma non dispone di autorizzazioni lex:GetBot.

User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: lex:GetBot on resource: OrderPizza

In questo caso, Mateo deve chiedere al suo amministratore di aggiornare le policy per permettergli di accedere al bot OrderPizza utilizzando l'operazione lex:GetBot. Non sono autorizzato a eseguire iam:PassRole

Se ricevi un errore che indica che non sei autorizzato a eseguire l'operazione iam:PassRole, devi contattare il tuo amministratore per ricevere assistenza. L'amministratore è la persona che ti ha fornito il nome utente e la password. Richiedi a tale persona di aggiornare le tue policy per poter passare un ruolo a Amazon Lex.

Alcuni servizi AWS consentono di passare un ruolo esistente a tale servizio, invece di creare un nuovo ruolo del servizio o ruolo collegato ai servizi. Per eseguire questa operazione, devi disporre delle autorizzazioni per passare il ruolo al servizio.

L'errore di esempio seguente si verifica quando un utente IAM denominato marymajor cerca di utilizzare la console per eseguire un'operazione in Amazon Lex. Tuttavia, l'operazione richiede che il servizio disponga delle autorizzazioni concesse da un ruolo del servizio. Mary non dispone di autorizzazioni per passare il ruolo al servizio.

User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole

In questo caso, Mary chiede all'amministratore di aggiornare la sue policy per poter eseguire l'operazione iam:PassRole.

243 Amazon Lex Guida per gli sviluppatori Risoluzione dei problemi

Desidero visualizzare le mie chiavi di accesso

Dopo aver creato le chiavi di accesso utente IAM, puoi visualizzare l'ID chiave di accesso in qualsiasi momento. Tuttavia, non puoi visualizzare nuovamente la chiave di accesso segreta. Se perdi la chiave segreta, devi creare una nuova coppia di chiavi di accesso.

Le chiavi di accesso sono composte da due parti: un ID chiave di accesso (ad esempio AKIAIOSFODNN7EXAMPLE) e una chiave di accesso segreta (ad esempio, wJalrXUtnFEMI/K7MDENG/ bPxRfiCYEXAMPLEKEY). Come un nome utente e una password, è necessario utilizzare sia l'ID chiave di accesso sia la chiave di accesso segreta insieme per autenticare le richieste dell'utente. Gestisci le tue chiavi di accesso in modo sicuro mentre crei il nome utente e la password. Important

Non fornire le chiavi di accesso a terze parti, neppure per aiutare a trovare l'ID utente canonico. Se lo facessi, daresti a qualcuno accesso permanente al tuo account.

Quando crei una coppia di chiavi di accesso, ti viene chiesto di salvare l'ID chiave di accesso e la chiave di accesso segreta in una posizione sicura. La chiave di accesso segreta è disponibile solo al momento della creazione. Se perdi la chiave di accesso segreta, devi aggiungere nuove chiavi di accesso all'utente IAM. È possibile avere massimo due chiavi di accesso. Se ne hai già due, devi eliminare una coppia di chiavi prima di crearne una nuova. Per visualizzare le istruzioni, consulta Gestione delle chiavi di accesso nella Guida per l'utente di IAM. Sono un amministratore e desidero consentire ad altri utenti di accedere a Amazon Lex

Per consentire ad altri utenti di accedere ad Amazon Lex, devi creare un'entità IAM (utente o ruolo) per la persona o l'applicazione che richiede l'accesso. Tale utente o applicazione utilizzerà le credenziali dell'entità per accedere ad AWS. Dovrai quindi collegare all'entità una policy che conceda le autorizzazioni corrette in Amazon Lex.

Per iniziare immediatamente, consulta Creazione dei primi utenti e gruppi delegati IAM nella Guida per l'utente di IAM. Voglio consentire alle persone esterne al mio account AWS di accedere alle mie risorse Amazon Lex

Puoi creare un ruolo che può essere utilizzato dagli utenti in altri account o da persone esterne all'organizzazione per accedere alle tue risorse. Puoi specificare chi è attendibile per l'assunzione del ruolo. Per servizi che supportano policy basate su risorse o liste di controllo accessi, puoi utilizzare tali policy per concedere alle persone l'accesso alle tue risorse.

Per ulteriori informazioni, consulta gli argomenti seguenti:

• Per capire se Amazon Lex supporta queste funzionalità, consulta Come funziona Amazon Lex con IAM (p. 235). • Per ottenere informazioni su come fornire accesso alle risorse negli account AWS che possiedi, consulta Fornire l’accesso a un utente IAM in un altro account AWS che si possiede nella Guida per l'utente di IAM. • Per capire come fornire l'accesso alle risorse ad account AWS di terze parti, consulta Concessione dell'accesso agli account AWS di proprietà di terze parti nella Guida per l'utente di IAM. • Per capire come fornire l'accesso tramite la federazione delle identità, consulta Fornire accesso a utenti autenticati esternamente (Federazione delle identità) nella Guida per l'utente di IAM.

244 Amazon Lex Guida per gli sviluppatori Using Service-Linked Roles

• Per informazioni sulla differenza tra l'utilizzo di ruoli e policy basate su risorse per l'accesso tra account, consulta Differenza tra i ruoli IAM e le policy basate su risorse nella Guida per l'utente di IAM.

Using Service-Linked Roles for Amazon Lex

Amazon Lex utilizza AWS Identity and Access Management (IAM) ruoli collegati ai servizi. Un ruolo collegato ai servizi è un tipo univoco di ruolo IAM collegato direttamente a Amazon Lex. I ruoli collegati ai servizi sono definiti automaticamente da Amazon Lex e includono tutte le autorizzazioni richieste dal servizio per eseguire chiamate agli altri servizi AWS per tuo conto.

Un ruolo collegato ai servizi semplifica la configurazione di Amazon Lex perché non dovrai più aggiungere manualmente le autorizzazioni necessarie. Amazon Lex definisce le autorizzazioni dei relativi ruoli associati ai servizi e, salvo diversamente definito, solo Amazon Lex potrà assumere i propri ruoli. Le autorizzazioni definite includono la policy di trust e la policy delle autorizzazioni. Una policy delle autorizzazioni specifica non può essere collegata a un'altra entità IAM.

È possibile eliminare un ruolo collegato ai servizi solo dopo aver eliminato le risorse correlate. Questa procedura protegge le risorse Amazon Lex poiché impedisce la rimozione involontaria dell'autorizzazione ad accedere alle risorse. Service-Linked Roles Permissions for Amazon Lex

Amazon Lex utilizza due ruoli collegati ai servizi:

• AWSServiceRoleForLexBots – Amazon Lex uses this service-linked role to invoke Amazon Polly to synthesize speech responses for your bot, to call Amazon Comprehend for sentiment analyisis, and optionally Amazon Kendra for searching indexes. • AWSServiceRoleForLexChannels – Amazon Lex uses this service-linked role to post text to your bot when managing channels.

Per consentire a un'entità IAM, ad esempio un utente, un gruppo o un ruolo, di creare, modificare o eliminare un ruolo collegato ai servizi, devi configurare le autorizzazioni. Per ulteriori informazioni, consultare Autorizzazioni del ruolo collegato ai servizi nella Guida per l'utente di IAM. Creating a Service-Linked Role for Amazon Lex

Non è necessario creare manualmente un ruolo collegato ai servizi. Quando crei un bot, un canale bot o un intento di ricerca Amazon Kendra in AWS Management Console, Amazon Lex crea automaticamente il ruolo collegato ai servizi.

Se elimini questo ruolo collegato ai servizi e quindi devi ricrearlo di nuovo, puoi utilizzare lo stesso processo per ricreare il ruolo nel tuo account. Quando crei un nuovo bot, un'associazione di canali o un intento di ricerca Amazon Kendra, Amazon Lex crea nuovamente il ruolo collegato ai servizi.

È inoltre possibile utilizzare l'AWS CLI per creare un ruolo collegato ai servizi con il caso d'uso AWSServiceRoleForLexBots. Nell'AWS CLI crea un ruolo collegato ai servizi con il nome di servizio Amazon Lex. Per ulteriori informazioni, vedi Step 1: Create a Service-Linked Role (AWS CLI) (p. 111). Se elimini il ruolo collegato ai servizi, puoi utilizzare lo stesso processo per crearlo nuovamente. Editing a Service-Linked Role for Amazon Lex

Amazon Lex non permette di modificare i ruoli collegati ai servizi Amazon Lex. Dopo aver creato un ruolo collegato ai servizi, non è possibile modificare il relativo ruolo perché varie entità possono farvi riferimento. Puoi tuttavia modificare la descrizione del ruolo utilizzando IAM. Per ulteriori informazioni, consulta Modifica di un ruolo collegato ai servizi in Guida per l'utente di IAM.

245 Amazon Lex Guida per gli sviluppatori Deleting a Service-Linked Role for Amazon Lex

Deleting a Service-Linked Role for Amazon Lex

Se non è più necessario utilizzare una caratteristica o un servizio che richiede un ruolo collegato ai servizi, ti consigliamo di eliminare quel ruolo. In questo modo non sarà più presente un'entità non utilizzata che non viene monitorata e gestita attivamente. Tuttavia, è necessario effettuare la pulizia delle risorse associate al ruolo collegato ai servizi prima di poterlo eliminare manualmente. Note

Se il servizio Amazon Lex utilizza tale ruolo quando tenti di eliminare le risorse, è possibile che l'eliminazione non abbia esito positivo. In questo caso, attendi alcuni minuti e quindi ripeti l'operazione.

Per eliminare le risorse Amazon Lex utilizzate dai ruoli collegati ai servizi:

1. Elimina tutti i canali bot che stai usando. 2. Elimina eventuali bot nel tuo account.

To manually delete the service-linked role using IAM

Utilizza la console IAM, l'AWS CLI o l'API AWS per eliminare i ruoli collegati ai servizi Amazon Lex. Per ulteriori dettagli, consulta Eliminazione di un ruolo collegato ai servizi nella Guida per l'utente di IAM. Supported Regions for Amazon Lex Service-Linked Roles

Amazon Lex supporta l'utilizzo di ruoli collegati ai servizi in tutte le regioni in cui il servizio è disponibile. Per ulteriori informazioni, vedi Amazon Lex endpoints and quotas.

Monitoraggio in Amazon Lex

Il monitoraggio è importante per assicurare l'affidabilità, la disponibilità e le prestazioni dei chatbot di Amazon Lex. Questo argomento descrive come utilizzare Amazon CloudWatch Logs e AWS CloudTrail per monitorare Amazon Lex e descrive il runtime di Amazon Lex nonché i parametri di associazione del canale.

Argomenti • Monitoraggio di Amazon Lex con Amazon CloudWatch (p. 246) • Monitoraggio di chiamate API di Amazon Lex con log di AWS CloudTrail (p. 254)

Monitoraggio di Amazon Lex con Amazon CloudWatch

Per monitorare lo stato dei bot di Amazon Lex, puoi utilizzare Amazon CloudWatch. Con CloudWatch, puoi ottenere parametri per singole operazioni Amazon Lex o operazioni Amazon Lex globali per il tuo account. Puoi anche configurare allarmi di CloudWatch per ricevere una notifica quando uno o più parametri superano una soglia che hai definito. Ad esempio, puoi monitorare il numero di richieste effettuate a un bot in un determinato periodo di tempo, visualizzare la latenza delle richieste riuscite o attivare un allarme quando gli errori superano una soglia. CloudWatch Parametri per Amazon Lex

Per ottenere i parametri per le operazioni di Amazon Lex, devi specificare le seguenti informazioni:

246 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

• La dimensione del parametro. Una dimensione è un set di coppie nome-valore utilizzate per identificare un parametro. Amazon Lex include tre dimensioni: • BotAlias, BotName, Operation • BotAlias, BotName, InputMode, Operation • BotName, BotVersion, InputMode, Operation • Il nome parametro, ad esempio MissedUtteranceCount o RuntimeRequestCount.

Puoi ottenere i parametri per Amazon Lex con la AWS Management Console, l'AWS CLI o l'API di CloudWatch. Puoi utilizzare l'API di CloudWatch mediante uno dei kit SDK (Software Development Kit) di Amazon AWS o gli strumenti dell'API di CloudWatch. La console di Amazon Lex visualizza i grafici in base ai dati non elaborati dell'API di CloudWatch.

Per monitorare CloudWatch con Amazon Lex, devi disporre delle autorizzazioni di CloudWatch appropriate. Per ulteriori informazioni, consulta Autenticazione e controllo degli accessi per Amazon CloudWatch nella Guida per Amazon CloudWatch l'utente di . Visualizzazione dei parametri Amazon Lex

Visualizza Amazon Lex i parametri utilizzando la Amazon Lex console o la CloudWatch console .

Per visualizzare i parametri (console Amazon Lex)

1. Accedi alla AWS Management Console e apri la console Amazon Lex all'indirizzo https:// console.aws.amazon.com/lex/. 2. Dall'elenco di bot, scegli quello di cui intendi visualizzare i parametri. 3. Selezionare Monitoring (Monitoraggio). I parametri sono visualizzati nei grafici.

Per visualizzare i parametri (console CloudWatch)

1. Accedere alla AWS Management Console e aprire la console CloudWatch all'indirizzo https:// console.aws.amazon.com/cloudwatch/. 2. Seleziona Metrics (Parametri), All Metrics (Tutti i parametri), quindi AWS/Lex. 3. Scegliere la dimensione, scegliere un nome parametro, quindi scegliere Add to graph (Aggiungi al grafico). 4. Seleziona un valore per l'intervallo di date. Il numero di parametri per l'intervallo di date selezionato è visualizzato nel grafico.

Creazione di un allarme

Un CloudWatch allarme controlla un singolo parametro per un periodo di tempo specificato ed esegue una o più operazioni: l'invio di una notifica a un Amazon Simple Notification Service Amazon SNS argomento o a una Auto Scaling policy (). L'operazione o le operazioni sono basate sul valore del parametro relativo a una determinata soglia per un certo numero di periodi specificati. CloudWatch può anche inviare un Amazon SNS messaggio quando lo stato dell'allarme cambia.

CloudWatchGli allarmi di richiamano operazioni solo quando lo stato cambia e persiste per il periodo specificato.

Per impostare un allarme

1. Accedere alla AWS Management Console e aprire la console CloudWatch all'indirizzo https:// console.aws.amazon.com/cloudwatch/. 2. Seleziona Alarms (Allarmi), quindi Create Alarm (Crea allarme).

247 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

3. Seleziona AWS/Lex Metrics (Parametri AWS/Lex), quindi un parametro. 4. In Time Range (Intervallo di tempo), scegli un intervallo di tempo durante il quale eseguire il monitoraggio, quindi scegli Next (Successivo). 5. Immettere un Name (Nome) e una Description (Descrizione). 6. Per Whenever (Ogni volta), scegli >= e digita un valore massimo. 7. Se desideri che CloudWatch invii un'e-mail quando viene raggiunto lo stato dell'allarme, nella sezione Actions (Operazioni), per Whenever this alarm (Ogni volta che lo stato di questo allarme), scegli State is ALARM (Stato è ALLARME). Per Send notification to (Invia notifica a), scegli un elenco di indirizzi o New list (Nuovo elenco) e crea un nuovo elenco di indirizzi. 8. Visualizza un'anteprima dell'allarme nella sezione Alarm Preview (Anteprima allarme). Se sei soddisfatto dell'allarme, scegli Create Alarm (Crea allarme).

Parametri CloudWatch per il runtime Amazon Lex

Nella tabella seguente sono descritti i parametri di runtime di Amazon Lex.

Parametro Descrizione

KendraIndexAccessError Il numero di volte che non Amazon Lex è stato in grado di accedere Amazon Kendra all'indice.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

KendraLatency La quantità di tempo necessaria Amazon Kendra per rispondere a una richiesta da AMAZON.KendraSearchIntent.

Dimensioni valide per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotVersion, Operation, InputMode • BotName, BotAlias, Operation, InputMode

Dimensioni valide per l'operazione PostText:

• BotName, BotVersion, Operation • BotName, BotAlias, Operation

Unità: millisecondi

KendraSuccess Il numero di richieste riuscite da AMAZON.KendraSearchIntent Amazon Kendra all'indice .

Dimensioni valide per PostContent l'operazione con Text o Speech InputMode:

248 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

Parametro Descrizione • BotName, BotVersion, Operation, InputMode • BotName, BotAlias, Operation, InputMode

Dimensioni valide per l'operazione PostText:

• BotName, BotVersion, Operation • BotName, BotAlias, Operation

Unità: numero

KendraSystemErrors Il numero di volte che non Amazon Lex è stato in grado di eseguire query Amazon Kendra sull'indice.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

KendraThrottledEvents Il numero di volte in cui le richieste sono state Amazon Kendra limitate da AMAZON.KendraSearchIntent.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

MissedUtteranceCount Il numero di enunciazioni non riconosciute nel periodo specificato.

Dimensioni valide per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotVersion, Operation, InputMode • BotName, BotAlias, Operation, InputMode

Dimensioni valide per l'operazione PostText:

• BotName, BotVersion, Operation • BotName, BotAlias, Operation

249 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

Parametro Descrizione

RuntimeInvalidLambdaResponsesIl numero di AWS Lambdarisposte Lambda() non valide nel periodo specificato.

Dimensione valida per PostContentl'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

RuntimeLambdaErrors Il numero di errori di runtime di Lambda nel periodo specificato.

Dimensione valida per l'operazione PostContent con Text Speech o InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

RuntimePollyErrors Il numero di risposte Amazon Polly non valide nel periodo specificato.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

RuntimeRequestCount Il numero di richieste di runtime nel periodo specificato.

Dimensioni valide per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotVersion, Operation, InputMode • BotName, BotAlias, Operation, InputMode

Dimensioni valide per l'operazione PostText:

• BotName, BotVersion, Operation • BotName, BotAlias, Operation

Unità: numero

250 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

Parametro Descrizione

RuntimeSuccessfulRequestLatencyLa latenza per le richieste eseguite correttamente tra il momento in cui la richiesta è stata effettuata e quello in cui la risposta è stata generata.

Dimensioni valide per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotVersion, Operation, InputMode • BotName, BotAlias, Operation, InputMode

Dimensioni valide per l'operazione PostText:

• BotName, BotVersion, Operation • BotName, BotAlias, Operation

Unità: millisecondi

RuntimeSystemErrors Il numero di errori di sistema nel periodo specificato. L'intervallo di codici di risposta per un errore di sistema è compreso tra 500 e 599.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

RuntimeThrottledEvents Il numero di richieste sottoposte a throttling. Amazon Lex sottopone a throttling una richiesta quando riceve più richieste del limite di transazioni per secondo impostato per il tuo account. Se il limite impostato per il tuo account viene superato frequentemente, puoi richiedere un aumento del limite. Per richiedere un aumento, consulta Service Limits per AWS.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

251 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

Parametro Descrizione

RuntimeUserErrors Il numero di errori utente nel periodo specificato. L'intervallo di codici di risposta per un errore utente è compreso tra 400 e 499.

Dimensione valida per PostContent l'operazione con Text o Speech InputMode:

• BotName, BotAlias, Operation, InputMode

Dimensione valida per l'operazione PostText:

• BotName, BotAlias, Operation

Unità: numero

I parametri di runtime di Amazon Lex utilizzano lo spazio dei nomi AWS/Lex e forniscono i parametri nelle seguenti dimensioni. Puoi raggruppare i parametri per dimensioni nella console CloudWatch:

Dimensione Descrizione

BotName, BotAlias, Raggruppa i parametri per alias del bot, nome del bot, operazione Operation, InputMode (PostContent) e tipo di input (testo o voce).

BotName, BotVersion, Raggruppa i parametri per nome di bot, versione del bot, operazione Operation, InputMode (PostContent) e tipo di input (testo o voce).

BotName, BotVersion, Raggruppa i parametri per nome di bot, versione dei bot e operazione, Operation PostText.

BotName, BotAlias, Raggruppa i parametri per nome di bot, alias del bot e operazione, Operation PostText.

Parametri di CloudWatch per le associazioni di canale di Amazon Lex

Un'associazione di canale è l'associazione tra Amazon Lex e un canale di messaggistica, ad esempio Facebook. Nella tabella seguente sono descritti i parametri per le associazioni di canale per Amazon Lex.

Parametro Descrizione

BotChannelAuthErrors Il numero di errori di autenticazione restituiti dal canale di messaggistica nel periodo di tempo specificato. Un errore di autenticazione indica che il token segreto fornito durante la creazione del canale non è valido o è scaduto.

BotChannelConfigurationErrorsIl numero di errori di configurazione nel periodo specificato. Un errore di configurazione indica che una o più voci di configurazione per il canale non sono valide.

BotChannelInboundThrottledEventsIl numero di volte che i messaggi inviati dal canale di messaggistica sono stati sottoposti a throttling da Amazon Lex nel periodo specificato.

252 Amazon Lex Guida per gli sviluppatori Monitoraggio di Amazon Lex con CloudWatch

Parametro Descrizione

BotChannelOutboundThrottledEventsIl numero di volte che gli eventi in uscita da Amazon Lex al canale di messaggistica sono stati sottoposti a throttling nel periodo di tempo specificato.

BotChannelRequestCount Il numero di richieste effettuate su un canale nel periodo di tempo specificato.

BotChannelResponseCardErrorsIl numero di volte che Amazon Lex non è riuscito a pubblicare schede di risposta nel periodo specificato.

BotChannelSystemErrors Il numero di errori interni che si sono verificati in Amazon Lex per un canale nel periodo specificato.

I parametri per le associazioni di canale per Amazon Lex; utilizzano lo spazio dei nomi AWS/Lex e forniscono parametri per la seguente dimensione. Puoi raggruppare i parametri per dimensioni nella console CloudWatch:

Dimensione Descrizione

BotAlias, Raggruppa i parametri per alias del bot, nome del canale, nome del bot e BotChannelName, origine del traffico. BotName, Source

CloudWatchParametri per i log delle conversazioni

Amazon Lex utilizza i seguenti parametri per registrare le conversazioni:

Parametro Descrizione

ConversationLogsAudioDeliverySuccess Il numero di log audio consegnati correttamente al bucket S3 nel periodo di tempo specificato.

Unità: numero

ConversationLogsAudioDeliveryFailure Il numero di log audio che non è stato possibile consegnare al bucket S3 nel periodo di tempo specificato. Un errore di consegna indica un errore con le risorse configurate per i log delle conversazioni. Gli errori possono includere autorizzazioni IAM insufficienti, una chiave AWS KMS inaccessibile o un bucket S3 inaccessibile.

Unità: numero

ConversationLogsTextDeliverySuccess Il numero di log di testo consegnati correttamente a CloudWatch Logs nel periodo di tempo specificato.

Unità: numero

ConversationLogsTextDeliveryFailure Il numero di log di testo che non è stato possibile consegnare a CloudWatch Logs nel periodo di tempo specificato. Un errore di consegna indica un errore con le risorse configurate per i log

253 Amazon Lex Guida per gli sviluppatori Registrazione di chiamate dell'API di Amazon Lex con AWS CloudTrail

Parametro Descrizione delle conversazioni. Gli errori possono includere autorizzazioni IAM insufficienti, una chiave AWS KMS inaccessibile o un gruppo di log CloudWatch Logs inaccessibile.

Unità: numero

I parametri dei log delle conversazioni di Amazon Lex utilizzano lo spazio dei nomi AWS/Lex e forniscono i parametri per le dimensioni riportate di seguito. Puoi raggruppare i parametri per dimensione nella console CloudWatch.

Dimensione Descrizione

BotAlias Raggruppa i parametri in base all'alias del bot.

BotName Raggruppa i parametri in base al nome del bot.

BotVersion Raggruppa i parametri in base alla versione del bot.

Monitoraggio di chiamate API di Amazon Lex con log di AWS CloudTrail

Amazon Lex è integrato con AWS CloudTrail, un servizio che offre un record delle operazioni eseguite da un utente, un ruolo o un AWS servizio in Amazon Lex. CloudTrail acquisisce un sottoinsieme di chiamate API per Amazon Lex come eventi, incluse le chiamate dalla Amazon Lex console e le chiamate dal codice alle Amazon Lex APIs . Se crei un trail, puoi abilitare la distribuzione continua di eventi CloudTrail in un bucket Amazon S3 includendo eventi per Amazon Lex. Se non configuri un trail, è comunque possibile visualizzare gli eventi più recenti nella console di CloudTrail in Event history (Cronologia eventi). Le informazioni raccolte da CloudTrail permettono di determinare la richiesta effettuata a Amazon Lex, l'indirizzo IP da cui è stata effettuata la richiesta, l'autore della richiesta, il momento in cui è stata effettuata e altri dettagli.

Per ulteriori informazioni su CloudTrail, incluse le modalità di configurazione e abilitazione, consulta la AWS CloudTrail User Guide. Amazon Lex Informazioni di in CloudTrail

CloudTrail è abilitato sull'account AWS al momento della sua creazione. Quando si verifica un'attività di eventi supportata in Amazon Lex, l'attività viene registrata in un evento CloudTrail insieme ad altri eventi del servizio AWS in Event history (Cronologia eventi). È possibile visualizzare, cercare e scaricare gli eventi recenti nell'account AWS. Per ulteriori informazioni, consulta Visualizzazione di eventi mediante la cronologia eventi di CloudTrail .

Per una registrazione continua degli eventi nell'account AWS che includa eventi per Amazon Lex, crea un trail. Un CloudTrailtrailAmazon Simple Storage Service consente a di fornire i file di log in un bucket Amazon S3 (). Per impostazione predefinita, quando crei un trail nella console , il trail si applica a tutti i parametri AWS. Il trail registra gli eventi di tutti i Regions nella AWS partizione e distribuisce i file di log nel bucket S3 specificato. Inoltre, puoi configurare altri AWS servizi per analizzare con maggiore dettaglio e utilizzare i dati raccolti nei CloudTrail log . Per ulteriori informazioni, consulta:

• Panoramica della creazione di un trail

254 Amazon Lex Guida per gli sviluppatori Registrazione di chiamate dell'API di Amazon Lex con AWS CloudTrail

• CloudTrail Servizi e integrazioni supportati • Configurazione delle notifiche Amazon SNS per CloudTrail • Ricezione di file CloudTrail di log da più regioni e Ricezione di file di CloudTrail log da più account

Amazon Lex supporta la registrazione delle seguenti operazioni come eventi nei file CloudTrail di log di :

• CreateBotVersion (p. 269) • CreateIntentVersion (p. 274) • CreateSlotTypeVersion (p. 280) • DeleteBot (p. 284) • DeleteBotAlias (p. 286) • DeleteBotChannelAssociation (p. 288) • DeleteBotVersion (p. 290) • DeleteIntent (p. 292) • DeleteIntentVersion (p. 294) • DeleteSlotType (p. 296) • DeleteSlotTypeVersion (p. 298) • DeleteUtterances (p. 300) • GetBot (p. 302) • GetBotAlias (p. 307) • GetBotAliases (p. 310) • GetBotChannelAssociation (p. 313) • GetBotChannelAssociations (p. 317) • GetBots (p. 320) • GetBotVersions (p. 323) • GetBuiltinIntent (p. 326) • GetBuiltinIntents (p. 328) • GetBuiltinSlotTypes (p. 330) • GetSlotTypeVersions (p. 364) • GetUtterancesView (p. 367) • PutBot (p. 372) • PutBotAlias (p. 383) • PutIntent (p. 388) • PutSlotType (p. 400)

Ogni evento o voce di log contiene informazioni sull'utente che ha generato la richiesta. Queste informazioni consentono di determinare quanto segue:

• Se la richiesta è stata effettuata con le credenziali utente IAM o radice • Se la richiesta è stata effettuata con le credenziali di sicurezza temporanee per un ruolo o un utente federato • Se la richiesta è stata effettuata da un altro servizio AWS

Per ulteriori informazioni, consulta Elemento CloudTrail userIdentity.

Per informazioni sulle operazioni di Amazon Lex registrate nei log di CloudTrail, consulta la pagina relativa al servizio di costruzione di modelli di Amazon Lex. Ad esempio, le chiamate alle operazioni PutBot (p. 372), GetBot (p. 302) e DeleteBot (p. 284) generano voci nel log di CloudTrail. Le operazioni

255 Amazon Lex Guida per gli sviluppatori Registrazione di chiamate dell'API di Amazon Lex con AWS CloudTrail documentate nelle sezioni relative al servizio di runtime di Amazon Lex, a PostContent (p. 425) e a PostText (p. 434), non vengono registrate. Esempio: Voci di file di log Amazon Lex

Un trail è una configurazione che consente la distribuzione di eventi come file di log in un bucket S3 specificato. I file di CloudTrail log di contengono una o più voci di log. Un evento rappresenta una singola richiesta da qualsiasi sorgente e include informazioni sull'operazione richiesta, la data e l'ora dell'operazione, i parametri della richiesta e così via. I file di log di CloudTrail non sono uno stack trace ordinato delle chiamate API pubbliche, pertanto queste non vengono visualizzate in un ordine specifico.

La voce CloudTrail di log di esempio seguente mostra il risultato di una chiamata PutBot all'operazione .

{ "eventVersion": "1.05", "userIdentity": { "type": "AssumedRole | FederatedUser | IAMUser | Root | SAMLUser | WebIdentityUser", "principalId": "principal ID", "arn": "ARN", "accountId": "account ID", "accessKeyId": "access key ID", "userName": "user name" }, "eventTime": "timestamp", "eventSource": "lex.amazonaws.com", "eventName": "PutBot", "awsRegion": "region", "sourceIPAddress": "source IP address", "userAgent": "user agent", "requestParameters": { "name": "CloudTrailBot", "intents": [ { "intentVersion": "11", "intentName": "TestCloudTrail" } ], "voiceId": "Salli", "childDirected": false, "locale": "en-US", "idleSessionTTLInSeconds": 500, "processBehavior": "BUILD", "description": "CloudTrail test bot", "clarificationPrompt": { "messages": [ { "contentType": "PlainText", "content": "I didn't understand you. wWat would you like to do?" } ], "maxAttempts": 2 }, "abortStatement": { "messages": [ { "contentType": "PlainText", "content": "Sorry. I'm not able to assist at this time." } ] } }, "responseElements": {

256 Amazon Lex Guida per gli sviluppatori Convalida della conformità

"voiceId": "Salli", "locale": "en-US", "childDirected": false, "abortStatement": { "messages": [ { "contentType": "PlainText", "content": "Sorry. I'm not able to assist at this time." } ] }, "status": "BUILDING", "createdDate": "timestamp", "lastUpdatedDate": "timestamp", "idleSessionTTLInSeconds": 500, "intents": [ { "intentVersion": "11", "intentName": "TestCloudTrail" } ], "clarificationPrompt": { "messages": [ { "contentType": "PlainText", "content": "I didn't understand you. What would you like to do?" } ], "maxAttempts": 2 }, "version": "$LATEST", "description": "CloudTrail test bot", "checksum": "checksum", "name": "CloudTrailBot" }, "requestID": "request ID", "eventID": "event ID", "eventType": "AwsApiCall", "recipientAccountId": "account ID" } }

Convalida della conformità per Amazon Lex

Revisori di terze parti valutano la sicurezza e la conformità di Amazon Lex come parte di più programmi di conformità di AWS. Amazon Lex è un servizio idoneo per HIPAA. È conforme a PCI, SOC e ISO. Puoi scaricare i report di audit di terze parti utilizzando AWS Artifact. Per ulteriori informazioni, consulta Download dei rapporti in AWS Artifact.

La responsabilità di conformità durante l'utilizzo di Amazon Lex è determinata dalla riservatezza dei dati, dagli obiettivi di conformità dell'azienda e dalle leggi e normative applicabili. Se l'utilizzo di Amazon Lex è soggetto a conformità con standard quali PCI, AWS fornisce le seguenti risorse utili:

• Guide Quick Start su sicurezza e conformità Guide alla – distribuzione che illustrano considerazioni relative all'architettura e forniscono procedure per la distribuzione di ambienti di base incentrati sulla sicurezza e sulla conformità su AWS • Whitepaper sull'architettura per compliance e sicurezza HIPAA: questo whitepaper descrive in che modo le aziende possono utilizzare AWS per creare applicazioni conformi ai requisiti HIPAA.

257 Amazon Lex Guida per gli sviluppatori Resilienza

• AWS Risorse per la conformità – Una raccolta di cartelle di lavoro e guide che potrebbero essere utili per industria e ubicazione • AWS Config – Questo servizio valuta il livello di conformità delle configurazioni delle risorse con pratiche interne, linee guida e regolamenti industriali • AWS Security Hub – Una panoramica completa dello stato di sicurezza all'interno di AWS che consente di verificare la conformità con gli standard industriali e le best practice di sicurezza

Per un elenco di servizi AWS nell'ambito di programmi di conformità specifici, consulta Servizi AWS coperti dal programma di conformità. Per informazioni generali, consulta Programmi per la conformità di AWS.

Resilienza in Amazon Lex

L'infrastruttura AWS globale è basata su AWS regioni e zone di disponibilità. AWS Le regioni forniscono più zone di disponibilità fisicamente separate e isolate, che sono connesse con reti altamente ridondanti, a bassa latenza e throughput elevato. Con le zone di disponibilità, è possibile progettare e gestire le applicazioni e database che eseguono il failover automatico tra zone di disponibilità senza interruzioni. Le zone di disponibilità sono più disponibili, tolleranti ai guasti e scalabili rispetto alle infrastrutture a data center singolo o multiplo.

Per ulteriori informazioni sulle regioni e le zone di disponibilità AWS, consulta Infrastruttura globale di AWS.

Oltre all'infrastruttura AWS globale , Amazon Lex offre diverse caratteristiche per supportare la resilienza dei dati e le esigenze di backup.

Sicurezza dell'infrastruttura in Amazon Lex

In qualità di servizio gestito, Amazon Lex è protetto dalle procedure di sicurezza di rete AWS globali di descritte nel whitepaper Amazon Web Services: panoramica dei processi di sicurezza.

Utilizza le chiamate all’API pubblicate di AWS per accedere a Amazon Lex tramite la rete. I client devono supportare Transport Layer Security (TLS) 1.0. È consigliabile TLS 1.2 o versioni successive. I client devono inoltre supportare le suite di cifratura con PFS (Perfect Forward Secrecy), ad esempio Ephemeral Diffie-Hellman (DHE) o Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). La maggior parte dei sistemi moderni come Java 7 e versioni successive, supporta tali modalità. Inoltre, le richieste devono essere firmate utilizzando un ID chiave di accesso e una chiave di accesso segreta che è associata a un'entità IAM In alternativa, puoi utilizzare AWS Security Token Service (AWS STS) per generare credenziali di sicurezza temporanee per firmare le richieste.

Puoi chiamare queste operazioni API da qualsiasi posizione di rete, ma Amazon Lex supporta le policy di accesso basate sulle risorse, che possono includere limitazioni in base all'indirizzo IP di origine. È inoltre possibile utilizzare Amazon Lex le policy per controllare l'accesso da endpoint Amazon Virtual Private Cloud (Amazon VPC) specifici o VPCsda . Di fatto, questo isola l'accesso di rete a una determinata Amazon Lex risorsa solo dal VPC specifico all'interno della AWS rete.

258 Amazon Lex Guida per gli sviluppatori Supported Regions

Guidelines and Quotas in Amazon Lex

In queste sezioni vengono illustrate le linee guida e le quote relative all'utilizzo di Amazon Lex.

Argomenti • Supported Regions (p. 259) • General Guidelines (p. 259) • Quotas (p. 261)

Supported Regions

Per un elenco di AWS Regioni dove Amazon Lex è disponibile, vedere Regioni e endpoint AWS nella Amazon Web Services General Reference.

General Guidelines

In questa sezione vengono illustrate le linee guida generali relative all'utilizzo di Amazon Lex.

• Signing requests – All Amazon Lex model-building and runtime API operations in the Riferimento alle API (p. 266) use signature V4 for authenticating requests. For more information about authenticating requests, see Signature Version 4 Signing Process in the Riferimento generale Amazon Web Services.

For PostContent (p. 425), Amazon Lex uses the unsigned payload option described in Signature Calculations for the Authorization Header: Transferring Payload in a Single Chunk (AWS Signature Version 4) in the Amazon Simple Storage Service (S3) API Reference.

When you use the unsigned payload option, don't include the hash of the payload in the canonical request. Instead, you use the literal string "UNSIGNED-PAYLOAD" as the hash of the payload. Also include a header with the name x-amz-content-sha256 and the value UNSIGNED-PAYLOAD in the PostContent request.

• Note the following about how Amazon Lex captures slot values from user utterances:

Amazon Lex uses the enumeration values you provide in a slot type definition to train its machine learning models. Suppose you define an intent called GetPredictionIntent with the following sample utterance:

"Tell me the prediction for {Sign}"

259 Amazon Lex Guida per gli sviluppatori General Guidelines

Where {Sign} is a slot of custom type ZodiacSign. It has 12 enumeration values, Aries through Pisces. From the user utterance "Tell me the prediction for ..." Amazon Lex understands what follows is a zodiac sign.

When the valueSelectionStrategy field is set to ORIGINAL_VALUE using the PutSlotType (p. 400) operation, or if Expand values is selected in the console, if the user says "Tell me the prediction for earth", Amazon Lex infers that "earth" is a ZodiacSign and passes it to your client application or Lambda functions. You must check that slot values have valid values before using them in your fulfillment activity.

If you set the valueSelectionStrategy field to TOP_RESOLUTION using the PutSlotType (p. 400) operation, or if Restrict to slot values and synonyms is selected in the console, the values that are returned are limited to the values that you defined for the slot type. For example, if the user says "Tell me the prediction for earth" the value would not be recognized because it is not one of the values defined for the slot type. When you define synonyms for slot values, they are recognized the same as a slot value, however, the slot value is returned instead of the synonym.

When Amazon Lex calls a Lambda function or returns the result of a speech interaction with your client application, the case of the slot values is not guaranteed. For example, if you are eliciting values for the AMAZON.Movie built-in slot type, and a user says or types "Gone with the wind," Amazon Lex may return "Gone with the Wind," "gone with the wind," or "Gone With The Wind." In text interactions, the case of the slot values matches the text entered or the slot value, depending on the value of the valueResolutionStrategy field.

• Amazon Lex does not support the AMAZON.LITERAL built-in slot type that the Alexa Skills Kit supports. However, Amazon Lex supports creating custom slot types that you can use to implement this functionality. As mentioned in the previous bullet, you can capture values outside the custom slot type definition. Add more and diverse enumeration values to boost the automatic speech recognition (ASR) and natural language understanding (NLU) accuracy.

• The AMAZON.DATE and AMAZON.TIME built-in slot types capture both absolute and relative dates and times. Relative dates and times are resolved in the region where Amazon Lex is processing the request.

For the AMAZON.TIME built-in slot type, if the user doesn't specify that a time is before or after noon, the time is ambiguous and Amazon Lex will prompt the user again. We recommend prompts that elicit an absolute time. For example, use a prompt such as "When do you want your pizza delivered? You can say 6 PM or 6 in the evening."

• Providing confusable training data in your bot reduces Amazon Lex's ability to understand user input. Consider these examples:

Suppose you have two intents (OrderPizza and OrderDrink) in your bot and both are configured with an "I want to order" utterance. This utterance does not map to a specific intent that Amazon Lex can

260 Amazon Lex Guida per gli sviluppatori Quotas

learn from while building the language model for the bot at build time. As a result, when a user inputs this utterance at runtime, Amazon Lex can't pick an intent with a high degree of confidence.

Consider another example where you define a custom intent for getting a confirmation from the user (for example, MyCustomConfirmationIntent) and configure the intent with the utterances "Yes" and "No." Note that Amazon Lex also has a language model for understanding user confirmations. This can create conflicting situation. When the user responds with a "Yes," does this mean that this is a confirmation for the ongoing intent or that the user is requesting the custom intent that you created?

In general, the sample utterances you provide should map to a specific intent and, optionally, to specific slot values.

• The runtime API operations PostContent (p. 425) and PostText (p. 434) take a user ID as the required parameter. Developers can set this to any value that meets the constraints described in the API. We recommend you don't use this parameter to send any confidential information such as user logins, emails, or social security numbers. This ID is primarily used to uniquely identify conversation with a bot (there can be multiple users ordering pizza).

• If your client application uses Amazon Cognito for authentication, you might use the Amazon Cognito user ID as Amazon Lex user ID. Note that any Lambda function configured for your bot must have its own authentication mechanism to identify the user on whose behalf Amazon Lex is invoking the Lambda function.

• We encourage you to define an intent that captures a user's intention to discontinue the conversation. For example, you can define an intent (NothingIntent) with sample utterances ("I don't want anything", "exit", "bye bye"), no slots, and no Lambda function configured as a code hook. This lets users gracefully close a conversation.

Quotas

In questa sezione vengono descritte le quote attuali di Amazon Lex Tali quote sono raggruppate per categorie.

Argomenti • Runtime Service Quotas (p. 261) • Model Building Quotas (p. 262)

Runtime Service Quotas

Oltre alle quote descritte nella documentazione di riferimento dell'API, tieni presente quanto segue: API Quotas

• Speech input to the PostContent (p. 425) operation can be up to 15 seconds long.

261 Amazon Lex Guida per gli sviluppatori Model Building Quotas

• In both the runtime API operations PostContent (p. 425) and PostText (p. 434), the input text size can be up to 1024 Unicode characters.

• The maximum size of PostContent headers is 16 KB. The maximum size of request and session headers combined is 12 KB.

• The maximum input size to a Lambda function is 12 KB. The maximum output size is 25 KB, of which 12 KB can be session attributes.

Using the $LATEST version

• The $LATEST version of your bot should only be used for manual testing. Amazon Lex limits the number of runtime requests that you can make to the $LATEST version of the bot.

• When you update the $LATEST version of the bot, Amazon Lex terminates any in-progress conversations for any client application using the $LATEST version of the bot. Generally, you should not use the $LATEST version of a bot in production because $LATEST version can be updated. You should publish a version and use it instead.

• When you update an alias, Amazon Lex takes a few minutes to pick up the change. When you modify the $LATEST version of the bot, the change is picked up immediately.

Session Timeout

• The session timeout set when the bot was created determines how long the bot retains conversation context, such as current user intent and slot data.

• After a user starts the conversation with your bot and until the session expires, Amazon Lex uses the same bot version, even if you update the bot alias to point to another version.

Model Building Quotas

La costruzione del modello fa riferimento alla creazione e alla gestione dei bot. Ciò include la creazione e la gestione di bot, intenti, tipi di slot, slot e associazioni di canali bot.

Argomenti • Bot Quotas (p. 263) • Intent Quotas (p. 264) • Slot Type Quotas (p. 265)

262 Amazon Lex Guida per gli sviluppatori Model Building Quotas

Bot Quotas

• You configure prompts and statements throughout the model building API. Each of these prompts or statements can have up to five messages and each message can contain from 1 to 1000 UTF-8 characters.

• When using message groups you can define up to five message groups for each message. Each message group can contain a maximum of five messages, and you are limited to 15 messages in all message groups.

• You can define sample utterances for intents and slots. You can use a maximum of 200,000 characters for all utterances.

• Each slot type can define a maximum of 10,000 values and synonyms. Each bot can contain a maximum of 50,000 slot type values and synonyms.

• Bot, alias, and bot channel association names are case insensitive at the time of creation. If you create PizzaBot and then try to create pizzaBot, you will get an error. However, when accessing a resource, the resource names are case sensitive, you must specify PizzaBot and not pizzaBot. These names must be between 2 and 50 ASCII characters.

• The maximum number of versions you can publish for all resource types is 100. Note that there is no versioning for aliases.

• Within a bot, intent names and slot names must be unique, you can't have an intent and a slot by the same name.

• You can create a bot that is configured to support multiple intents. If two intents have a slot by the same name, then the corresponding slot type must be the same.

For example, suppose you create a bot to support two intents (OrderPizza and OrderDrink). If both these intents have the size slot, then the slot type must be the same in both places.

In addition, the sample utterances you provide for a slot in one of the intents applies to a slot with the same name in other intents.

• You can associate a maximum of 100 intents with a bot.

• When you create a bot, you specify a session timeout. The session timeout can be between one minute and one day. The default is five minutes.

• You can create up to five aliases for a bot.

263 Amazon Lex Guida per gli sviluppatori Model Building Quotas

• You can create up to 100 bots per AWS account.

• You cannot create multiple intents that extend from the same built-in intent.

Intent Quotas

• Intent and slot names are case insensitive at the time of creation. That is, if you create OrderPizza intent and then again try to create another orderPizza intent, you will get an error. However, when accessing these resources, the resource names are case sensitive, specify OrderPizza and not orderPizza. These names must be between 1 and 100 ASCII characters.

• An intent can have up to 1,500 sample utterances. A minimum of one sample utterance is required. Each sample utterance can be up to 200 UTF-8 characters long. You can use up to 200,000 characters for all intent and slot utterances in a bot. A sample utterance for an intent: • Can refer to zero or more slot names. • Can refer to a slot name only once.

For example:

I want a pizza I want a {pizzaSize} pizza I want a {pizzaSize} {pizzaTopping} pizza

• Although each intent supports up to 1,500 utterances, if you use fewer utterances Amazon Lex may have a better ability to recognize inputs outside your provided set.

• You can create up to five message groups for each message in an intent. There can be a total of 15 messages in all message groups for a message.

• The console can only create message groups for the conclusionStatement and followUpPrompt messages. You can create message groups for any other message using the Amazon Lex API.

• Each slot can have up to 10 sample utterances. Each sample utterance must refer to the slot name exactly once. For example:

{pizzaSize} please

• Each bot can have a maximum of 200,000 characters for intent and slot utterances combined.

• You cannot provide utterances for intents that extend from built-in intents. For all other intents you must provide at least one sample utterance. Intents contain slots, but the slot level sample utterances are optional.

264 Amazon Lex Guida per gli sviluppatori Model Building Quotas

• Built-in intents • Currently, Amazon Lex does not support slot elicitation for built-in intents. You cannot create Lambda functions to return the ElicitSlot directive in the response with an intent that is derived from built-in intents. For more information, see Formato della risposta (p. 145). • The service does not support adding sample utterances to built-in intents. Similarly, you cannot add or remove slots to built-in intents.

• You can create up to 1,000 intents per AWS account. You can create up to 100 slots in an intent.

Slot Type Quotas

• Slot type names are case insensitive at the time of creation. If you create the PizzaSize slot type and then again try to create the pizzaSize slot type, you will get an error. However, when accessing these resources, the resource names are case sensitive (you must specify PizzaSize and not pizzaSize). Names must be between 1 and 100 ASCII characters.

• A custom slot type you create can have a maximum of 10,000 enumeration values and synonyms. Each value can be up to 140 UTF-8 characters long. The enumeration values and synonyms cannot contain duplicates.

• For a slot type value, where appropriate, specify both upper and lower case. For example, for a slot type called Procedure, if value is MRI, specify both "MRI" and "mri" as values.

• Built-in slot types – Currently, Amazon Lex doesn't support adding enumeration values or synonyms for the built-in slot types.

265 Amazon Lex Guida per gli sviluppatori Actions

Riferimento alle API

Questa sezione fornisce la documentazione per le operazioni API di Amazon Lex. Per un elenco di regioni AWS in cui è disponibile Amazon Lex, consulta Regioni ed endpoint AWS in Riferimenti generali di Amazon Web Services.

Argomenti

• Actions (p. 266) • Data Types (p. 447)

Actions

The following actions are supported by Amazon Lex Model Building Service:

• CreateBotVersion (p. 269) • CreateIntentVersion (p. 274) • CreateSlotTypeVersion (p. 280) • DeleteBot (p. 284) • DeleteBotAlias (p. 286) • DeleteBotChannelAssociation (p. 288) • DeleteBotVersion (p. 290) • DeleteIntent (p. 292) • DeleteIntentVersion (p. 294) • DeleteSlotType (p. 296) • DeleteSlotTypeVersion (p. 298) • DeleteUtterances (p. 300) • GetBot (p. 302) • GetBotAlias (p. 307) • GetBotAliases (p. 310) • GetBotChannelAssociation (p. 313) • GetBotChannelAssociations (p. 317) • GetBots (p. 320) • GetBotVersions (p. 323) • GetBuiltinIntent (p. 326) • GetBuiltinIntents (p. 328) • GetBuiltinSlotTypes (p. 330) • GetExport (p. 332) • GetImport (p. 335) • GetIntent (p. 338) • GetIntents (p. 344) • GetIntentVersions (p. 347) • GetMigration (p. 350) • GetMigrations (p. 354)

266 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• GetSlotType (p. 357) • GetSlotTypes (p. 361) • GetSlotTypeVersions (p. 364) • GetUtterancesView (p. 367) • ListTagsForResource (p. 370) • PutBot (p. 372) • PutBotAlias (p. 383) • PutIntent (p. 388) • PutSlotType (p. 400) • StartImport (p. 406) • StartMigration (p. 410) • TagResource (p. 414) • UntagResource (p. 416)

The following actions are supported by Amazon Lex Runtime Service:

• DeleteSession (p. 418) • GetSession (p. 421) • PostContent (p. 425) • PostText (p. 434) • PutSession (p. 442)

Amazon Lex Model Building Service

The following actions are supported by Amazon Lex Model Building Service:

• CreateBotVersion (p. 269) • CreateIntentVersion (p. 274) • CreateSlotTypeVersion (p. 280) • DeleteBot (p. 284) • DeleteBotAlias (p. 286) • DeleteBotChannelAssociation (p. 288) • DeleteBotVersion (p. 290) • DeleteIntent (p. 292) • DeleteIntentVersion (p. 294) • DeleteSlotType (p. 296) • DeleteSlotTypeVersion (p. 298) • DeleteUtterances (p. 300) • GetBot (p. 302) • GetBotAlias (p. 307) • GetBotAliases (p. 310) • GetBotChannelAssociation (p. 313) • GetBotChannelAssociations (p. 317) • GetBots (p. 320) • GetBotVersions (p. 323) • GetBuiltinIntent (p. 326)

267 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• GetBuiltinIntents (p. 328) • GetBuiltinSlotTypes (p. 330) • GetExport (p. 332) • GetImport (p. 335) • GetIntent (p. 338) • GetIntents (p. 344) • GetIntentVersions (p. 347) • GetMigration (p. 350) • GetMigrations (p. 354) • GetSlotType (p. 357) • GetSlotTypes (p. 361) • GetSlotTypeVersions (p. 364) • GetUtterancesView (p. 367) • ListTagsForResource (p. 370) • PutBot (p. 372) • PutBotAlias (p. 383) • PutIntent (p. 388) • PutSlotType (p. 400) • StartImport (p. 406) • StartMigration (p. 410) • TagResource (p. 414) • UntagResource (p. 416)

268 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

CreateBotVersion Service: Amazon Lex Model Building Service

Creates a new version of the bot based on the $LATEST version. If the $LATEST version of this resource hasn't changed since you created the last version, Amazon Lex doesn't create a new version. It returns the last created version. Note

You can update only the $LATEST version of the bot. You can't update the numbered versions that you create with the CreateBotVersion operation.

When you create the first version of a bot, Amazon Lex sets the version to 1. Subsequent versions increment by 1. For more information, see Controllo delle versioni (p. 136).

This operation requires permission for the lex:CreateBotVersion action. Request Syntax

POST /bots/name/versions HTTP/1.1 Content-type: application/json

{ "checksum": "string" }

URI Request Parameters

The request uses the following URI parameters. name (p. 269)

The name of the bot that you want to create a new version of. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request accepts the following data in JSON format. checksum (p. 269)

Identifies a specific revision of the $LATEST version of the bot. If you specify a checksum and the $LATEST version of the bot has a different checksum, a PreconditionFailedException exception is returned and Amazon Lex doesn't publish a new version. If you don't specify a checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201

269 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Content-type: application/json

{ "abortStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "checksum": "string", "childDirected": boolean, "clarificationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number, "description": "string", "detectSentiment": boolean, "enableModelImprovements": boolean, "failureReason": "string", "idleSessionTTLInSeconds": number, "intents": [ { "intentName": "string", "intentVersion": "string" } ], "lastUpdatedDate": number, "locale": "string", "name": "string", "status": "string", "version": "string", "voiceId": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service. abortStatement (p. 269)

The message that Amazon Lex uses to cancel a conversation. For more information, see PutBot (p. 372).

Type: Statement (p. 491) object checksum (p. 269)

Checksum identifying the version of the bot that was created.

Type: String

270 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service childDirected (p. 269)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to the Children's Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field. By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. By specifying false in the childDirected field, you confirm that your use of Amazon Lex is not related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may not specify a default value for the childDirected field that does not accurately reflect whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in whole or in part, to children under age 13, you must obtain any required verifiable parental consent under COPPA. For information regarding the use of Amazon Lex in connection with websites, programs, or other applications that are directed or targeted, in whole or in part, to children under age 13, see the Amazon Lex FAQ.

Type: Boolean clarificationPrompt (p. 269)

The message that Amazon Lex uses when it doesn't understand the user's request. For more information, see PutBot (p. 372).

Type: Prompt (p. 480) object createdDate (p. 269)

The date when the bot version was created.

Type: Timestamp description (p. 269)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. detectSentiment (p. 269)

Indicates whether utterances entered by the user should be sent to Amazon Comprehend for sentiment analysis.

Type: Boolean enableModelImprovements (p. 269)

Indicates whether the bot uses accuracy improvements. true indicates that the bot is using the improvements, otherwise, false.

Type: Boolean failureReason (p. 269)

If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.

Type: String

271 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service idleSessionTTLInSeconds (p. 269)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. For more information, see PutBot (p. 372).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400. intents (p. 269)

An array of Intent objects. For more information, see PutBot (p. 372).

Type: Array of Intent (p. 466) objects lastUpdatedDate (p. 269)

The date when the $LATEST version of this bot was updated.

Type: Timestamp locale (p. 269)

Specifies the target locale for the bot.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR name (p. 269)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ status (p. 269)

When you send a request to create or update a bot, Amazon Lex sets the status response element to BUILDING. After Amazon Lex builds the bot, it sets status to READY. If Amazon Lex can't build the bot, it sets status to FAILED. Amazon Lex returns the reason for the failure in the failureReason response element.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT version (p. 269)

The version of the bot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ voiceId (p. 269)

The Amazon Polly voice ID that Amazon Lex uses for voice interactions with the user.

Type: String

272 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

273 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

CreateIntentVersion Service: Amazon Lex Model Building Service

Creates a new version of an intent based on the $LATEST version of the intent. If the $LATEST version of this intent hasn't changed since you last updated it, Amazon Lex doesn't create a new version. It returns the last version you created. Note

You can update only the $LATEST version of the intent. You can't update the numbered versions that you create with the CreateIntentVersion operation.

When you create a version of an intent, Amazon Lex sets the version to 1. Subsequent versions increment by 1. For more information, see Controllo delle versioni (p. 136).

This operation requires permissions to perform the lex:CreateIntentVersion action. Request Syntax

POST /intents/name/versions HTTP/1.1 Content-type: application/json

{ "checksum": "string" }

URI Request Parameters

The request uses the following URI parameters. name (p. 274)

The name of the intent that you want to create a new version of. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request accepts the following data in JSON format. checksum (p. 274)

Checksum of the $LATEST version of the intent that should be used to create the new version. If you specify a checksum and the $LATEST version of the intent has a different checksum, Amazon Lex returns a PreconditionFailedException exception and doesn't publish a new version. If you don't specify a checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201

274 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Content-type: application/json

{ "checksum": "string", "conclusionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "confirmationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number, "description": "string", "dialogCodeHook": { "messageVersion": "string", "uri": "string" }, "followUpPrompt": { "prompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } }, "fulfillmentActivity": { "codeHook": { "messageVersion": "string", "uri": "string" }, "type": "string" }, "inputContexts": [ { "name": "string" } ],

275 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"kendraConfiguration": { "kendraIndex": "string", "queryFilterString": "string", "role": "string" }, "lastUpdatedDate": number, "name": "string", "outputContexts": [ { "name": "string", "timeToLiveInSeconds": number, "turnsToLive": number } ], "parentIntentSignature": "string", "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "sampleUtterances": [ "string" ], "slots": [ { "defaultValueSpec": { "defaultValueList": [ { "defaultValue": "string" } ] }, "description": "string", "name": "string", "obfuscationSetting": "string", "priority": number, "responseCard": "string", "sampleUtterances": [ "string" ], "slotConstraint": "string", "slotType": "string", "slotTypeVersion": "string", "valueElicitationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } } ], "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service.

276 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service checksum (p. 274)

Checksum of the intent version created.

Type: String conclusionStatement (p. 274)

After the Lambda function specified in the fulfillmentActivity field fulfills the intent, Amazon Lex conveys this statement to the user.

Type: Statement (p. 491) object confirmationPrompt (p. 274)

If defined, the prompt that Amazon Lex uses to confirm the user's intent before fulfilling it.

Type: Prompt (p. 480) object createdDate (p. 274)

The date that the intent was created.

Type: Timestamp description (p. 274)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. dialogCodeHook (p. 274)

If defined, Amazon Lex invokes this Lambda function for each user input.

Type: CodeHook (p. 459) object followUpPrompt (p. 274)

If defined, Amazon Lex uses this prompt to solicit additional user activity after the intent is fulfilled.

Type: FollowUpPrompt (p. 463) object fulfillmentActivity (p. 274)

Describes how the intent is fulfilled.

Type: FulfillmentActivity (p. 464) object inputContexts (p. 274)

An array of InputContext objects that lists the contexts that must be active for Amazon Lex to choose the intent in a conversation with the user.

Type: Array of InputContext (p. 465) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items. kendraConfiguration (p. 274)

Configuration information, if any, for connecting an Amazon Kendra index with the AMAZON.KendraSearchIntent intent.

Type: KendraConfiguration (p. 469) object

277 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service lastUpdatedDate (p. 274)

The date that the intent was updated.

Type: Timestamp name (p. 274)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ outputContexts (p. 274)

An array of OutputContext objects that lists the contexts that the intent activates when the intent is fulfilled.

Type: Array of OutputContext (p. 479) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. parentIntentSignature (p. 274)

A unique identifier for a built-in intent.

Type: String rejectionStatement (p. 274)

If the user answers "no" to the question defined in confirmationPrompt, Amazon Lex responds with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 491) object sampleUtterances (p. 274)

An array of sample utterances configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200. slots (p. 274)

An array of slot types that defines the information required to fulfill the intent.

Type: Array of Slot (p. 482) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items. version (p. 274)

The version number assigned to the new version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

278 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

279 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

CreateSlotTypeVersion Service: Amazon Lex Model Building Service

Creates a new version of a slot type based on the $LATEST version of the specified slot type. If the $LATEST version of this resource has not changed since the last version that you created, Amazon Lex doesn't create a new version. It returns the last version that you created. Note

You can update only the $LATEST version of a slot type. You can't update the numbered versions that you create with the CreateSlotTypeVersion operation.

When you create a version of a slot type, Amazon Lex sets the version to 1. Subsequent versions increment by 1. For more information, see Controllo delle versioni (p. 136).

This operation requires permissions for the lex:CreateSlotTypeVersion action. Request Syntax

POST /slottypes/name/versions HTTP/1.1 Content-type: application/json

{ "checksum": "string" }

URI Request Parameters

The request uses the following URI parameters. name (p. 280)

The name of the slot type that you want to create a new version for. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request accepts the following data in JSON format. checksum (p. 280)

Checksum for the $LATEST version of the slot type that you want to publish. If you specify a checksum and the $LATEST version of the slot type has a different checksum, Amazon Lex returns a PreconditionFailedException exception and doesn't publish the new version. If you don't specify a checksum, Amazon Lex publishes the $LATEST version.

Type: String

Required: No

Response Syntax

HTTP/1.1 201

280 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Content-type: application/json

{ "checksum": "string", "createdDate": number, "description": "string", "enumerationValues": [ { "synonyms": [ "string" ], "value": "string" } ], "lastUpdatedDate": number, "name": "string", "parentSlotTypeSignature": "string", "slotTypeConfigurations": [ { "regexConfiguration": { "pattern": "string" } } ], "valueSelectionStrategy": "string", "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service. checksum (p. 280)

Checksum of the $LATEST version of the slot type.

Type: String createdDate (p. 280)

The date that the slot type was created.

Type: Timestamp description (p. 280)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. enumerationValues (p. 280)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 462) objects

Array Members: Minimum number of 0 items. Maximum number of 10000 items. lastUpdatedDate (p. 280)

The date that the slot type was updated. When you create a resource, the creation date and last update date are the same.

Type: Timestamp

281 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service name (p. 280)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ parentSlotTypeSignature (p. 280)

The built-in slot type used a the parent of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+ slotTypeConfigurations (p. 280)

Configuration information that extends the parent built-in slot type.

Type: Array of SlotTypeConfiguration (p. 487) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. valueSelectionStrategy (p. 280)

The strategy that Amazon Lex uses to determine the value of the slot. For more information, see PutSlotType (p. 400).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION version (p. 280)

The version assigned to the new slot type version.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

282 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

283 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteBot Service: Amazon Lex Model Building Service

Deletes all versions of the bot, including the $LATEST version. To delete a specific version of the bot, use the DeleteBotVersion (p. 290) operation. The DeleteBot operation doesn't immediately remove the bot schema. Instead, it is marked for deletion and removed later.

Amazon Lex stores utterances indefinitely for improving the ability of your bot to respond to user inputs. These utterances are not removed when the bot is deleted. To remove the utterances, use the DeleteUtterances (p. 300) operation.

If a bot has an alias, you can't delete it. Instead, the DeleteBot operation returns a ResourceInUseException exception that includes a reference to the alias that refers to the bot. To remove the reference to the bot, delete the alias. If you get the same exception again, delete the referring alias until the DeleteBot operation is successful.

This operation requires permissions for the lex:DeleteBot action. Request Syntax

DELETE /bots/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 284)

The name of the bot. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

284 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

285 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteBotAlias Service: Amazon Lex Model Building Service

Deletes an alias for the specified bot.

You can't delete an alias that is used in the association between a bot and a messaging channel. If an alias is used in a channel association, the DeleteBot operation returns a ResourceInUseException exception that includes a reference to the channel association that refers to the bot. You can remove the reference to the alias by deleting the channel association. If you get the same exception again, delete the referring association until the DeleteBotAlias operation is successful. Request Syntax

DELETE /bots/botName/aliases/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botName (p. 286)

The name of the bot that the alias points to.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes name (p. 286)

The name of the alias to delete. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

286 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

287 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteBotChannelAssociation Service: Amazon Lex Model Building Service

Deletes the association between an Amazon Lex bot and a messaging platform.

This operation requires permission for the lex:DeleteBotChannelAssociation action. Request Syntax

DELETE /bots/botName/aliases/aliasName/channels/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. aliasName (p. 288)

An alias that points to the specific version of the Amazon Lex bot to which this association is being made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes botName (p. 288)

The name of the Amazon Lex bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes name (p. 288)

The name of the association. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

288 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

289 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteBotVersion Service: Amazon Lex Model Building Service

Deletes a specific version of a bot. To delete all versions of a bot, use the DeleteBot (p. 284) operation.

This operation requires permissions for the lex:DeleteBotVersion action. Request Syntax

DELETE /bots/name/versions/version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 290)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes version (p. 290)

The version of the bot to delete. You cannot delete the $LATEST version of the bot. To delete the $LATEST version, use the DeleteBot (p. 284) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Required: Yes

Request Body

The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

290 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

291 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteIntent Service: Amazon Lex Model Building Service

Deletes all versions of the intent, including the $LATEST version. To delete a specific version of the intent, use the DeleteIntentVersion (p. 294) operation.

You can delete a version of an intent only if it is not referenced. To delete an intent that is referred to in one or more bots (see Amazon Lex: come funziona (p. 3)), you must remove those references first. Note

If you get the ResourceInUseException exception, it provides an example reference that shows where the intent is referenced. To remove the reference to the intent, either update the bot or delete it. If you get the same exception when you attempt to delete the intent again, repeat until the intent has no references and the call to DeleteIntent is successful.

This operation requires permission for the lex:DeleteIntent action. Request Syntax

DELETE /intents/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 292)

The name of the intent. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

292 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

293 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteIntentVersion Service: Amazon Lex Model Building Service

Deletes a specific version of an intent. To delete all versions of a intent, use the DeleteIntent (p. 292) operation.

This operation requires permissions for the lex:DeleteIntentVersion action. Request Syntax

DELETE /intents/name/versions/version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 294)

The name of the intent.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes version (p. 294)

The version of the intent to delete. You cannot delete the $LATEST version of the intent. To delete the $LATEST version, use the DeleteIntent (p. 292) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

294 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

295 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteSlotType Service: Amazon Lex Model Building Service

Deletes all versions of the slot type, including the $LATEST version. To delete a specific version of the slot type, use the DeleteSlotTypeVersion (p. 298) operation.

You can delete a version of a slot type only if it is not referenced. To delete a slot type that is referred to in one or more intents, you must remove those references first. Note

If you get the ResourceInUseException exception, the exception provides an example reference that shows the intent where the slot type is referenced. To remove the reference to the slot type, either update the intent or delete it. If you get the same exception when you attempt to delete the slot type again, repeat until the slot type has no references and the DeleteSlotType call is successful.

This operation requires permission for the lex:DeleteSlotType action. Request Syntax

DELETE /slottypes/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 296)

The name of the slot type. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

296 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

297 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteSlotTypeVersion Service: Amazon Lex Model Building Service

Deletes a specific version of a slot type. To delete all versions of a slot type, use the DeleteSlotType (p. 296) operation.

This operation requires permissions for the lex:DeleteSlotTypeVersion action. Request Syntax

DELETE /slottypes/name/version/version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 298)

The name of the slot type.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes version (p. 298)

The version of the slot type to delete. You cannot delete the $LATEST version of the slot type. To delete the $LATEST version, use the DeleteSlotType (p. 296) operation.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400

298 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404 ResourceInUseException

The resource that you are attempting to delete is referred to by another resource. Use this information to remove references to the resource that you are trying to delete.

The body of the exception contains a JSON object that describes the resource.

{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,

"resourceReference": {

"name": string, "version": string } }

HTTP Status Code: 400

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

299 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

DeleteUtterances Service: Amazon Lex Model Building Service

Deletes stored utterances.

Amazon Lex stores the utterances that users send to your bot. Utterances are stored for 15 days for use with the GetUtterancesView (p. 367) operation, and then stored indefinitely for use in improving the ability of your bot to respond to user input.

Use the DeleteUtterances operation to manually delete stored utterances for a specific user. When you use the DeleteUtterances operation, utterances stored for improving your bot's ability to respond to user input are deleted immediately. Utterances stored for use with the GetUtterancesView operation are deleted after 15 days.

This operation requires permissions for the lex:DeleteUtterances action.

Request Syntax

DELETE /bots/botName/utterances/userId HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botName (p. 300)

The name of the bot that stored the utterances.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes userId (p. 300)

The unique identifier for the user that made the utterances. This is the user ID that was sent in the PostContent or PostText operation request that contained the utterance.

Length Constraints: Minimum length of 2. Maximum length of 100.

Required: Yes

Request Body

The request does not have a request body.

Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

300 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

301 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBot Service: Amazon Lex Model Building Service

Returns metadata information for a specific bot. You must provide the bot name and the bot version or alias.

This operation requires permissions for the lex:GetBot action. Request Syntax

GET /bots/name/versions/versionoralias HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 302)

The name of the bot. The name is case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes versionoralias (p. 302)

The version or alias of the bot.

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "abortStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "checksum": "string", "childDirected": boolean, "clarificationPrompt": { "maxAttempts": number, "messages": [ { "content": "string",

302 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number, "description": "string", "detectSentiment": boolean, "enableModelImprovements": boolean, "failureReason": "string", "idleSessionTTLInSeconds": number, "intents": [ { "intentName": "string", "intentVersion": "string" } ], "lastUpdatedDate": number, "locale": "string", "name": "string", "nluIntentConfidenceThreshold": number, "status": "string", "version": "string", "voiceId": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. abortStatement (p. 302)

The message that Amazon Lex returns when the user elects to end the conversation without completing it. For more information, see PutBot (p. 372).

Type: Statement (p. 491) object checksum (p. 302)

Checksum of the bot used to identify a specific revision of the bot's $LATEST version.

Type: String childDirected (p. 302)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to the Children's Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field. By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. By specifying false in the childDirected field, you confirm that your use of Amazon Lex is not related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may not specify a default value for the childDirected field that does not accurately reflect whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in whole or in part, to children under age 13, you must obtain any required verifiable parental consent under

303 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

COPPA. For information regarding the use of Amazon Lex in connection with websites, programs, or other applications that are directed or targeted, in whole or in part, to children under age 13, see the Amazon Lex FAQ.

Type: Boolean clarificationPrompt (p. 302)

The message Amazon Lex uses when it doesn't understand the user's request. For more information, see PutBot (p. 372).

Type: Prompt (p. 480) object createdDate (p. 302)

The date that the bot was created.

Type: Timestamp description (p. 302)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. detectSentiment (p. 302)

Indicates whether user utterances should be sent to Amazon Comprehend for sentiment analysis.

Type: Boolean enableModelImprovements (p. 302)

Indicates whether the bot uses accuracy improvements. true indicates that the bot is using the improvements, otherwise, false.

Type: Boolean failureReason (p. 302)

If status is FAILED, Amazon Lex explains why it failed to build the bot.

Type: String idleSessionTTLInSeconds (p. 302)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. For more information, see PutBot (p. 372).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400. intents (p. 302)

An array of intent objects. For more information, see PutBot (p. 372).

Type: Array of Intent (p. 466) objects lastUpdatedDate (p. 302)

The date that the bot was updated. When you create a resource, the creation date and last updated date are the same.

Type: Timestamp

304 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service locale (p. 302)

The target locale for the bot.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR name (p. 302)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ nluIntentConfidenceThreshold (p. 302)

The score that determines where Amazon Lex inserts the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent is inserted if the confidence score for all intents is below this value. AMAZON.KendraSearchIntent is only inserted if it is configured for the bot.

Type: Double

Valid Range: Minimum value of 0. Maximum value of 1. status (p. 302)

The status of the bot.

When the status is BUILDING Amazon Lex is building the bot for testing and use.

If the status of the bot is READY_BASIC_TESTING, you can test the bot using the exact utterances specified in the bot's intents. When the bot is ready for full testing or to run, the status is READY.

If there was a problem with building the bot, the status is FAILED and the failureReason field explains why the bot did not build.

If the bot was saved but not built, the status is NOT_BUILT.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT version (p. 302)

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ voiceId (p. 302)

The Amazon Polly voice ID that Amazon Lex uses for voice interaction with the user. For more information, see PutBot (p. 372).

Type: String

305 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

306 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBotAlias Service: Amazon Lex Model Building Service

Returns information about an Amazon Lex bot alias. For more information about aliases, see Funzione Versioni multiple e alias (p. 136).

This operation requires permissions for the lex:GetBotAlias action. Request Syntax

GET /bots/botName/aliases/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botName (p. 307)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes name (p. 307)

The name of the bot alias. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "botName": "string", "botVersion": "string", "checksum": "string", "conversationLogs": { "iamRoleArn": "string", "logSettings": [ { "destination": "string", "kmsKeyArn": "string", "logType": "string", "resourceArn": "string", "resourcePrefix": "string" }

307 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

] }, "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botName (p. 307)

The name of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ botVersion (p. 307)

The version of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ checksum (p. 307)

Checksum of the bot alias.

Type: String conversationLogs (p. 307)

The settings that determine how Amazon Lex uses conversation logs for the alias.

Type: ConversationLogsResponse (p. 461) object createdDate (p. 307)

The date that the bot alias was created.

Type: Timestamp description (p. 307)

A description of the bot alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. lastUpdatedDate (p. 307)

The date that the bot alias was updated. When you create a resource, the creation date and the last updated date are the same.

Type: Timestamp

308 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service name (p. 307)

The name of the bot alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

309 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBotAliases Service: Amazon Lex Model Building Service

Returns a list of aliases for a specified Amazon Lex bot.

This operation requires permissions for the lex:GetBotAliases action. Request Syntax

GET /bots/botName/aliases/? maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botName (p. 310)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes maxResults (p. 310)

The maximum number of aliases to return in the response. The default is 50. .

Valid Range: Minimum value of 1. Maximum value of 50. nameContains (p. 310)

Substring to match in bot alias names. An alias will be returned if any part of its name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ nextToken (p. 310)

A pagination token for fetching the next page of aliases. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of aliases, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "BotAliases": [ { "botName": "string",

310 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"botVersion": "string", "checksum": "string", "conversationLogs": { "iamRoleArn": "string", "logSettings": [ { "destination": "string", "kmsKeyArn": "string", "logType": "string", "resourceArn": "string", "resourcePrefix": "string" } ] }, "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

BotAliases (p. 310)

An array of BotAliasMetadata objects, each describing a bot alias.

Type: Array of BotAliasMetadata (p. 450) objects nextToken (p. 310)

A pagination token for fetching next page of aliases. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of aliases, specify the pagination token in the next request.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

311 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

312 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBotChannelAssociation Service: Amazon Lex Model Building Service

Returns information about the association between an Amazon Lex bot and a messaging platform.

This operation requires permissions for the lex:GetBotChannelAssociation action. Request Syntax

GET /bots/botName/aliases/aliasName/channels/name HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. aliasName (p. 313)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes botName (p. 313)

The name of the Amazon Lex bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes name (p. 313)

The name of the association between the bot and the channel. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "botAlias": "string", "botConfiguration": { "string" : "string" }, "botName": "string",

313 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"createdDate": number, "description": "string", "failureReason": "string", "name": "string", "status": "string", "type": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botAlias (p. 313)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being made.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ botConfiguration (p. 313)

Provides information that the messaging platform needs to communicate with the Amazon Lex bot.

Type: String to string map

Map Entries: Maximum number of 10 items. botName (p. 313)

The name of the Amazon Lex bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ createdDate (p. 313)

The date that the association between the bot and the channel was created.

Type: Timestamp description (p. 313)

A description of the association between the bot and the channel.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. failureReason (p. 313)

If status is FAILED, Amazon Lex provides the reason that it failed to create the association.

Type: String name (p. 313)

The name of the association between the bot and the channel.

314 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ status (p. 313)

The status of the bot channel. • CREATED - The channel has been created and is ready for use. • IN_PROGRESS - Channel creation is in progress. • FAILED - There was an error creating the channel. For information about the reason for the failure, see the failureReason field.

Type: String

Valid Values: IN_PROGRESS | CREATED | FAILED type (p. 313)

The type of the messaging platform.

Type: String

Valid Values: Facebook | Slack | Twilio-Sms | Kik

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go

315 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

316 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBotChannelAssociations Service: Amazon Lex Model Building Service

Returns a list of all of the channels associated with the specified bot.

The GetBotChannelAssociations operation requires permissions for the lex:GetBotChannelAssociations action. Request Syntax

GET /bots/botName/aliases/aliasName/channels/? maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. aliasName (p. 317)

An alias pointing to the specific version of the Amazon Lex bot to which this association is being made.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^(-|^([A-Za-z]_?)+$)$

Required: Yes botName (p. 317)

The name of the Amazon Lex bot in the association.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes maxResults (p. 317)

The maximum number of associations to return in the response. The default is 50.

Valid Range: Minimum value of 1. Maximum value of 50. nameContains (p. 317)

Substring to match in channel association names. An association will be returned if any part of its name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz." To return all bot channel associations, use a hyphen ("-") as the nameContains parameter.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ nextToken (p. 317)

A pagination token for fetching the next page of associations. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of associations, specify the pagination token in the next request.

Request Body

The request does not have a request body.

317 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "botChannelAssociations": [ { "botAlias": "string", "botConfiguration": { "string" : "string" }, "botName": "string", "createdDate": number, "description": "string", "failureReason": "string", "name": "string", "status": "string", "type": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botChannelAssociations (p. 318)

An array of objects, one for each association, that provides information about the Amazon Lex bot and its association with the channel.

Type: Array of BotChannelAssociation (p. 452) objects nextToken (p. 318)

A pagination token that fetches the next page of associations. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of associations, specify the pagination token in the next request.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

318 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

319 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBots Service: Amazon Lex Model Building Service

Returns bot information as follows:

• If you provide the nameContains field, the response includes information for the $LATEST version of all bots whose name contains the specified string. • If you don't specify the nameContains field, the operation returns information about the $LATEST version of all of your bots.

This operation requires permission for the lex:GetBots action. Request Syntax

GET /bots/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 320)

The maximum number of bots to return in the response that the request will return. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. nameContains (p. 320)

Substring to match in bot names. A bot will be returned if any part of its name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ nextToken (p. 320)

A pagination token that fetches the next page of bots. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of bots, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "bots": [ { "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string", "status": "string",

320 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"version": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. bots (p. 320)

An array of botMetadata objects, with one entry for each bot.

Type: Array of BotMetadata (p. 454) objects nextToken (p. 320)

If the response is truncated, it includes a pagination token that you can specify in your next request to fetch the next page of bots.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go

321 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

322 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBotVersions Service: Amazon Lex Model Building Service

Gets information about all of the versions of a bot.

The GetBotVersions operation returns a BotMetadata object for each version of a bot. For example, if a bot has three numbered versions, the GetBotVersions operation returns four BotMetadata objects in the response, one for each numbered version and one for the $LATEST version.

The GetBotVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetBotVersions action. Request Syntax

GET /bots/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 323)

The maximum number of bot versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. name (p. 323)

The name of the bot for which versions should be returned.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes nextToken (p. 323)

A pagination token for fetching the next page of bot versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "bots": [ { "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string",

323 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"status": "string", "version": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. bots (p. 323)

An array of BotMetadata objects, one for each numbered version of the bot plus one for the $LATEST version.

Type: Array of BotMetadata (p. 454) objects nextToken (p. 323)

A pagination token for fetching the next page of bot versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET

324 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

325 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBuiltinIntent Service: Amazon Lex Model Building Service

Returns information about a built-in intent.

This operation requires permission for the lex:GetBuiltinIntent action. Request Syntax

GET /builtins/intents/signature HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. signature (p. 326)

The unique identifier for a built-in intent. To find the signature for an intent, see Standard Built-in Intents in the Alexa Skills Kit.

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "signature": "string", "slots": [ { "name": "string" } ], "supportedLocales": [ "string" ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. signature (p. 326)

The unique identifier for a built-in intent.

Type: String slots (p. 326)

An array of BuiltinIntentSlot objects, one entry for each slot type in the intent.

Type: Array of BuiltinIntentSlot (p. 457) objects

326 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service supportedLocales (p. 326)

A list of locales that the intent supports.

Type: Array of strings

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

327 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBuiltinIntents Service: Amazon Lex Model Building Service

Gets a list of built-in intents that meet the specified criteria.

This operation requires permission for the lex:GetBuiltinIntents action. Request Syntax

GET /builtins/intents/? locale=locale&maxResults=maxResults&nextToken=nextToken&signatureContains=signatureContains HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. locale (p. 328)

A list of locales that the intent supports.

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR maxResults (p. 328)

The maximum number of intents to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. nextToken (p. 328)

A pagination token that fetches the next page of intents. If this API call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of intents, use the pagination token in the next request. signatureContains (p. 328)

Substring to match in built-in intent signatures. An intent will be returned if any part of its signature matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz." To find the signature for an intent, see Standard Built-in Intents in the Alexa Skills Kit.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "intents": [ { "signature": "string", "supportedLocales": [ "string" ] } ], "nextToken": "string" }

328 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. intents (p. 328)

An array of builtinIntentMetadata objects, one for each intent in the response.

Type: Array of BuiltinIntentMetadata (p. 456) objects nextToken (p. 328)

A pagination token that fetches the next page of intents. If the response to this API call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of intents, specify the pagination token in the next request.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

329 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetBuiltinSlotTypes Service: Amazon Lex Model Building Service

Gets a list of built-in slot types that meet the specified criteria.

For a list of built-in slot types, see Slot Type Reference in the Alexa Skills Kit.

This operation requires permission for the lex:GetBuiltInSlotTypes action. Request Syntax

GET /builtins/slottypes/? locale=locale&maxResults=maxResults&nextToken=nextToken&signatureContains=signatureContains HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. locale (p. 330)

A list of locales that the slot type supports.

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR maxResults (p. 330)

The maximum number of slot types to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. nextToken (p. 330)

A pagination token that fetches the next page of slot types. If the response to this API call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of slot types, specify the pagination token in the next request. signatureContains (p. 330)

Substring to match in built-in slot type signatures. A slot type will be returned if any part of its signature matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "nextToken": "string", "slotTypes": [ { "signature": "string", "supportedLocales": [ "string" ] } ]

330 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

}

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. nextToken (p. 330)

If the response is truncated, the response includes a pagination token that you can use in your next request to fetch the next page of slot types.

Type: String slotTypes (p. 330)

An array of BuiltInSlotTypeMetadata objects, one entry for each slot type returned.

Type: Array of BuiltinSlotTypeMetadata (p. 458) objects

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

331 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetExport Service: Amazon Lex Model Building Service

Exports the contents of a Amazon Lex resource in a specified format. Request Syntax

GET /exports/?exportType=exportType&name=name&resourceType=resourceType&version=version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. exportType (p. 332)

The format of the exported data.

Valid Values: ALEXA_SKILLS_KIT | LEX

Required: Yes name (p. 332)

The name of the bot to export.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+

Required: Yes resourceType (p. 332)

The type of resource to export.

Valid Values: BOT | INTENT | SLOT_TYPE

Required: Yes version (p. 332)

The version of the bot to export.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "exportStatus": "string",

332 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"exportType": "string", "failureReason": "string", "name": "string", "resourceType": "string", "url": "string", "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. exportStatus (p. 332)

The status of the export. • IN_PROGRESS - The export is in progress. • READY - The export is complete. • FAILED - The export could not be completed.

Type: String

Valid Values: IN_PROGRESS | READY | FAILED exportType (p. 332)

The format of the exported data.

Type: String

Valid Values: ALEXA_SKILLS_KIT | LEX failureReason (p. 332)

If status is FAILED, Amazon Lex provides the reason that it failed to export the resource.

Type: String name (p. 332)

The name of the bot being exported.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+ resourceType (p. 332)

The type of the exported resource.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE url (p. 332)

An S3 pre-signed URL that provides the location of the exported resource. The exported resource is a ZIP archive that contains the exported resource in JSON format. The structure of the archive may change. Your code should not rely on the archive structure.

Type: String

333 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service version (p. 332)

The version of the bot being exported.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

334 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetImport Service: Amazon Lex Model Building Service

Gets information about an import job started with the StartImport operation. Request Syntax

GET /imports/importId HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. importId (p. 335)

The identifier of the import job information to return.

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "createdDate": number, "failureReason": [ "string" ], "importId": "string", "importStatus": "string", "mergeStrategy": "string", "name": "string", "resourceType": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. createdDate (p. 335)

A timestamp for the date and time that the import job was created.

Type: Timestamp failureReason (p. 335)

A string that describes why an import job failed to complete.

Type: Array of strings importId (p. 335)

The identifier for the specific import job.

335 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String importStatus (p. 335)

The status of the import job. If the status is FAILED, you can get the reason for the failure from the failureReason field.

Type: String

Valid Values: IN_PROGRESS | COMPLETE | FAILED mergeStrategy (p. 335)

The action taken when there was a conflict between an existing resource and a resource in the import file.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT name (p. 335)

The name given to the import job.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+ resourceType (p. 335)

The type of resource imported.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

336 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

337 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetIntent Service: Amazon Lex Model Building Service

Returns information about an intent. In addition to the intent name, you must specify the intent version.

This operation requires permissions to perform the lex:GetIntent action. Request Syntax

GET /intents/name/versions/version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 338)

The name of the intent. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes version (p. 338)

The version of the intent.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "checksum": "string", "conclusionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "confirmationPrompt": { "maxAttempts": number, "messages": [ {

338 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number, "description": "string", "dialogCodeHook": { "messageVersion": "string", "uri": "string" }, "followUpPrompt": { "prompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } }, "fulfillmentActivity": { "codeHook": { "messageVersion": "string", "uri": "string" }, "type": "string" }, "inputContexts": [ { "name": "string" } ], "kendraConfiguration": { "kendraIndex": "string", "queryFilterString": "string", "role": "string" }, "lastUpdatedDate": number, "name": "string", "outputContexts": [ { "name": "string", "timeToLiveInSeconds": number, "turnsToLive": number } ], "parentIntentSignature": "string", "rejectionStatement": { "messages": [ {

339 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "sampleUtterances": [ "string" ], "slots": [ { "defaultValueSpec": { "defaultValueList": [ { "defaultValue": "string" } ] }, "description": "string", "name": "string", "obfuscationSetting": "string", "priority": number, "responseCard": "string", "sampleUtterances": [ "string" ], "slotConstraint": "string", "slotType": "string", "slotTypeVersion": "string", "valueElicitationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } } ], "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. checksum (p. 338)

Checksum of the intent.

Type: String conclusionStatement (p. 338)

After the Lambda function specified in the fulfillmentActivity element fulfills the intent, Amazon Lex conveys this statement to the user.

Type: Statement (p. 491) object confirmationPrompt (p. 338)

If defined in the bot, Amazon Lex uses prompt to confirm the intent before fulfilling the user's request. For more information, see PutIntent (p. 388).

340 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: Prompt (p. 480) object createdDate (p. 338)

The date that the intent was created.

Type: Timestamp description (p. 338)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. dialogCodeHook (p. 338)

If defined in the bot, Amazon Amazon Lex invokes this Lambda function for each user input. For more information, see PutIntent (p. 388).

Type: CodeHook (p. 459) object followUpPrompt (p. 338)

If defined in the bot, Amazon Lex uses this prompt to solicit additional user activity after the intent is fulfilled. For more information, see PutIntent (p. 388).

Type: FollowUpPrompt (p. 463) object fulfillmentActivity (p. 338)

Describes how the intent is fulfilled. For more information, see PutIntent (p. 388).

Type: FulfillmentActivity (p. 464) object inputContexts (p. 338)

An array of InputContext objects that lists the contexts that must be active for Amazon Lex to choose the intent in a conversation with the user.

Type: Array of InputContext (p. 465) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items. kendraConfiguration (p. 338)

Configuration information, if any, to connect to an Amazon Kendra index with the AMAZON.KendraSearchIntent intent.

Type: KendraConfiguration (p. 469) object lastUpdatedDate (p. 338)

The date that the intent was updated. When you create a resource, the creation date and the last updated date are the same.

Type: Timestamp name (p. 338)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

341 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service outputContexts (p. 338)

An array of OutputContext objects that lists the contexts that the intent activates when the intent is fulfilled.

Type: Array of OutputContext (p. 479) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. parentIntentSignature (p. 338)

A unique identifier for a built-in intent.

Type: String rejectionStatement (p. 338)

If the user answers "no" to the question defined in confirmationPrompt, Amazon Lex responds with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 491) object sampleUtterances (p. 338)

An array of sample utterances configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200. slots (p. 338)

An array of intent slots configured for the intent.

Type: Array of Slot (p. 482) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items. version (p. 338)

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500

342 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

343 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetIntents Service: Amazon Lex Model Building Service

Returns intent information as follows:

• If you specify the nameContains field, returns the $LATEST version of all intents that contain the specified string. • If you don't specify the nameContains field, returns information about the $LATEST version of all intents.

The operation requires permission for the lex:GetIntents action. Request Syntax

GET /intents/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 344)

The maximum number of intents to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. nameContains (p. 344)

Substring to match in intent names. An intent will be returned if any part of its name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ nextToken (p. 344)

A pagination token that fetches the next page of intents. If the response to this API call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of intents, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "intents": [ { "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string", "version": "string"

344 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

} ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. intents (p. 344)

An array of Intent objects. For more information, see PutBot (p. 372).

Type: Array of IntentMetadata (p. 467) objects nextToken (p. 344)

If the response is truncated, the response includes a pagination token that you can specify in your next request to fetch the next page of intents.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2

345 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

346 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetIntentVersions Service: Amazon Lex Model Building Service

Gets information about all of the versions of an intent.

The GetIntentVersions operation returns an IntentMetadata object for each version of an intent. For example, if an intent has three numbered versions, the GetIntentVersions operation returns four IntentMetadata objects in the response, one for each numbered version and one for the $LATEST version.

The GetIntentVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetIntentVersions action. Request Syntax

GET /intents/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 347)

The maximum number of intent versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. name (p. 347)

The name of the intent for which versions should be returned.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes nextToken (p. 347)

A pagination token for fetching the next page of intent versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "intents": [ { "createdDate": number, "description": "string", "lastUpdatedDate": number,

347 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"name": "string", "version": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. intents (p. 347)

An array of IntentMetadata objects, one for each numbered version of the intent plus one for the $LATEST version.

Type: Array of IntentMetadata (p. 467) objects nextToken (p. 347)

A pagination token for fetching the next page of intent versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET

348 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

349 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetMigration Service: Amazon Lex Model Building Service

Provides details about an ongoing or complete migration from an Amazon Lex V1 bot to an Amazon Lex V2 bot. Use this operation to view the migration alerts and warnings related to the migration. Request Syntax

GET /migrations/migrationId HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. migrationId (p. 350)

The unique identifier of the migration to view. The migrationID is returned by the StartMigration (p. 410) operation.

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "alerts": [ { "details": [ "string" ], "message": "string", "referenceURLs": [ "string" ], "type": "string" } ], "migrationId": "string", "migrationStatus": "string", "migrationStrategy": "string", "migrationTimestamp": number, "v1BotLocale": "string", "v1BotName": "string", "v1BotVersion": "string", "v2BotId": "string", "v2BotRole": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service.

350 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service alerts (p. 350)

A list of alerts and warnings that indicate issues with the migration for the Amazon Lex V1 bot to Amazon Lex V2. You receive a warning when an Amazon Lex V1 feature has a different implementation in Amazon Lex V2.

For more information, see Migrating a bot in the Amazon Lex V2 developer guide.

Type: Array of MigrationAlert (p. 476) objects migrationId (p. 350)

The unique identifier of the migration. This is the same as the identifier used when calling the GetMigration operation.

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$ migrationStatus (p. 350)

Indicates the status of the migration. When the status is COMPLETE the migration is finished and the bot is available in Amazon Lex V2. There may be alerts and warnings that need to be resolved to complete the migration.

Type: String

Valid Values: IN_PROGRESS | COMPLETED | FAILED migrationStrategy (p. 350)

The strategy used to conduct the migration. • CREATE_NEW - Creates a new Amazon Lex V2 bot and migrates the Amazon Lex V1 bot to the new bot. • UPDATE_EXISTING - Overwrites the existing Amazon Lex V2 bot metadata and the locale being migrated. It doesn't change any other locales in the Amazon Lex V2 bot. If the locale doesn't exist, a new locale is created in the Amazon Lex V2 bot.

Type: String

Valid Values: CREATE_NEW | UPDATE_EXISTING migrationTimestamp (p. 350)

The date and time that the migration started.

Type: Timestamp v1BotLocale (p. 350)

The locale of the Amazon Lex V1 bot migrated to Amazon Lex V2.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR v1BotName (p. 350)

The name of the Amazon Lex V1 bot migrated to Amazon Lex V2.

Type: String

351 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ v1BotVersion (p. 350)

The version of the Amazon Lex V1 bot migrated to Amazon Lex V2.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ v2BotId (p. 350)

The unique identifier of the Amazon Lex V2 bot that the Amazon Lex V1 is being migrated to.

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$ v2BotRole (p. 350)

The IAM role that Amazon Lex uses to run the Amazon Lex V2 bot.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

352 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

353 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetMigrations Service: Amazon Lex Model Building Service

Gets a list of migrations between Amazon Lex V1 and Amazon Lex V2. Request Syntax

GET /migrations? maxResults=maxResults&migrationStatusEquals=migrationStatusEquals&nextToken=nextToken&sortByAttribute=sortByAttribute&sortByOrder=sortByOrder&v1BotNameContains=v1BotNameContains HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 354)

The maximum number of migrations to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. migrationStatusEquals (p. 354)

Filters the list to contain only migrations in the specified state.

Valid Values: IN_PROGRESS | COMPLETED | FAILED nextToken (p. 354)

A pagination token that fetches the next page of migrations. If the response to this operation is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of migrations, specify the pagination token in the request. sortByAttribute (p. 354)

The field to sort the list of migrations by. You can sort by the Amazon Lex V1 bot name or the date and time that the migration was started.

Valid Values: V1_BOT_NAME | MIGRATION_DATE_TIME sortByOrder (p. 354)

The order so sort the list.

Valid Values: ASCENDING | DESCENDING v1BotNameContains (p. 354)

Filters the list to contain only bots whose name contains the specified string. The string is matched anywhere in the bot name.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200

354 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Content-type: application/json

{ "migrationSummaries": [ { "migrationId": "string", "migrationStatus": "string", "migrationStrategy": "string", "migrationTimestamp": number, "v1BotLocale": "string", "v1BotName": "string", "v1BotVersion": "string", "v2BotId": "string", "v2BotRole": "string" } ], "nextToken": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. migrationSummaries (p. 354)

An array of summaries for migrations from Amazon Lex V1 to Amazon Lex V2. To see details of the migration, use the migrationId from the summary in a call to the GetMigration (p. 350) operation.

Type: Array of MigrationSummary (p. 477) objects nextToken (p. 354)

If the response is truncated, it includes a pagination token that you can specify in your next request to fetch the next page of migrations.

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

355 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

356 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetSlotType Service: Amazon Lex Model Building Service

Returns information about a specific version of a slot type. In addition to specifying the slot type name, you must specify the slot type version.

This operation requires permissions for the lex:GetSlotType action. Request Syntax

GET /slottypes/name/versions/version HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. name (p. 357)

The name of the slot type. The name is case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes version (p. 357)

The version of the slot type.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "checksum": "string", "createdDate": number, "description": "string", "enumerationValues": [ { "synonyms": [ "string" ], "value": "string" } ], "lastUpdatedDate": number, "name": "string", "parentSlotTypeSignature": "string", "slotTypeConfigurations": [

357 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

{ "regexConfiguration": { "pattern": "string" } } ], "valueSelectionStrategy": "string", "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. checksum (p. 357)

Checksum of the $LATEST version of the slot type.

Type: String createdDate (p. 357)

The date that the slot type was created.

Type: Timestamp description (p. 357)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. enumerationValues (p. 357)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 462) objects

Array Members: Minimum number of 0 items. Maximum number of 10000 items. lastUpdatedDate (p. 357)

The date that the slot type was updated. When you create a resource, the creation date and last update date are the same.

Type: Timestamp name (p. 357)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ parentSlotTypeSignature (p. 357)

The built-in slot type used as a parent for the slot type.

Type: String

358 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+ slotTypeConfigurations (p. 357)

Configuration information that extends the parent built-in slot type.

Type: Array of SlotTypeConfiguration (p. 487) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. valueSelectionStrategy (p. 357)

The strategy that Amazon Lex uses to determine the value of the slot. For more information, see PutSlotType (p. 400).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION version (p. 357)

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface

359 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

360 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetSlotTypes Service: Amazon Lex Model Building Service

Returns slot type information as follows:

• If you specify the nameContains field, returns the $LATEST version of all slot types that contain the specified string. • If you don't specify the nameContains field, returns information about the $LATEST version of all slot types.

The operation requires permission for the lex:GetSlotTypes action. Request Syntax

GET /slottypes/?maxResults=maxResults&nameContains=nameContains&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 361)

The maximum number of slot types to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. nameContains (p. 361)

Substring to match in slot type names. A slot type will be returned if any part of its name matches the substring. For example, "xyz" matches both "xyzabc" and "abcxyz."

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ nextToken (p. 361)

A pagination token that fetches the next page of slot types. If the response to this API call is truncated, Amazon Lex returns a pagination token in the response. To fetch next page of slot types, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "nextToken": "string", "slotTypes": [ { "createdDate": number, "description": "string", "lastUpdatedDate": number,

361 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"name": "string", "version": "string" } ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. nextToken (p. 361)

If the response is truncated, it includes a pagination token that you can specify in your next request to fetch the next page of slot types.

Type: String slotTypes (p. 361)

An array of objects, one for each slot type, that provides information such as the name of the slot type, the version, and a description.

Type: Array of SlotTypeMetadata (p. 488) objects

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go

362 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

363 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetSlotTypeVersions Service: Amazon Lex Model Building Service

Gets information about all versions of a slot type.

The GetSlotTypeVersions operation returns a SlotTypeMetadata object for each version of a slot type. For example, if a slot type has three numbered versions, the GetSlotTypeVersions operation returns four SlotTypeMetadata objects in the response, one for each numbered version and one for the $LATEST version.

The GetSlotTypeVersions operation always returns at least one version, the $LATEST version.

This operation requires permissions for the lex:GetSlotTypeVersions action. Request Syntax

GET /slottypes/name/versions/?maxResults=maxResults&nextToken=nextToken HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. maxResults (p. 364)

The maximum number of slot type versions to return in the response. The default is 10.

Valid Range: Minimum value of 1. Maximum value of 50. name (p. 364)

The name of the slot type for which versions should be returned.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes nextToken (p. 364)

A pagination token for fetching the next page of slot type versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "nextToken": "string", "slotTypes": [ { "createdDate": number, "description": "string",

364 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"lastUpdatedDate": number, "name": "string", "version": "string" } ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. nextToken (p. 364)

A pagination token for fetching the next page of slot type versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. To fetch the next page of versions, specify the pagination token in the next request.

Type: String slotTypes (p. 364)

An array of SlotTypeMetadata objects, one for each numbered version of the slot type plus one for the $LATEST version.

Type: Array of SlotTypeMetadata (p. 488) objects

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET

365 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

366 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

GetUtterancesView Service: Amazon Lex Model Building Service

Use the GetUtterancesView operation to get information about the utterances that your users have made to your bot. You can use this list to tune the utterances that your bot responds to.

For example, say that you have created a bot to order flowers. After your users have used your bot for a while, use the GetUtterancesView operation to see the requests that they have made and whether they have been successful. You might find that the utterance "I want flowers" is not being recognized. You could add this utterance to the OrderFlowers intent so that your bot recognizes that utterance. After you publish a new version of a bot, you can get information about the old version and the new so that you can compare the performance across the two versions.

Utterance statistics are generated once a day. Data is available for the last 15 days. You can request information for up to 5 versions of your bot in each request. Amazon Lex returns the most frequent utterances received by the bot in the last 15 days. The response contains information about a maximum of 100 utterances for each version.

If you set childDirected field to true when you created your bot, if you are using slot obfuscation with one or more slots, or if you opted out of participating in improving Amazon Lex, utterances are not available.

This operation requires permissions for the lex:GetUtterancesView action. Request Syntax

GET /bots/botname/utterances? view=aggregation&bot_versions=botVersions&status_type=statusType HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botname (p. 367)

The name of the bot for which utterance information should be returned.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ Required: Yes botVersions (p. 367)

An array of bot versions for which utterance information should be returned. The limit is 5 versions per request.

Array Members: Minimum number of 1 item. Maximum number of 5 items.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ Required: Yes statusType (p. 367)

To return utterances that were recognized and handled, use Detected. To return utterances that were not recognized, use Missed.

Valid Values: Detected | Missed

367 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "botName": "string", "utterances": [ { "botVersion": "string", "utterances": [ { "count": number, "distinctUsers": number, "firstUtteredDate": number, "lastUtteredDate": number, "utteranceString": "string" } ] } ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botName (p. 368)

The name of the bot for which utterance information was returned.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ utterances (p. 368)

An array of UtteranceList (p. 494) objects, each containing a list of UtteranceData (p. 493) objects describing the utterances that were processed by your bot. The response contains a maximum of 100 UtteranceData objects for each version. Amazon Lex returns the most frequent utterances received by the bot in the last 15 days.

Type: Array of UtteranceList (p. 494) objects

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

368 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

369 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ListTagsForResource Service: Amazon Lex Model Building Service

Gets a list of tags associated with the specified resource. Only bots, bot aliases, and bot channels can have tags associated with them.

Request Syntax

GET /tags/resourceArn HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. resourceArn (p. 370)

The Amazon Resource Name (ARN) of the resource to get a list of tags for.

Length Constraints: Minimum length of 1. Maximum length of 1011.

Required: Yes

Request Body

The request does not have a request body.

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "tags": [ { "key": "string", "value": "string" } ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. tags (p. 370)

The tags associated with a resource.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

370 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

371 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PutBot Service: Amazon Lex Model Building Service

Creates an Amazon Lex conversational bot or replaces an existing bot. When you create or update a bot you are only required to specify a name, a locale, and whether the bot is directed toward children under age 13. You can use this to add intents later, or to remove intents from an existing bot. When you create a bot with the minimum information, the bot is created or updated but Amazon Lex returns the response FAILED. You can build the bot after you add one or more intents. For more information about Amazon Lex bots, see Amazon Lex: come funziona (p. 3).

If you specify the name of an existing bot, the fields in the request replace the existing values in the $LATEST version of the bot. Amazon Lex removes any fields that you don't provide values for in the request, except for the idleTTLInSeconds and privacySettings fields, which are set to their default values. If you don't specify values for required fields, Amazon Lex throws an exception.

This operation requires permissions for the lex:PutBot action. For more information, see Identity and Access Management per Amazon Lex (p. 231).

Request Syntax

PUT /bots/name/versions/$LATEST HTTP/1.1 Content-type: application/json

{ "abortStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "checksum": "string", "childDirected": boolean, "clarificationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createVersion": boolean, "description": "string", "detectSentiment": boolean, "enableModelImprovements": boolean, "idleSessionTTLInSeconds": number, "intents": [ { "intentName": "string", "intentVersion": "string" } ], "locale": "string", "nluIntentConfidenceThreshold": number, "processBehavior": "string", "tags": [

372 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

{ "key": "string", "value": "string" } ], "voiceId": "string" }

URI Request Parameters

The request uses the following URI parameters. name (p. 372)

The name of the bot. The name is not case sensitive.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request accepts the following data in JSON format. abortStatement (p. 372)

When Amazon Lex can't understand the user's input in context, it tries to elicit the information a few times. After that, Amazon Lex sends the message defined in abortStatement to the user, and then cancels the conversation. To set the number of retries, use the valueElicitationPrompt field for the slot type.

For example, in a pizza ordering bot, Amazon Lex might ask a user "What type of crust would you like?" If the user's response is not one of the expected responses (for example, "thin crust, "deep dish," etc.), Amazon Lex tries to elicit a correct response a few more times.

For example, in a pizza ordering application, OrderPizza might be one of the intents. This intent might require the CrustType slot. You specify the valueElicitationPrompt field when you create the CrustType slot.

If you have defined a fallback intent the cancel statement will not be sent to the user, the fallback intent is used instead. For more information, see AMAZON.FallbackIntent.

Type: Statement (p. 491) object

Required: No checksum (p. 372)

Identifies a specific revision of the $LATEST version.

When you create a new bot, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception.

When you want to update a bot, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

373 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: No childDirected (p. 372)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to the Children's Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field. By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. By specifying false in the childDirected field, you confirm that your use of Amazon Lex is not related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may not specify a default value for the childDirected field that does not accurately reflect whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in whole or in part, to children under age 13, you must obtain any required verifiable parental consent under COPPA. For information regarding the use of Amazon Lex in connection with websites, programs, or other applications that are directed or targeted, in whole or in part, to children under age 13, see the Amazon Lex FAQ.

Type: Boolean

Required: Yes clarificationPrompt (p. 372)

When Amazon Lex doesn't understand the user's intent, it uses this message to get clarification. To specify how many times Amazon Lex should repeat the clarification prompt, use the maxAttempts field. If Amazon Lex still doesn't understand, it sends the message in the abortStatement field.

When you create a clarification prompt, make sure that it suggests the correct response from the user. for example, for a bot that orders pizza and drinks, you might create this clarification prompt: "What would you like to do? You can say 'Order a pizza' or 'Order a drink.'"

If you have defined a fallback intent, it will be invoked if the clarification prompt is repeated the number of times defined in the maxAttempts field. For more information, see AMAZON.FallbackIntent.

If you don't define a clarification prompt, at runtime Amazon Lex will return a 400 Bad Request exception in three cases: • Follow-up prompt - When the user responds to a follow-up prompt but does not provide an intent. For example, in response to a follow-up prompt that says "Would you like anything else today?" the user says "Yes." Amazon Lex will return a 400 Bad Request exception because it does not have a clarification prompt to send to the user to get an intent. • Lambda function - When using a Lambda function, you return an ElicitIntent dialog type. Since Amazon Lex does not have a clarification prompt to get an intent from the user, it returns a 400 Bad Request exception. • PutSession operation - When using the PutSession operation, you send an ElicitIntent dialog type. Since Amazon Lex does not have a clarification prompt to get an intent from the user, it returns a 400 Bad Request exception.

Type: Prompt (p. 480) object

Required: No createVersion (p. 372)

When set to true a new numbered version of the bot is created. This is the same as calling the CreateBotVersion operation. If you don't specify createVersion, the default is false.

374 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: Boolean

Required: No description (p. 372)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No detectSentiment (p. 372)

When set to true user utterances are sent to Amazon Comprehend for sentiment analysis. If you don't specify detectSentiment, the default is false.

Type: Boolean

Required: No enableModelImprovements (p. 372)

Set to true to enable access to natural language understanding improvements.

When you set the enableModelImprovements parameter to true you can use the nluIntentConfidenceThreshold parameter to configure confidence scores. For more information, see Confidence Scores.

You can only set the enableModelImprovements parameter in certain Regions. If you set the parameter to true, your bot has access to accuracy improvements.

The Regions where you can set the enableModelImprovements parameter to true are: • US East (N. Virginia) (us-east-1) • US West (Oregon) (us-west-2) • Asia Pacific (Sydney) (ap-southeast-2) • EU (Ireland) (eu-west-1)

In other Regions, the enableModelImprovements parameter is set to true by default. In these Regions setting the parameter to false throws a ValidationException exception.

Type: Boolean

Required: No idleSessionTTLInSeconds (p. 372)

The maximum time in seconds that Amazon Lex retains the data gathered in a conversation.

A user interaction session remains active for the amount of time specified. If no conversation occurs during this time, the session expires and Amazon Lex deletes any data provided before the timeout.

For example, suppose that a user chooses the OrderPizza intent, but gets sidetracked halfway through placing an order. If the user doesn't complete the order within the specified time, Amazon Lex discards the slot information that it gathered, and the user must start over.

If you don't include the idleSessionTTLInSeconds element in a PutBot operation request, Amazon Lex uses the default value. This is also true if the request replaces an existing bot.

The default is 300 seconds (5 minutes).

375 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400.

Required: No intents (p. 372)

An array of Intent objects. Each intent represents a command that a user can express. For example, a pizza ordering bot might support an OrderPizza intent. For more information, see Amazon Lex: come funziona (p. 3).

Type: Array of Intent (p. 466) objects

Required: No locale (p. 372)

Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale of the bot.

The default is en-US.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR

Required: Yes nluIntentConfidenceThreshold (p. 372)

Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted if they are configured for the bot.

You must set the enableModelImprovements parameter to true to use confidence scores in the following regions. • US East (N. Virginia) (us-east-1) • US West (Oregon) (us-west-2) • Asia Pacific (Sydney) (ap-southeast-2) • EU (Ireland) (eu-west-1)

In other Regions, the enableModelImprovements parameter is set to true by default.

For example, suppose a bot is configured with the confidence threshold of 0.80 and the AMAZON.FallbackIntent. Amazon Lex returns three alternative intents with the following confidence scores: IntentA (0.70), IntentB (0.60), IntentC (0.50). The response from the PostText operation would be: • AMAZON.FallbackIntent • IntentA • IntentB • IntentC

Type: Double

Valid Range: Minimum value of 0. Maximum value of 1.

Required: No

376 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service processBehavior (p. 372)

If you set the processBehavior element to BUILD, Amazon Lex builds the bot so that it can be run. If you set the element to SAVE Amazon Lex saves the bot, but doesn't build it.

If you don't specify this value, the default value is BUILD.

Type: String

Valid Values: SAVE | BUILD

Required: No tags (p. 372)

A list of tags to add to the bot. You can only add tags when you create a bot, you can't use the PutBot operation to update the tags on a bot. To update tags, use the TagResource operation.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Required: No voiceId (p. 372)

The Amazon Polly voice ID that you want Amazon Lex to use for voice interactions with the user. The locale configured for the voice must match the locale of the bot. For more information, see Voices in Amazon Polly in the Amazon Polly Developer Guide.

Type: String

Required: No

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "abortStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "checksum": "string", "childDirected": boolean, "clarificationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number,

377 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"createVersion": boolean, "description": "string", "detectSentiment": boolean, "enableModelImprovements": boolean, "failureReason": "string", "idleSessionTTLInSeconds": number, "intents": [ { "intentName": "string", "intentVersion": "string" } ], "lastUpdatedDate": number, "locale": "string", "name": "string", "nluIntentConfidenceThreshold": number, "status": "string", "tags": [ { "key": "string", "value": "string" } ], "version": "string", "voiceId": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. abortStatement (p. 377)

The message that Amazon Lex uses to cancel a conversation. For more information, see PutBot (p. 372).

Type: Statement (p. 491) object checksum (p. 377)

Checksum of the bot that you created.

Type: String childDirected (p. 377)

For each Amazon Lex bot created with the Amazon Lex Model Building Service, you must specify whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to the Children's Online Privacy Protection Act (COPPA) by specifying true or false in the childDirected field. By specifying true in the childDirected field, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. By specifying false in the childDirected field, you confirm that your use of Amazon Lex is not related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. You may not specify a default value for the childDirected field that does not accurately reflect whether your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA.

If your use of Amazon Lex relates to a website, program, or other application that is directed in whole or in part, to children under age 13, you must obtain any required verifiable parental consent under

378 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

COPPA. For information regarding the use of Amazon Lex in connection with websites, programs, or other applications that are directed or targeted, in whole or in part, to children under age 13, see the Amazon Lex FAQ.

Type: Boolean clarificationPrompt (p. 377)

The prompts that Amazon Lex uses when it doesn't understand the user's intent. For more information, see PutBot (p. 372).

Type: Prompt (p. 480) object createdDate (p. 377)

The date that the bot was created.

Type: Timestamp createVersion (p. 377)

True if a new version of the bot was created. If the createVersion field was not specified in the request, the createVersion field is set to false in the response.

Type: Boolean description (p. 377)

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. detectSentiment (p. 377)

true if the bot is configured to send user utterances to Amazon Comprehend for sentiment analysis. If the detectSentiment field was not specified in the request, the detectSentiment field is false in the response.

Type: Boolean enableModelImprovements (p. 377)

Indicates whether the bot uses accuracy improvements. true indicates that the bot is using the improvements, otherwise, false.

Type: Boolean failureReason (p. 377)

If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.

Type: String idleSessionTTLInSeconds (p. 377)

The maximum length of time that Amazon Lex retains the data gathered in a conversation. For more information, see PutBot (p. 372).

Type: Integer

Valid Range: Minimum value of 60. Maximum value of 86400. intents (p. 377)

An array of Intent objects. For more information, see PutBot (p. 372).

379 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: Array of Intent (p. 466) objects lastUpdatedDate (p. 377)

The date that the bot was updated. When you create a resource, the creation date and last updated date are the same.

Type: Timestamp locale (p. 377)

The target locale for the bot.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR name (p. 377)

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ nluIntentConfidenceThreshold (p. 377)

The score that determines where Amazon Lex inserts the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent is inserted if the confidence score for all intents is below this value. AMAZON.KendraSearchIntent is only inserted if it is configured for the bot.

Type: Double

Valid Range: Minimum value of 0. Maximum value of 1. status (p. 377)

When you send a request to create a bot with processBehavior set to BUILD, Amazon Lex sets the status response element to BUILDING.

In the READY_BASIC_TESTING state you can test the bot with user inputs that exactly match the utterances configured for the bot's intents and values in the slot types.

If Amazon Lex can't build the bot, Amazon Lex sets status to FAILED. Amazon Lex returns the reason for the failure in the failureReason response element.

When you set processBehavior to SAVE, Amazon Lex sets the status code to NOT BUILT.

When the bot is in the READY state you can test and publish the bot.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT tags (p. 377)

A list of tags associated with the bot.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

380 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service version (p. 377)

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ voiceId (p. 377)

The Amazon Polly voice ID that Amazon Lex uses for voice interaction with the user. For more information, see PutBot (p. 372).

Type: String

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript

381 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

382 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PutBotAlias Service: Amazon Lex Model Building Service

Creates an alias for the specified version of the bot or replaces an alias for the specified bot. To change the version of the bot that the alias points to, replace the alias. For more information about aliases, see Funzione Versioni multiple e alias (p. 136).

This operation requires permissions for the lex:PutBotAlias action.

Request Syntax

PUT /bots/botName/aliases/name HTTP/1.1 Content-type: application/json

{ "botVersion": "string", "checksum": "string", "conversationLogs": { "iamRoleArn": "string", "logSettings": [ { "destination": "string", "kmsKeyArn": "string", "logType": "string", "resourceArn": "string" } ] }, "description": "string", "tags": [ { "key": "string", "value": "string" } ] }

URI Request Parameters

The request uses the following URI parameters. botName (p. 383)

The name of the bot.

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes name (p. 383)

The name of the alias. The name is not case sensitive.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

383 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Request Body

The request accepts the following data in JSON format. botVersion (p. 383)

The version of the bot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes checksum (p. 383)

Identifies a specific revision of the $LATEST version.

When you create a new bot alias, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception.

When you want to update a bot alias, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No conversationLogs (p. 383)

Settings for conversation logs for the alias.

Type: ConversationLogsRequest (p. 460) object

Required: No description (p. 383)

A description of the alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No tags (p. 383)

A list of tags to add to the bot alias. You can only add tags when you create an alias, you can't use the PutBotAlias operation to update the tags on a bot alias. To update tags, use the TagResource operation.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Required: No

Response Syntax

HTTP/1.1 200

384 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Content-type: application/json

{ "botName": "string", "botVersion": "string", "checksum": "string", "conversationLogs": { "iamRoleArn": "string", "logSettings": [ { "destination": "string", "kmsKeyArn": "string", "logType": "string", "resourceArn": "string", "resourcePrefix": "string" } ] }, "createdDate": number, "description": "string", "lastUpdatedDate": number, "name": "string", "tags": [ { "key": "string", "value": "string" } ] }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botName (p. 384)

The name of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ botVersion (p. 384)

The version of the bot that the alias points to.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ checksum (p. 384)

The checksum for the current version of the alias.

Type: String conversationLogs (p. 384)

The settings that determine how Amazon Lex uses conversation logs for the alias.

385 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: ConversationLogsResponse (p. 461) object createdDate (p. 384)

The date that the bot alias was created.

Type: Timestamp description (p. 384)

A description of the alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. lastUpdatedDate (p. 384)

The date that the bot alias was updated. When you create a resource, the creation date and the last updated date are the same.

Type: Timestamp name (p. 384)

The name of the alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ tags (p. 384)

A list of tags associated with a bot.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

386 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

387 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PutIntent Service: Amazon Lex Model Building Service

Creates an intent or replaces an existing intent.

To define the interaction between the user and your bot, you use one or more intents. For a pizza ordering bot, for example, you would create an OrderPizza intent. To create an intent or replace an existing intent, you must provide the following:

• Intent name. For example, OrderPizza. • Sample utterances. For example, "Can I order a pizza, please." and "I want to order a pizza." • Information to be gathered. You specify slot types for the information that your bot will request from the user. You can specify standard slot types, such as a date or a time, or custom slot types such as the size and crust of a pizza. • How the intent will be fulfilled. You can provide a Lambda function or configure the intent to return the intent information to the client application. If you use a Lambda function, when all of the intent information is available, Amazon Lex invokes your Lambda function. If you configure your intent to return the intent information to the client application.

You can specify other optional information in the request, such as:

• A confirmation prompt to ask the user to confirm an intent. For example, "Shall I order your pizza?" • A conclusion statement to send to the user after the intent has been fulfilled. For example, "I placed your pizza order." • A follow-up prompt that asks the user for additional activity. For example, asking "Do you want to order a drink with your pizza?"

If you specify an existing intent name to update the intent, Amazon Lex replaces the values in the $LATEST version of the intent with the values in the request. Amazon Lex removes fields that you don't provide in the request. If you don't specify the required fields, Amazon Lex throws an exception. When you update the $LATEST version of an intent, the status field of any bot that uses the $LATEST version of the intent is set to NOT_BUILT. For more information, see Amazon Lex: come funziona (p. 3).

This operation requires permissions for the lex:PutIntent action. Request Syntax

PUT /intents/name/versions/$LATEST HTTP/1.1 Content-type: application/json

{ "checksum": "string", "conclusionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "confirmationPrompt": { "maxAttempts": number, "messages": [

388 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

{ "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createVersion": boolean, "description": "string", "dialogCodeHook": { "messageVersion": "string", "uri": "string" }, "followUpPrompt": { "prompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } }, "fulfillmentActivity": { "codeHook": { "messageVersion": "string", "uri": "string" }, "type": "string" }, "inputContexts": [ { "name": "string" } ], "kendraConfiguration": { "kendraIndex": "string", "queryFilterString": "string", "role": "string" }, "outputContexts": [ { "name": "string", "timeToLiveInSeconds": number, "turnsToLive": number } ], "parentIntentSignature": "string", "rejectionStatement": { "messages": [ { "content": "string",

389 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "sampleUtterances": [ "string" ], "slots": [ { "defaultValueSpec": { "defaultValueList": [ { "defaultValue": "string" } ] }, "description": "string", "name": "string", "obfuscationSetting": "string", "priority": number, "responseCard": "string", "sampleUtterances": [ "string" ], "slotConstraint": "string", "slotType": "string", "slotTypeVersion": "string", "valueElicitationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } } ] }

URI Request Parameters

The request uses the following URI parameters. name (p. 388)

The name of the intent. The name is not case sensitive.

The name can't match a built-in intent name, or a built-in intent name with "AMAZON." removed. For example, because there is a built-in intent called AMAZON.HelpIntent, you can't create a custom intent called HelpIntent.

For a list of built-in intents, see Standard Built-in Intents in the Alexa Skills Kit.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

Request Body

The request accepts the following data in JSON format.

390 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service checksum (p. 388)

Identifies a specific revision of the $LATEST version.

When you create a new intent, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception.

When you want to update a intent, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No conclusionStatement (p. 388)

The statement that you want Amazon Lex to convey to the user after the intent is successfully fulfilled by the Lambda function.

This element is relevant only if you provide a Lambda function in the fulfillmentActivity. If you return the intent to the client application, you can't specify this element. Note

The followUpPrompt and conclusionStatement are mutually exclusive. You can specify only one.

Type: Statement (p. 491) object

Required: No confirmationPrompt (p. 388)

Prompts the user to confirm the intent. This question should have a yes or no answer.

Amazon Lex uses this prompt to ensure that the user acknowledges that the intent is ready for fulfillment. For example, with the OrderPizza intent, you might want to confirm that the order is correct before placing it. For other intents, such as intents that simply respond to user questions, you might not need to ask the user for confirmation before providing the information. Note

You you must provide both the rejectionStatement and the confirmationPrompt, or neither.

Type: Prompt (p. 480) object

Required: No createVersion (p. 388)

When set to true a new numbered version of the intent is created. This is the same as calling the CreateIntentVersion operation. If you do not specify createVersion, the default is false.

Type: Boolean

Required: No description (p. 388)

A description of the intent.

391 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No dialogCodeHook (p. 388)

Specifies a Lambda function to invoke for each user input. You can invoke this Lambda function to personalize user interaction.

For example, suppose your bot determines that the user is John. Your Lambda function might retrieve John's information from a backend database and prepopulate some of the values. For example, if you find that John is gluten intolerant, you might set the corresponding intent slot, GlutenIntolerant, to true. You might find John's phone number and set the corresponding session attribute.

Type: CodeHook (p. 459) object

Required: No followUpPrompt (p. 388)

Amazon Lex uses this prompt to solicit additional activity after fulfilling an intent. For example, after the OrderPizza intent is fulfilled, you might prompt the user to order a drink.

The action that Amazon Lex takes depends on the user's response, as follows: • If the user says "Yes" it responds with the clarification prompt that is configured for the bot. • if the user says "Yes" and continues with an utterance that triggers an intent it starts a conversation for the intent. • If the user says "No" it responds with the rejection statement configured for the the follow-up prompt. • If it doesn't recognize the utterance it repeats the follow-up prompt again.

The followUpPrompt field and the conclusionStatement field are mutually exclusive. You can specify only one.

Type: FollowUpPrompt (p. 463) object

Required: No fulfillmentActivity (p. 388)

Required. Describes how the intent is fulfilled. For example, after a user provides all of the information for a pizza order, fulfillmentActivity defines how the bot places an order with a local pizza store.

You might configure Amazon Lex to return all of the intent information to the client application, or direct it to invoke a Lambda function that can process the intent (for example, place an order with a pizzeria).

Type: FulfillmentActivity (p. 464) object

Required: No inputContexts (p. 388)

An array of InputContext objects that lists the contexts that must be active for Amazon Lex to choose the intent in a conversation with the user.

Type: Array of InputContext (p. 465) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items.

Required: No

392 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service kendraConfiguration (p. 388)

Configuration information required to use the AMAZON.KendraSearchIntent intent to connect to an Amazon Kendra index. For more information, see AMAZON.KendraSearchIntent.

Type: KendraConfiguration (p. 469) object

Required: No outputContexts (p. 388)

An array of OutputContext objects that lists the contexts that the intent activates when the intent is fulfilled.

Type: Array of OutputContext (p. 479) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Required: No parentIntentSignature (p. 388)

A unique identifier for the built-in intent to base this intent on. To find the signature for an intent, see Standard Built-in Intents in the Alexa Skills Kit.

Type: String

Required: No rejectionStatement (p. 388)

When the user answers "no" to the question defined in confirmationPrompt, Amazon Lex responds with this statement to acknowledge that the intent was canceled. Note

You must provide both the rejectionStatement and the confirmationPrompt, or neither.

Type: Statement (p. 491) object

Required: No sampleUtterances (p. 388)

An array of utterances (strings) that a user might say to signal the intent. For example, "I want {PizzaSize} pizza", "Order {Quantity} {PizzaSize} pizzas".

In each utterance, a slot name is enclosed in curly braces.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200.

Required: No slots (p. 388)

An array of intent slots. At runtime, Amazon Lex elicits required slot values from the user using prompts defined in the slots. For more information, see Amazon Lex: come funziona (p. 3).

Type: Array of Slot (p. 482) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items.

393 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: No

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "checksum": "string", "conclusionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "confirmationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "createdDate": number, "createVersion": boolean, "description": "string", "dialogCodeHook": { "messageVersion": "string", "uri": "string" }, "followUpPrompt": { "prompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } }, "fulfillmentActivity": { "codeHook": { "messageVersion": "string", "uri": "string"

394 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

}, "type": "string" }, "inputContexts": [ { "name": "string" } ], "kendraConfiguration": { "kendraIndex": "string", "queryFilterString": "string", "role": "string" }, "lastUpdatedDate": number, "name": "string", "outputContexts": [ { "name": "string", "timeToLiveInSeconds": number, "turnsToLive": number } ], "parentIntentSignature": "string", "rejectionStatement": { "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" }, "sampleUtterances": [ "string" ], "slots": [ { "defaultValueSpec": { "defaultValueList": [ { "defaultValue": "string" } ] }, "description": "string", "name": "string", "obfuscationSetting": "string", "priority": number, "responseCard": "string", "sampleUtterances": [ "string" ], "slotConstraint": "string", "slotType": "string", "slotTypeVersion": "string", "valueElicitationPrompt": { "maxAttempts": number, "messages": [ { "content": "string", "contentType": "string", "groupNumber": number } ], "responseCard": "string" } } ], "version": "string"

395 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

}

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. checksum (p. 394)

Checksum of the $LATESTversion of the intent created or updated.

Type: String conclusionStatement (p. 394)

After the Lambda function specified in thefulfillmentActivityintent fulfills the intent, Amazon Lex conveys this statement to the user.

Type: Statement (p. 491) object confirmationPrompt (p. 394)

If defined in the intent, Amazon Lex prompts the user to confirm the intent before fulfilling it.

Type: Prompt (p. 480) object createdDate (p. 394)

The date that the intent was created.

Type: Timestamp createVersion (p. 394)

True if a new version of the intent was created. If the createVersion field was not specified in the request, the createVersion field is set to false in the response.

Type: Boolean description (p. 394)

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. dialogCodeHook (p. 394)

If defined in the intent, Amazon Lex invokes this Lambda function for each user input.

Type: CodeHook (p. 459) object followUpPrompt (p. 394)

If defined in the intent, Amazon Lex uses this prompt to solicit additional user activity after the intent is fulfilled.

Type: FollowUpPrompt (p. 463) object fulfillmentActivity (p. 394)

If defined in the intent, Amazon Lex invokes this Lambda function to fulfill the intent after the user provides all of the information required by the intent.

Type: FulfillmentActivity (p. 464) object

396 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service inputContexts (p. 394)

An array of InputContext objects that lists the contexts that must be active for Amazon Lex to choose the intent in a conversation with the user.

Type: Array of InputContext (p. 465) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items. kendraConfiguration (p. 394)

Configuration information, if any, required to connect to an Amazon Kendra index and use the AMAZON.KendraSearchIntent intent.

Type: KendraConfiguration (p. 469) object lastUpdatedDate (p. 394)

The date that the intent was updated. When you create a resource, the creation date and last update dates are the same.

Type: Timestamp name (p. 394)

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$ outputContexts (p. 394)

An array of OutputContext objects that lists the contexts that the intent activates when the intent is fulfilled.

Type: Array of OutputContext (p. 479) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. parentIntentSignature (p. 394)

A unique identifier for the built-in intent that this intent is based on.

Type: String rejectionStatement (p. 394)

If the user answers "no" to the question defined in confirmationPrompt Amazon Lex responds with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 491) object sampleUtterances (p. 394)

An array of sample utterances that are configured for the intent.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 1500 items.

Length Constraints: Minimum length of 1. Maximum length of 200. slots (p. 394)

An array of intent slots that are configured for the intent.

397 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: Array of Slot (p. 482) objects

Array Members: Minimum number of 0 items. Maximum number of 100 items. version (p. 394)

The version of the intent. For a new intent, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python

398 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Ruby V3

399 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PutSlotType Service: Amazon Lex Model Building Service

Creates a custom slot type or replaces an existing custom slot type.

To create a custom slot type, specify a name for the slot type and a set of enumeration values, which are the values that a slot of this type can assume. For more information, see Amazon Lex: come funziona (p. 3).

If you specify the name of an existing slot type, the fields in the request replace the existing values in the $LATEST version of the slot type. Amazon Lex removes the fields that you don't provide in the request. If you don't specify required fields, Amazon Lex throws an exception. When you update the $LATEST version of a slot type, if a bot uses the $LATEST version of an intent that contains the slot type, the bot's status field is set to NOT_BUILT.

This operation requires permissions for the lex:PutSlotType action. Request Syntax

PUT /slottypes/name/versions/$LATEST HTTP/1.1 Content-type: application/json

{ "checksum": "string", "createVersion": boolean, "description": "string", "enumerationValues": [ { "synonyms": [ "string" ], "value": "string" } ], "parentSlotTypeSignature": "string", "slotTypeConfigurations": [ { "regexConfiguration": { "pattern": "string" } } ], "valueSelectionStrategy": "string" }

URI Request Parameters

The request uses the following URI parameters. name (p. 400)

The name of the slot type. The name is not case sensitive.

The name can't match a built-in slot type name, or a built-in slot type name with "AMAZON." removed. For example, because there is a built-in slot type called AMAZON.DATE, you can't create a custom slot type called DATE.

For a list of built-in slot types, see Slot Type Reference in the Alexa Skills Kit.

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

400 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: Yes

Request Body

The request accepts the following data in JSON format. checksum (p. 400)

Identifies a specific revision of the $LATEST version.

When you create a new slot type, leave the checksum field blank. If you specify a checksum you get a BadRequestException exception.

When you want to update a slot type, set the checksum field to the checksum of the most recent revision of the $LATEST version. If you don't specify the checksum field, or if the checksum does not match the $LATEST version, you get a PreconditionFailedException exception.

Type: String

Required: No createVersion (p. 400)

When set to true a new numbered version of the slot type is created. This is the same as calling the CreateSlotTypeVersion operation. If you do not specify createVersion, the default is false.

Type: Boolean

Required: No description (p. 400)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No enumerationValues (p. 400)

A list of EnumerationValue objects that defines the values that the slot type can take. Each value can have a list of synonyms, which are additional values that help train the machine learning model about the values that it resolves for a slot.

A regular expression slot type doesn't require enumeration values. All other slot types require a list of enumeration values.

When Amazon Lex resolves a slot value, it generates a resolution list that contains up to five possible values for the slot. If you are using a Lambda function, this resolution list is passed to the function. If you are not using a Lambda function you can choose to return the value that the user entered or the first value in the resolution list as the slot value. The valueSelectionStrategy field indicates the option to use.

Type: Array of EnumerationValue (p. 462) objects

Array Members: Minimum number of 0 items. Maximum number of 10000 items.

Required: No

401 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service parentSlotTypeSignature (p. 400)

The built-in slot type used as the parent of the slot type. When you define a parent slot type, the new slot type has all of the same configuration as the parent.

Only AMAZON.AlphaNumeric is supported.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+

Required: No slotTypeConfigurations (p. 400)

Configuration information that extends the parent built-in slot type. The configuration is added to the settings for the parent slot type.

Type: Array of SlotTypeConfiguration (p. 487) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Required: No valueSelectionStrategy (p. 400)

Determines the slot resolution strategy that Amazon Lex uses to return slot type values. The field can be set to one of the following values: • ORIGINAL_VALUE - Returns the value entered by the user, if the user value is similar to the slot value. • TOP_RESOLUTION - If there is a resolution list for the slot, return the first value in the resolution list as the slot type value. If there is no resolution list, null is returned.

If you don't specify the valueSelectionStrategy, the default is ORIGINAL_VALUE.

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION

Required: No

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "checksum": "string", "createdDate": number, "createVersion": boolean, "description": "string", "enumerationValues": [ { "synonyms": [ "string" ], "value": "string" } ], "lastUpdatedDate": number, "name": "string", "parentSlotTypeSignature": "string",

402 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

"slotTypeConfigurations": [ { "regexConfiguration": { "pattern": "string" } } ], "valueSelectionStrategy": "string", "version": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. checksum (p. 402)

Checksum of the $LATEST version of the slot type.

Type: String createdDate (p. 402)

The date that the slot type was created.

Type: Timestamp createVersion (p. 402)

True if a new version of the slot type was created. If the createVersion field was not specified in the request, the createVersion field is set to false in the response.

Type: Boolean description (p. 402)

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200. enumerationValues (p. 402)

A list of EnumerationValue objects that defines the values that the slot type can take.

Type: Array of EnumerationValue (p. 462) objects

Array Members: Minimum number of 0 items. Maximum number of 10000 items. lastUpdatedDate (p. 402)

The date that the slot type was updated. When you create a slot type, the creation date and last update date are the same.

Type: Timestamp name (p. 402)

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

403 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Pattern: ^([A-Za-z]_?)+$ parentSlotTypeSignature (p. 402)

The built-in slot type used as the parent of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+ slotTypeConfigurations (p. 402)

Configuration information that extends the parent built-in slot type.

Type: Array of SlotTypeConfiguration (p. 487) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items. valueSelectionStrategy (p. 402)

The slot resolution strategy that Amazon Lex uses to determine the value of the slot. For more information, see PutSlotType (p. 400).

Type: String

Valid Values: ORIGINAL_VALUE | TOP_RESOLUTION version (p. 402)

The version of the slot type. For a new slot type, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

404 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

PreconditionFailedException

The checksum of the resource that you are trying to change does not match the checksum in the request. Check the resource's checksum and try again.

HTTP Status Code: 412

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

405 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

StartImport Service: Amazon Lex Model Building Service

Starts a job to import a resource to Amazon Lex. Request Syntax

POST /imports/ HTTP/1.1 Content-type: application/json

{ "mergeStrategy": "string", "payload": blob, "resourceType": "string", "tags": [ { "key": "string", "value": "string" } ] }

URI Request Parameters

The request does not use any URI parameters. Request Body

The request accepts the following data in JSON format. mergeStrategy (p. 406)

Specifies the action that the StartImport operation should take when there is an existing resource with the same name. • FAIL_ON_CONFLICT - The import operation is stopped on the first conflict between a resource in the import file and an existing resource. The name of the resource causing the conflict is in the failureReason field of the response to the GetImport operation.

OVERWRITE_LATEST - The import operation proceeds even if there is a conflict with an existing resource. The $LASTEST version of the existing resource is overwritten with the data from the import file.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT

Required: Yes payload (p. 406)

A zip archive in binary format. The archive should contain one file, a JSON file containing the resource to import. The resource should match the type specified in the resourceType field.

Type: Base64-encoded binary data object

Required: Yes resourceType (p. 406)

Specifies the type of resource to export. Each resource also exports any resources that it depends on.

406 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• A bot exports dependent intents. • An intent exports dependent slot types.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE

Required: Yes tags (p. 406)

A list of tags to add to the imported bot. You can only add tags when you import a bot, you can't add tags to an intent or slot type.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Required: No

Response Syntax

HTTP/1.1 201 Content-type: application/json

{ "createdDate": number, "importId": "string", "importStatus": "string", "mergeStrategy": "string", "name": "string", "resourceType": "string", "tags": [ { "key": "string", "value": "string" } ] }

Response Elements

If the action is successful, the service sends back an HTTP 201 response.

The following data is returned in JSON format by the service. createdDate (p. 407)

A timestamp for the date and time that the import job was requested.

Type: Timestamp importId (p. 407)

The identifier for the specific import job.

Type: String importStatus (p. 407)

The status of the import job. If the status is FAILED, you can get the reason for the failure using the GetImport operation.

407 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Valid Values: IN_PROGRESS | COMPLETE | FAILED mergeStrategy (p. 407)

The action to take when there is a merge conflict.

Type: String

Valid Values: OVERWRITE_LATEST | FAIL_ON_CONFLICT name (p. 407)

The name given to the import job.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+ resourceType (p. 407)

The type of resource to import.

Type: String

Valid Values: BOT | INTENT | SLOT_TYPE tags (p. 407)

A list of tags added to the imported bot.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface

408 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

409 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

StartMigration Service: Amazon Lex Model Building Service

Starts migrating a bot from Amazon Lex V1 to Amazon Lex V2. Migrate your bot when you want to take advantage of the new features of Amazon Lex V2.

For more information, see Migrating a bot in the Amazon Lex developer guide. Request Syntax

POST /migrations HTTP/1.1 Content-type: application/json

{ "migrationStrategy": "string", "v1BotName": "string", "v1BotVersion": "string", "v2BotName": "string", "v2BotRole": "string" }

URI Request Parameters

The request does not use any URI parameters. Request Body

The request accepts the following data in JSON format. migrationStrategy (p. 410)

The strategy used to conduct the migration. • CREATE_NEW - Creates a new Amazon Lex V2 bot and migrates the Amazon Lex V1 bot to the new bot. • UPDATE_EXISTING - Overwrites the existing Amazon Lex V2 bot metadata and the locale being migrated. It doesn't change any other locales in the Amazon Lex V2 bot. If the locale doesn't exist, a new locale is created in the Amazon Lex V2 bot.

Type: String

Valid Values: CREATE_NEW | UPDATE_EXISTING

Required: Yes v1BotName (p. 410)

The name of the Amazon Lex V1 bot that you are migrating to Amazon Lex V2.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: Yes v1BotVersion (p. 410)

The version of the bot to migrate to Amazon Lex V2. You can migrate the $LATEST version as well as any numbered version.

410 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes v2BotName (p. 410)

The name of the Amazon Lex V2 bot that you are migrating the Amazon Lex V1 bot to. • If the Amazon Lex V2 bot doesn't exist, you must use the CREATE_NEW migration strategy. • If the Amazon Lex V2 bot exists, you must use the UPDATE_EXISTING migration strategy to change the contents of the Amazon Lex V2 bot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([0-9a-zA-Z][_-]?)+$

Required: Yes v2BotRole (p. 410)

The IAM role that Amazon Lex uses to run the Amazon Lex V2 bot.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Required: Yes

Response Syntax

HTTP/1.1 202 Content-type: application/json

{ "migrationId": "string", "migrationStrategy": "string", "migrationTimestamp": number, "v1BotLocale": "string", "v1BotName": "string", "v1BotVersion": "string", "v2BotId": "string", "v2BotRole": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 202 response.

The following data is returned in JSON format by the service. migrationId (p. 411)

The unique identifier that Amazon Lex assigned to the migration.

411 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$ migrationStrategy (p. 411)

The strategy used to conduct the migration.

Type: String

Valid Values: CREATE_NEW | UPDATE_EXISTING migrationTimestamp (p. 411)

The date and time that the migration started.

Type: Timestamp v1BotLocale (p. 411)

The locale used for the Amazon Lex V1 bot.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR v1BotName (p. 411)

The name of the Amazon Lex V1 bot that you are migrating to Amazon Lex V2.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$ v1BotVersion (p. 411)

The version of the bot to migrate to Amazon Lex V2.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+ v2BotId (p. 411)

The unique identifier for the Amazon Lex V2 bot.

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$ v2BotRole (p. 411)

The IAM role that Amazon Lex uses to run the Amazon Lex V2 bot.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

412 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Errors

AccessDeniedException

Your IAM user or role does not have permission to call the Amazon Lex V2 APIs required to migrate your bot.

HTTP Status Code: 403 BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

413 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

TagResource Service: Amazon Lex Model Building Service

Adds the specified tags to the specified resource. If a tag key already exists, the existing value is replaced with the new value.

Request Syntax

POST /tags/resourceArn HTTP/1.1 Content-type: application/json

{ "tags": [ { "key": "string", "value": "string" } ] }

URI Request Parameters

The request uses the following URI parameters. resourceArn (p. 414)

The Amazon Resource Name (ARN) of the bot, bot alias, or bot channel to tag.

Length Constraints: Minimum length of 1. Maximum length of 1011.

Required: Yes

Request Body

The request accepts the following data in JSON format. tags (p. 414)

A list of tag keys to add to the resource. If a tag key already exists, the existing value is replaced with the new value.

Type: Array of Tag (p. 492) objects

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Required: Yes

Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body.

414 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409 InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

415 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

UntagResource Service: Amazon Lex Model Building Service

Removes tags from a bot, bot alias or bot channel. Request Syntax

DELETE /tags/resourceArn?tagKeys=tagKeys HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. resourceArn (p. 416)

The Amazon Resource Name (ARN) of the resource to remove the tags from.

Length Constraints: Minimum length of 1. Maximum length of 1011.

Required: Yes tagKeys (p. 416)

A list of tag keys to remove from the resource. If a tag key does not exist on the resource, it is ignored.

Array Members: Minimum number of 0 items. Maximum number of 200 items.

Length Constraints: Minimum length of 1. Maximum length of 128.

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 204

Response Elements

If the action is successful, the service sends back an HTTP 204 response with an empty HTTP body. Errors

BadRequestException

The request is not well formed. For example, a value is invalid or a required field is missing. Check the field values, and try again.

HTTP Status Code: 400 ConflictException

There was a conflict processing the request. Try your request again.

HTTP Status Code: 409

416 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

InternalFailureException

An internal Amazon Lex error occurred. Try your request again.

HTTP Status Code: 500 LimitExceededException

The request exceeded a limit. Try your request again.

HTTP Status Code: 429 NotFoundException

The resource specified in the request was not found. Check the resource and try again.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

Amazon Lex Runtime Service

The following actions are supported by Amazon Lex Runtime Service:

• DeleteSession (p. 418) • GetSession (p. 421) • PostContent (p. 425) • PostText (p. 434) • PutSession (p. 442)

417 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

DeleteSession Service: Amazon Lex Runtime Service

Removes session information for a specified bot, alias, and user ID. Request Syntax

DELETE /bot/botName/alias/botAlias/user/userId/session HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botAlias (p. 418)

The alias in use for the bot that contains the session data.

Required: Yes botName (p. 418)

The name of the bot that contains the session data.

Required: Yes userId (p. 418)

The identifier of the user associated with the session data.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Required: Yes

Request Body

The request does not have a request body. Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "botAlias": "string", "botName": "string", "sessionId": "string", "userId": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. botAlias (p. 418)

The alias in use for the bot associated with the session data.

418 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Type: String botName (p. 418)

The name of the bot associated with the session data.

Type: String sessionId (p. 418)

The unique identifier for the session.

Type: String userId (p. 418)

The ID of the client application user.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Errors

BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in progress, or contains unbuilt changes.

HTTP Status Code: 400 ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409 InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500 LimitExceededException

Exceeded a limit.

HTTP Status Code: 429 NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++

419 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

• AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

420 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

GetSession Service: Amazon Lex Runtime Service

Returns session information for a specified bot, alias, and user ID.

Request Syntax

GET /bot/botName/alias/botAlias/user/userId/session/? checkpointLabelFilter=checkpointLabelFilter HTTP/1.1

URI Request Parameters

The request uses the following URI parameters. botAlias (p. 421)

The alias in use for the bot that contains the session data.

Required: Yes botName (p. 421)

The name of the bot that contains the session data.

Required: Yes checkpointLabelFilter (p. 421)

A string used to filter the intents returned in the recentIntentSummaryView structure.

When you specify a filter, only intents with their checkpointLabel field set to that string are returned.

Length Constraints: Minimum length of 1. Maximum length of 255.

Pattern: [a-zA-Z0-9-]+ userId (p. 421)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your bot.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Required: Yes

Request Body

The request does not have a request body.

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "activeContexts": [

421 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

{ "name": "string", "parameters": { "string" : "string" }, "timeToLive": { "timeToLiveInSeconds": number, "turnsToLive": number } } ], "dialogAction": { "fulfillmentState": "string", "intentName": "string", "message": "string", "messageFormat": "string", "slots": { "string" : "string" }, "slotToElicit": "string", "type": "string" }, "recentIntentSummaryView": [ { "checkpointLabel": "string", "confirmationStatus": "string", "dialogActionType": "string", "fulfillmentState": "string", "intentName": "string", "slots": { "string" : "string" }, "slotToElicit": "string" } ], "sessionAttributes": { "string" : "string" }, "sessionId": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. activeContexts (p. 421)

A list of active contexts for the session. A context can be set when an intent is fulfilled or by calling the PostContent, PostText, or PutSession operation.

You can use a context to control the intents that can follow up an intent, or to modify the operation of your application.

Type: Array of ActiveContext (p. 495) objects

Array Members: Minimum number of 0 items. Maximum number of 20 items. dialogAction (p. 421)

Describes the current state of the bot.

Type: DialogAction (p. 498) object

422 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service recentIntentSummaryView (p. 421)

An array of information about the intents used in the session. The array can contain a maximum of three summaries. If more than three intents are used in the session, the recentIntentSummaryView operation contains information about the last three intents used.

If you set the checkpointLabelFilter parameter in the request, the array contains only the intents with the specified label.

Type: Array of IntentSummary (p. 503) objects

Array Members: Minimum number of 0 items. Maximum number of 3 items. sessionAttributes (p. 421)

Map of key/value pairs representing the session-specific context information. It contains application information passed between Amazon Lex and a client application.

Type: String to string map sessionId (p. 421)

A unique identifier for the session.

Type: String

Errors

BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in progress, or contains unbuilt changes.

HTTP Status Code: 400 InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500 LimitExceededException

Exceeded a limit.

HTTP Status Code: 429 NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go

423 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

• AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

424 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

PostContent Service: Amazon Lex Runtime Service

Sends user input (text or speech) to Amazon Lex. Clients use this API to send text and audio requests to Amazon Lex at runtime. Amazon Lex interprets the user input using the machine learning model that it built for the bot.

The PostContent operation supports audio input at 8kHz and 16kHz. You can use 8kHz audio to achieve higher speech recognition accuracy in telephone audio applications.

In response, Amazon Lex returns the next message to convey to the user. Consider the following example messages:

• For a user input "I would like a pizza," Amazon Lex might return a response with a message eliciting slot data (for example, PizzaSize): "What size pizza would you like?". • After the user provides all of the pizza order information, Amazon Lex might return a response with a message to get user confirmation: "Order the pizza?". • After the user replies "Yes" to the confirmation prompt, Amazon Lex might return a conclusion statement: "Thank you, your cheese pizza has been ordered.".

Not all Amazon Lex messages require a response from the user. For example, conclusion statements do not require a response. Some messages require only a yes or no response. In addition to the message, Amazon Lex provides additional context about the message in the response that you can use to enhance client behavior, such as displaying the appropriate client user interface. Consider the following examples:

• If the message is to elicit slot data, Amazon Lex returns the following context information: • x-amz-lex-dialog-state header set to ElicitSlot • x-amz-lex-intent-name header set to the intent name in the current context • x-amz-lex-slot-to-elicit header set to the slot name for which the message is eliciting information • x-amz-lex-slots header set to a map of slots configured for the intent with their current values • If the message is a confirmation prompt, the x-amz-lex-dialog-state header is set to Confirmation and the x-amz-lex-slot-to-elicit header is omitted. • If the message is a clarification prompt configured for the intent, indicating that the user intent is not understood, the x-amz-dialog-state header is set to ElicitIntent and the x-amz-slot-to- elicit header is omitted.

In addition, Amazon Lex also returns your application-specific sessionAttributes. For more information, see Managing Conversation Context. Request Syntax

POST /bot/botName/alias/botAlias/user/userId/content HTTP/1.1 x-amz-lex-session-attributes: sessionAttributes x-amz-lex-request-attributes: requestAttributes Content-Type: contentType Accept: accept x-amz-lex-active-contexts: activeContexts inputStream

URI Request Parameters

The request uses the following URI parameters.

425 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service accept (p. 425)

You pass this value as the Accept HTTP header.

The message Amazon Lex returns in the response can be either text or speech based on the Accept HTTP header value in the request. • If the value is text/plain; charset=utf-8, Amazon Lex returns text in the response. • If the value begins with audio/, Amazon Lex returns speech in the response. Amazon Lex uses Amazon Polly to generate the speech (using the configuration you specified in the Accept header). For example, if you specify audio/mpeg as the value, Amazon Lex returns speech in the MPEG format. • If the value is audio/pcm, the speech returned is audio/pcm in 16-bit, little endian format. • The following are the accepted values: • audio/mpeg • audio/ogg • audio/pcm • text/plain; charset=utf-8 • audio/* (defaults to mpeg) activeContexts (p. 425)

A list of contexts active for the request. A context can be activated when a previous intent is fulfilled, or by including the context in the request,

If you don't specify a list of contexts, Amazon Lex will use the current list of contexts for the session. If you specify an empty list, all contexts for the session are cleared. botAlias (p. 425)

Alias of the Amazon Lex bot.

Required: Yes botName (p. 425)

Name of the Amazon Lex bot.

Required: Yes contentType (p. 425)

You pass this value as the Content-Type HTTP header.

Indicates the audio format or text. The header value must start with one of the following prefixes: • PCM format, audio data must be in little-endian byte order. • audio/l16; rate=16000; channels=1 • audio/x-l16; sample-rate=16000; channel-count=1 • audio/lpcm; sample-rate=8000; sample-size-bits=16; channel-count=1; is-big-endian=false • Opus format • audio/x-cbr-opus-with-preamble; preamble-size=0; bit-rate=256000; frame-size-milliseconds=4 • Text format • text/plain; charset=utf-8

Required: Yes requestAttributes (p. 425)

You pass this value as the x-amz-lex-request-attributes HTTP header.

426 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Request-specific information passed between Amazon Lex and a client application. The value must be a JSON serialized and base64 encoded map with string keys and values. The total size of the requestAttributes and sessionAttributes headers is limited to 12 KB.

The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes with the prefix x-amz-lex:. For more information, see Setting Request Attributes. sessionAttributes (p. 425)

You pass this value as the x-amz-lex-session-attributes HTTP header. Application-specific information passed between Amazon Lex and a client application. The value must be a JSON serialized and base64 encoded map with string keys and values. The total size of the sessionAttributes and requestAttributes headers is limited to 12 KB. For more information, see Setting Session Attributes. userId (p. 425)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your bot. At runtime, each request must contain the userID field. To decide the user ID to use for your application, consider the following factors. • The userID field must not contain any personally identifiable information of the user, for example, name, personal identification numbers, or other end user personal information. • If you want a user to start a conversation on one device and continue on another device, use a user- specific identifier. • If you want the same user to be able to have two independent conversations on two different devices, choose a device-specific identifier. • A user can't have two independent conversations with two different versions of the same bot. For example, a user can't have a conversation with the PROD and BETA versions of the same bot. If you anticipate that a user will need to have conversation with two different versions, for example, while testing, include the bot alias in the user ID to separate the two conversations.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+ Required: Yes

Request Body

The request accepts the following binary data. inputStream (p. 425)

User input in PCM or Opus audio format or text format as described in the Content-Type HTTP header.

You can stream audio data to Amazon Lex or you can create a local buffer that captures all of the audio data before sending. In general, you get better performance if you stream audio data rather than buffering the data locally.

Required: Yes

Response Syntax

HTTP/1.1 200

427 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Content-Type: contentType x-amz-lex-intent-name: intentName x-amz-lex-nlu-intent-confidence: nluIntentConfidence x-amz-lex-alternative-intents: alternativeIntents x-amz-lex-slots: slots x-amz-lex-session-attributes: sessionAttributes x-amz-lex-sentiment: sentimentResponse x-amz-lex-message: message x-amz-lex-encoded-message: encodedMessage x-amz-lex-message-format: messageFormat x-amz-lex-dialog-state: dialogState x-amz-lex-slot-to-elicit: slotToElicit x-amz-lex-input-transcript: inputTranscript x-amz-lex-encoded-input-transcript: encodedInputTranscript x-amz-lex-bot-version: botVersion x-amz-lex-session-id: sessionId x-amz-lex-active-contexts: activeContexts audioStream

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The response returns the following HTTP headers. activeContexts (p. 427)

A list of active contexts for the session. A context can be set when an intent is fulfilled or by calling the PostContent, PostText, or PutSession operation.

You can use a context to control the intents that can follow up an intent, or to modify the operation of your application. alternativeIntents (p. 427)

One to four alternative intents that may be applicable to the user's intent.

Each alternative includes a score that indicates how confident Amazon Lex is that the intent matches the user's intent. The intents are sorted by the confidence score. botVersion (p. 427)

The version of the bot that responded to the conversation. You can use this information to help determine if one version of a bot is performing better than another version.

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+|\$LATEST contentType (p. 427)

Content type as specified in the Accept HTTP header in the request. dialogState (p. 427)

Identifies the current state of the user interaction. Amazon Lex returns one of the following values as dialogState. The client can optionally use this information to customize the user interface. • ElicitIntent - Amazon Lex wants to elicit the user's intent. Consider the following examples:

For example, a user might utter an intent ("I want to order a pizza"). If Amazon Lex cannot infer the user intent from this utterance, it will return this dialog state. • ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response.

428 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

For example, Amazon Lex wants user confirmation before fulfilling an intent. Instead of a simple "yes" or "no" response, a user might respond with additional information. For example, "yes, but make it a thick crust pizza" or "no, I want to order a drink." Amazon Lex can process such additional information (in these examples, update the crust type slot or change the intent from OrderPizza to OrderDrink). • ElicitSlot - Amazon Lex is expecting the value of a slot for the current intent.

For example, suppose that in the response Amazon Lex sends this message: "What size pizza would you like?". A user might reply with the slot value (e.g., "medium"). The user might also provide additional information in the response (e.g., "medium thick crust pizza"). Amazon Lex can process such additional information appropriately. • Fulfilled - Conveys that the Lambda function has successfully fulfilled the intent. • ReadyForFulfillment - Conveys that the client has to fulfill the request. • Failed - Conveys that the conversation with the user failed.

This can happen for various reasons, including that the user does not provide an appropriate response to prompts from the service (you can configure how many times Amazon Lex can prompt a user for specific information), or if the Lambda function fails to fulfill the intent.

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Fulfilled | ReadyForFulfillment | Failed encodedInputTranscript (p. 427)

The text used to process the request.

If the input was an audio stream, the encodedInputTranscript field contains the text extracted from the audio stream. This is the text that is actually processed to recognize intents and slot values. You can use this information to determine if Amazon Lex is correctly processing the audio that you send.

The encodedInputTranscript field is base-64 encoded. You must decode the field before you can use the value. encodedMessage (p. 427)

The message to convey to the user. The message can come from the bot's configuration or from a Lambda function.

If the intent is not configured with a Lambda function, or if the Lambda function returned Delegate as the dialogAction.type in its response, Amazon Lex decides on the next course of action and selects an appropriate message from the bot's configuration based on the current interaction context. For example, if Amazon Lex isn't able to understand user input, it uses a clarification prompt message.

When you create an intent you can assign messages to groups. When messages are assigned to groups Amazon Lex returns one message from each group in the response. The message field is an escaped JSON string containing the messages. For more information about the structure of the JSON string returned, see Formati di messaggio supportati (p. 15).

If the Lambda function returns a message, Amazon Lex passes it to the client in its response.

The encodedMessage field is base-64 encoded. You must decode the field before you can use the value.

Length Constraints: Minimum length of 1. Maximum length of 1366. inputTranscript (p. 427)

This header has been deprecated.

The text used to process the request.

429 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

You can use this field only in the de-DE, en-AU, en-GB, en-US, es-419, es-ES, es-US, fr-CA, fr- FR, and it-IT locales. In all other locales, the inputTranscript field is null. You should use the encodedInputTranscript field instead.

If the input was an audio stream, the inputTranscript field contains the text extracted from the audio stream. This is the text that is actually processed to recognize intents and slot values. You can use this information to determine if Amazon Lex is correctly processing the audio that you send. intentName (p. 427)

Current user intent that Amazon Lex is aware of. message (p. 427)

This header has been deprecated.

You can only use this field in the de-DE, en-AU, en-GB, en-US, es-419, es-ES, es-US, fr-CA, fr-FR, and it-IT locales. In all other locales, the message field is null. You should use the encodedMessage field instead.

The message to convey to the user. The message can come from the bot's configuration or from a Lambda function.

If the intent is not configured with a Lambda function, or if the Lambda function returned Delegate as the dialogAction.type in its response, Amazon Lex decides on the next course of action and selects an appropriate message from the bot's configuration based on the current interaction context. For example, if Amazon Lex isn't able to understand user input, it uses a clarification prompt message.

When you create an intent you can assign messages to groups. When messages are assigned to groups Amazon Lex returns one message from each group in the response. The message field is an escaped JSON string containing the messages. For more information about the structure of the JSON string returned, see Formati di messaggio supportati (p. 15).

If the Lambda function returns a message, Amazon Lex passes it to the client in its response.

Length Constraints: Minimum length of 1. Maximum length of 1024. messageFormat (p. 427)

The format of the response message. One of the following values: • PlainText - The message contains plain UTF-8 text. • CustomPayload - The message is a custom format for the client. • SSML - The message contains text formatted for voice output. • Composite - The message contains an escaped JSON object containing one or more messages from the groups that messages were assigned to when the intent was created.

Valid Values: PlainText | CustomPayload | SSML | Composite nluIntentConfidence (p. 427)

Provides a score that indicates how confident Amazon Lex is that the returned intent is the one that matches the user's intent. The score is between 0.0 and 1.0.

The score is a relative score, not an absolute score. The score may change based on improvements to Amazon Lex. sentimentResponse (p. 427)

The sentiment expressed in an utterance.

When the bot is configured to send utterances to Amazon Comprehend for sentiment analysis, this field contains the result of the analysis.

430 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service sessionAttributes (p. 427)

Map of key/value pairs representing the session-specific context information. sessionId (p. 427)

The unique identifier for the session. slots (p. 427)

Map of zero or more intent slots (name/value pairs) Amazon Lex detected from the user input during the conversation. The field is base-64 encoded.

Amazon Lex creates a resolution list containing likely values for a slot. The value that it returns is determined by the valueSelectionStrategy selected when the slot type was created or updated. If valueSelectionStrategy is set to ORIGINAL_VALUE, the value provided by the user is returned, if the user value is similar to the slot values. If valueSelectionStrategy is set to TOP_RESOLUTION Amazon Lex returns the first value in the resolution list or, if there is no resolution list, null. If you don't specify a valueSelectionStrategy, the default is ORIGINAL_VALUE. slotToElicit (p. 427)

If the dialogState value is ElicitSlot, returns the name of the slot for which Amazon Lex is eliciting a value.

The response returns the following as the HTTP body. audioStream (p. 427)

The prompt (or statement) to convey to the user. This is based on the bot configuration and context. For example, if Amazon Lex did not understand the user intent, it sends the clarificationPrompt configured for the bot. If the intent requires confirmation before taking the fulfillment action, it sends the confirmationPrompt. Another example: Suppose that the Lambda function successfully fulfilled the intent, and sent a message to convey to the user. Then Amazon Lex sends that message in the response.

Errors

BadGatewayException

Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda) failed with an internal service error.

HTTP Status Code: 502 BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in progress, or contains unbuilt changes.

HTTP Status Code: 400 ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409 DependencyFailedException

One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, • If Amazon Lex does not have sufficient permissions to call a Lambda function.

431 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

• If a Lambda function takes longer than 30 seconds to execute. • If a fulfillment Lambda function returns a Delegate dialog action without removing any slot values.

HTTP Status Code: 424 InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500 LimitExceededException

Exceeded a limit.

HTTP Status Code: 429 LoopDetectedException

This exception is not used.

HTTP Status Code: 508 NotAcceptableException

The accept header in the request does not have a valid value.

HTTP Status Code: 406 NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404 RequestTimeoutException

The input speech is too long.

HTTP Status Code: 408 UnsupportedMediaTypeException

The Content-Type header (PostContent API) has an invalid value.

HTTP Status Code: 415

Examples

Example 1

In this request, the URI identifies a bot (Traffic), bot version ($LATEST), and end user name (someuser). The Content-Type header identifies the format of the audio in the body. Amazon Lex also supports other formats. To convert audio from one format to another, if necessary, you can use SoX open source software. You specify the format in which you want to get the response by adding the Accept HTTP header.

In the response, the x-amz-lex-message header shows the response that Amazon Lex returned. The client can then send this response to the user. The same message is sent in audio/MPEG format through chunked encoding (as requested).

Sample Request

"POST /bot/Traffic/alias/$LATEST/user/someuser/content HTTP/1.1[\r][\n]" "x-amz-lex-session-attributes: eyJ1c2VyTmFtZSI6IkJvYiJ9[\r][\n]"

432 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

"Content-Type: audio/x-l16; channel-count=1; sample-rate=16000f[\r][\n]" "Accept: audio/mpeg[\r][\n]" "Host: runtime.lex.us-east-1.amazonaws.com[\r][\n]" "Authorization: AWS4-HMAC-SHA256 Credential=BLANKED_OUT/20161230/us-east-1/lex/ aws4_request, SignedHeaders=accept;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-lex-session- attributes, Signature=78ca5b54ea3f64a17ff7522de02cd90a9acd2365b45a9ce9b96ea105bb1c7ec2[\r] [\n]" "X-Amz-Date: 20161230T181426Z[\r][\n]" "X-Amz-Content-Sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855[\r] [\n]" "Transfer-Encoding: chunked[\r][\n]" "Connection: Keep-Alive[\r][\n]" "User-Agent: Apache-HttpClient/4.5.x (Java/1.8.0_112)[\r][\n]" "Accept-Encoding: gzip,deflate[\r][\n]" "[\r][\n]" "1000[\r][\n]" "[0x7][0x0][0x7][0x0][\n]" "[0x0][0x7][0x0][0xfc][0xff][\n]" "[0x0][\n]" …

Sample Response

"HTTP/1.1 200 OK[\r][\n]" "x-amzn-RequestId: cc8b34af-cebb-11e6-a35c-55f3a992f28d[\r][\n]" "x-amz-lex-message: Sorry, can you repeat that?[\r][\n]" "x-amz-lex-dialog-state: ElicitIntent[\r][\n]" "x-amz-lex-session-attributes: eyJ1c2VyTmFtZSI6IkJvYiJ9[\r][\n]" "Content-Type: audio/mpeg[\r][\n]" "Transfer-Encoding: chunked[\r][\n]" "Date: Fri, 30 Dec 2016 18:14:28 GMT[\r][\n]" "[\r][\n]" "2000[\r][\n]" "ID3[0x4][0x0][0x0][0x0][0x0][0x0]#TSSE[0x0][0x0][0x0][0xf][0x0][0x0] [0x3]Lavf57.41.100[0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0x0][0xff] [0xf3]`[0xc4][0x0][0x1b]{[0x8d][0xe8][0x1]C[0x18][0x1][0x0]J[0xe0]`b[0xdd][0xd1][0xb] [0xfd][0x11][0xdf][0xfe]";[0xbb][0xbb][0x9f][0xee][0xee][0xee][0xee]|DDD/[0xff][0xff] [0xff][0xff]www?D[0xf7]w^?[0xff][0xfa]h[0x88][0x85][0xfe][0x88][0x88][0x88][[0xa2]'[0xff] [0xfa]"{[0x9f][0xe8][0x88]]D[0xeb][0xbb][0xbb][0xa2]!u[0xfd][0xdd][0xdf][0x88][0x94] [0x0]F[0xef][0xa1]8[0x0][0x82]w[0x88]N[0x0][0x0][0x9b][0xbb][0xe8][0xe …

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

433 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

PostText Service: Amazon Lex Runtime Service

Sends user input to Amazon Lex. Client applications can use this API to send requests to Amazon Lex at runtime. Amazon Lex then interprets the user input using the machine learning model it built for the bot.

In response, Amazon Lex returns the next message to convey to the user an optional responseCard to display. Consider the following example messages:

• For a user input "I would like a pizza", Amazon Lex might return a response with a message eliciting slot data (for example, PizzaSize): "What size pizza would you like?" • After the user provides all of the pizza order information, Amazon Lex might return a response with a message to obtain user confirmation "Proceed with the pizza order?". • After the user replies to a confirmation prompt with a "yes", Amazon Lex might return a conclusion statement: "Thank you, your cheese pizza has been ordered.".

Not all Amazon Lex messages require a user response. For example, a conclusion statement does not require a response. Some messages require only a "yes" or "no" user response. In addition to the message, Amazon Lex provides additional context about the message in the response that you might use to enhance client behavior, for example, to display the appropriate client user interface. These are the slotToElicit, dialogState, intentName, and slots fields in the response. Consider the following examples:

• If the message is to elicit slot data, Amazon Lex returns the following context information: • dialogState set to ElicitSlot • intentName set to the intent name in the current context • slotToElicit set to the slot name for which the message is eliciting information • slots set to a map of slots, configured for the intent, with currently known values • If the message is a confirmation prompt, the dialogState is set to ConfirmIntent and SlotToElicit is set to null. • If the message is a clarification prompt (configured for the intent) that indicates that user intent is not understood, the dialogState is set to ElicitIntent and slotToElicit is set to null.

In addition, Amazon Lex also returns your application-specific sessionAttributes. For more information, see Managing Conversation Context. Request Syntax

POST /bot/botName/alias/botAlias/user/userId/text HTTP/1.1 Content-type: application/json

{ "activeContexts": [ { "name": "string", "parameters": { "string" : "string" }, "timeToLive": { "timeToLiveInSeconds": number, "turnsToLive": number } } ], "inputText": "string", "requestAttributes": {

434 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

"string" : "string" }, "sessionAttributes": { "string" : "string" } }

URI Request Parameters

The request uses the following URI parameters. botAlias (p. 434)

The alias of the Amazon Lex bot.

Required: Yes botName (p. 434)

The name of the Amazon Lex bot.

Required: Yes userId (p. 434)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your bot. At runtime, each request must contain the userID field.

To decide the user ID to use for your application, consider the following factors. • The userID field must not contain any personally identifiable information of the user, for example, name, personal identification numbers, or other end user personal information. • If you want a user to start a conversation on one device and continue on another device, use a user- specific identifier. • If you want the same user to be able to have two independent conversations on two different devices, choose a device-specific identifier. • A user can't have two independent conversations with two different versions of the same bot. For example, a user can't have a conversation with the PROD and BETA versions of the same bot. If you anticipate that a user will need to have conversation with two different versions, for example, while testing, include the bot alias in the user ID to separate the two conversations.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Required: Yes

Request Body

The request accepts the following data in JSON format. activeContexts (p. 434)

A list of contexts active for the request. A context can be activated when a previous intent is fulfilled, or by including the context in the request,

If you don't specify a list of contexts, Amazon Lex will use the current list of contexts for the session. If you specify an empty list, all contexts for the session are cleared.

Type: Array of ActiveContext (p. 495) objects

435 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Array Members: Minimum number of 0 items. Maximum number of 20 items.

Required: No inputText (p. 434)

The text that the user entered (Amazon Lex interprets this text).

When you are using the AWS CLI, you can't pass a URL in the --input-text parameter. Pass the URL using the --cli-input-json parameter instead.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1024.

Required: Yes requestAttributes (p. 434)

Request-specific information passed between Amazon Lex and a client application.

The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes with the prefix x-amz-lex:.

For more information, see Setting Request Attributes.

Type: String to string map

Required: No sessionAttributes (p. 434)

Application-specific information passed between Amazon Lex and a client application.

For more information, see Setting Session Attributes.

Type: String to string map

Required: No

Response Syntax

HTTP/1.1 200 Content-type: application/json

{ "activeContexts": [ { "name": "string", "parameters": { "string" : "string" }, "timeToLive": { "timeToLiveInSeconds": number, "turnsToLive": number } } ], "alternativeIntents": [ { "intentName": "string", "nluIntentConfidence": {

436 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

"score": number }, "slots": { "string" : "string" } } ], "botVersion": "string", "dialogState": "string", "intentName": "string", "message": "string", "messageFormat": "string", "nluIntentConfidence": { "score": number }, "responseCard": { "contentType": "string", "genericAttachments": [ { "attachmentLinkUrl": "string", "buttons": [ { "text": "string", "value": "string" } ], "imageUrl": "string", "subTitle": "string", "title": "string" } ], "version": "string" }, "sentimentResponse": { "sentimentLabel": "string", "sentimentScore": "string" }, "sessionAttributes": { "string" : "string" }, "sessionId": "string", "slots": { "string" : "string" }, "slotToElicit": "string" }

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The following data is returned in JSON format by the service. activeContexts (p. 436)

A list of active contexts for the session. A context can be set when an intent is fulfilled or by calling the PostContent, PostText, or PutSession operation.

You can use a context to control the intents that can follow up an intent, or to modify the operation of your application.

Type: Array of ActiveContext (p. 495) objects

Array Members: Minimum number of 0 items. Maximum number of 20 items.

437 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service alternativeIntents (p. 436)

One to four alternative intents that may be applicable to the user's intent.

Each alternative includes a score that indicates how confident Amazon Lex is that the intent matches the user's intent. The intents are sorted by the confidence score.

Type: Array of PredictedIntent (p. 505) objects

Array Members: Maximum number of 4 items. botVersion (p. 436)

The version of the bot that responded to the conversation. You can use this information to help determine if one version of a bot is performing better than another version.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: [0-9]+|\$LATEST dialogState (p. 436)

Identifies the current state of the user interaction. Amazon Lex returns one of the following values as dialogState. The client can optionally use this information to customize the user interface. • ElicitIntent - Amazon Lex wants to elicit user intent.

For example, a user might utter an intent ("I want to order a pizza"). If Amazon Lex cannot infer the user intent from this utterance, it will return this dialogState. • ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response.

For example, Amazon Lex wants user confirmation before fulfilling an intent.

Instead of a simple "yes" or "no," a user might respond with additional information. For example, "yes, but make it thick crust pizza" or "no, I want to order a drink". Amazon Lex can process such additional information (in these examples, update the crust type slot value, or change intent from OrderPizza to OrderDrink). • ElicitSlot - Amazon Lex is expecting a slot value for the current intent.

For example, suppose that in the response Amazon Lex sends this message: "What size pizza would you like?". A user might reply with the slot value (e.g., "medium"). The user might also provide additional information in the response (e.g., "medium thick crust pizza"). Amazon Lex can process such additional information appropriately. • Fulfilled - Conveys that the Lambda function configured for the intent has successfully fulfilled the intent. • ReadyForFulfillment - Conveys that the client has to fulfill the intent. • Failed - Conveys that the conversation with the user failed.

This can happen for various reasons including that the user did not provide an appropriate response to prompts from the service (you can configure how many times Amazon Lex can prompt a user for specific information), or the Lambda function failed to fulfill the intent.

Type: String

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Fulfilled | ReadyForFulfillment | Failed intentName (p. 436)

The current user intent that Amazon Lex is aware of.

438 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Type: String message (p. 436)

The message to convey to the user. The message can come from the bot's configuration or from a Lambda function.

If the intent is not configured with a Lambda function, or if the Lambda function returned Delegate as the dialogAction.type its response, Amazon Lex decides on the next course of action and selects an appropriate message from the bot's configuration based on the current interaction context. For example, if Amazon Lex isn't able to understand user input, it uses a clarification prompt message.

When you create an intent you can assign messages to groups. When messages are assigned to groups Amazon Lex returns one message from each group in the response. The message field is an escaped JSON string containing the messages. For more information about the structure of the JSON string returned, see Formati di messaggio supportati (p. 15).

If the Lambda function returns a message, Amazon Lex passes it to the client in its response.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1024. messageFormat (p. 436)

The format of the response message. One of the following values: • PlainText - The message contains plain UTF-8 text. • CustomPayload - The message is a custom format defined by the Lambda function. • SSML - The message contains text formatted for voice output. • Composite - The message contains an escaped JSON object containing one or more messages from the groups that messages were assigned to when the intent was created.

Type: String

Valid Values: PlainText | CustomPayload | SSML | Composite nluIntentConfidence (p. 436)

Provides a score that indicates how confident Amazon Lex is that the returned intent is the one that matches the user's intent. The score is between 0.0 and 1.0. For more information, see Confidence Scores.

The score is a relative score, not an absolute score. The score may change based on improvements to Amazon Lex.

Type: IntentConfidence (p. 502) object responseCard (p. 436)

Represents the options that the user has to respond to the current prompt. Response Card can come from the bot configuration (in the Amazon Lex console, choose the settings button next to a slot) or from a code hook (Lambda function).

Type: ResponseCard (p. 506) object sentimentResponse (p. 436)

The sentiment expressed in and utterance.

When the bot is configured to send utterances to Amazon Comprehend for sentiment analysis, this field contains the result of the analysis.

Type: SentimentResponse (p. 507) object

439 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service sessionAttributes (p. 436)

A map of key-value pairs representing the session-specific context information.

Type: String to string map sessionId (p. 436)

A unique identifier for the session.

Type: String slots (p. 436)

The intent slots that Amazon Lex detected from the user input in the conversation.

Amazon Lex creates a resolution list containing likely values for a slot. The value that it returns is determined by the valueSelectionStrategy selected when the slot type was created or updated. If valueSelectionStrategy is set to ORIGINAL_VALUE, the value provided by the user is returned, if the user value is similar to the slot values. If valueSelectionStrategy is set to TOP_RESOLUTION Amazon Lex returns the first value in the resolution list or, if there is no resolution list, null. If you don't specify a valueSelectionStrategy, the default is ORIGINAL_VALUE.

Type: String to string map slotToElicit (p. 436)

If the dialogState value is ElicitSlot, returns the name of the slot for which Amazon Lex is eliciting a value.

Type: String

Errors

BadGatewayException

Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda) failed with an internal service error.

HTTP Status Code: 502 BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in progress, or contains unbuilt changes.

HTTP Status Code: 400 ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409 DependencyFailedException

One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, • If Amazon Lex does not have sufficient permissions to call a Lambda function. • If a Lambda function takes longer than 30 seconds to execute. • If a fulfillment Lambda function returns a Delegate dialog action without removing any slot values.

HTTP Status Code: 424

440 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500 LimitExceededException

Exceeded a limit.

HTTP Status Code: 429 LoopDetectedException

This exception is not used.

HTTP Status Code: 508 NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

441 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

PutSession Service: Amazon Lex Runtime Service

Creates a new session or modifies an existing session with an Amazon Lex bot. Use this operation to enable your application to set the state of the bot.

For more information, see Managing Sessions.

Request Syntax

POST /bot/botName/alias/botAlias/user/userId/session HTTP/1.1 Accept: accept Content-type: application/json

{ "activeContexts": [ { "name": "string", "parameters": { "string" : "string" }, "timeToLive": { "timeToLiveInSeconds": number, "turnsToLive": number } } ], "dialogAction": { "fulfillmentState": "string", "intentName": "string", "message": "string", "messageFormat": "string", "slots": { "string" : "string" }, "slotToElicit": "string", "type": "string" }, "recentIntentSummaryView": [ { "checkpointLabel": "string", "confirmationStatus": "string", "dialogActionType": "string", "fulfillmentState": "string", "intentName": "string", "slots": { "string" : "string" }, "slotToElicit": "string" } ], "sessionAttributes": { "string" : "string" } }

URI Request Parameters

The request uses the following URI parameters.

442 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service accept (p. 442)

The message that Amazon Lex returns in the response can be either text or speech based depending on the value of this field. • If the value is text/plain; charset=utf-8, Amazon Lex returns text in the response. • If the value begins with audio/, Amazon Lex returns speech in the response. Amazon Lex uses Amazon Polly to generate the speech in the configuration that you specify. For example, if you specify audio/mpeg as the value, Amazon Lex returns speech in the MPEG format. • If the value is audio/pcm, the speech is returned as audio/pcm in 16-bit, little endian format. • The following are the accepted values: • audio/mpeg • audio/ogg • audio/pcm • audio/* (defaults to mpeg) • text/plain; charset=utf-8 botAlias (p. 442)

The alias in use for the bot that contains the session data.

Required: Yes botName (p. 442)

The name of the bot that contains the session data.

Required: Yes userId (p. 442)

The ID of the client application user. Amazon Lex uses this to identify a user's conversation with your bot.

Length Constraints: Minimum length of 2. Maximum length of 100.

Pattern: [0-9a-zA-Z._:-]+

Required: Yes

Request Body

The request accepts the following data in JSON format. activeContexts (p. 442)

A list of contexts active for the request. A context can be activated when a previous intent is fulfilled, or by including the context in the request,

If you don't specify a list of contexts, Amazon Lex will use the current list of contexts for the session. If you specify an empty list, all contexts for the session are cleared.

Type: Array of ActiveContext (p. 495) objects

Array Members: Minimum number of 0 items. Maximum number of 20 items.

Required: No dialogAction (p. 442)

Sets the next action that the bot should take to fulfill the conversation.

443 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Type: DialogAction (p. 498) object

Required: No recentIntentSummaryView (p. 442)

A summary of the recent intents for the bot. You can use the intent summary view to set a checkpoint label on an intent and modify attributes of intents. You can also use it to remove or add intent summary objects to the list.

An intent that you modify or add to the list must make sense for the bot. For example, the intent name must be valid for the bot. You must provide valid values for: • intentName • slot names • slotToElict

If you send the recentIntentSummaryView parameter in a PutSession request, the contents of the new summary view replaces the old summary view. For example, if a GetSession request returns three intents in the summary view and you call PutSession with one intent in the summary view, the next call to GetSession will only return one intent.

Type: Array of IntentSummary (p. 503) objects

Array Members: Minimum number of 0 items. Maximum number of 3 items.

Required: No sessionAttributes (p. 442)

Map of key/value pairs representing the session-specific context information. It contains application information passed between Amazon Lex and a client application.

Type: String to string map

Required: No

Response Syntax

HTTP/1.1 200 Content-Type: contentType x-amz-lex-intent-name: intentName x-amz-lex-slots: slots x-amz-lex-session-attributes: sessionAttributes x-amz-lex-message: message x-amz-lex-encoded-message: encodedMessage x-amz-lex-message-format: messageFormat x-amz-lex-dialog-state: dialogState x-amz-lex-slot-to-elicit: slotToElicit x-amz-lex-session-id: sessionId x-amz-lex-active-contexts: activeContexts audioStream

Response Elements

If the action is successful, the service sends back an HTTP 200 response.

The response returns the following HTTP headers.

444 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service activeContexts (p. 444)

A list of active contexts for the session. contentType (p. 444)

Content type as specified in the Accept HTTP header in the request. dialogState (p. 444)

• ConfirmIntent - Amazon Lex is expecting a "yes" or "no" response to confirm the intent before fulfilling an intent. • ElicitIntent - Amazon Lex wants to elicit the user's intent. • ElicitSlot - Amazon Lex is expecting the value of a slot for the current intent. • Failed - Conveys that the conversation with the user has failed. This can happen for various reasons, including the user does not provide an appropriate response to prompts from the service, or if the Lambda function fails to fulfill the intent. • Fulfilled - Conveys that the Lambda function has sucessfully fulfilled the intent. • ReadyForFulfillment - Conveys that the client has to fulfill the intent.

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Fulfilled | ReadyForFulfillment | Failed encodedMessage (p. 444)

The next message that should be presented to the user.

The encodedMessage field is base-64 encoded. You must decode the field before you can use the value.

Length Constraints: Minimum length of 1. Maximum length of 1366. intentName (p. 444)

The name of the current intent. message (p. 444)

This header has been deprecated.

The next message that should be presented to the user.

You can only use this field in the de-DE, en-AU, en-GB, en-US, es-419, es-ES, es-US, fr-CA, fr-FR, and it-IT locales. In all other locales, the message field is null. You should use the encodedMessage field instead.

Length Constraints: Minimum length of 1. Maximum length of 1024. messageFormat (p. 444)

The format of the response message. One of the following values: • PlainText - The message contains plain UTF-8 text. • CustomPayload - The message is a custom format for the client. • SSML - The message contains text formatted for voice output. • Composite - The message contains an escaped JSON object containing one or more messages from the groups that messages were assigned to when the intent was created.

Valid Values: PlainText | CustomPayload | SSML | Composite sessionAttributes (p. 444)

Map of key/value pairs representing session-specific context information.

445 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service sessionId (p. 444)

A unique identifier for the session. slots (p. 444)

Map of zero or more intent slots Amazon Lex detected from the user input during the conversation.

Amazon Lex creates a resolution list containing likely values for a slot. The value that it returns is determined by the valueSelectionStrategy selected when the slot type was created or updated. If valueSelectionStrategy is set to ORIGINAL_VALUE, the value provided by the user is returned, if the user value is similar to the slot values. If valueSelectionStrategy is set to TOP_RESOLUTION Amazon Lex returns the first value in the resolution list or, if there is no resolution list, null. If you don't specify a valueSelectionStrategy the default is ORIGINAL_VALUE. slotToElicit (p. 444)

If the dialogState is ElicitSlot, returns the name of the slot for which Amazon Lex is eliciting a value.

The response returns the following as the HTTP body. audioStream (p. 444)

The audio version of the message to convey to the user.

Errors

BadGatewayException

Either the Amazon Lex bot is still building, or one of the dependent services (Amazon Polly, AWS Lambda) failed with an internal service error.

HTTP Status Code: 502 BadRequestException

Request validation failed, there is no usable message in the context, or the bot build failed, is still in progress, or contains unbuilt changes.

HTTP Status Code: 400 ConflictException

Two clients are using the same AWS account, Amazon Lex bot, and user ID.

HTTP Status Code: 409 DependencyFailedException

One of the dependencies, such as AWS Lambda or Amazon Polly, threw an exception. For example, • If Amazon Lex does not have sufficient permissions to call a Lambda function. • If a Lambda function takes longer than 30 seconds to execute. • If a fulfillment Lambda function returns a Delegate dialog action without removing any slot values.

HTTP Status Code: 424 InternalFailureException

Internal service error. Retry the call.

HTTP Status Code: 500

446 Amazon Lex Guida per gli sviluppatori Data Types

LimitExceededException

Exceeded a limit.

HTTP Status Code: 429 NotAcceptableException

The accept header in the request does not have a valid value.

HTTP Status Code: 406 NotFoundException

The resource (such as the Amazon Lex bot or an alias) that is referred to is not found.

HTTP Status Code: 404

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for JavaScript • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3

Data Types

The following data types are supported by Amazon Lex Model Building Service:

• BotAliasMetadata (p. 450) • BotChannelAssociation (p. 452) • BotMetadata (p. 454) • BuiltinIntentMetadata (p. 456) • BuiltinIntentSlot (p. 457) • BuiltinSlotTypeMetadata (p. 458) • CodeHook (p. 459) • ConversationLogsRequest (p. 460) • ConversationLogsResponse (p. 461) • EnumerationValue (p. 462) • FollowUpPrompt (p. 463) • FulfillmentActivity (p. 464) • InputContext (p. 465) • Intent (p. 466) • IntentMetadata (p. 467)

447 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• KendraConfiguration (p. 469) • LogSettingsRequest (p. 471) • LogSettingsResponse (p. 473) • Message (p. 475) • MigrationAlert (p. 476) • MigrationSummary (p. 477) • OutputContext (p. 479) • Prompt (p. 480) • ResourceReference (p. 481) • Slot (p. 482) • SlotDefaultValue (p. 485) • SlotDefaultValueSpec (p. 486) • SlotTypeConfiguration (p. 487) • SlotTypeMetadata (p. 488) • SlotTypeRegexConfiguration (p. 490) • Statement (p. 491) • Tag (p. 492) • UtteranceData (p. 493) • UtteranceList (p. 494)

The following data types are supported by Amazon Lex Runtime Service:

• ActiveContext (p. 495) • ActiveContextTimeToLive (p. 496) • Button (p. 497) • DialogAction (p. 498) • GenericAttachment (p. 500) • IntentConfidence (p. 502) • IntentSummary (p. 503) • PredictedIntent (p. 505) • ResponseCard (p. 506) • SentimentResponse (p. 507)

Amazon Lex Model Building Service

The following data types are supported by Amazon Lex Model Building Service:

• BotAliasMetadata (p. 450) • BotChannelAssociation (p. 452) • BotMetadata (p. 454) • BuiltinIntentMetadata (p. 456) • BuiltinIntentSlot (p. 457) • BuiltinSlotTypeMetadata (p. 458) • CodeHook (p. 459) • ConversationLogsRequest (p. 460) • ConversationLogsResponse (p. 461)

448 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• EnumerationValue (p. 462) • FollowUpPrompt (p. 463) • FulfillmentActivity (p. 464) • InputContext (p. 465) • Intent (p. 466) • IntentMetadata (p. 467) • KendraConfiguration (p. 469) • LogSettingsRequest (p. 471) • LogSettingsResponse (p. 473) • Message (p. 475) • MigrationAlert (p. 476) • MigrationSummary (p. 477) • OutputContext (p. 479) • Prompt (p. 480) • ResourceReference (p. 481) • Slot (p. 482) • SlotDefaultValue (p. 485) • SlotDefaultValueSpec (p. 486) • SlotTypeConfiguration (p. 487) • SlotTypeMetadata (p. 488) • SlotTypeRegexConfiguration (p. 490) • Statement (p. 491) • Tag (p. 492) • UtteranceData (p. 493) • UtteranceList (p. 494)

449 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BotAliasMetadata Service: Amazon Lex Model Building Service

Provides information about a bot alias. Contents botName

The name of the bot to which the alias points.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No botVersion

The version of the Amazon Lex bot to which the alias points.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No checksum

Checksum of the bot alias.

Type: String

Required: No conversationLogs

Settings that determine how Amazon Lex uses conversation logs for the alias.

Type: ConversationLogsResponse (p. 461) object

Required: No createdDate

The date that the bot alias was created.

Type: Timestamp

Required: No description

A description of the bot alias.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No

450 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service lastUpdatedDate

The date that the bot alias was updated. When you create a resource, the creation date and last updated date are the same.

Type: Timestamp

Required: No name

The name of the bot alias.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

451 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BotChannelAssociation Service: Amazon Lex Model Building Service

Represents an association between an Amazon Lex bot and an external messaging platform. Contents botAlias

An alias pointing to the specific version of the Amazon Lex bot to which this association is being made.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No botConfiguration

Provides information necessary to communicate with the messaging platform.

Type: String to string map

Map Entries: Maximum number of 10 items.

Required: No botName

The name of the Amazon Lex bot to which this association is being made. Note

Currently, Amazon Lex supports associations with Facebook and Slack, and Twilio.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No createdDate

The date that the association between the Amazon Lex bot and the channel was created.

Type: Timestamp

Required: No description

A text description of the association you are creating.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No failureReason

If status is FAILED, Amazon Lex provides the reason that it failed to create the association.

452 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Type: String

Required: No name

The name of the association between the bot and the channel.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No status

The status of the bot channel. • CREATED - The channel has been created and is ready for use. • IN_PROGRESS - Channel creation is in progress. • FAILED - There was an error creating the channel. For information about the reason for the failure, see the failureReason field.

Type: String

Valid Values: IN_PROGRESS | CREATED | FAILED

Required: No type

Specifies the type of association by indicating the type of channel being established between the Amazon Lex bot and the external messaging platform.

Type: String

Valid Values: Facebook | Slack | Twilio-Sms | Kik

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

453 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BotMetadata Service: Amazon Lex Model Building Service

Provides information about a bot. . Contents createdDate

The date that the bot was created.

Type: Timestamp

Required: No description

A description of the bot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No lastUpdatedDate

The date that the bot was updated. When you create a bot, the creation date and last updated date are the same.

Type: Timestamp

Required: No name

The name of the bot.

Type: String

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No status

The status of the bot.

Type: String

Valid Values: BUILDING | READY | READY_BASIC_TESTING | FAILED | NOT_BUILT

Required: No version

The version of the bot. For a new bot, the version is always $LATEST.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

454 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

455 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BuiltinIntentMetadata Service: Amazon Lex Model Building Service

Provides metadata for a built-in intent. Contents signature

A unique identifier for the built-in intent. To find the signature for an intent, see Standard Built-in Intents in the Alexa Skills Kit.

Type: String

Required: No supportedLocales

A list of identifiers for the locales that the intent supports.

Type: Array of strings

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

456 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BuiltinIntentSlot Service: Amazon Lex Model Building Service

Provides information about a slot used in a built-in intent. Contents name

A list of the slots defined for the intent.

Type: String

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

457 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

BuiltinSlotTypeMetadata Service: Amazon Lex Model Building Service

Provides information about a built in slot type. Contents signature

A unique identifier for the built-in slot type. To find the signature for a slot type, see Slot Type Reference in the Alexa Skills Kit.

Type: String

Required: No supportedLocales

A list of target locales for the slot.

Type: Array of strings

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

458 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

CodeHook Service: Amazon Lex Model Building Service

Specifies a Lambda function that verifies requests to a bot or fulfills the user's request to a bot.. Contents messageVersion

The version of the request-response that you want Amazon Lex to use to invoke your Lambda function. For more information, see Utilizzo delle funzioni Lambda (p. 140).

Type: String

Length Constraints: Minimum length of 1. Maximum length of 5.

Required: Yes uri

The Amazon Resource Name (ARN) of the Lambda function.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: arn:aws[a-zA-Z-]*:lambda:[a-z]+-[a-z]+(-[a-z]+)*-[0-9]:[0-9] {12}:function:[a-zA-Z0-9-_]+(\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f] {4}-[0-9a-f]{12})?(:[a-zA-Z0-9-_]+)?

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

459 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConversationLogsRequest Service: Amazon Lex Model Building Service

Provides the settings needed for conversation logs. Contents iamRoleArn

The Amazon Resource Name (ARN) of an IAM role with permission to write to your CloudWatch Logs for text logs and your S3 bucket for audio logs. If audio encryption is enabled, this role also provides access permission for the AWS KMS key used for encrypting audio logs. For more information, see Creating an IAM Role and Policy for Conversation Logs.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Required: Yes logSettings

The settings for your conversation logs. You can log the conversation text, conversation audio, or both.

Type: Array of LogSettingsRequest (p. 471) objects

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

460 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ConversationLogsResponse Service: Amazon Lex Model Building Service

Contains information about conversation log settings. Contents iamRoleArn

The Amazon Resource Name (ARN) of the IAM role used to write your logs to CloudWatch Logs or an S3 bucket.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Required: No logSettings

The settings for your conversation logs. You can log text, audio, or both.

Type: Array of LogSettingsResponse (p. 473) objects

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

461 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

EnumerationValue Service: Amazon Lex Model Building Service

Each slot type can have a set of values. Each enumeration value represents a value the slot type can take.

For example, a pizza ordering bot could have a slot type that specifies the type of crust that the pizza should have. The slot type could include the values

• thick • thin • stuffed

Contents synonyms

Additional values related to the slot type value.

Type: Array of strings

Length Constraints: Minimum length of 1. Maximum length of 140.

Required: No value

The value of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 140.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

462 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

FollowUpPrompt Service: Amazon Lex Model Building Service

A prompt for additional activity after an intent is fulfilled. For example, after the OrderPizza intent is fulfilled, you might prompt the user to find out whether the user wants to order drinks. Contents prompt

Prompts for information from the user.

Type: Prompt (p. 480) object

Required: Yes rejectionStatement

If the user answers "no" to the question defined in the prompt field, Amazon Lex responds with this statement to acknowledge that the intent was canceled.

Type: Statement (p. 491) object

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

463 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

FulfillmentActivity Service: Amazon Lex Model Building Service

Describes how the intent is fulfilled after the user provides all of the information required for the intent. You can provide a Lambda function to process the intent, or you can return the intent information to the client application. We recommend that you use a Lambda function so that the relevant logic lives in the Cloud and limit the client-side code primarily to presentation. If you need to update the logic, you only update the Lambda function; you don't need to upgrade your client application.

Consider the following examples:

• In a pizza ordering application, after the user provides all of the information for placing an order, you use a Lambda function to place an order with a pizzeria. • In a gaming application, when a user says "pick up a rock," this information must go back to the client application so that it can perform the operation and update the graphics. In this case, you want Amazon Lex to return the intent data to the client.

Contents codeHook

A description of the Lambda function that is run to fulfill the intent.

Type: CodeHook (p. 459) object

Required: No type

How the intent should be fulfilled, either by running a Lambda function or by returning the slot data to the client application.

Type: String

Valid Values: ReturnIntent | CodeHook

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

464 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

InputContext Service: Amazon Lex Model Building Service

The name of a context that must be active for an intent to be selected by Amazon Lex. Contents name

The name of the context.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

465 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Intent Service: Amazon Lex Model Building Service

Identifies the specific version of an intent. Contents intentName

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes intentVersion

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

466 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

IntentMetadata Service: Amazon Lex Model Building Service

Provides information about an intent. Contents createdDate

The date that the intent was created.

Type: Timestamp

Required: No description

A description of the intent.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No lastUpdatedDate

The date that the intent was updated. When you create an intent, the creation date and last updated date are the same.

Type: Timestamp

Required: No name

The name of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No version

The version of the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

467 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

468 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

KendraConfiguration Service: Amazon Lex Model Building Service

Provides configuration information for the AMAZON.KendraSearchIntent intent. When you use this intent, Amazon Lex searches the specified Amazon Kendra index and returns documents from the index that match the user's utterance. For more information, see AMAZON.KendraSearchIntent. Contents kendraIndex

The Amazon Resource Name (ARN) of the Amazon Kendra index that you want the AMAZON.KendraSearchIntent intent to search. The index must be in the same account and Region as the Amazon Lex bot. If the Amazon Kendra index does not exist, you get an exception when you call the PutIntent operation.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: arn:aws:kendra:[a-z]+-[a-z]+-[0-9]:[0-9]{12}:index\/[a-zA-Z0-9][a-zA- Z0-9_-]*

Required: Yes queryFilterString

A query filter that Amazon Lex sends to Amazon Kendra to filter the response from the query. The filter is in the format defined by Amazon Kendra. For more information, see Filtering queries.

You can override this filter string with a new filter string at runtime.

Type: String

Length Constraints: Minimum length of 0.

Required: No role

The Amazon Resource Name (ARN) of an IAM role that has permission to search the Amazon Kendra index. The role must be in the same account and Region as the Amazon Lex bot. If the role does not exist, you get an exception when you call the PutIntent operation.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: arn:aws:iam::[0-9]{12}:role/.*

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

469 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

470 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

LogSettingsRequest Service: Amazon Lex Model Building Service

Settings used to configure delivery mode and destination for conversation logs. Contents destination

Where the logs will be delivered. Text logs are delivered to a CloudWatch Logs log group. Audio logs are delivered to an S3 bucket.

Type: String

Valid Values: CLOUDWATCH_LOGS | S3

Required: Yes kmsKeyArn

The Amazon Resource Name (ARN) of the AWS KMS customer managed key for encrypting audio logs delivered to an S3 bucket. The key does not apply to CloudWatch Logs and is optional for S3 buckets.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:kms:[\w\-]+:[\d]{12}:(?:key\/[\w\-]+|alias\/[a-zA-Z0-9: \/_\-]{1,256})$

Required: No logType

The type of logging to enable. Text logs are delivered to a CloudWatch Logs log group. Audio logs are delivered to an S3 bucket.

Type: String

Valid Values: AUDIO | TEXT

Required: Yes resourceArn

The Amazon Resource Name (ARN) of the CloudWatch Logs log group or S3 bucket where the logs should be delivered.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:(?:logs:[\w\-]+:[\d]{12}:log-group:[\.\-_/#A-Za-z0-9] {1,512}(?::\*)?|s3:::[a-z0-9][\.\-a-z0-9]{1,61}[a-z0-9])$

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

471 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

472 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

LogSettingsResponse Service: Amazon Lex Model Building Service

The settings for conversation logs. Contents destination

The destination where logs are delivered.

Type: String

Valid Values: CLOUDWATCH_LOGS | S3

Required: No kmsKeyArn

The Amazon Resource Name (ARN) of the key used to encrypt audio logs in an S3 bucket.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:kms:[\w\-]+:[\d]{12}:(?:key\/[\w\-]+|alias\/[a-zA-Z0-9: \/_\-]{1,256})$

Required: No logType

The type of logging that is enabled.

Type: String

Valid Values: AUDIO | TEXT

Required: No resourceArn

The Amazon Resource Name (ARN) of the CloudWatch Logs log group or S3 bucket where the logs are delivered.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:(?:logs:[\w\-]+:[\d]{12}:log-group:[\.\-_/#A-Za-z0-9] {1,512}(?::\*)?|s3:::[a-z0-9][\.\-a-z0-9]{1,61}[a-z0-9])$

Required: No resourcePrefix

The resource prefix is the first part of the S3 object key within the S3 bucket that you specified to contain audio logs. For CloudWatch Logs it is the prefix of the log stream name within the log group that you specified.

Type: String

Length Constraints: Maximum length of 1024.

473 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

474 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Message Service: Amazon Lex Model Building Service

The message object that provides the message text and its type. Contents content

The text of the message.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1000.

Required: Yes contentType

The content type of the message string.

Type: String

Valid Values: PlainText | SSML | CustomPayload

Required: Yes groupNumber

Identifies the message group that the message belongs to. When a group is assigned to a message, Amazon Lex returns one message from each group in the response.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 5.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

475 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

MigrationAlert Service: Amazon Lex Model Building Service

Provides information about alerts and warnings that Amazon Lex sends during a migration. The alerts include information about how to resolve the issue. Contents details

Additional details about the alert.

Type: Array of strings

Required: No message

A message that describes why the alert was issued.

Type: String

Required: No referenceURLs

A link to the Amazon Lex documentation that describes how to resolve the alert.

Type: Array of strings

Required: No type

The type of alert. There are two kinds of alerts: • ERROR - There was an issue with the migration that can't be resolved. The migration stops. • WARN - There was an issue with the migration that requires manual changes to the new Amazon Lex V2 bot. The migration continues.

Type: String

Valid Values: ERROR | WARN

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

476 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

MigrationSummary Service: Amazon Lex Model Building Service

Provides information about migrating a bot from Amazon Lex V1 to Amazon Lex V2. Contents migrationId

The unique identifier that Amazon Lex assigned to the migration.

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$

Required: No migrationStatus

The status of the operation. When the status is COMPLETE the bot is available in Amazon Lex V2. There may be alerts and warnings that need to be resolved to complete the migration.

Type: String

Valid Values: IN_PROGRESS | COMPLETED | FAILED

Required: No migrationStrategy

The strategy used to conduct the migration.

Type: String

Valid Values: CREATE_NEW | UPDATE_EXISTING

Required: No migrationTimestamp

The date and time that the migration started.

Type: Timestamp

Required: No v1BotLocale

The locale of the Amazon Lex V1 bot that is the source of the migration.

Type: String

Valid Values: de-DE | en-AU | en-GB | en-IN | en-US | es-419 | es-ES | es-US | fr-FR | fr-CA | it-IT | ja-JP | ko-KR

Required: No v1BotName

The name of the Amazon Lex V1 bot that is the source of the migration.

Type: String

477 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Length Constraints: Minimum length of 2. Maximum length of 50.

Pattern: ^([A-Za-z]_?)+$

Required: No v1BotVersion

The version of the Amazon Lex V1 bot that is the source of the migration.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No v2BotId

The unique identifier of the Amazon Lex V2 that is the destination of the migration.

Type: String

Length Constraints: Fixed length of 10.

Pattern: ^[0-9a-zA-Z]+$

Required: No v2BotRole

The IAM role that Amazon Lex uses to run the Amazon Lex V2 bot.

Type: String

Length Constraints: Minimum length of 20. Maximum length of 2048.

Pattern: ^arn:[\w\-]+:iam::[\d]{12}:role/.+$

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

478 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

OutputContext Service: Amazon Lex Model Building Service

The specification of an output context that is set when an intent is fulfilled. Contents name

The name of the context.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes timeToLiveInSeconds

The number of seconds that the context should be active after it is first sent in a PostContent or PostText response. You can set the value between 5 and 86,400 seconds (24 hours).

Type: Integer

Valid Range: Minimum value of 5. Maximum value of 86400.

Required: Yes turnsToLive

The number of conversation turns that the context should be active. A conversation turn is one PostContent or PostText request and the corresponding response from Amazon Lex.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 20.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

479 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Prompt Service: Amazon Lex Model Building Service

Obtains information from the user. To define a prompt, provide one or more messages and specify the number of attempts to get information from the user. If you provide more than one message, Amazon Lex chooses one of the messages to use to prompt the user. For more information, see Amazon Lex: come funziona (p. 3). Contents maxAttempts

The number of times to prompt the user for information.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 5.

Required: Yes messages

An array of objects, each of which provides a message string and its type. You can specify the message string in plain text or in Speech Synthesis Markup Language (SSML).

Type: Array of Message (p. 475) objects

Array Members: Minimum number of 1 item. Maximum number of 15 items.

Required: Yes responseCard

A response card. Amazon Lex uses this prompt at runtime, in the PostText API response. It substitutes session attributes and slot values for placeholders in the response card. For more information, see Utilizzo di una scheda di risposta (p. 216).

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

480 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

ResourceReference Service: Amazon Lex Model Building Service

Describes the resource that refers to the resource that you are attempting to delete. This object is returned as part of the ResourceInUseException exception. Contents name

The name of the resource that is using the resource that you are trying to delete.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: [a-zA-Z_]+

Required: No version

The version of the resource that is using the resource that you are trying to delete.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

481 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Slot Service: Amazon Lex Model Building Service

Identifies the version of a specific slot. Contents defaultValueSpec

A list of default values for the slot. Default values are used when Amazon Lex hasn't determined a value for a slot. You can specify default values from context variables, session attributes, and defined values.

Type: SlotDefaultValueSpec (p. 486) object

Required: No description

A description of the slot.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No name

The name of the slot.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z](-|_|.)?)+$

Required: Yes obfuscationSetting

Determines whether a slot is obfuscated in conversation logs and stored utterances. When you obfuscate a slot, the value is replaced by the slot name in curly braces ({}). For example, if the slot name is "full_name", obfuscated values are replaced with "{full_name}". For more information, see Slot Obfuscation .

Type: String

Valid Values: NONE | DEFAULT_OBFUSCATION

Required: No priority

Directs Amazon Lex the order in which to elicit this slot value from the user. For example, if the intent has two slots with priorities 1 and 2, AWS Amazon Lex first elicits a value for the slot with priority 1.

If multiple slots share the same priority, the order in which Amazon Lex elicits values is arbitrary.

Type: Integer

Valid Range: Minimum value of 0. Maximum value of 100.

Required: No

482 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service responseCard

A set of possible responses for the slot type used by text-based clients. A user chooses an option from the response card, instead of using text to reply.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No sampleUtterances

If you know a specific pattern with which users might respond to an Amazon Lex request for a slot value, you can provide those utterances to improve accuracy. This is optional. In most cases, Amazon Lex is capable of understanding user utterances.

Type: Array of strings

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Length Constraints: Minimum length of 1. Maximum length of 200.

Required: No slotConstraint

Specifies whether the slot is required or optional.

Type: String

Valid Values: Required | Optional

Required: Yes slotType

The type of the slot, either a custom slot type that you defined or one of the built-in slot types.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^((AMAZON\.)_?|[A-Za-z]_?)+

Required: No slotTypeVersion

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No valueElicitationPrompt

The prompt that Amazon Lex uses to elicit the slot value from the user.

Type: Prompt (p. 480) object

Required: No

483 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

484 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

SlotDefaultValue Service: Amazon Lex Model Building Service

A default value for a slot. Contents defaultValue

The default value for the slot. You can specify one of the following: • #context-name.slot-name - The slot value "slot-name" in the context "context-name." • {attribute} - The slot value of the session attribute "attribute." • 'value' - The discrete value "value."

Type: String

Length Constraints: Minimum length of 1. Maximum length of 202.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

485 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

SlotDefaultValueSpec Service: Amazon Lex Model Building Service

Contains the default values for a slot. Default values are used when Amazon Lex hasn't determined a value for a slot. Contents defaultValueList

The default values for a slot. You can specify more than one default. For example, you can specify a default value to use from a matching context variable, a session attribute, or a fixed value.

The default value chosen is selected based on the order that you specify them in the list. For example, if you specify a context variable and a fixed value in that order, Amazon Lex uses the context variable if it is available, else it uses the fixed value.

Type: Array of SlotDefaultValue (p. 485) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

486 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

SlotTypeConfiguration Service: Amazon Lex Model Building Service

Provides configuration information for a slot type. Contents regexConfiguration

A regular expression used to validate the value of a slot.

Type: SlotTypeRegexConfiguration (p. 490) object

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

487 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

SlotTypeMetadata Service: Amazon Lex Model Building Service

Provides information about a slot type.. Contents createdDate

The date that the slot type was created.

Type: Timestamp

Required: No description

A description of the slot type.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 200.

Required: No lastUpdatedDate

The date that the slot type was updated. When you create a resource, the creation date and last updated date are the same.

Type: Timestamp

Required: No name

The name of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: No version

The version of the slot type.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

488 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

• AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

489 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

SlotTypeRegexConfiguration Service: Amazon Lex Model Building Service

Provides a regular expression used to validate the value of a slot. Contents pattern

A regular expression used to validate the value of a slot.

Use a standard regular expression. Amazon Lex supports the following characters in the regular expression: • A-Z, a-z • 0-9 • Unicode characters ("\ u")

Represent Unicode characters with four digits, for example "\u0041" or "\u005A".

The following regular expression operators are not supported: • Infinite repeaters: *, +, or {x,} with no upper bound. • Wild card (.)

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

490 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Statement Service: Amazon Lex Model Building Service

A collection of messages that convey information to the user. At runtime, Amazon Lex selects the message to convey. Contents messages

A collection of message objects.

Type: Array of Message (p. 475) objects

Array Members: Minimum number of 1 item. Maximum number of 15 items.

Required: Yes responseCard

At runtime, if the client is using the PostText API, Amazon Lex includes the response card in the response. It substitutes all of the session attributes and slot values for placeholders in the response card.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 50000.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

491 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

Tag Service: Amazon Lex Model Building Service

A list of key/value pairs that identify a bot, bot alias, or bot channel. Tag keys and values can consist of Unicode letters, digits, white space, and any of the following symbols: _ . : / = + - @. Contents key

The key for the tag. Keys are not case-sensitive and must be unique.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 128.

Required: Yes value

The value associated with a key. The value may be an empty string but it can't be null.

Type: String

Length Constraints: Minimum length of 0. Maximum length of 256.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

492 Amazon Lex Guida per gli sviluppatori Amazon Lex Model Building Service

UtteranceData Service: Amazon Lex Model Building Service

Provides information about a single utterance that was made to your bot. Contents count

The number of times that the utterance was processed.

Type: Integer

Required: No distinctUsers

The total number of individuals that used the utterance.

Type: Integer

Required: No firstUtteredDate

The date that the utterance was first recorded.

Type: Timestamp

Required: No lastUtteredDate

The date that the utterance was last recorded.

Type: Timestamp

Required: No utteranceString

The text that was entered by the user or the text representation of an audio clip.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2000.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

493 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

UtteranceList Service: Amazon Lex Model Building Service

Provides a list of utterances that have been made to a specific version of your bot. The list contains a maximum of 100 utterances. Contents botVersion

The version of the bot that processed the list.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 64.

Pattern: \$LATEST|[0-9]+

Required: No utterances

One or more UtteranceData (p. 493) objects that contain information about the utterances that have been made to a bot. The maximum number of object is 100.

Type: Array of UtteranceData (p. 493) objects

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

Amazon Lex Runtime Service

The following data types are supported by Amazon Lex Runtime Service:

• ActiveContext (p. 495) • ActiveContextTimeToLive (p. 496) • Button (p. 497) • DialogAction (p. 498) • GenericAttachment (p. 500) • IntentConfidence (p. 502) • IntentSummary (p. 503) • PredictedIntent (p. 505) • ResponseCard (p. 506) • SentimentResponse (p. 507)

494 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

ActiveContext Service: Amazon Lex Runtime Service

A context is a variable that contains information about the current state of the conversation between a user and Amazon Lex. Context can be set automatically by Amazon Lex when an intent is fulfilled, or it can be set at runtime using the PutContent, PutText, or PutSession operation. Contents name

The name of the context.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 100.

Pattern: ^([A-Za-z]_?)+$

Required: Yes parameters

State variables for the current context. You can use these values as default values for slots in subsequent events.

Type: String to string map

Map Entries: Minimum number of 0 items. Maximum number of 10 items.

Key Length Constraints: Minimum length of 1. Maximum length of 100.

Value Length Constraints: Minimum length of 1. Maximum length of 1024.

Required: Yes timeToLive

The length of time or number of turns that a context remains active.

Type: ActiveContextTimeToLive (p. 496) object

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

495 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

ActiveContextTimeToLive Service: Amazon Lex Runtime Service

The length of time or number of turns that a context remains active. Contents timeToLiveInSeconds

The number of seconds that the context should be active after it is first sent in a PostContent or PostText response. You can set the value between 5 and 86,400 seconds (24 hours).

Type: Integer

Valid Range: Minimum value of 5. Maximum value of 86400.

Required: No turnsToLive

The number of conversation turns that the context should be active. A conversation turn is one PostContent or PostText request and the corresponding response from Amazon Lex.

Type: Integer

Valid Range: Minimum value of 1. Maximum value of 20.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

496 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Button Service: Amazon Lex Runtime Service

Represents an option to be shown on the client platform (Facebook, Slack, etc.) Contents text

Text that is visible to the user on the button.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 15.

Required: Yes value

The value sent to Amazon Lex when a user chooses the button. For example, consider button text "NYC." When the user chooses the button, the value sent can be "New York City."

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1000.

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

497 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

DialogAction Service: Amazon Lex Runtime Service

Describes the next action that the bot should take in its interaction with the user and provides information about the context in which the action takes place. Use the DialogAction data type to set the interaction to a specific state, or to return the interaction to a previous state. Contents fulfillmentState

The fulfillment state of the intent. The possible values are: • Failed - The Lambda function associated with the intent failed to fulfill the intent. • Fulfilled - The intent has fulfilled by the Lambda function associated with the intent. • ReadyForFulfillment - All of the information necessary for the intent is present and the intent ready to be fulfilled by the client application.

Type: String

Valid Values: Fulfilled | Failed | ReadyForFulfillment

Required: No intentName

The name of the intent.

Type: String

Required: No message

The message that should be shown to the user. If you don't specify a message, Amazon Lex will use the message configured for the intent.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 1024.

Required: No messageFormat • PlainText - The message contains plain UTF-8 text. • CustomPayload - The message is a custom format for the client. • SSML - The message contains text formatted for voice output. • Composite - The message contains an escaped JSON object containing one or more messages. For more information, see Message Groups.

Type: String

Valid Values: PlainText | CustomPayload | SSML | Composite

Required: No slots

Map of the slots that have been gathered and their values.

Type: String to string map

498 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

Required: No slotToElicit

The name of the slot that should be elicited from the user.

Type: String

Required: No type

The next action that the bot should take in its interaction with the user. The possible values are: • ConfirmIntent - The next action is asking the user if the intent is complete and ready to be fulfilled. This is a yes/no question such as "Place the order?" • Close - Indicates that the there will not be a response from the user. For example, the statement "Your order has been placed" does not require a response. • Delegate - The next action is determined by Amazon Lex. • ElicitIntent - The next action is to determine the intent that the user wants to fulfill. • ElicitSlot - The next action is to elicit a slot value from the user.

Type: String

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Close | Delegate

Required: Yes

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

499 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

GenericAttachment Service: Amazon Lex Runtime Service

Represents an option rendered to the user when a prompt is shown. It could be an image, a button, a link, or text. Contents attachmentLinkUrl

The URL of an attachment to the response card.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Required: No buttons

The list of options to show to the user.

Type: Array of Button (p. 497) objects

Array Members: Minimum number of 0 items. Maximum number of 5 items.

Required: No imageUrl

The URL of an image that is displayed to the user.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 2048.

Required: No subTitle

The subtitle shown below the title.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 80.

Required: No title

The title of the option.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 80.

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++

500 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

• AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

501 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

IntentConfidence Service: Amazon Lex Runtime Service

Provides a score that indicates the confidence that Amazon Lex has that an intent is the one that satisfies the user's intent. Contents score

A score that indicates how confident Amazon Lex is that an intent satisfies the user's intent. Ranges between 0.00 and 1.00. Higher scores indicate higher confidence.

Type: Double

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

502 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

IntentSummary Service: Amazon Lex Runtime Service

Provides information about the state of an intent. You can use this information to get the current state of an intent so that you can process the intent, or so that you can return the intent to its previous state. Contents checkpointLabel

A user-defined label that identifies a particular intent. You can use this label to return to a previous intent.

Use the checkpointLabelFilter parameter of the GetSessionRequest operation to filter the intents returned by the operation to those with only the specified label.

Type: String

Length Constraints: Minimum length of 1. Maximum length of 255.

Pattern: [a-zA-Z0-9-]+

Required: No confirmationStatus

The status of the intent after the user responds to the confirmation prompt. If the user confirms the intent, Amazon Lex sets this field to Confirmed. If the user denies the intent, Amazon Lex sets this value to Denied. The possible values are: • Confirmed - The user has responded "Yes" to the confirmation prompt, confirming that the intent is complete and that it is ready to be fulfilled. • Denied - The user has responded "No" to the confirmation prompt. • None - The user has never been prompted for confirmation; or, the user was prompted but did not confirm or deny the prompt.

Type: String

Valid Values: None | Confirmed | Denied

Required: No dialogActionType

The next action that the bot should take in its interaction with the user. The possible values are: • ConfirmIntent - The next action is asking the user if the intent is complete and ready to be fulfilled. This is a yes/no question such as "Place the order?" • Close - Indicates that the there will not be a response from the user. For example, the statement "Your order has been placed" does not require a response. • ElicitIntent - The next action is to determine the intent that the user wants to fulfill. • ElicitSlot - The next action is to elicit a slot value from the user.

Type: String

Valid Values: ElicitIntent | ConfirmIntent | ElicitSlot | Close | Delegate

Required: Yes fulfillmentState

The fulfillment state of the intent. The possible values are:

503 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

• Failed - The Lambda function associated with the intent failed to fulfill the intent. • Fulfilled - The intent has fulfilled by the Lambda function associated with the intent. • ReadyForFulfillment - All of the information necessary for the intent is present and the intent ready to be fulfilled by the client application.

Type: String

Valid Values: Fulfilled | Failed | ReadyForFulfillment

Required: No intentName

The name of the intent.

Type: String

Required: No slots

Map of the slots that have been gathered and their values.

Type: String to string map

Required: No slotToElicit

The next slot to elicit from the user. If there is not slot to elicit, the field is blank.

Type: String

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

504 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

PredictedIntent Service: Amazon Lex Runtime Service

An intent that Amazon Lex suggests satisfies the user's intent. Includes the name of the intent, the confidence that Amazon Lex has that the user's intent is satisfied, and the slots defined for the intent. Contents intentName

The name of the intent that Amazon Lex suggests satisfies the user's intent.

Type: String

Required: No nluIntentConfidence

Indicates how confident Amazon Lex is that an intent satisfies the user's intent.

Type: IntentConfidence (p. 502) object

Required: No slots

The slot and slot values associated with the predicted intent.

Type: String to string map

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

505 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

ResponseCard Service: Amazon Lex Runtime Service

If you configure a response card when creating your bots, Amazon Lex substitutes the session attributes and slot values that are available, and then returns it. The response card can also come from a Lambda function ( dialogCodeHook and fulfillmentActivity on an intent). Contents contentType

The content type of the response.

Type: String

Valid Values: application/vnd.amazonaws.card.generic

Required: No genericAttachments

An array of attachment objects representing options.

Type: Array of GenericAttachment (p. 500) objects

Array Members: Minimum number of 0 items. Maximum number of 10 items.

Required: No version

The version of the response card format.

Type: String

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

506 Amazon Lex Guida per gli sviluppatori Amazon Lex Runtime Service

SentimentResponse Service: Amazon Lex Runtime Service

The sentiment expressed in an utterance.

When the bot is configured to send utterances to Amazon Comprehend for sentiment analysis, this field structure contains the result of the analysis. Contents sentimentLabel

The inferred sentiment that Amazon Comprehend has the highest confidence in.

Type: String

Required: No sentimentScore

The likelihood that the sentiment was correctly inferred.

Type: String

Required: No

See Also

For more information about using this API in one of the language-specific AWS SDKs, see the following:

• AWS SDK for C++ • AWS SDK for Go • AWS SDK for Java V2 • AWS SDK for Ruby V3

507 Amazon Lex Guida per gli sviluppatori

Cronologia dei documenti per Amazon Lex

• Ultimo aggiornamento della documentazione: 23 Novembre 2020

La tabella che segue descrive le modifiche importanti apportate in ogni versione di Amazon Lex. Per ricevere notifiche sugli aggiornamenti di questa documentazione, puoi abbonarti a un feed RSS.

update-history-change update-history-description update-history-date

Nuova caratteristica Amazon Lex ora supporta le November 23, 2020 impostazioni locali tedesco (tedesco) (de-DE) e spagnolo (America latina) (es-419). Per ulteriori informazioni, consulta Lingue supportate da Amazon Lex.

Nuova caratteristica Amazon Lex ora supporta November 19, 2020 l'utilizzo di contesti per gestire gli intenti di attivazione. Per ulteriori informazioni, consulta Impostazione del contesto dell'intento.

Nuova caratteristica Amazon Lex ora supporta le November 11, 2020 impostazioni locali francese (fr- FR), francese canadese (fr-CA), italiano (it-IT) e spagnolo (es-ES). Per un elenco completo delle impostazioni locali supportate, consulta Lingue supportate da Amazon Lex.

Nuova caratteristica Amazon Lex ora supporta le September 22, 2020 impostazioni locali in spagnolo (Stati Uniti) (es-US). Per ulteriori informazioni, consulta Lingue supportate da Amazon Lex.

Nuova caratteristica Amazon Lex ora supporta le September 15, 2020 impostazioni locali in inglese (Regno Unito). Per ulteriori informazioni, consulta Lingue supportate da Amazon Lex.

Nuova caratteristica Amazon Lex supporta ora le September 8, 2020 impostazioni locali in inglese (Australia) (en-AU). Per ulteriori informazioni, consulta Lingue supportate da Amazon Lex.

508 Amazon Lex Guida per gli sviluppatori

Nuova caratteristica Amazon Lex ora dispone di 7 September 8, 2020 nuovi intenti incorporati e 9 nuovi tipi di slot integrati. Per ulteriori informazioni, consulta Intenti incorporati e tipi di slot.

Nuovo esempio Scopri come creare un bot August 10, 2020 Amazon Lex che gli agenti di assistenza clienti possono utilizzare per rispondere alle domande dei clienti cercando risposte con Amazon Kendra. Per ulteriori informazioni, consulta Esempio: Assistente agente call center .

Nuova caratteristica Amazon Lex può ora restituire August 6, 2020 fino a quattro intenti alternativi basati sui punteggi di attendibilità. Per ulteriori informazioni, consulta Utilizzo dei punteggi di affidabilità.

Espansione regionale Amazon Lex è ora disponibile June 30, 2020 in Asia Pacifico (Tokyo) (ap- northeast-1).

Nuova caratteristica Amazon Lex ora supporta June 11, 2020 la ricerca di indici Amazon Kendra per le risposte alle domande frequenti. Per ulteriori informazioni, consulta AMAZON.KendraSearchIntent.

Nuova caratteristica Amazon Lex ora restituisce June 9, 2020 più informazioni nei log delle conversazioni. Per ulteriori informazioni, consulta Visualizzazione dei log di testo in Amazon CloudWatch Logs.

Espansione regionale Amazon Lex è ora disponibile in April 23, 2020 Asia Pacifico (Singapore) (ap- southeast-1), Regione Europa (Francoforte) (eu-central-1) e Regione Europa (Londra) (eu- west-2).

Nuova caratteristica Amazon Lex ora supporta il March 12, 2020 tagging. Puoi utilizzare il tagging per identificare le risorse, allocare i costi e controllare l'accesso. Per ulteriori informazioni, consulta l'articolo relativo altagging delle risorse Amazon Lex.

509 Amazon Lex Guida per gli sviluppatori

Nuova caratteristica Amazon Lex ora supporta February 6, 2020 le espressioni regolari per il tipo di slot incorporato AMAZON.AlphaNumeric. Per maggiori informazioni, consulta AMAZON.AlphaNumeric.

Nuova caratteristica Ora Amazon Lex può registrare le December 19, 2019 informazioni sulle conversazioni e nascondere i valori di slot nei log. Per ulteriori informazioni, consulta Creazione di Conversation Logs e Offuscamento degli slot.

Espansione regionale Amazon Lex è ora disponibile December 17, 2019 in Asia Pacifico (Sydney) (ap- southeast-2).

Nuova caratteristica Amazon Lex è ora conforme a December 10, 2019 HIPAA. Per ulteriori informazioni, consulta Convalida di conformità per Amazon Lex.

Nuova caratteristica Amazon Lex può ora inviare November 21, 2019 enunciati utente a Amazon Comprehend per analizzare l'emozione dell'enunciato. Per ulteriori informazioni, consulta Analisi emozione.

Nuova caratteristica Amazon Lex è ora conforme November 19, 2019 allo standard SOC Per ulteriori informazioni, consulta Convalida di conformità per Amazon Lex.

Nuova caratteristica Amazon Lex è ora conforme a October 17, 2019 PCI. Per ulteriori informazioni, consulta Convalida di conformità per Amazon Lex.

Nuova caratteristica Aggiunto il supporto per October 10, 2019 l'aggiunta di un checkpoint a un intento in modo da poter facilmente tornare all'intento durante una conversazione. Per ulteriori informazioni, consulta Gestione delle sessioni.

Nuova caratteristica Aggiunto il supporto per October 3, 2019 AMAZON.FallbackIntent in modo che il bot possa gestire situazioni in cui l'input utente non sia come previsto. Per ulteriori informazioni, consultare AMAZON.FallbackIntent.

510 Amazon Lex Guida per gli sviluppatori

Nuova caratteristica Amazon Lex consente di gestire August 8, 2019 le informazioni relative alla sessione per i bot. Per ulteriori informazioni, consulta Gestione di sessioni con l’API Amazon Lex.

Espansione regionale (p. 508) Amazon Lex è ora disponibile in May 8, 2018 Stati Uniti occidentali (Oregon) (us-west-2).

Nuova caratteristica (p. 508) Aggiunto il supporto per February 13, 2018 l'esportazione e l'importazione in formato Amazon Lex. Per ulteriori informazioni, consulta Importazione ed esportazione di Bot Amazon Lex, intenti e tipi di slot.

Nuova caratteristica (p. 508) Amazon Lex ora supporta February 8, 2018 i messaggi di risposta aggiuntivi per i bot. Per ulteriori informazioni, consulta la sezione relativa alle risposte.

Espansione regionale (p. 508) Amazon Lex è ora disponibile in November 21, 2017 Regione Europa (Irlanda) (eu- west-1).

Nuova caratteristica (p. 508) Aggiunto il supporto per November 20, 2017 la distribuzione dei bot di Amazon Lex su Kik. Per ulteriori informazioni, consulta Integrazione di un bot di Amazon Lex con Kik.

Nuova caratteristica (p. 508) Aggiunto il supporto per i November 3, 2017 nuovi tipi di slot integrati e gli attributi di richiesta. Per ulteriori informazioni, consultare Tipi di slot integrati e Impostazione attributi richiesta.

Nuova caratteristica (p. 508) Aggiunta l'esportazione alla September 7, 2017 caratteristica Alexa Skills Kit. Per ulteriori informazioni, consultare Esportazione in una competenza di Alexa.

Nuova caratteristica (p. 508) Aggiunto il supporto dei sinonimi August 31, 2017 per i valori dei tipi di slot. Per ulteriori informazioni, consultare Tipi di slot personalizzati.

Nuova caratteristica (p. 508) Aggiunta l'integrazione AWS August 15, 2017 CloudTrail. Per ulteriori informazioni, consulta Monitoraggio di chiamate dell'API Amazon Lex con log AWS CloudTrail.

511 Amazon Lex Guida per gli sviluppatori

Documentazione Aggiunti esempi di nozioni di May 22, 2017 ampliata (p. 508) base per AWS CLI. Per ulteriori informazioni, consulta https:// docs.aws.amazon.com/lex/latest/ dg/gs-cli.html

Nuova guida (p. 508) La prima versione della Guida per April 19, 2017 l'utente di Amazon Lex.

512 Amazon Lex Guida per gli sviluppatori

Glossario AWS

Per la terminologia AWS più recente, consulta il glossario AWS nella AWS General Reference.

513 Amazon Lex Guida per gli sviluppatori

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

dxiv