Lex Helper Library
A modern, type-safe Python library for building Amazon Lex chatbots with ease
The Lex Helper library is an extensive collection of functions and classes that make it easier to work with Lex. It's designed to make building Lex fulfillment lambdas easier, more efficient, understandable, and consistent. Gone are the days of accidentally mistyping a slot name, using a dictionary within a dictionary within a dictionary, or not being able to find where the code for a specific intent is.
Table of Contents
- Why Use Lex Helper?
- Installation
- Quick Start
- Core Features
- Bedrock Usage Examples
- Smart Disambiguation
- Examples
- Documentation
- Development Setup
Why Use Lex Helper?
- Simplified Intent Management: Each intent's logic lives in its own file under an
intents/directory, making it easy to locate, maintain, and scale your bot's capabilities without navigating complex nested handlers. The library will dynamically load the intent handler based on the intent name.
- Type-Safe Session Attributes: Define your session attributes as a Pydantic model, eliminating runtime errors from typos or incorrect data types. Get full IDE autocomplete support and catch errors before they reach production.
-
Automatic Request/Response Handling: Stop wrestling with deeply nested dictionaries. The library handles all the Lex request/response formatting, letting you focus on your bot's business logic.
-
Channel-Aware Formatting: Built-in support for different channels (SMS, Lex console, etc.) ensures your responses are properly formatted regardless of how users interact with your bot.
-
Error Handling Made Easy: Comprehensive exception handling and error reporting help you quickly identify and fix issues in your fulfillment logic.
-
Reduced Boilerplate: Common Lex operations like transitioning between intents, handling dialog states, and managing session attributes are simplified into clean, intuitive methods.
-
Smart Disambiguation: Automatically handle ambiguous user input with intelligent clarification prompts. Optional AI-powered responses using Amazon Bedrock create natural, contextual disambiguation messages that improve user experience.
-
Developer Experience: Get the benefits of modern Python features like type hints, making your code more maintainable and easier to understand. Full IDE support means better autocomplete and fewer runtime errors.
Installation
pip install lex-helper
For Lambda deployment, see Lambda Layer Deployment Guide.
Development Setup
This project uses modern Python tooling for development:
Prerequisites
- Python >= 3.12
- uv for dependency management
Quick Setup
# Install uv (if not already installed)
pip install uv
# Clone the repository and install dependencies
git clone <repository-url>
cd lex-helper
uv sync --dev
# Install pre-commit hooks for code quality
uv run pre-commit install
Development Commands
# Run tests
uv run pytest
# Run tests with coverage
uv run pytest --cov=lex_helper
# Code linting and formatting
uv run ruff check . # Check for issues
uv run ruff check --fix . # Fix issues automatically
uv run ruff format . # Format code
# Type checking
pyright
# Run all quality checks (includes documentation QA)
uv run pre-commit run --all-files
# Documentation quality assurance
make docs-qa # Comprehensive documentation checks
make docs-serve # Local documentation server
For detailed migration information from older tooling, see the Migration Guide.
Quick Start
1. Create Session Attributes
from pydantic import ConfigDict, Field
from lex_helper import SessionAttributes
class CustomSessionAttributes(SessionAttributes):
model_config = ConfigDict(extra="allow")
user_name: str = Field(default="", description="User's name")
visit_count: int = Field(default=0, description="Number of visits")
2. Create Main Handler
from typing import Any
from lex_helper import Config, LexHelper
from .session_attributes import CustomSessionAttributes
def lambda_handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
config = Config(
session_attributes=CustomSessionAttributes(),
package_name="your_project.intents"
)
lex_helper = LexHelper(config=config)
return lex_helper.handler(event, context)
3. Create Intent Handlers
Structure your intents in an intents/ directory:
your_project/
├── intents/
│ ├── __init__.py
│ ├── welcome_intent.py
│ └── booking_intent.py
├── session_attributes.py
└── handler.py
Core Features
Dialog Utilities
- get_intent, get_slot, set_slot: Manage intent and slot data
- elicit_intent, elicit_slot, delegate: Control dialog flow
- close: Complete dialog interactions
- transition_to_intent: Navigate between intents
- any_unknown_slot_choices, handle_any_unknown_slot_choice: Handle invalid inputs
- get_active_contexts, remove_context: Manage conversation context
- load_messages: Parse message data
Message Management
- MessageManager: Centralized message management with locale support
- get_message, set_locale: Load and retrieve localized messages from YAML files
- Supports
messages_{localeId}.yamlfiles (e.g.,messages_en_US.yaml,messages_es_ES.yaml) - Automatic fallback to
messages.yamlfor missing locales
Smart Disambiguation
- Intelligent Intent Resolution: Automatically detects ambiguous user input and presents clarifying options
- AI-Powered Responses: Optional Bedrock integration for contextual, natural language disambiguation messages
- Configurable Thresholds: Fine-tune when disambiguation triggers based on confidence scores and similarity
- Multi-Selection Support: Users can choose via text, numbers, letters, or button clicks
- Graceful Fallbacks: Seamless fallback to static messages if AI services are unavailable
Bedrock Integration
- invoke_bedrock: Direct integration with Amazon Bedrock models
- Supports multiple model families (Claude, Titan, Jurassic, Cohere, Llama)
- Automatic fallback between on-demand and inference profile modes
- Converse API: Unified interface for model interactions with system prompt support
- InvokeModel API: Traditional model invocation (default behavior)
Documentation
Recommended Reading Order:
- Best Practices Guide: Start here for detailed usage patterns, advanced examples, and code organization
- Testing Guide: Then learn comprehensive testing strategies for your Lex bots
- Lambda Layer Deployment: Finally, deploy as Lambda layers for better performance
Development Documentation:
- Development Guide: Complete development workflow, testing, and contribution guidelines
Bedrock Usage Examples
Basic InvokeModel API
from lex_helper import invoke_bedrock
response = invoke_bedrock(
prompt="What are the airports in Los Angeles?",
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
max_tokens=200,
temperature=0.1
)
print(response['text'])
Converse API with System Prompt
response = invoke_bedrock(
prompt="What are the airports in Los Angeles?",
model_id="anthropic.claude-3-5-sonnet-20240620-v1:0",
max_tokens=200,
temperature=0.1,
use_converse=True,
system_prompt="You are a travel expert. Provide accurate airport information."
)
print(response['text'])
Smart Disambiguation
Handle ambiguous user input intelligently with automatic clarification prompts:
Basic Setup
from lex_helper import Config, LexHelper
from lex_helper.core.disambiguation.types import DisambiguationConfig
# Enable disambiguation with default settings
config = Config(
session_attributes=CustomSessionAttributes(),
enable_disambiguation=True,
disambiguation_config=DisambiguationConfig(
confidence_threshold=0.5, # Trigger when confidence < 50%
max_candidates=2, # Show up to 2 options
)
)
AI-Powered Disambiguation
from lex_helper.core.disambiguation.types import BedrockDisambiguationConfig
# Enable Bedrock for intelligent, contextual responses
bedrock_config = BedrockDisambiguationConfig(
enabled=True,
model_id="anthropic.claude-3-haiku-20240307-v1:0",
system_prompt="You are a helpful assistant that creates clear, "
"friendly disambiguation messages for users."
)
disambiguation_config = DisambiguationConfig(
confidence_threshold=0.5,
bedrock_config=bedrock_config, # AI-powered responses
)
Example Interaction
User: "I need help with my booking"
Static Response:
"I can help you with several things. What would you like to do?"
Buttons: ["Book Flight", "Change Flight", "Cancel Flight"]
AI-Powered Response:
"I'd be happy to help with your booking! Are you looking to make
changes to an existing reservation or book a new flight?"
Buttons: ["Modify existing booking", "Book new flight"]
For detailed configuration options, see Smart Disambiguation Documentation.
Examples
- Basic Example: See
examples/basic_handler/for a simple implementation - Comprehensive Example: For production-ready patterns, see the documentation for:
- Advanced intent organization and management
- Complex session attribute handling
- Multi-turn conversation flows
- Error handling and fallback strategies
- Best practices for bot architecture
- Production deployment patterns
Metadata
Release files for lex-helper 0.0.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| lex_helper-0.0.3.tar.gz | 66.2 kB | With provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| lex_helper-0.0.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 138.8 kB
Release files / lex_helper-0.0.3.tar.gz
| Download URL | lex_helper-0.0.3.tar.gz |
|---|---|
| Size | 66.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1e998395542267511056caeca6d24eaf34e72fb90d1adc0bd1f1e3f2ea903c44
|
|
BLAKE2b-256 checksum How to use checksums |
85cd22dadde067e19d00a2206d58f484a798ba3475c7557bdd78d8649913b1ed
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2025.
Transparency logRelease files / lex_helper-0.0.3-py3-none-any.whl
| Download URL | lex_helper-0.0.3-py3-none-any.whl |
|---|---|
| Size | 72.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3c75d36a5bc5ef98d6069df06ba36545ce6a2bc086be227e9a4b4de5ec484901
|
|
BLAKE2b-256 checksum How to use checksums |
4f765f779467271291670aef467d51d51af010309f7615b1eec9b6dcb2dfe581
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2025.
Transparency logSecurity for lex-helper 0.0.3
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.
Full provenance
All 2 files in this release have been uploaded with provenance metadata.
Attestation for lex_helper-0.0.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 18, 2025.
Transparency logA 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.