o
    gJ                     @   s   d dl mZmZ d dlmZmZ d dlmZ d dlm	Z	m
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 d d
lmZ G dd deZG dd dZdS )    )
ChatOpenAIOpenAIEmbeddings)ChatPromptTemplateMessagesPlaceholder)ChromaDB)create_history_aware_retrievercreate_retrieval_chain)create_stuff_documents_chain)BaseChatMessageHistory)RunnableWithMessageHistoryDocument)BaseRetriever)JsonOutputParserc                       sF   e Zd Z		d fdd	Zdd Zdefdd	Zdefd
dZ  ZS )ChromaCustomRetrieverN   c                    s\   t    t| d| t| d| t| d| t| d| | t| dt  d S )Nchroma_collectionembedding_functiontop_kfilter	openai_ef)super__init__object__setattr__build_filterr   )selfr   r   selected_filesr   	__class__ 1/var/www/html/XCapMarket/services/docchat/chat.pyr      s   
zChromaCustomRetriever.__init__c                 C   s>   g }|r| dd|ii |si S t|dkr|d S d|iS )N	file_namez$in   r   z$and)appendlen)r   filesfiltersr    r    r!   r      s   z"ChromaCustomRetriever.build_filterqueryc                 C   sH   | j |}| jj|g| j| jd}dd t|d d |d d D S )N)query_embeddings	n_resultswherec                 S   s   g | ]
\}}t ||d qS ))page_contentmetadatar   ).0docmetar    r    r!   
<listcomp>-   s    
zAChromaCustomRetriever._get_relevant_documents.<locals>.<listcomp>	documentsr   	metadatas)r   embed_queryr   r(   r   r   zip)r   r(   	embeddingresultsr    r    r!   _get_relevant_documents(   s   z-ChromaCustomRetriever._get_relevant_documentsc                    s   |  |S N)r8   )r   r(   r    r    r!   _aget_relevant_documents2   s   
z.ChromaCustomRetriever._aget_relevant_documents)Nr   )	__name__
__module____qualname__r   r   strr8   r:   __classcell__r    r    r   r!   r      s    
r   c                   @   sP   e Zd Zdd Zdd Zdd Zdd Zd	ed
efddZ	ded
efddZ
dS )ConversationalRAGc                 C   sp   || _ t|ddd| _t | _|| _d| | _| jjj| j| jj	d| _
|  | _|  | _|  | _|| _d S )Ng333333?T)modeltemperature	streamingchat_)r   )r   r   llmr   	chroma_db
project_idcollection_namechroma_clientget_collectionr   
collectionr   history_aware_retrievercreate_qa_chainquestion_answer_chaincreate_conversational_rag_chainconversational_rag_chainhistory_provider)r   r   rG   rQ   ai_modelr    r    r!   r   7   s   





zConversationalRAG.__init__c                 C   sB   d}t d|ftddg}t| j| jj| jdd}t| j	||S )Na  Given a chat history and the latest user question which might reference context in the chat history, formulate a standalone question which can be understood without the chat history. Do NOT answer the question, just reformulate it if needed and otherwise return it as is.systemchat_historyhumanz{input}r   )r   r   r   r   )
r   from_messagesr   r   rK   rF   r   r   r   rE   )r   contextualize_q_system_promptcontextualize_q_prompt	retrieverr    r    r!   r   G   s"   z0ConversationalRAG.create_history_aware_retrieverc                 C   s(   d}t d|ftddg}t| j|S )Nuo  
You are an AI-powered Investment Banking Analyst. Your role is to support deal teams with research, analysis, 
and presentation material preparation across M&A, capital markets, and strategic advisory mandates. Maintain a 
highly professional, data-driven, and concise tone. Use financial terminology appropriately and ensure all insights 
are substantiated by logic, precedent, or relevant data.

## Core Functions:
- Conduct industry and company research using credible sources and databases
- Build and analyze financial models including DCF, comparable company, and precedent transaction analyses
- Create polished, professional PowerPoint slides for pitch books, CIMs, management presentations, and market updates
- Synthesize complex financial and strategic information into concise insights for internal and client-facing use
- Monitor M&A, equity, and debt capital markets to identify relevant transactions and trends
- Assist with due diligence by summarizing key findings from data rooms and public filings
- Maintain accuracy, clarity, and consistency across deliverables

## Communication Style:
- Use a professional and analytical tone
- Be concise and structured in all written responses
- Support assertions with data or citations when possible
- Prioritize clarity and eliminate fluff
- Never speculate—only provide informed, defensible perspectives

## Formatting Guidelines:
- Use bullet points and short paragraphs for readability
- Clearly label financial metrics, dates, and sources
- Avoid jargon unless appropriate for an investment banking audience
- Keep bullet points clean and without terminal punctuation

{context}
rS   rT   rU   )r   rW   r   r	   rE   )r   system_prompt	qa_promptr    r    r!   rM   `   s   !z!ConversationalRAG.create_qa_chainc                 C   s   t t| j| j| jddddS )NinputrT   answer)input_messages_keyhistory_messages_keyoutput_messages_key)r   r   rL   rN   get_session_history)r   r    r    r!   rO      s   z1ConversationalRAG.create_conversational_rag_chain
session_idreturnc                 C   s   | j S r9   )rQ   )r   rc   r    r    r!   rb      s   z%ConversationalRAG.get_session_historycombined_answerc                 C   s.   ddg}t |}|| jB }|d|i}|S )z
        Generate a summary of the combined answer using the language model.

        :param combined_answer: The full answer to be summarized.
        :return: A summarized version of the answer.
        )rS   zp
                    Summarize the following answer in a concise manner in less than 5 words:


                )rV   z2Here is the answer to summarize: {combined_answer}re   )r   rW   rE   invoke)r   re   llm_messagechat_promptchainresponser    r    r!   get_summary_of_combined_answer   s   

z0ConversationalRAG.get_summary_of_combined_answerN)r;   r<   r=   r   r   rM   rO   r>   r
   rb   rk   r    r    r    r!   r@   6   s    +r@   N)langchain_openair   r   langchain.prompts.chatr   r   utils.chroma_dbr   langchain.chainsr   r   (langchain.chains.combine_documents.stuffr	   langchain_core.chat_historyr
    langchain_core.runnables.historyr   langchain_core.documentsr   langchain_core.retrieversr   langchain_core.output_parsersr   r   r@   r    r    r    r!   <module>   s    (