Amazon Lex Tutorial Build a Chatbot & Connect It to Amazon Connect
Amazon Lex Tutorial Build a Chatbot & Connect It to Amazon Connect

Amazon Lex Tutorial: Build a Chatbot & Connect It to Amazon Connect (2026)

Quick answer: Amazon Lex is AWS’s service for building chatbots and voice bots that understand natural language. You create a bot, add intents (what the customer wants), sample utterances (how they say it) and slots (details you need to collect), then build and test it. To use it in a contact center, publish a bot version and alias, add it to your Amazon Connect instance, and call it from a contact flow with the Get customer input block. Standard pricing is $0.004 per speech request and $0.00075 per text request.

Amazon Lex powers the “how can I help you today?” moment in thousands of IVRs and chat widgets. Instead of “press 1 for billing”, customers just say what they need, and Lex works out the intent and collects the details.

In this Amazon Lex tutorial you’ll build a real order-status bot step by step, connect it to Amazon Connect for voice and chat, and add a Lambda function so it can look up live data. No prior Lex experience is needed.

What is Amazon Lex?

Amazon Lex is a fully managed AWS service for building conversational interfaces, chatbots and voice bots, using the same speech recognition and language understanding technology behind Alexa. It combines two capabilities:

  • Automatic speech recognition (ASR): turns spoken words into text.
  • Natural language understanding (NLU): works out what the text means: the customer’s intent and the details inside it.

Common uses include IVR self-service (order status, balance checks, password resets), website and app chatbots, appointment booking, and routing callers to the right queue based on what they say. The current version is Amazon Lex V2; all new bots should use it.

Key Lex concepts in plain English

Concept What it means Example
Bot The whole conversational assistant OrderHelperBot
Intent A goal the customer wants to achieve CheckOrderStatus, SpeakToAgent
Utterance A sample phrase that triggers an intent “Where is my order?”, “Track my parcel”
Slot A piece of information the bot must collect OrderNumber
Slot type The kind of value a slot accepts AMAZON.AlphaNumeric, AMAZON.Date, or a custom list
Prompt What the bot asks to fill a slot “What’s your order number?”
Fulfillment What happens once all slots are filled A Lambda function looks up the order
Version / Alias A frozen snapshot of the bot, and a pointer to it Version 1, alias prod
FallbackIntent Built-in intent for anything the bot doesn’t understand “Sorry, I didn’t get that.”

Build your first Amazon Lex chatbot

We’ll build OrderHelperBot, which answers “where is my order?” by voice and chat. Use the same AWS Region as your Amazon Connect instance.

Step 1: Create the bot

  1. Open the Amazon Lex V2 console and choose Create bot.
  2. Choose Create a blank bot (traditional). You can also use the generative descriptive bot builder, covered later.
  3. Name it OrderHelperBot.
  4. Under IAM permissions, choose Create a role with basic Amazon Lex permissions.
  5. For the COPPA question (Children’s Online Privacy Protection Act), choose No unless your bot is aimed at children under 13.
  6. Keep the idle session timeout at 5 minutes and choose Next.

Step 2: Add a language and voice

Select English (US) (or your language) and pick a voice for spoken responses, for example Danielle or Joanna. Leave the intent classification confidence score threshold at the default 0.40 for now. Choose Done.

Step 3: Create the CheckOrderStatus intent

  1. Rename the default intent (or add a new one) to CheckOrderStatus.
  2. Add at least 10–15 sample utterances. Variety matters more than quantity:
    Where is my order
    Track my order
    I want to check my order status
    Has my parcel shipped
    Where is my order {OrderNumber}
    Check order {OrderNumber}
    When will my package arrive
    My delivery hasn't arrived
    Order status please
    I'm calling about an order

Writing {OrderNumber} inside an utterance lets customers give the slot value in the same sentence, so the bot doesn’t need to ask again.

Step 4: Add the OrderNumber slot

  1. In the Slots section, choose Add slot.
  2. Name: OrderNumber. Slot type: AMAZON.AlphaNumeric (use AMAZON.Number if your order IDs are digits only).
  3. Prompt: “Sure, what’s your order number?”
  4. Mark the slot as Required.

Voice tip: for alphanumeric IDs over the phone, open the slot’s advanced options and set a slot resolution / spelling style (such as “spell by letter”). This greatly improves recognition of values like “AB12345”.

Step 5: Add a confirmation and closing response

Optionally turn on Confirmation: “Just to confirm, your order number is {OrderNumber}?” This is very useful on voice, where misheard digits are common. For now, set a simple closing response: “Thanks, let me check order {OrderNumber}.”

Also add a second intent, SpeakToAgent, with utterances such as “agent”, “talk to a person” and “representative”. Customers must always have a way out.

Step 6: Build and test

Choose Save intent, then Build (it takes about a minute). Open the Test panel and type “where is my order”. The bot should ask for the order number. Try a few phrasings you didn’t add as utterances; Lex’s NLU should still recognise most of them.

Step 7: Add a Lambda function for real answers

Right now the bot collects the order number but can’t look anything up. A Lambda fulfillment code hook fixes that. Create a Python Lambda function in the same Region:

ORDERS = {  # demo data - replace with DynamoDB or your order API
    "AB12345": {"status": "shipped", "eta": "18 November"},
    "CD67890": {"status": "being packed", "eta": "20 November"},
}

def close(intent_name, message, attributes=None):
    """Build a Lex V2 response that ends the intent."""
    return {
        "sessionState": {
            "dialogAction": {"type": "Close"},
            "intent": {"name": intent_name, "state": "Fulfilled"},
            "sessionAttributes": attributes or {},
        },
        "messages": [{"contentType": "PlainText", "content": message}],
    }

def lambda_handler(event, context):
    intent = event["sessionState"]["intent"]
    slots = intent.get("slots") or {}
    slot = slots.get("OrderNumber") or {}
    order_id = ((slot.get("value") or {}).get("interpretedValue") or "").upper()

    order = ORDERS.get(order_id)
    if not order:
        return close(intent["name"],
                     f"Sorry, I couldn't find order {order_id}. Let me get someone to help.",
                     {"orderFound": "false"})

    return close(intent["name"],
                 f"Order {order_id} is {order['status']} and should arrive on {order['eta']}.",
                 {"orderFound": "true", "orderStatus": order["status"]})

Then connect it to the bot:

  1. In the CheckOrderStatus intent, under Fulfillment, turn on Use a Lambda function for fulfillment (in advanced options).
  2. Go to Aliases → TestBotAlias → English (US) and select your Lambda function and version ($LATEST for testing).
  3. Build and test again: “where is my order AB12345” should now return the real status.

The sessionAttributes you return (orderFound, orderStatus) travel back to Amazon Connect, so your contact flow can branch on them. For more on Lambda patterns, timeouts and error handling, see our Amazon Connect Lambda integration guide.

Connect your Lex bot to Amazon Connect

Step 8: Publish a version and alias

Don’t use TestBotAlias in production. It has low limits and is meant for testing only.

  1. In your bot, go to Bot versions → Create version. This freezes the current design as Version 1.
  2. Go to Aliases → Create alias, name it prod and point it to Version 1.
  3. In the prod alias language settings, attach your Lambda function (ideally a Lambda alias, also called prod).

Later, when you change the bot, create Version 2, test it, then simply repoint the prod alias. Your contact flows don’t need to change.

Step 9: Add the bot to your Connect instance

  1. Open the Amazon Connect console and select your instance alias.
  2. Choose Flows in the left menu.
  3. Under Amazon Lex, select the Region, the bot OrderHelperBot and the alias prod, then choose Add Amazon Lex Bot.

This grants Amazon Connect permission to call the bot. You can also add bots from the Amazon Connect admin website under Routing → Bots.

Step 10: Use the bot in a contact flow

  1. In your inbound flow, add a Get customer input block.
  2. Set the greeting prompt, for example “Hi, thanks for calling. How can I help you today?” (text-to-speech or a recorded prompt).
  3. Open the Amazon Lex tab, select OrderHelperBot and alias prod.
  4. Under Intents, add CheckOrderStatus and SpeakToAgent. Each becomes an output branch.
  5. Connect the branches:
    • CheckOrderStatus → Lex has already spoken the answer. Add a Check contact attributes block on $.Lex.SessionAttributes.orderFound: true → “Anything else?” or disconnect; false → transfer to queue.
    • SpeakToAgent → Set working queue → Transfer to queue.
    • Default and Error → a friendly retry or transfer to an agent.
  6. Save and Publish the flow, then assign it to a phone number or your chat widget.

Useful values available in the flow after the Lex block:

Value Reference
Matched intent $.Lex.IntentName
A slot value $.Lex.Slots.OrderNumber
Session attributes from Lambda $.Lex.SessionAttributes.orderStatus
Customer sentiment (if enabled) $.Lex.SentimentResponse.Label

Save anything you need later into contact attributes with a Set contact attributes block, so agents see it in their screen when the call is transferred. New to flows? Start with our Amazon Connect contact flows guide.

Generative AI features in Amazon Lex

Lex now includes optional generative AI features, powered by Amazon Bedrock, that reduce manual work:

  • Descriptive bot builder: describe the bot in plain English (“a bot that books hotel rooms and checks reservations”) and Lex drafts the intents, utterances and slots for you to review.
  • Utterance generation: generates sample utterances for an intent, a quick way to cover more phrasings.
  • Assisted slot resolution: uses an LLM to understand slot values that standard NLU misses, such as “the day after tomorrow”.
  • QnAIntent: answers FAQs directly from a knowledge base (such as a Bedrock knowledge base), with no need to build an intent for every question.

For fully open-ended conversations, Amazon Connect also offers AI agents that go beyond intent-based bots. See Amazon Connect AI agents explained for when to use each.

Amazon Lex pricing

Lex charges per request, with no upfront fees. Standard (request-and-response) pricing:

Request type Price Example cost
Speech request $0.004 per request 100,000 requests = $400
Text request $0.00075 per request 100,000 requests = $75

A “request” is one customer turn. A 4-turn voice conversation is 4 speech requests, about $0.016. Streaming conversations and generative AI features are priced separately; check the official Amazon Lex pricing page for current rates. New AWS accounts can use AWS Free Tier credits to experiment.

Using Lex inside Amazon Connect? Under the newer Amazon Connect Customer pricing, Lex requests made from your Connect instance are included in the per-channel rate. Under the older à la carte model they’re billed separately. Our Amazon Connect pricing guide explains both.

Best practices and common mistakes

  1. Always offer an exit. Include a SpeakToAgent intent, and route the Default and Error branches to a human. Trapping callers is the fastest way to destroy CSAT.
  2. Write utterances from real calls. Pull phrases from call transcripts or chat logs instead of guessing. Lex’s analytics and utterance statistics show what customers actually say that the bot missed.
  3. Keep intents distinct. “CheckOrder” and “TrackOrder” as separate intents will confuse the model. Merge overlapping intents.
  4. Confirm important slots on voice. Read back numbers before acting on them.
  5. Never point production at TestBotAlias or $LATEST. Use versions and aliases for both the bot and Lambda.
  6. Keep Lambda fast. Customers hear silence while it runs. Aim for well under a second, and play a prompt before anything slow.
  7. Measure containment. Track how many conversations the bot resolves without an agent; it’s one of the key call center KPIs for self-service.
  8. Turn on conversation logs (text and audio) to CloudWatch or S3, with sensitive slots marked as obfuscated so card numbers or dates of birth aren’t stored in logs.

Frequently asked questions

Is Amazon Lex free?

No. It’s pay-per-request, but costs are low: $0.004 per speech request and $0.00075 per text request. New AWS accounts can use AWS Free Tier credits while learning.

What is the difference between Amazon Lex V1 and V2?

Lex V2 is the current version. It supports multiple languages in one bot, a better console, versions and aliases per language, streaming conversations and the generative AI features. All new bots should be built on V2.

Can Amazon Lex be used without Amazon Connect?

Yes. Lex works on its own in websites, mobile apps, Slack, Facebook Messenger and Twilio SMS, or through the Lex runtime API from any application.

Is Amazon Lex the same as ChatGPT?

No. Classic Lex is an intent-based bot: it recognises defined goals and collects specific details, which makes it predictable and good for transactions. Large language models generate free-form answers. Lex’s generative features and Amazon Connect AI agents combine both approaches.

What languages does Amazon Lex support?

Lex supports many languages and locales, including several varieties of English, Spanish, French, German, Italian, Portuguese, Japanese, Korean, Chinese and Hindi. Check the AWS documentation for the current list and which features each language supports.

How do I pass data from Amazon Connect to Lex?

In the Get customer input block, set session attributes (for example, the customer’s name or account tier from a previous Lambda lookup). Lex and its Lambda function receive them in sessionState.sessionAttributes.

Next steps

🎓 Want to work on Amazon Connect in real projects?

Join our live, instructor-led Amazon Connect training: 17 modules, 75+ hours, 80% hands-on labs, rated 4.8★ by our trainees. Or test yourself first with our free practice exams.