o
    hi                     @   sr   d dl Z d dlmZ d dlmZ d dlmZ d dlm	Z	 ddl
mZmZ d dlZeeZddd	ZdddZdS )    N)SentenceTransformer)settings)get_object_or_404   )FileChatbot   c              
   C   s  zt t| |d}tjttjd d}td}d|j }d	|
 }||gd }g }	t }
zq|j|d}|j|g|d	d
gd}td|  tt|d	 d |d
 d }|jdd d |d| D ]8\}}|d}ztjj|d}|	|jj|d|d W qh tjy   td| d |
| Y qhw W n) ty } ztd| dt|  ddt| iW  Y d}~W S d}~ww |	dd |
D dW S  ty } ztdt|  dt|iW  Y d}~S d}~ww )a  
    Retrieve RAG entries from ChromaDB for a given chatbot and query.
    
    Args:
        chatbot_id (int): ID of the chatbot.
        user (User): Authenticated user making the request.
        query (str): User input query.
        n_results (int): Number of RAG results to retrieve (default: 3).
    
    Returns:
        dict: Contains 'results' (list of RAG entries), 'warnings' (list of warnings),
              and 'error' (if any).
    )iduser	chroma_db)pathzall-MiniLM-L6-v2chatbot_ r   )name	metadatas	distances)query_embeddings	n_resultsincludezChroma query results: c                 S   s   | d S )Nr    )xr   r   0/var/www/ai-chatbot-integration/chatbot/utils.py<lambda>4   s    z&retrieve_rag_entries.<locals>.<lambda>)keyNfile_id)r	   text)	file_namer   distanceFile with ID 
 not foundzFailed to query collection z: errorzNo RAG data available: c                 S   s   g | ]}d | dqS )r   r   r   ).0fidr   r   r   
<listcomp>I   s    z(retrieve_rag_entries.<locals>.<listcomp>resultswarningszRAG retrieval failed: )r   r   chromadbPersistentClientstrr   
MEDIA_ROOTr   r	   joinsplitencodesetget_collectionqueryloggerdebuglistzipsortgetr   objectsappendfiler   DoesNotExistwarningadd	Exception	exception)
chatbot_idr
   r0   r   chatbotchroma_clientembeddercollection_namequery_embeddingrag_resultsmissing_files
collectionquery_resultsresult_pairsmetadatar   r   r9   er   r   r   retrieve_rag_entries   s^   

 rL   Tc              
   C   s&  t | |||}d|v r|S |d |d d}|rzSd}|d7 }t|d dD ]\}}	|| d|	d	  d
|	d dd|	d  d7 }q&|d| 7 }tjtjd td}
|
|}|j|d< t	
d|d   W |S  ty } zt	dt|  ddt| iW  Y d}~S d}~ww |S )aC  
    Retrieve RAG entries and optionally generate an AI response.
    
    Args:
        chatbot_id (int): ID of the chatbot.
        user (User): Authenticated user making the request.
        message (str): User input message/query.
        n_results (int): Number of RAG results to retrieve (default: 3).
        include_ai (bool): Whether to query the AI model for a response (default: True).
    
    Returns:
        dict: Contains 'results' (RAG entries), 'response' (AI response if include_ai=True),
              'warnings' (list of warnings), and 'error' (if any).
    r    r%   r&   r$   a  General guidelines:
             use the inclusive, inspiring, global local blend for tone, 
               be conscise. ask to rewrite the question if it is not obvious in answer. if you detect that user message is in another language, answer in that language.
zRelevant document excerpts:
r   z. From r   z (Similarity: r   z.4fz):
r   z

zUser message: )api_keyzgemini-1.5-flashresponsezAI response: zFailed to query AI model: z Failed to get response from AI: N)rL   	enumerategenai	configurer   GEMINI_API_KEYGenerativeModelgenerate_contentr   r1   r2   r=   r>   r)   )r?   r
   messager   
include_airag_dataresponse_datacontextidxresultmodelrN   rK   r   r   r   retrieve_ai_responseP   s2   0


r]   )r   )r   T)r'   sentence_transformersr   google.generativeaigenerativeairP   django.confr   django.shortcutsr   modelsr   r   logging	getLogger__name__r1   rL   r]   r   r   r   r   <module>   s    

E