o
    sg!                     @   s   d Z ddlZddlZ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mZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ e  e ZG dd dZedkrqe Zeej dddddd dS dS )z!Service to recommend acquisitions    N)load_dotenv)ChatPromptTemplate)JsonOutputParser)
ChatOpenAI)OPENAI_API_KEYOPENAI_MODEL_35)
FundGroupsPEShops)ChromaDB)DynamoDB)load_sic_codes)
parsed_urlc                	   @   sp   e Zd ZdZdd Z			ddededed	efd
dZ	ddede	e fddZ
dded	efddZdd ZdS )PERecommendationzClass to recommend acquisitionsc                 C   s$   t tddd| _t ttdd| _d S )Nzgpt-4og?)api_key
model_nametemperatureg?)r   r   openai_llm_4r   openai_llm_3)self r   B/var/www/html/XCapMarket/services/recommender/pe_recommendation.py__init__   s   zPERecommendation.__init__N   company_overviewproduct_descriptionnum_of_fundsinvestment_criteriac           
   	   C   sf   |du r| j n|}ttd}tg d}||B |B }||| |||dur,t|ndd}	|	S )zGet hypothetical companiesNpydantic_object))systemzYou are an investment banking managing director.
                    Being provided a company's overview and product description.)r   a"  Think about this step by step:

                        1) use the information to classify the company into a industry.

                        2) Become an investment banker for that industry and sector.

                        3) Take in the product description and anonymize it

                        4) Generate a synthetic investment thesis of a Private Equity shop who is interested in the company

                        5) Provide a minimum of {num_of_funds} PE shops that would be interested in the company

                        r   z{json_structure})humanz{product_description})r!   z9Consider these investment criteria: {investment_criteria} )r   json_structurezcompany overviewr   r   )	r   r   r	   r   from_messagesinvokeget_format_instructionsjsondumps)
r   r   r   open_ai_modelr   r   parserchat_templatechainresponser   r   r   get_hypo_pe_shop(   s"   	

z!PERecommendation.get_hypo_pe_shoptarget_company_descriptionfundsc                 C   s   |du r| j n|}ttd}dg i}d}tdt||D ]0}||||  }t|}	tg d}
|
|B |B }|	|
 |	|d}|d |d  q|S )zRegroup fundsNr   groups
   r   ))r   zYou are an investment banking managing director.
                        Being provided with a set of company's product description.
                        You are recommending PE shops that can acquire this company)r   aI  Think about this step by step:

                            1) Use the investment thesis to classify the funds into relevant groups.

                            2) Create a minimum of 2 groups and maximum of 5 with a recommendation of 3 groups.
                            3) Provide a rational for why the funds were grouped together especially with the provided description of target company. This should be clear and concise and should not be more than 3 sentences.
                            4) In the fund urls list, don't include the acquiring company.
                        r    )r!   z'funds to group: ***
 {funds_json} 
 ***)r!   z.acquiring company: ***
 {target_company} 
 ***)r#   
funds_jsontarget_company)r   r   r   rangelenr'   r(   r   r$   r%   r&   extend)r   r/   r0   r)   r*   previous_output
batch_sizeifunds_for_this_runr3   r+   r,   r-   r   r   r   regroup_funds^   s&   

	zPERecommendation.regroup_fundscompany_urlc                 C   s   t  }t|ddj}|jj|gd}|d d }|jj|gd}|d d }| j||d|d}g }	|d D ]}
|
d	 d
kr>q5|	|j|
d	 |j	dd q5i }|	D ]}t
|d d D ]\}}||d d | d||< q[qQ| j|t| d}|S )z$Get PE recommendations for a companyF)urlcheck_redirect)ids	documentsr   r   )r   r   r	   investment_thesisr"      )	n_resultsr@   )fund_urlrB   )r/   r0   )Query_ChromaDBr   r>   product_collectiongetoverview_collectionr.   appendretrive_by_collectionfund_collection	enumerater<   listvalues)r   r=   r   query_chromacompanyr   company_overview_docsr   recommended_pe_shopspe_shops_similar_to_recspe_shopfunds_recommendedgroupr:   recommended_fund_urlregrouped_companiesr   r   r   get_recommendations   sF   	
z$PERecommendation.get_recommendationsc                 C   sB   t  }|d D ]}g }|d D ]
}||| q||d< q|S )zNTransform the output of the recommender to the format expected by the frontendr1   r0   )r   rJ   get_item_for_fund_recommender)r   recommender_outputget_itemrW   new_fund_listfundr   r   r   *transform_recommender_output_for_front_end   s   
z;PERecommendation.transform_recommender_output_for_front_end)Nr   N)N)__name__
__module____qualname____doc__r   strintdictr.   rN   r<   rZ   r`   r   r   r   r   r      s.    
7
72r   __main__zhttps://bossinsights.com/zFinance or Software or FinTechz1 million to 50 millionzNorth America)industryzinvestment size	geography)r   )!rd   r'   loggingosdotenvr   langchain.promptsr   langchain_core.output_parsersr   langchain_openair   configs.configr   r   models.pe_shopsr   r	   utils.chroma_dbr
   rF   utils.dynamo_dbr   utils.load_sic_codesr   utils.url_parserr   sic_codes_dictr   ra   pe_shop_recsprintrZ   r   r   r   r   <module>   s<     =