Core API¶
The core module contains the main functionality for handling Amazon Lex requests, managing dialog state, and processing session attributes. This is where you'll find the primary LexHelper class and essential utilities.
Main Handler¶
LexHelper¶
LexHelper(config: Config[T])
Source code in lex_helper/core/handler.py
                    Functions¶
    Primary entry point for the lex_helper library.
This function is designed to handle AWS Lambda events triggered by Amazon Lex. It processes the incoming event and context, and utilizes custom session attributes if provided. The function orchestrates the entire flow, including parsing the Lex request, handling intents, managing session state, and formatting the response for the channel.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| event | dict[str, Any] | The event data from AWS Lambda, typically containing the Lex request. | required | 
| context | Any | The context object provided by AWS Lambda, containing runtime information. | required | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | dict[str, Any]: A formatted response ready to be sent back to Amazon Lex. | 
Source code in lex_helper/core/handler.py
              
    Handle disambiguation responses and trigger disambiguation when needed.
This handler processes user responses to disambiguation questions and triggers new disambiguation when confidence is low.
Source code in lex_helper/core/handler.py
              
    Route the incoming request based on intent. The JSON body of the request is provided in the event slot.
Source code in lex_helper/core/handler.py
              Configuration¶
    
              Bases: BaseModel
Dialog Utilities¶
The dialog module provides essential functions for managing conversation flow and dialog state.
Standard util methods to manage dialog state
Functions¶
    Extracts the sentiment from the first interpretation in a LexRequest.
This function checks if the 'interpretations' attribute exists in the LexRequest and retrieves the sentiment from the first interpretation if available.
Parameters: lex_request (LexRequest): The LexRequest object containing interpretations.
Returns: Optional[str]: The sentiment string if available, otherwise None.
Raises: AttributeError: If the 'interpretations' attribute is missing or not a list.
Source code in lex_helper/core/dialog.py
              
    Removes a specific context from the active contexts list.
Parameters: context_list (ActiveContexts): The list of active contexts. context_name (str): The name of the context to remove.
Returns: ActiveContexts: The updated list of active contexts without the specified context.
Source code in lex_helper/core/dialog.py
              
    Removes inactive contexts from the active contexts list in a LexRequest.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: ActiveContexts: The updated list of active contexts with inactive ones removed.
Source code in lex_helper/core/dialog.py
              
    Closes the dialog with the user by setting the intent state to 'Fulfilled'.
Parameters: lex_request (LexRequest): The LexRequest object containing session state. messages (LexMessages): The messages to send to the user.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
    Elicits the user's intent by sending a message and updating session attributes.
Parameters: messages (LexMessages): The messages to send to the user. lex_request (LexRequest): The LexRequest object containing session state.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
elicit_slot(slot_to_elicit: LexSlot | str, messages: LexMessages, lex_request: LexRequest[T]) -> LexResponse[T]
Elicits a specific slot from the user by sending a message and updating session attributes.
Parameters: slot_to_elicit (LexSlot | str): The slot to elicit from the user. messages (LexMessages): The messages to send to the user. lex_request (LexRequest): The LexRequest object containing session state.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
    Delegates the dialog to Lex by updating the session state and returning a response.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
    Extracts the text of the buttons from a list of LexImageResponseCard messages.
This function loops through a list of messages, checks if each message is an instance of LexImageResponseCard, and if so, extracts the text of each button in the imageResponseCard attribute of the message. The function then returns a JSON-encoded list of the extracted button texts.
Parameters: messages (LexMessages): The list of messages to process.
Returns: str: A JSON-encoded list of the extracted button texts.
Source code in lex_helper/core/dialog.py
              
    Retrieves the intent from a LexRequest.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: Intent: The intent object from the session state.
Raises: ValueError: If no intent is found in the request.
Source code in lex_helper/core/dialog.py
              
    Retrieves the value of a slot from an intent.
Parameters: slot_name (LexSlot | str): The name of the slot to retrieve. intent (Intent): The intent object containing the slot. kwargs (Any): Additional arguments for slot value preference.
Returns: Any: The value of the slot if available, otherwise None.
Source code in lex_helper/core/dialog.py
              
get_composite_slot(slot_name: str, intent: Intent, preference: str | None = None) -> dict[str, str | None] | None
Retrieves the values from sub-slots of a given slot from an intent.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| slot_name | str | Name of the slot to be fetched. | required | 
| intent | Intent | Intent object containing the slot. | required | 
| preference | Optional[str], default=None | Preference for value type ('interpretedValue' or 'originalValue'). If no preference is provided and 'interpretedValue' is available, it's used. Otherwise, 'originalValue' is used. | None | 
Returns:
| Type | Description | 
|---|---|
| dict[str, str | None] | None | Dict[str, Union[str, None]] or None: Dictionary containing the subslot names and their corresponding values, or None if the slot or subslots don't exist. | 
Raises:
| Type | Description | 
|---|---|
| Exception | Any exception that occurs while fetching the slot. | 
Source code in lex_helper/core/dialog.py
              
    Retrieves the value from a slot dictionary.
Parameters: slot (dict[str, Any]): The slot dictionary containing the value. kwargs (Any): Additional arguments for slot value preference.
Returns: Any: The interpreted or original value of the slot if available, otherwise None.
Source code in lex_helper/core/dialog.py
              
set_subslot(composite_slot_name: LexSlot, subslot_name: str, subslot_value: Any | None, intent: Intent) -> Intent
Sets a subslot value within a composite slot in the given intent.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| composite_slot_name | str | The name of the composite slot within the intent. | required | 
| subslot_name | str | The name of the subslot to be set. | required | 
| subslot_value | Optional[Any] | The value to be set for the subslot. If None, the subslot is set to None. | required | 
| intent | Intent | The intent containing the slots. | required | 
Returns:
| Name | Type | Description | 
|---|---|---|
| Intent | Intent | The updated intent with the modified subslot value. | 
Source code in lex_helper/core/dialog.py
              
    Sets a slot value in the given intent.
Parameters: slot_name (LexSlot): The name of the slot to set. slot_value (Optional[str]): The value to set for the slot. intent (Intent): The intent containing the slots.
Returns: Intent: The updated intent with the modified slot value.
Source code in lex_helper/core/dialog.py
              
get_composite_slot_subslot(composite_slot: LexSlot, sub_slot: Any, intent: Intent, **kwargs: Any) -> str | None
Retrieves the value of a subslot from a composite slot in an intent.
Parameters: composite_slot (LexSlot): The composite slot containing the subslot. sub_slot (Any): The name of the subslot to retrieve. intent (Intent): The intent object containing the slots. kwargs (Any): Additional arguments for slot value preference.
Returns: Optional[str]: The value of the subslot if available, otherwise None.
Source code in lex_helper/core/dialog.py
              
    Retrieves the active contexts from a LexRequest.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: ActiveContexts: The list of active contexts.
Source code in lex_helper/core/dialog.py
              
    Retrieves the invocation label from a LexRequest.
Parameters: lex_request (LexRequest): The LexRequest object containing the invocation label.
Returns: str: The invocation label.
Source code in lex_helper/core/dialog.py
              
    Safely deletes a session attribute from a LexRequest.
Parameters: lex_request (LexRequest): The LexRequest object containing session attributes. attribute (str): The name of the attribute to delete.
Returns: LexRequest: The updated LexRequest with the attribute deleted.
Source code in lex_helper/core/dialog.py
              
    Extracts common components from the intent request.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: tuple: A tuple containing the intent, active contexts, session attributes, and invocation label.
Source code in lex_helper/core/dialog.py
              
    Checks if the user provided an invalid response to a previous slot elicitation.
Use this function at the beginning of your intent handlers to detect when users respond with unrecognized choices (e.g., "X" when options were "A, B, C").
Usage
if dialog.any_unknown_slot_choices(lex_request): return dialog.handle_any_unknown_slot_choice(lex_request)
Continue with normal intent logic¶
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: bool: True if there are unknown slot choices, otherwise False.
Source code in lex_helper/core/dialog.py
              
    Automatically handles invalid slot responses by delegating back to Lex or using custom logic.
This function processes the invalid choice and either continues the conversation or triggers custom error handling via unknown_choice_handler.
Usage
if dialog.any_unknown_slot_choices(lex_request): return dialog.handle_any_unknown_slot_choice(lex_request)
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
unknown_choice_handler(lex_request: LexRequest[T], choice: str | LexSlot | None, handle_unknown: bool | None = True, next_intent: str | None = None, next_invo_label: str | None = '') -> LexResponse[T]
Customizable handler for processing invalid user choices.
Override this function or call it directly to implement custom logic when users provide invalid responses to slot elicitations (buttons, multiple choice, etc.).
Usage
Custom handling¶
return dialog.unknown_choice_handler( lex_request=lex_request, choice="invalid_response", next_intent="clarification_intent" )
Or override the function entirely for global custom behavior¶
Parameters: lex_request (LexRequest): The LexRequest object containing session state. choice (str | LexSlot | None): The invalid choice provided by the user. handle_unknown (Optional[bool]): Whether to handle unknown choices. next_intent (Optional[str]): The next intent to transition to. next_invo_label (Optional[str]): The next invocation label.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
callback_original_intent_handler(lex_request: LexRequest[T], messages: LexMessages | None = None) -> LexResponse[T]
Handles switching the conversation flow to an initial intent. Assume a scenario in which the conversation flow starts with intent A, transitions to intent B, returns to intent A after fulfilling the steps in intent B.
For instance, from a MakeReservation intent to an Authenticate intent and back to the MakeReservation intent.
This method assumes that the session attributes callback_event and callback_handler have been populated from the calling intent A as in the example below.
lex_request.sessionState.sessionAttributes.callback_handler = lex_request.sessionState.intent.name
lex_request.sessionState.sessionAttributes.callback_event = json.dumps(lex_request, default=str)
message = (
    f"Before I can help your reservation, you will need to authenticate. "
)
return dialog.transition_to_intent(
    intent_name="Authenticate",
    lex_request=lex_request,
    messages=[LexPlainText(content=message)]
)
Invoke callback_original_intent_handler from intent B to switch back to the original intent.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| lex_request | LexRequest[T] | description | required | 
Returns:
| Type | Description | 
|---|---|
| LexResponse[T] | LexResponse[T]: description | 
Source code in lex_helper/core/dialog.py
              
    Reprompts the user for a slot value by sending a message.
Parameters: lex_request (LexRequest): The LexRequest object containing session state.
Returns: LexResponse: The response object to be sent back to Lex.
Source code in lex_helper/core/dialog.py
              
    Loads messages from a JSON string into LexMessages objects.
Parameters: messages (str): The JSON string containing messages.
Returns: LexMessages: The list of LexMessages objects.
Source code in lex_helper/core/dialog.py
              
    Use this to parse a Lambda event into a LexRequest object.
Parameters: data (dict[str, Any]): The Lambda event data. sessionAttributes (Optional[T]): The session attributes to use.
Returns: LexRequest[T]: The parsed LexRequest object.
Source code in lex_helper/core/dialog.py
              Session Management¶
Session attributes provide type-safe state management across conversation turns.
Type Definitions¶
Core type definitions used throughout the library.
Classes¶
Disambiguation¶
Smart disambiguation functionality for handling ambiguous user input using AI.
Disambiguation Handler¶
Disambiguation Handler for the Smart Disambiguation feature.
This module provides the DisambiguationHandler class that orchestrates the disambiguation process, generates user-friendly clarification responses, and processes user selections to route to the appropriate intent.
Classes¶
DisambiguationHandler(config: DisambiguationConfig | None = None)
Handles disambiguation response generation and user selection processing.
This class is responsible for creating user-friendly clarification messages when multiple intents are possible matches, and processing user responses to route them to the correct intent handler.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| config | DisambiguationConfig | None | Configuration options for disambiguation behavior | None | 
Source code in lex_helper/core/disambiguation/handler.py
                    Functions¶
handle_disambiguation(lex_request: LexRequest[T], candidates: list[IntentCandidate]) -> LexResponse[T]
Generate disambiguation response with clarifying questions.
Creates a response that presents the user with options to clarify their intent, using buttons for easy selection.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| lex_request | LexRequest[T] | The original Lex request | required | 
| candidates | list[IntentCandidate] | List of intent candidates to present | required | 
Returns:
| Type | Description | 
|---|---|
| LexResponse[T] | LexResponse with disambiguation options | 
Source code in lex_helper/core/disambiguation/handler.py
              
    Process user's response to disambiguation and route to selected intent.
Analyzes the user's input to determine which intent they selected and updates the request to route to that intent.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| lex_request | LexRequest[T] | The Lex request with user's disambiguation response | required | 
Returns:
| Type | Description | 
|---|---|
| LexResponse[T] | None | None if this isn't a disambiguation response, otherwise routes | 
| LexResponse[T] | None | to the selected intent by updating the request | 
Source code in lex_helper/core/disambiguation/handler.py
              Functions¶
Disambiguation Analyzer¶
DisambiguationAnalyzer for intelligent intent disambiguation.
This module provides the core analysis functionality for determining when disambiguation should occur and which intent candidates to present to users.
Attributes¶
Classes¶
DisambiguationAnalyzer(config: DisambiguationConfig | None = None)
Analyzes user input to determine disambiguation candidates.
The analyzer uses Lex's NLU confidence scores to identify potential intent matches and determine when disambiguation should be triggered based on configurable thresholds.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| config | DisambiguationConfig | None | Configuration options for disambiguation behavior. If None, uses default configuration. | None | 
Source code in lex_helper/core/disambiguation/analyzer.py
                    
                  Functions¶
analyze_request(lex_request: LexRequest[SessionAttributes]) -> DisambiguationResult
Analyze Lex request and return disambiguation candidates.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| lex_request | LexRequest[SessionAttributes] | The Lex request containing interpretations with confidence scores | required | 
Returns:
| Type | Description | 
|---|---|
| DisambiguationResult | DisambiguationResult containing analysis results and candidates | 
Source code in lex_helper/core/disambiguation/analyzer.py
              
extract_intent_scores(lex_request: LexRequest[SessionAttributes]) -> IntentScores
Extract confidence scores from Lex interpretations.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| lex_request | LexRequest[SessionAttributes] | The Lex request containing interpretations | required | 
Returns:
| Type | Description | 
|---|---|
| IntentScores | Dictionary mapping intent names to confidence scores (0.0-1.0) | 
Source code in lex_helper/core/disambiguation/analyzer.py
              
should_disambiguate(scores: IntentScores, threshold: float) -> bool
Determine if disambiguation is needed based on confidence scores.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| scores | IntentScores | Dictionary of intent names to confidence scores | required | 
| threshold | float | Minimum confidence threshold to avoid disambiguation | required | 
Returns:
| Type | Description | 
|---|---|
| bool | True if disambiguation should be triggered, False otherwise | 
Source code in lex_helper/core/disambiguation/analyzer.py
              Bedrock Generator¶
Bedrock-powered text generation for Smart Disambiguation.
This module provides intelligent, contextual disambiguation message generation using Amazon Bedrock models to create more natural and helpful clarification responses based on user input and available intent candidates.
Classes¶
BedrockDisambiguationGenerator(config: BedrockDisambiguationConfig)
Generates disambiguation messages using Amazon Bedrock models.
This class creates contextual, intelligent disambiguation messages by analyzing user input and available intent candidates, then using Bedrock to generate natural language clarification text and button labels.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| config | BedrockDisambiguationConfig | Configuration for Bedrock text generation | required | 
Source code in lex_helper/core/disambiguation/bedrock_generator.py
                    
                  Functions¶
generate_clarification_message(user_input: str, candidates: list[IntentCandidate], context: dict[str, Any] | None = None) -> str
Generate a contextual clarification message using Bedrock.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| user_input | str | The original user input that was ambiguous | required | 
| candidates | list[IntentCandidate] | List of intent candidates to choose from | required | 
| context | dict[str, Any] | None | Optional context information (session data, etc.) | None | 
Returns:
| Type | Description | 
|---|---|
| str | Generated clarification message text | 
Source code in lex_helper/core/disambiguation/bedrock_generator.py
              
generate_button_labels(candidates: list[IntentCandidate], user_input: str | None = None) -> list[str]
Generate improved button labels using Bedrock.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| candidates | list[IntentCandidate] | List of intent candidates | required | 
| user_input | str | None | Optional user input for context | None | 
Returns:
| Type | Description | 
|---|---|
| list[str] | List of generated button labels | 
Source code in lex_helper/core/disambiguation/bedrock_generator.py
              Functions¶
Disambiguation Types¶
Type definitions for the Smart Disambiguation feature.
This module contains all the data classes and type definitions needed for intelligent disambiguation of ambiguous user input in lex-helper.
Attributes¶
module-attribute
  
¶
    Type alias for intent name to confidence score mapping
module-attribute
  
¶
    Type alias for disambiguation message templates
Classes¶
dataclass
  
¶
IntentCandidate(intent_name: str, confidence_score: float, display_name: str, description: str, required_slots: list[str] = (lambda: [])())
Represents a potential intent match for disambiguation.
Contains the intent information along with confidence scoring and user-friendly display information for presenting options to users.
dataclass
  
¶
DisambiguationResult(should_disambiguate: bool, candidates: list[IntentCandidate] = (lambda: [])(), confidence_scores: dict[str, float] = (lambda: {})())
Result of disambiguation analysis.
Contains the decision on whether disambiguation should occur and all the information needed to present options to the user.
Attributes¶
instance-attribute
  
¶
    Whether disambiguation should be triggered based on analysis
class-attribute
      instance-attribute
  
¶
candidates: list[IntentCandidate] = field(default_factory=lambda: [])
List of intent candidates to present to the user
class-attribute
      instance-attribute
  
¶
    Raw confidence scores for all analyzed intents
dataclass
  
¶
BedrockDisambiguationConfig(enabled: bool = False, model_id: str = 'anthropic.claude-3-haiku-20240307-v1:0', region_name: str = 'us-east-1', max_tokens: int = 200, temperature: float = 0.3, system_prompt: str = (lambda: 'You are a helpful assistant that creates clear, concise disambiguation messages for chatbot users. When users provide ambiguous input, help them choose between available options with friendly, natural language.')(), fallback_to_static: bool = True)
Configuration for Bedrock-powered disambiguation text generation.
Allows using Amazon Bedrock models to generate contextual and intelligent disambiguation messages and button text based on the user's input and available intent candidates.
Attributes¶
class-attribute
      instance-attribute
  
¶
    Whether to use Bedrock for generating disambiguation text
class-attribute
      instance-attribute
  
¶
    Bedrock model ID to use for text generation
class-attribute
      instance-attribute
  
¶
    AWS region for Bedrock service
class-attribute
      instance-attribute
  
¶
    Maximum tokens for generated response
class-attribute
      instance-attribute
  
¶
    Temperature for text generation (0.0-1.0, lower = more deterministic)
class-attribute
      instance-attribute
  
¶
system_prompt: str = field(default_factory=lambda: 'You are a helpful assistant that creates clear, concise disambiguation messages for chatbot users. When users provide ambiguous input, help them choose between available options with friendly, natural language.')
System prompt for the Bedrock model
class-attribute
      instance-attribute
  
¶
    Whether to fall back to static messages if Bedrock fails
dataclass
  
¶
DisambiguationConfig(confidence_threshold: float = 0.6, max_candidates: int = 3, fallback_to_original: bool = True, min_candidates: int = 2, similarity_threshold: float = 0.15, enable_logging: bool = True, custom_intent_groups: dict[str, list[str]] = (lambda: {})(), custom_messages: dict[str, str] = (lambda: {})(), bedrock_config: BedrockDisambiguationConfig = BedrockDisambiguationConfig())
Configuration options for the disambiguation system.
Allows developers to customize disambiguation behavior including thresholds, candidate limits, and custom intent groupings.
Attributes¶
class-attribute
      instance-attribute
  
¶
    Minimum confidence score to avoid disambiguation (0.0-1.0)
class-attribute
      instance-attribute
  
¶
    Maximum number of intent candidates to present to users
class-attribute
      instance-attribute
  
¶
    Whether to fall back to original behavior if disambiguation fails
class-attribute
      instance-attribute
  
¶
    Minimum number of candidates required to trigger disambiguation
class-attribute
      instance-attribute
  
¶
    Maximum difference between top scores to trigger disambiguation (0.0-1.0)
class-attribute
      instance-attribute
  
¶
    Whether to enable detailed logging of disambiguation events
class-attribute
      instance-attribute
  
¶
    Custom groupings of related intents for better disambiguation
class-attribute
      instance-attribute
  
¶
    Custom clarification messages for specific disambiguation scenarios
class-attribute
      instance-attribute
  
¶
bedrock_config: BedrockDisambiguationConfig = field(default_factory=BedrockDisambiguationConfig)
Configuration for Bedrock-powered text generation
Utility Functions¶
Additional core utilities for common operations.
Intent Name Utilities¶
Bedrock Integration¶
Amazon Bedrock invocation utilities for Lex Helper.
This module provides functionality to invoke Amazon Bedrock models with proper error handling and response formatting.
Classes¶
    
              Bases: Exception
Custom exception for Bedrock invocation errors.
Functions¶
invoke_bedrock(prompt: str, model_id: str, max_tokens: int | None = None, temperature: float | None = None, top_p: float | None = None, stop_sequences: list[str] | None = None, region_name: str = 'us-east-1', **kwargs: Any) -> dict[str, Any]
Invoke Bedrock model using InvokeModel API.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| prompt | str | Input prompt | required | 
| model_id | str | Bedrock model identifier | required | 
| max_tokens | int | None | Maximum tokens to generate | None | 
| temperature | float | None | Randomness control (0.0-1.0) | None | 
| top_p | float | None | Nucleus sampling (0.0-1.0) | None | 
| stop_sequences | list[str] | None | Stop generation sequences | None | 
| region_name | str | AWS region | 'us-east-1' | 
| **kwargs | Any | Additional model parameters | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | Dict with text, usage, raw_response | 
Source code in lex_helper/core/invoke_bedrock.py
              
invoke_bedrock_converse(messages: list[dict[str, Any]], model_id: str, max_tokens: int | None = None, temperature: float | None = None, top_p: float | None = None, stop_sequences: list[str] | None = None, system_prompt: str | None = None, region_name: str = 'us-east-1', **kwargs: Any) -> dict[str, Any]
Invoke Bedrock model using Converse API with full message support.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| messages | list[dict[str, Any]] | List of message dicts with role and content | required | 
| model_id | str | Bedrock model identifier | required | 
| max_tokens | int | None | Maximum tokens to generate | None | 
| temperature | float | None | Randomness control (0.0-1.0) | None | 
| top_p | float | None | Nucleus sampling (0.0-1.0) | None | 
| stop_sequences | list[str] | None | Stop generation sequences | None | 
| system_prompt | str | None | System prompt for conversation | None | 
| region_name | str | AWS region | 'us-east-1' | 
| **kwargs | Any | Additional parameters | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | Dict with text, usage, raw_response | 
Example
messages = [ ... {"role": "user", "content": [{"text": "Hello"}]}, ... {"role": "assistant", "content": [{"text": "Hi there!"}]}, ... {"role": "user", "content": [{"text": "How are you?"}]} ... ] response = invoke_bedrock_converse( ... messages=messages, ... model_id="anthropic.claude-3-haiku-20240307-v1:0", ... system_prompt="You are a helpful assistant" ... )
Source code in lex_helper/core/invoke_bedrock.py
              
invoke_bedrock_simple_converse(prompt: str, model_id: str, max_tokens: int | None = None, temperature: float | None = None, top_p: float | None = None, stop_sequences: list[str] | None = None, system_prompt: str | None = None, region_name: str = 'us-east-1', **kwargs: Any) -> dict[str, Any]
Simple converse wrapper that converts prompt to messages format.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| prompt | str | Single user prompt | required | 
| model_id | str | Bedrock model identifier | required | 
| system_prompt | str | None | System prompt for conversation | None | 
| max_tokens | int | None | Maximum tokens to generate | None | 
| temperature | float | None | Sampling temperature | None | 
| top_p | float | None | Top-p sampling parameter | None | 
| region_name | str | AWS region name | 'us-east-1' | 
| **kwargs | Any | Additional arguments passed to invoke_bedrock_converse | {} | 
Returns:
| Type | Description | 
|---|---|
| dict[str, Any] | Dict with text, usage, raw_response | 
Source code in lex_helper/core/invoke_bedrock.py
              Message Manager¶
Message Manager for Lex Helper Library.
This module provides centralized message management for Lambda functions using the lex-helper library. It loads messages from a YAML file in the Lambda function's directory structure.
Classes¶
    Singleton class for managing messages from YAML files with locale support.
Automatically loads messages from locale-specific files: - messages_{localeId}.yaml (e.g., messages_en_US.yaml, messages_es_ES.yaml) - Falls back to messages.yaml if locale-specific file not found
Search locations: 1. Custom path from MESSAGES_YAML_PATH environment variable 2. Lambda function root directory 3. Common subdirectories: messages/, config/, resources/, data/ 4. Relative paths from current working directory
Functions¶
classmethod
  
¶
    Set the current locale and load messages for it.
classmethod
  
¶
    Get message by key, supporting nested keys with dot notation.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| key | str | Message key to lookup (e.g., "agent.confirmation") | required | 
| default | str | None | Optional default value if key not found | None | 
| locale | str | None | Optional locale override (uses current locale if not specified) | None | 
Returns:
| Type | Description | 
|---|---|
| str | The message string | 
Example
MessageManager.set_locale("en_US") MessageManager.get_message("greeting") "Hello! How can I assist you today?"
MessageManager.get_message("greeting", locale="es_ES") "¡Hola! ¿Cómo puedo ayudarte hoy?"
Source code in lex_helper/core/message_manager.py
              
classmethod
  
¶
    
classmethod
  
¶
    
Functions¶
    
    Convenience function to get a message.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| key | str | Message key to lookup | required | 
| default | str | None | Optional default value if key not found | None | 
| locale | str | None | Optional locale override | None | 
Returns:
| Type | Description | 
|---|---|
| str | The message string | 
Source code in lex_helper/core/message_manager.py
              Logging Utilities¶
Logging utilities for the lex-helper library.
This module provides consistent logging functionality across the library, following Python logging best practices for libraries.
Functions¶
    Get a logger for the given module name.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| name | str | The module name, typically name | required | 
Returns:
| Type | Description | 
|---|---|
| Logger | A logger instance configured for the module | 
Source code in lex_helper/core/logging_utils.py
              
            
    Log request details at DEBUG level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| request | LexRequest[Any] | The Lex request to log | required | 
Source code in lex_helper/core/logging_utils.py
              
    Log exception with context at ERROR level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| exc | Exception | The exception that occurred | required | 
| context | str | Additional context about where the exception occurred | required | 
Source code in lex_helper/core/logging_utils.py
              
    Log handler invocation at DEBUG level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| handler_name | str | Name of the handler being invoked | required | 
| intent_name | str | None | Name of the intent being handled (if applicable) | None | 
Source code in lex_helper/core/logging_utils.py
              
log_http_request(logger: Logger, method: str, url: str, status_code: int | None = None, response_time: float | None = None) -> None
Log HTTP request details at DEBUG level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| method | str | HTTP method (GET, POST, etc.) | required | 
| url | str | Request URL | required | 
| status_code | int | None | HTTP response status code (if available) | None | 
| response_time | float | None | Request response time in seconds (if available) | None | 
Source code in lex_helper/core/logging_utils.py
              
log_bedrock_invocation(logger: Logger, model_id: str, success: bool, error_message: str | None = None) -> None
Log Bedrock model invocation at appropriate level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| model_id | str | The Bedrock model ID being invoked | required | 
| success | bool | Whether the invocation was successful | required | 
| error_message | str | None | Error message if invocation failed | None | 
Source code in lex_helper/core/logging_utils.py
              
log_session_attribute_update(logger: Logger, attribute_name: str, old_value: Any, new_value: Any) -> None
Log session attribute updates at DEBUG level.
Parameters:
| Name | Type | Description | Default | 
|---|---|---|---|
| logger | Logger | The logger instance to use | required | 
| attribute_name | str | Name of the session attribute | required | 
| old_value | Any | Previous value | required | 
| new_value | Any | New value | required | 
Source code in lex_helper/core/logging_utils.py
              Next: Explore the Channels API for channel-specific formatting functionality.