o
    y	i,                     @   st   d Z ddlZddlZddlZddlmZmZmZ ddlZddl	m
Z
 ddlmZ ddlmZ G dd dZe ZdS )	zo
Novalite Bedrock Service for Amazon Bedrock Integration
Handles text generation using Amazon's Novalite model
    N)OptionalDictAny)ClientError)Config)Logc                
   @   s   e Zd ZdZdd Zddedededee fd	d
ZddedededefddZ	dedee fddZ
defddZdeeef fddZdS )NovaliteBedrockServicez
    Service for generating text responses using Amazon Bedrock's Novalite model.
    Provides cost-effective alternative to OpenAI GPT models.
    c              
   C   s   t j| _t j| _t j| _t j| _zt	j
d| jt jt jd| _td| j d| j  W d S  tyK } ztd|  d | _W Y d }~d S d }~ww )Nzbedrock-runtime)Zregion_nameZaws_access_key_idZaws_secret_access_keyu3   🤖 Novalite Bedrock Service initialized - Model: z
, Region: u)   ❌ Failed to initialize Bedrock client: )r   ZNOVALITE_MODEL_IDmodel_id
AWS_REGIONregionZNOVALITE_MAX_TOKENS
max_tokensZNOVALITE_TEMPERATUREtemperatureboto3ZclientAWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYbedrock_clientr   info	Exceptionerror)selfe r   $services/novalite_bedrock_service.py__init__   s"    zNovaliteBedrockService.__init__N
user_inputsystem_promptconversation_historyreturnc              
      s   z6t d|dd  d | |||}| |I dH }|r0t d|dd  d |W S t d W dS  tyR } zt d|  W Y d}~dS d}~ww )	aK  
        Generate a text response using Novalite model.
        
        Args:
            user_input: User's input text
            system_prompt: System prompt for the bot
            conversation_history: Previous conversation messages
            
        Returns:
            Generated response text or None if failed
        u.   🤖 Generating Nova Lite response for input: N2   ...u"   ✅ Nova Lite response generated: d   u%   ⚠️ No response from Nova Lite APIu)   ❌ Error generating Nova Lite response: )r   r   _build_messages_call_bedrock_apiZwarningr   r   )r   r   r   r   messagesZresponse_textr   r   r   r   generate_response*   s   
z(NovaliteBedrockService.generate_responsec              
   C   s  g }t | dr
| js\td tdt| d td|dd  d d	|v r1td
 nd|v r;td ntd tdt| d td|dd  d d| _ntdt| d d| d}|dd|igd |r|dd D ]H}t|trd|v r||d d|d igd qd|v r|d dkrdnd}||d|d igd q|ddt|	ddigd q|dd|igd |S )a  
        Build messages array for Novalite API.
        
        Args:
            user_input: Current user input
            system_prompt: System prompt
            conversation_history: Previous conversation
            
        Returns:
            Messages array for API
        _session_initializedu*   🧠 Nova Lite System Prompt Source Check:u   🧠 System Prompt Length: z charactersu.   🧠 System Prompt Preview (first 200 chars): N   r   zKNOWLEDGE BASE CONTEXTuO   🧠 ✅ System prompt includes KNOWLEDGE BASE CONTEXT - from bot configurationz.MCube's professional telephony voice assistantua   🧠 ✅ System prompt includes 'MCube's professional telephony voice assistant' - from config.pyuY   🧠 ❓ System prompt source unclear - neither bot config nor config.py pattern detectedu,   🧠 Final Nova Lite System Message Length: u?   🧠 Final Nova Lite System Message Preview (first 300 chars): i,  Tu8   🧠 Using persistent Nova Lite session (prompt length: z chars)z#[SYSTEM INSTRUCTIONS - MANDATORY]

a5  

[END OF SYSTEM INSTRUCTIONS]

IMPORTANT: You MUST follow ALL instructions above, including:
- Collecting user details (name, phone, email) when appropriate
- Following behavioral rules
- Using correct tone and language
- Handling transfers with confirmation

Now, please respond to the user's request below.usertextrolecontentir*   r+   typeZ	assistant )
hasattrr%   r   r   lenappend
isinstancedictstrget)r   r   r   r   r#   Zfinal_system_messagemsgr*   r   r   r   r!   J   sZ   




z&NovaliteBedrockService._build_messagesr#   c              
      s   | j std dS zltdt| d | j jdddtd|id}t|d	 	 }d
|v rmd|d
 v rm|d
 d }d|v rmt
|d trm|d D ]}d|v rl|d }td|dd  d |   W S qNtd|  W dS  ty } zc|jd d }|jd d }	td| d|	  |dkrtd tdtjrdnd  tdtjrdnd  tdtj  td| j  td td | j  W Y d}~dS d}~w ty } ztd!|  d"dl}
td#|
   W Y d}~dS d}~ww )$z
        Make API call to Amazon Bedrock.
        
        Args:
            messages: Messages array for Nova Lite API
            
        Returns:
            Generated text or None
        u9   ❌ Bedrock client not initialized - cannot make API callNu&   🧠 Sending request to Nova API with z	 messageszamazon.nova-lite-v1:0zapplication/jsonr#   )ZmodelIdZcontentTypeZacceptbodyr6   outputmessager+   r(   u   🧠 Nova Lite generated: r    r   u)   ❌ Unexpected Nova API response format: ErrorZCodeZMessageu   ❌ Bedrock API error (z): ZUnrecognizedClientExceptionu'   🔐 AWS Authentication failed - Check:z   1. AWS_ACCESS_KEY_ID: u   ✅ Setu   ❌ Missingz   2. AWS_SECRET_ACCESS_KEY: z   3. AWS_REGION: z   4. Model ID: u@      → Verify credentials are valid and have Bedrock permissionsu2      → Check if Nova Lite is available in region: u*   ❌ Unexpected error calling Bedrock API: r   u   ❌ Traceback: )r   r   r   debugr/   Zinvoke_modeljsondumpsloadsreadr1   liststripr   responser   r   r   r
   r	   r   r   	traceback
format_exc)r   r#   rA   Zresponse_bodyr8   r+   Zgenerated_textr   Z
error_codeZerror_messagerB   r   r   r   r"      s^   
	

z(NovaliteBedrockService._call_bedrock_apic              
      s   z1| j std W dS dddddddgi}| |I dH }|r+td	 W d
S td W dS  tyM } ztd|  W Y d}~dS d}~ww )z
        Test connection to Amazon Bedrock.
        
        Returns:
            True if connection successful, False otherwise
        u"   ❌ Bedrock client not initializedFr#   r'   z$System: You are a helpful assistant.r)   ZHelloNu/   ✅ Novalite Bedrock connection test successfulTu+   ❌ Novalite Bedrock connection test failedu/   ❌ Error testing Novalite Bedrock connection: )r   r   r   r"   r   r   )r   Ztest_requestrA   r   r   r   r   test_connection   s*   


z&NovaliteBedrockService.test_connectionc                 C   s   | j | j| j| jddS )z
        Get information about the current model configuration.
        
        Returns:
            Dictionary with model information
        Znovalite_bedrock)r	   r   r   r   Zservice_type)r	   r   r   r   )r   r   r   r   get_model_info	  s   z%NovaliteBedrockService.get_model_info)N)__name__
__module____qualname____doc__r   r3   r?   r   r$   r!   r"   boolrD   r   r   rE   r   r   r   r   r      s      ]A!r   )rI   r;   ZasyncioZaiohttptypingr   r   r   r   Zbotocore.exceptionsr   Zconfigr   Zservices.log_utilsr   r   Znovalite_bedrock_servicer   r   r   r   <module>   s      
