Skip to main content

@cxbuilder/aws-lex

CI/CD Pipeline npm version PyPI version View on Construct Hub

Overview

The @cxbuilder/aws-lex package provides higher-level (L2) constructs for AWS LexV2 bot creation using the AWS CDK. It significantly simplifies the process of building conversational interfaces with Amazon Lex by abstracting away the complexity of the AWS LexV2 L1 constructs.

Why Use This Library?

AWS LexV2 L1 constructs are notoriously difficult to understand and use correctly. They require deep knowledge of the underlying CloudFormation resources and complex property structures. This library addresses these challenges by:

  • Simplifying the API: Providing an intuitive, object-oriented interface for defining bots, intents, slots, and locales
  • Automating best practices: Handling versioning and alias management automatically
  • Reducing boilerplate: Eliminating repetitive code for common bot configurations
  • Improving maintainability: Using classes with encapsulated transformation logic instead of complex nested objects

Key Features

  • Automatic versioning: Creates a bot version and associates it with the live alias when input changes
  • Simplified intent creation: Define intents with utterances and slots using a clean, declarative syntax
  • Multi-locale support: Easily create bots that support multiple languages
  • Lambda integration: Streamlined setup for dialog and fulfillment Lambda hooks
  • Extensible design: For complex use cases, you can always drop down to L1 constructs or fork the repository

Installation

Node.js

npm install @cxbuilder/aws-lex

Python

pip install cxbuilder-aws-lex

Quick Start

Create a simple yes/no bot with multi-language support:

TypeScript

import { App, Stack } from 'aws-cdk-lib';
import { Bot, Intent, Locale } from '@cxbuilder/aws-lex';

const app = new App();
const stack = new Stack(app, 'MyLexStack');

new Bot(stack, 'YesNoBot', {
  name: 'my-yes-no-bot',
  locales: [
    new Locale({
      localeId: 'en_US',
      voiceId: 'Joanna',
      intents: [
        new Intent({
          name: 'Yes',
          utterances: ['yes', 'yeah', 'yep', 'absolutely', 'of course'],
        }),
        new Intent({
          name: 'No',
          utterances: ['no', 'nope', 'never', 'absolutely not', 'no way'],
        }),
      ],
    }),
    new Locale({
      localeId: 'es_US',
      voiceId: 'Lupe',
      intents: [
        new Intent({
          name: 'Yes',
          utterances: ['sí', 'claro', 'por supuesto', 'correcto', 'exacto'],
        }),
        new Intent({
          name: 'No',
          utterances: ['no', 'para nada', 'negativo', 'jamás', 'en absoluto'],
        }),
      ],
    }),
  ],
});

Advanced Example: Bot with Slots and Lambda Integration

import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Bot, Intent, Locale, Slot } from '@cxbuilder/aws-lex';

const fulfillmentLambda = new NodejsFunction(stack, 'Handler', {
  entry: './src/bot-handler.ts',
});

new Bot(stack, 'BookingBot', {
  name: 'hotel-booking-bot',
  locales: [
    new Locale({
      localeId: 'en_US',
      voiceId: 'Joanna',
      codeHook: {
        fn: fulfillmentLambda,
        fulfillment: true,
      },
      intents: [
        new Intent({
          name: 'BookHotel',
          utterances: [
            'I want to book a room',
            'Book a hotel for {checkInDate}',
            'I need a room in {city}',
          ],
          slots: [
            new Slot({
              name: 'city',
              slotTypeName: 'AMAZON.City',
              elicitationMessages: ['Which city would you like to visit?'],
              required: true,
            }),
            new Slot({
              name: 'checkInDate',
              slotTypeName: 'AMAZON.Date',
              elicitationMessages: ['What date would you like to check in?'],
              required: true,
            }),
          ],
        }),
      ],
    }),
  ],
});

Architecture

The library uses a class-based approach with the following main components:

  • Bot: The main construct that creates the Lex bot resource
  • Locale: Configures language-specific settings and resources
  • Intent: Defines conversational intents with utterances and slots
  • Slot: Defines input parameters for intents
  • SlotType: Defines custom slot types with enumeration values

Advanced Usage

While this library simplifies common use cases, you can still leverage the full power of AWS LexV2 for complex scenarios:

  • Rich responses: For bots that use cards and complex response types
  • Custom dialog management: For sophisticated conversation flows
  • Advanced slot validation: For complex input validation requirements

In these cases, you can either extend the library classes or drop down to the L1 constructs as needed.

Bot Replication

When Lex replication is enabled, the Lex service automatically replicates the bot configuration to the replica region. However, the following resources are not automatically replicated:

  • Lambda handler permissions
  • Amazon Connect instance associations
  • Conversation log group configurations

The BotReplica construct handles creating these resources in the replica region.

Example: Multi-Region Bot Setup

import { App, Stack } from 'aws-cdk-lib';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Bot, BotReplica, Intent, Locale } from '@cxbuilder/aws-lex';

const app = new App();

// Primary region (us-east-1)
class EastStack extends Stack {
  public readonly bot: Bot;
  public readonly botHandler: NodejsFunction;

  constructor(scope: App, id: string) {
    super(scope, id, { env: { region: 'us-east-1' } });

    this.botHandler = new NodejsFunction(this, 'BotHandler', {
      entry: './src/bot-handler.ts',
    });

    this.bot = new Bot(this, 'MyBot', {
      name: 'customer-service-bot',
      handler: this.botHandler,
      replicaRegions: ['us-west-2'],
      connectInstanceArn:
        'arn:aws:connect:us-east-1:123456789012:instance/abc123',
      locales: [
        new Locale({
          localeId: 'en_US',
          voiceId: 'Joanna',
          intents: [
            new Intent({
              name: 'GetHelp',
              utterances: ['I need help', 'Can you help me'],
            }),
          ],
        }),
      ],
    });
  }
}

// Replica region (us-west-2)
class WestStack extends Stack {
  public readonly botHandler: NodejsFunction;
  public readonly botReplica: BotReplica;

  constructor(scope: App, id: string, eastStack: EastStack) {
    super(scope, id, { env: { region: 'us-west-2' } });

    this.botHandler = new NodejsFunction(this, 'BotHandler', {
      entry: './src/bot-handler.ts',
    });

    this.botReplica = new BotReplica(this, 'MyBotReplica', {
      botName: eastStack.bot.botName,
      botId: eastStack.bot.botId,
      botAliasId: eastStack.bot.botAliasId,
      handler: this.botHandler,
      connectInstanceArn:
        'arn:aws:connect:us-west-2:123456789012:instance/abc123',
    });
  }
}

const eastStack = new EastStack(app, 'EastStack');
const westStack = new WestStack(app, 'WestStack', eastStack);

BotReplica Properties

  • botName (required): The name of the bot from the primary region
  • botId (required): The bot ID from the primary region
  • botAliasId (required): The bot alias ID from the primary region
  • handler (optional): Lambda function to use as the bot handler in the replica region
  • connectInstanceArn (optional): ARN of the Amazon Connect instance to associate with the bot
  • logGroup (optional): Set to false to disable automatic log group creation (default: true)

ConnectAgentBot

ConnectAgentBot is a purpose-built construct that wires an Amazon Lex bot to Amazon Q in Connect (formerly Amazon Wisdom). It configures the AMAZON.QInConnectIntent automatically and grants the bot role the IAM permissions required to create and query Q in Connect sessions — so you only need to supply your assistant ARN and locale settings.

When to use

Use ConnectAgentBot when you want an Amazon Connect contact flow to hand off to Q in Connect for generative AI-assisted responses. The bot acts as the bridge: Connect invokes the Lex bot, the bot triggers QInConnectIntent, and Q in Connect returns an AI-generated response via ((x-amz-lex:q-in-connect-response)).

Example

import { App, Stack } from 'aws-cdk-lib';
import { ConnectAgentBot } from '@cxbuilder/aws-lex';

const app = new App();
const stack = new Stack(app, 'AgentBotStack');

new ConnectAgentBot(stack, 'AgentBot', {
  name: 'my-agent-bot',
  assistantArn: 'arn:aws:wisdom:us-east-1:123456789012:assistant/abc-123',
  connectInstanceArn: 'arn:aws:connect:us-east-1:123456789012:instance/xyz-456',
  locales: [
    { localeId: 'en_US', voiceId: 'Joanna' },
  ],
});

ConnectAgentBot Properties

  • name (required): Name of the Lex bot
  • assistantArn (required): ARN of the Amazon Q in Connect assistant
  • connectInstanceArn (required): ARN of the Amazon Connect instance to associate with the bot
  • locales (required): Array of locale configurations

ConnectAgentBotLocale Properties

  • localeId (required): Lex locale identifier (e.g. en_US)
  • voiceId (optional): Amazon Polly voice ID
  • speechFoundationModelArn (optional): Bedrock foundation model ARN for speech. Defaults to amazon.nova-2-sonic-v1:0 in the stack's region

What it configures automatically

  • A single AmazonQinConnect intent backed by AMAZON.QInConnectIntent
  • Fulfillment response set to ((x-amz-lex:q-in-connect-response))
  • Fallback intent routed through a dialog code hook that ends the conversation on success, failure, or timeout
  • Bot role policies for wisdom:GetAssistant, wisdom:CreateSession, wisdom:SendMessage, and wisdom:GetNextMessage

Utilities

throttleDeploy

Deploying multiple Lex bots in parallel can hit AWS Lex API limits, causing deployment failures. This function solves that by controlling deployment concurrency through dependency chains, organizing bots into batches where each batch deploys sequentially while different batches can still deploy in parallel.

About

Built and maintained by CXBuilder, an AWS Advanced Tier partner that designs, builds and operates Amazon Connect contact centers on AWS.

License

MIT

Metadata

Release files for cxbuilder-aws-lex 1.4.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cxbuilder-aws-lex 1.4.4
File Size Uploaded Provenance Actions
cxbuilder_aws_lex-1.4.4.tar.gz 239.6 kB Without provenance Details for cxbuilder_aws_lex-1.4.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cxbuilder-aws-lex 1.4.4
File Interpreter ABI Platform Actions
cxbuilder_aws_lex-1.4.4-py3-none-any.whl Python 3 none any Details for cxbuilder_aws_lex-1.4.4-py3-none-any.whl

Total release size: 476.5 kB

Release files / cxbuilder_aws_lex-1.4.4.tar.gz

Download URL cxbuilder_aws_lex-1.4.4.tar.gz
Size 239.6 kB
Tags Source
SHA-256 checksum
How to use checksums
2f9bcda29268ca1f0d83ef0afdba80a42a8f5bb07a344972fd7059472110f92c
BLAKE2b-256 checksum
How to use checksums
f053998aa2c2f1b953da1c1009b9f67d24ae3e560cac1c9f06985aae83e19e34
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Release files / cxbuilder_aws_lex-1.4.4-py3-none-any.whl

Download URL cxbuilder_aws_lex-1.4.4-py3-none-any.whl
Size 236.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
750ba8299e1ec7b7ae8f3957c2d350bc453e878b23266909266e4603836da41e
BLAKE2b-256 checksum
How to use checksums
68b9b9177c35503de67ddd7bffda89a95072812d5a6a132cef3f1a3387976335
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Security for cxbuilder-aws-lex 1.4.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page