o
    sg1                     @   s  d Z ddlZddlZddlZddlZddlZddlm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 dd	lmZ dd
lmZ ddlmZ ddlmZ e	  ddlmZmZ e ZG dd dZedkred dZ e Z!e"e!#e Z$ee$ dS dS )Class to run the LLM model    N)datetime)load_dotenv)ChatPromptTemplate)JsonOutputParser)
ChatOpenAI)OPENAI_TOKEN_LIMIT)LeadershipResults)SICCode)check_token_limit)load_sic_codes)OPENAI_API_KEYOPENAI_MODEL_35c                   @   s@   e Zd ZdZdd Zdd ZdddZd	efd
dZdd Z	dS )LLMChatr   c                 C   s   t dttd| _dS )r   皙?temperature
model_nameapi_keyN)r   r   r   llm)self r   5/var/www/html/XCapMarket/utils/llm_company_profile.py__init__   s   zLLMChat.__init__c                    s   t |trt|ttd }d}d}|D ]J}z| |||I dH }W n2 tjyU } z%t| t	
dt d| td | |||I dH }W Y d}~nd}~ww |dur_|j}|}q|S )z3
        Request a summary from OpenAI API
        g       @ Nz%s:OpenAI Rate Limit Error: %sz%Y-%m-%D %H:%M:%S   )
isinstancestrr   intr   openai_request_callopenaiRateLimitErrorprintloggingerrorr   todaystrftimetimesleepcontent)r   	page_textopenai_promptresponse_text	seed_textpg_textresponseer   r   r   openai_request%   s<   

zLLMChat.openai_requestNc           
   
      s   z.ddddd|fg}|r| d t|}tdttd}||B }|||d	I d
H }|W S  tyF }	 zt|	 W Y d
}	~	d
S d
}	~	ww )z:Call the OpenAI API to get the response for the given text)systemzYou are an expert consultant. Step 1 based on the text, become an expert in that company's industry and then follow the instructions below.)r2   zEYour responses should be formatted in bullets each 20 tokens or less.)r2   zYou will communicate in a formal tone, ensuring clear, succinct and professional dialogue. It will provide communication with precision, avoiding colloquial language and maintaining a serious demeanor.)humanz{page_text}r3   )userzYou have already provided a summary here * {seed_text}*. Only provide a summary if you have more to add. Otherwise, return the same summary.r   r   )r*   r-   N)	appendr   from_messagesr   r   r   ainvoke	Exceptionr"   )
r   r*   r+   r-   prompt_temppromptr   chainr/   r0   r   r   r   r   G   s8   

zLLMChat.openai_request_callproduct_infoc                    sb   |du r	t dttd}tg d}|| jB |B }|tt	||
 dI dH }|d S )z.Get the SIC code for the provided product_infoNzProduct info is requiredpydantic_object))r2   z6You are a helpful AI bot in company SIC code analysis.)r2   zOUse these SIC codes and the related industry and sector. {sic_dict_json_string})r2   zmTake in the product information and provide the SIC code for the company. Do not provide NAIC or other codes.)r3   z'Product Description: 
 {product_info} 
)r3   z{JSONoutput})sic_dict_json_stringr<   
JSONoutputcode)
ValueErrorr   r
   r   r6   r   r7   jsondumpssic_dictget_format_instructions)r   r<   parserchat_templater;   chain_responser   r   r   product_to_sicw   s   

zLLMChat.product_to_sicc                    sV   |du r	t dttd}tg d}|| jB |B }||| dI dH }|S )z Map the leadership using the LLMNzCompany leadership is requiredr=   ))r2   z8You are a helpful AI bot in company leadership analysis.)r2   a  Given a list of leadership names and titles.

                    Return a structured output with leader names, titles and linkedin links if provided. If there are multiple linkedin links that match, choose the first one. If there isn't a match, leave it blank)r2   zGReturn a json list including the leader name, title, and linkedin link.)r3   z$Leadership: 
 {company_leadership} 
)r2   z;Structure the JSON output using this template. {JSONoutput})company_leadershipr@   )rB   r   r	   r   r6   r   r7   rF   )r   rK   rG   rH   r;   rI   r   r   r   map_leadership   s   

zLLMChat.map_leadership)N)
__name__
__module____qualname____doc__r   r1   r   r   rJ   rL   r   r   r   r   r      s    
"0#r   __main__hiaZ  
    Elon Musk: Founder and CEO
    - Elon Musk: CEO
    - Max Hodak: President
    - Vanessa Tolosa: Vice President of Engineering
    - Philip Sabes: Vice President of Neuroscience
    - Tim Hanson: Vice President of Manufacturing
    - Jared Birchall: Vice President of Legal Affairs
    - Steve Petrou: Vice President of Finance
    - DJ Seo: Vice President of Implant Systems
    - Ben Rapoport: Vice President of Hardware
    - Will Brandler: Vice President of Software
    - Eric Whitmire: Vice President of Clinical Research
    - Matthew MacDougall: Vice President of Business Development
    )%rP   asynciorC   r#   osr'   r   r    dotenvr   langchain.promptsr   langchain_core.output_parsersr   langchain_openair   configs.configr   1services.company_profile.data_classes.llm_resultsr	   .services.company_profile.data_classes.SIC_coder
   utils.check_token_limitr   utils.load_sic_codesr   r   r   rE   r   rM   r"   rK   r   runrL   mappingr   r   r   r   <module>   s:     &