CloudBrum
CloudBrum · Cloud decision-support platform
AWS AI and machine learning

Amazon LexCreatedLast reviewedReading time~18 minLevelBeginner to advanced

Amazon Web Services · AI and machine learning · Voice and text bots

Amazon Lex turns a spoken or typed request into a conversation your application can handle. A support bot can identify a ticket-status request, ask for the missing ticket number and pass the collected details to your backend. Lex V2 supplies language understanding and dialogue state; your application still authenticates the customer and decides which records they may access. Start with one useful task and its failure paths before adding a long menu of intents.

On this page (17 sections)

    Mind map: Amazon Lex at a glance

    Amazon Lex mind map Amazon Lex at a glance: Conversation: Intents name tasks, Slots collect details, Fallback handles misses; Configuration: Locale and utterances, Validation prompts, Build before publishing; Release: Immutable bot version, Alias selects a version, Test the deployed locale; Runtime: RecognizeText, One ID per conversation, Read dialogue state; Fulfillment: Lambda hook, Authorize the customer, Prevent duplicate writes; Operations: Throttle each session, Watch fallback patterns, Protect transcripts; Billing: Text or speech requests, Streaming has its meter, Include backend costs; Alternatives: Azure Bot Service, Google CX Agent Studio, Direct model application. Amazon Lex V2 at a glance Recognize the task, collect what is missing, then check the business operation CloudBrum Cloud decision-support platform CloudBrum Intents name tasks Slots collect details Fallback handles misses Conversation Locale and utterances Validation prompts Build before publishing Configuration Immutable bot version Alias selects a version Test the deployed locale Release RecognizeText One ID per conversation Read dialogue state Runtime Lambda hook Authorize the customer Prevent duplicate writes Fulfillment Throttle each session Watch fallback patterns Protect transcripts Operations Text or speech requests Streaming has its meter Include backend costs Billing Azure Bot Service Google CX Agent Studio Direct model application Alternatives Amazon Lex17-point analysis CloudBrum· 17-point cloud service analysis cloudbrum.com
    CloudBrum Amazon Lex at a glance · 17-point analysis Conversation Intents name tasks Slots collect details Fallback handles misses Configuration Locale and utterances Validation prompts Build before publishing Release Immutable bot version Alias selects a version Test the deployed locale Runtime RecognizeText One ID per conversation Read dialogue state Fulfillment Lambda hook Authorize the customer Prevent duplicate writes Operations Throttle each session Watch fallback patterns Protect transcripts Billing Text or speech requests Streaming has its meter Include backend costs Alternatives Azure Bot Service Google CX Agent Studio Direct model application CloudBrum · cloudbrum.com

    Free to share. The downloaded image includes the CloudBrum link.

    Key features (summary)

    • Intent and slot conversationsDefine a task such as checking a support ticket, then the details needed to carry it out. Lex can ask for a missing slot instead of requiring the customer to provide everything in a single sentence.
    • Text and speech inputA text client uses RecognizeText; voice integrations use the appropriate audio or streaming operation. A voice bot also needs tests for recognition errors, interruptions and the time a caller waits between turns.
    • A dialogue that has stateThe response identifies what the bot expects next. ElicitSlot, ConfirmIntent and Close describe different moments in a conversation. A successful HTTP request does not tell the client which moment it reached.
    • Optional assisted language understandingAWS offers Assisted NLU to improve intent classification and slot resolution using language models within the configured bot tasks. Evaluate its behavior, supported configuration and billing separately from the basic example on this page.
    • Versions and aliasesAn alias gives an application a stable target while a tested bot version changes behind it. Build and verify the intended locale before moving a production alias; editing the draft is not the same release action.
    • Hooks into application logicA Lambda hook can validate a value or fulfill an intent. The hook must check the authenticated business context and handle repeated work safely, rather than trusting an order number simply because Lex recognized it.

    Basic concepts

    Intent
    The action the conversation is trying to reach. TicketStatus and CancelTicket should have different acceptance rules even when users mention the same ticket identifier.
    Slot
    A named value the intent needs. An alphanumeric slot can recognize a ticket reference, but your backend must still check that the reference exists and belongs to the signed-in customer.
    Utterance and fallback
    Example utterances teach the expected task. A fallback is a deliberate route for an unsupported or uncertain request; it should offer a useful next step instead of repeatedly asking the same question.
    Locale
    The language configuration is part of the deployed bot. An alias working for one locale is not evidence that another locale was built or has equivalent utterances and slot behavior.
    Session state
    A conversation carries its active intent, slots and dialogue action between turns. Replacing the session ID on every request makes the bot forget which question it just asked.
    Fulfillment state
    ReadyForFulfillment means the details are ready for application work. Fulfilled reports completion in the bot workflow. Neither state supplies independent proof that a payment, cancellation or database write was authorized.

    How to create & configure it

    Publish a small ticket-status conversation

    1. Write down the task and the escape routeUse synthetic ticket references and define the answer for an unknown ticket, an unauthenticated customer and a request the bot cannot handle. Decide when to offer a person rather than another automated prompt.
    2. Create a V2 bot and a localeChoose the Region, service role and conversation idle timeout. Add the intended language, then begin with a few varied ways to ask for ticket status. Keep the scope narrow enough to inspect every route.
    3. Add the required ticket slotUse an appropriate slot type and a prompt that explains which reference the customer should provide. Test punctuation, corrections and a value supplied in the opening request. A format match alone must not grant access to a ticket.
    4. Connect validation and fulfillmentPut authorization and record lookup in the application or a Lambda hook. Bind the conversation to the authenticated customer outside user-editable text and make any write operation idempotent.
    5. Build, test and publishBuild the locale, inspect failures, create a bot version and point an alias to it. The runtime examples need that bot ID, alias ID and a supported locale; the Terraform tab creates only the initial draft resource.
    6. Exercise the application channelSend several turns through the same conversation ID. Test timeouts and retries at the actual client, then check the backend outcome as well as the text shown by the bot. Record which alias/version was tested.

    Try a correction such as “not that ticket, use the other number” during slot collection. A bot that succeeds only when every first answer is correct is a fragile support workflow.

    Common issues after configuration

    SymptomLikely causeWhat to check / fix
    The bot keeps asking its first questionThe client starts a new session for every messageKeep a stable, opaque session ID for the conversation. Reset it deliberately when a conversation ends; do not use a shared constant for every customer.
    A runtime request cannot find the bot or localeThe IDs, Region, alias or built locale do not matchDescribe the alias and inspect its locale configuration. A draft in the console and a published alias are separate targets. Check which regional endpoint the application actually calls.
    The correct ticket number selects an unexpected taskThe example phrases overlap or intent evidence is weakReview failed conversations and add representative utterances. Calibrate confidence rules on your own test set; increasing a threshold without inspecting fallback behavior can simply move more people into a dead end.
    Two messages interfere with one anotherSeveral workers advance the same conversation concurrentlySerialize turns within a session while allowing different sessions to run independently. A global queue is unnecessary, but a single conversation needs a consistent order.
    The user sees completion but the ticket was not updatedBot dialogue state and backend outcome were treated as the same eventCorrelate the fulfillment result with the operation recorded by the backend. Treat an uncertain network result as unresolved work; do not repeat a consequential operation blindly.
    A hook fails after a successful test without itThe Lambda permission, alias association or event/response contract is wrongCheck the V2 event shape, invocation permission and the alias/locale hook setting. Validate slot input before returning the documented dialogue action and session state.

    Use cases: when and where to use it

    Good fit

    • A bounded support task with explicit details to collect and a clear handoff.
    • Voice or text intake that belongs in an AWS application.
    • Conversations where predictable prompts and state matter more than an unrestricted answer.
    • A workflow with a backend that can validate identity, permissions and the requested operation.

    Consider something else

    • Open-ended research or document synthesis: compare a Bedrock application and its retrieval design.
    • A page only needs a fixed form with no conversational benefit: a normal form may be faster to complete.
    • A decision needs legal, medical or financial authority: a conversational interface cannot supply that authority.
    • The team cannot maintain fallback, language and handoff tests: narrow the proposed bot before expanding its intent list.

    Pros: why consider it?

    Why teams choose it

    • Slot elicitation can turn an incomplete request into a structured task.
    • Versioned aliases provide a practical release boundary for clients.
    • The AWS runtime and Lambda integration fit existing AWS application patterns.
    • A bounded dialogue makes some failure cases easier to enumerate than a broad assistant prompt.

    Trade-offs to weigh

    • Similar intents and poorly designed prompts can create repetitive conversations.
    • Each language and channel needs evidence from its own test conversations.
    • The application still owns customer authentication and business authorization.
    • Voice quality, telephony, fulfillment and support handoff add work beyond the bot definition.

    Common threats, vulnerabilities & risks

    RiskSeverityWhy it mattersMitigation
    A recognized identifier exposes another customer’s recordHighSlot extraction can correctly read a reference the caller is not allowed to use.Authorize the lookup against the authenticated principal at the backend.
    A retry repeats an external actionHighThe client loses a reply after fulfillment may already have happened.Use an operation identifier and reconcile ambiguous results before resubmitting a write.
    Conversation history leaks through logsHighTranscripts and slot values can contain contact details, account references or unexpected sensitive text.Choose logging and retention deliberately, restrict access and redact unnecessary fields.
    A draft change reaches users without the intended testsMediumA team tests one configuration and routes the application to another alias or locale.Record the deployed version and verify its actual runtime target before release.
    The bot traps someone in a loopMediumRepeated fallback or slot prompts prevent a customer from reaching help.Set a recovery policy and test transfer, cancellation and accessible alternatives.
    Generated interpretation changes the taskMediumAn assisted or generative feature can behave differently on ambiguous input.Compare task-routing errors before enabling it and keep consequential checks outside model inference.

    Performance optimisation

    • Measure the delay from user input to the next usable prompt, including the fulfillment hook.
    • Reuse a runtime client and avoid rebuilding credentials for every turn.
    • Keep independent conversations concurrent, with ordered processing inside each session.
    • Move slow application work behind an appropriate workflow rather than blocking every dialogue turn.
    • For voice, measure recognition, response audio and interruption behavior together.
    • Test quotas using the intended Region and alias instead of extrapolating from a console demonstration.

    Reduce monthly cost

    A useful cost measure is the spend needed to finish a support task. A cheap individual turn can still produce an expensive interaction when the customer must repeat a reference several times.

    • Estimate turns per completed task, not just the number of people opening the chat.
    • Separate text requests, speech requests and streaming usage in the forecast.
    • Track repeated prompts and fallback loops; they consume requests without resolving the task.
    • Include Lambda, hosting, logging, any model features and contact-centre charges.
    • Keep automated evaluation traffic identifiable so it does not disappear into the production bill.
    • Compare the whole workflow with a simpler interface when a bot requires many turns for routine input.

    Request/response pricing and continuous streaming use different units. Counting one voice call as one ordinary speech request can badly understate the bill.

    Security optimisation

    • Give the application only the Lex runtime actions and alias resources it needs.
    • Treat the Lex service role, caller identity and Lambda execution role as separate permission boundaries.
    • Keep session identifiers opaque and scoped to one authenticated conversation.
    • Protect transcript stores with appropriate access controls and KMS policies where customer-managed encryption is used.
    • Do not put credentials, payment data or authorization decisions into user-editable session attributes.
    • Review AWS data-use, conversation logging and deletion settings before accepting sensitive production traffic.

    Governance & compliance

    Guardrails

    • Name an owner for every supported task and escalation path.
    • Record languages, channels, alias versions and the evidence required to release them.
    • Approve changes to backend permissions independently of prompt and utterance edits.

    Conversation quality in operation

    • Review unresolved tasks, fallback loops and transfers by intent.
    • Inspect timeout, throttling and hook errors alongside latency.
    • Retest corrections, account switching and unauthorized-record requests after releases.

    Keep evaluation transcripts synthetic where possible. For production evidence, define who may inspect a conversation and how long each copy is retained; turning off one log destination does not remove exports already sent elsewhere.

    Reduce carbon footprint

    • Remove avoidable dialogue loops before treating every extra turn as useful engagement.
    • Use stored test results when the deployed model and test inputs have not changed.
    • Expire obsolete transcript exports and unused application resources under a retention policy.
    • Do not publish a carbon-per-conversation number based only on the account’s total cloud footprint.

    Pricing

    Purchase options

    Text requests Request/response meter

    AWS’s public pricing example uses $0.00075 per text request. Confirm the applicable Region, configuration and current terms before budgeting.

    Speech requests Request/response meter

    The same official example uses $0.004 per speech request. It does not price an entire multi-turn telephone call as one request.

    Continuous streaming Separate interaction model

    Estimate the documented streaming units for the actual speech and text exchange rather than reusing request/response rates.

    Surrounding services Additional usage

    Fulfillment, transcript storage, monitoring, contact-centre integration and optional features can add charges.

    What you actually pay for

    • Runtime usage under the selected interaction model.
    • Any separately billed assisted, generative or design-time capability you enable.
    • Application compute, logging, storage and downstream API calls.
    • Telephony and human handoff when they are part of the channel.

    Rates above come from the official Amazon Lex pricing example, checked on 21 November 2026. They are illustrative request/response rates, not a quote for every Region, feature or streaming conversation.

    Important code references

    Configure and publish the ticket-status bot first. The CLI checks an existing alias and sends a synthetic text turn. Terraform provisions a draft bot and service role, not its full dialogue. Python calls the V2 runtime and saves the response privately; C# reads that export and reports the dialogue state without treating it as proof of a business transaction. Supply the same session ID for later turns of one conversation.

    # Existing built locale and published alias; replace the identifiers.
    LEX_REGION=us-east-1
    LEX_BOT_ID=replace-bot-id
    LEX_ALIAS_ID=replace-alias-id
    LEX_SESSION_ID=replace-with-one-opaque-conversation-id
    aws lexv2-models describe-bot-alias --region "$LEX_REGION" \
      --bot-id "$LEX_BOT_ID" --bot-alias-id "$LEX_ALIAS_ID"
    aws lexv2-runtime recognize-text --region "$LEX_REGION" \
      --bot-id "$LEX_BOT_ID" --bot-alias-id "$LEX_ALIAS_ID" \
      --locale-id en_US --session-id "$LEX_SESSION_ID" \
      --text "I want to check a support ticket"
    # Inspect sessionState and messages. Do not log real ticket details in a shared shell.
    # The application caller needs scoped runtime permission; the bot service role is separate.
    terraform {
      required_providers {
        aws = { source = "hashicorp/aws", version = "~> 6.0" }
      }
    }
    variable "region" { default = "us-east-1" }
    provider "aws" { region = var.region }
    data "aws_caller_identity" "current" {}
    data "aws_partition" "current" {}
    resource "aws_iam_role" "lex" {
      name = "cloudbrum-lex-text-demo"
      assume_role_policy = jsonencode({
        Version = "2012-10-17"
        Statement = [{
          Effect = "Allow"
          Principal = { Service = "lexv2.amazonaws.com" }
          Action = "sts:AssumeRole"
          Condition = {
            StringEquals = { "aws:SourceAccount" = data.aws_caller_identity.current.account_id }
            ArnLike = {
              "aws:SourceArn" = format("arn:%s:lex:%s:%s:bot/*",
                data.aws_partition.current.partition, var.region,
                data.aws_caller_identity.current.account_id)
            }
          }
        }]
      })
    }
    resource "aws_lexv2models_bot" "support" {
      name                        = "cloudbrum-ticket-demo"
      role_arn                    = aws_iam_role.lex.arn
      idle_session_ttl_in_seconds  = 300
      type                        = "Bot"
      data_privacy { child_directed = false }
    }
    output "bot_id" { value = aws_lexv2models_bot.support.id }
    # Add a locale, intents, slots, build, version and alias before runtime calls.
    # This text-only draft does not configure voice permissions or a fulfillment hook.
    # pip install boto3
    # Configure the AWS credential chain and AWS_DEFAULT_REGION for this bot.
    import json
    import os
    import sys
    import boto3
    from botocore.config import Config
    
    
    def send_turn(client, bot_id, alias_id, session_id, text, locale_id="en_US"):
        return client.recognize_text(
            botId=bot_id, botAliasId=alias_id, localeId=locale_id,
            sessionId=session_id, text=text,
        )
    
    
    def dialogue_status(response):
        state = response.get("sessionState") or {}
        action = state.get("dialogAction") or {}
        intent = state.get("intent") or {}
        if intent.get("state") == "Failed":
            return "fulfillment_failed"
        if action.get("type") == "ElicitSlot":
            return "waiting_for_slot"
        if action.get("type") == "ConfirmIntent":
            return "waiting_for_confirmation"
        if action.get("type") == "Close" and intent.get("state") == "Fulfilled":
            return "bot_reports_fulfilled; verify the backend outcome"
        return "dialogue_continues_or_needs_inspection"
    
    
    if __name__ == "__main__":
        # python lex_turn.py BOT_ID ALIAS_ID SESSION_ID "synthetic text" result.json
        bot_id, alias_id, session_id, text, output_path = sys.argv[1:]
        client = boto3.client("lexv2-runtime", config=Config(
            connect_timeout=5, read_timeout=20,
            retries={"mode": "standard", "total_max_attempts": 1},
        ))
        # No automatic replay: an uncertain reply may follow an executed backend action.
        result = send_turn(client, bot_id, alias_id, session_id, text)
        fd = os.open(output_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as target:
            json.dump(result, target)
        print(dialogue_status(result))
        # Keep responses protected; do not print slot values or raw conversation text.
    // .NET console app: dotnet run -- result.json
    // Reads the Python export; it does not call AWS or authorize a backend operation.
    using System.Text.Json;
    
    using var json = JsonDocument.Parse(File.ReadAllText(args[0]));
    if (!json.RootElement.TryGetProperty("sessionState", out var session))
    {
        Console.WriteLine("Inspect: no session state returned.");
        return;
    }
    var action = session.TryGetProperty("dialogAction", out var a) &&
        a.TryGetProperty("type", out var t) ? t.GetString() : null;
    var state = session.TryGetProperty("intent", out var intent) &&
        intent.TryGetProperty("state", out var s) ? s.GetString() : null;
    var status = (action, state) switch {
        (_, "Failed") => "Fulfillment failed.",
        ("ElicitSlot", _) => "Waiting for a slot.",
        ("ConfirmIntent", _) => "Waiting for confirmation.",
        ("Close", "Fulfilled") => "Bot reports fulfillment; verify the backend outcome.",
        _ => "Dialogue continues or needs inspection."
    };
    Console.WriteLine(status);
    // A successful request or a Fulfilled intent is not independent transaction evidence.

    Best videos to explore

    These official AWS talks provide conversation-design and integration background. They include older console screens and broader solutions with their own dependencies. Use the current Lex V2 documentation and this guide’s V2 request shapes for implementation.

    AWS re:Invent 2020: Create sophisticated conversational experiences using Amazon LexOfficial · Amazon Web Services · Intermediate · Watch on YouTube
    Multi-lingual FAQ bots with agent transfer using Amazon Lex, Kendra, Connect, and open source QnABotOfficial · Amazon Web Services · Advanced · Watch on YouTube

    Interview questions

    BasicWhat does Amazon Lex do?

    It identifies conversational tasks, collects details through slots and manages dialogue over voice or text. The application connects that conversation to authenticated data and business operations.

    BasicShould a new integration use Lex V2?

    Yes. This guide uses the V2 model and runtime APIs. Older examples with different bot identifiers, slot structures or runtime operations need a migration review rather than a renamed SDK import.

    BasicWhat is the difference between an intent and a slot?

    An intent names the task; a slot supplies a value needed for that task. Checking a ticket is an intent, while its reference number is a slot. Neither tells the backend which records the caller is authorized to see.

    IntermediateWhy does the bot forget the previous answer?

    Check whether the client changes the session ID between turns. Keep one opaque ID for the active conversation and submit its turns in order. Share neither the session ID nor its state across unrelated users.

    IntermediateWhy use a bot alias instead of a draft?

    An alias can point clients to a tested bot version while keeping their configured target stable. Build and verify the relevant locale before promotion, and keep the deployed alias/version in the release record.

    IntermediateDoes Fulfilled prove that an order or ticket was changed?

    No. It reports the intent state supplied by the bot workflow. Reconcile the backend operation separately, especially after a timeout or retry, and require authorization before carrying out any change.

    IntermediateWhen do I need a Lambda hook?

    Use application logic or a hook for validation and fulfillment that the bot configuration cannot provide by itself. Check the V2 request/response contract, invocation permission and alias/locale association.

    IntermediateCan Lex understand speech and multiple languages?

    Lex supports voice and text with locale-specific capabilities. Verify the current language, feature and Region support, then test recognition and task completion on representative speakers rather than assuming one locale describes every other one.

    AdvancedWhat does Assisted NLU change?

    It adds model-assisted intent classification and slot resolution within the configured bot tasks. Evaluate supported settings, task errors and applicable charges before enabling it; application authorization and fulfillment checks still belong outside that interpretation.

    AdvancedHow should an application retry a timed-out turn?

    First determine whether the backend action might already have run. Retain the session and operation context, make writes idempotent and reconcile uncertain results. Blindly replaying the conversation input can repeat consequential work.

    AdvancedHow do I estimate Lex costs?

    Forecast the relevant text, speech or streaming units and the turns needed to complete each task. Add fulfillment, hosting, storage, logging, optional features and any telephony or handoff charges.

    AdvancedWhat are the Azure and Google Cloud alternatives?

    Azure Bot Service connects a bot application to channels, with dialogue and language understanding supplied by its application stack. Google CX Agent Studio builds generative conversational applications; legacy Dialogflow CX flows have a separate API and billing model. Compare the whole task rather than just the chat box.

    Similar or alternative services on other clouds

    CapabilityAWSAzureGoogle Cloud
    ServiceAmazon Lex V2Azure Bot ServiceCustomer Experience Agent Studio
    Main boundaryNLU, slots and dialogue stateChannel registration plus your hosted applicationGenerative agent application and tools
    Task designIntents, slots and promptsApplication code/SDK with chosen language servicesAgent instructions, tool contracts and evaluations
    Runtime targetBot, alias, locale and sessionBot endpoint and channel conversationApplication, deployment and session
    Backend workLambda or application fulfillmentHosted business logic and APIsConfigured server/client tools with authorization
    Budget comparisonRequests or streaming unitsChannel plan plus hosting and AI servicesCurrent Studio sessions; legacy CX meters differ

    Use Lambda for appropriate hooks, DynamoDB for application-owned conversation or operation records, and CloudWatch for operational evidence. If the task is primarily open-ended generation, compare Bedrock rather than forcing every response into an intent tree.

    Did you find this article helpful?

    Your answer helps us improve this page for the next reader.

    Sources and further reading

    CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.