o
    Zh<"                     @   s   d dl Z d dlmZmZmZ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mZ d dlmZ defd	d
ZdefddZdededefddZG dd deZdS )    N)AnyDictListOptionalcast)AgentActionAgentFinish)BaseCallbackHandler)BaseMessage)ChatGeneration	LLMResultguard_importreturnc                   C   s   t d S )zImport the infino client.Zinfinopy)r   ZInfinoClient r   r   d/var/www/html/lang_env/lib/python3.10/site-packages/langchain_community/callbacks/infino_callback.pyimport_infino   s   r   c                   C   s   t dS )z6Import tiktoken for counting tokens for OpenAI models.tiktokenr   r   r   r   r   import_tiktoken   s   r   stringopenai_model_namec                 C   s"   t  }||}t|| }|S )zCalculate num tokens for OpenAI with tiktoken package.

    Official documentation: https://github.com/openai/openai-cookbook/blob/main
                            /examples/How_to_count_tokens_with_tiktoken.ipynb
    )r   Zencoding_for_modellenencode)r   r   r   encoding
num_tokensr   r   r   get_num_tokens   s   
r   c                   @   s  e Zd ZdZ			d<dee dee deddfdd	Z	
d=dedededdfddZ	de
eef dee deddfddZdededdfddZdededdfddZdededdfddZde
eef de
eef deddfdd Zd!e
eef deddfd"d#Zdededdfd$d%Zde
eef d&ededdfd'd(Zd)ededefd*d+Z		d>d,ed-ee d.ee deddf
d/d0Zdededdfd1d2Zd3ededdfd4d5Zd6ededdfd7d8Zde
eef d9eee  deddfd:d;ZdS )?InfinoCallbackHandlerz%Callback Handler that logs to Infino.NFmodel_idmodel_versionverboser   c                 C   s*   t  | _|| _|| _|| _d| _d| _d S )NFzgpt-3.5-turbo)r   clientr   r   r   is_chat_openai_modelchat_openai_model_name)selfr   r   r   r   r   r   __init__%   s   
zInfinoCallbackHandler.__init__Tkeyvalueis_tsc                 C   s`   dt t ||d| j| jdi}| jrtd| d|  |r(| j| dS | j| dS )a  Send the key-value to Infino.

        Parameters:
        key (str): the key to send to Infino.
        value (Any): the value to send to Infino.
        is_ts (bool): if True, the value is part of a time series, else it
                      is sent as a log message.
        datelabels)r   r   z	Tracking z with Infino: N)	inttimer   r   r   printr    Z	append_tsZ
append_log)r#   r%   r&   r'   payloadr   r   r   _send_to_infino3   s   z%InfinoCallbackHandler._send_to_infino
serializedpromptskwargsc                 K   s.   |D ]
}| j d|dd qd| _t | _dS )z=Log the prompts to Infino, and set start time and error flag.promptFr'   r   N)r.   errorr+   
start_time)r#   r/   r0   r1   r2   r   r   r   on_llm_startS   s   z"InfinoCallbackHandler.on_llm_starttokenc                 K      dS )z)Do nothing when a new token is generated.Nr   )r#   r7   r1   r   r   r   on_llm_new_tokene      z&InfinoCallbackHandler.on_llm_new_tokenresponsec                 K   s   t   | _| j| j }| d| | d| j |jD ]}|D ]}| jd|jdd qq|jdur^t|jt	r^|jd }|dur^|d }|d	 }|d
 }	| d| | d	| | d
|	 | j
rzddd |D }
t|
| jd}	| d
|	 dS dS )z<Log the latency, error, token usage, and response to Infino.Zlatencyr4   Zprompt_responseFr3   Ntoken_usageprompt_tokenstotal_tokenscompletion_tokens c                 s   s$    | ]}t tt t|jjV  qd S N)r   strr   messagecontent).0
generationr   r   r   	<genexpr>   s
    
z3InfinoCallbackHandler.on_llm_end.<locals>.<genexpr>r   )r+   end_timer5   r.   r4   generationstextZ
llm_output
isinstancer   r!   joinr   r"   )r#   r;   r1   durationrJ   rF   r<   r=   r>   r?   messagesr   r   r   
on_llm_endi   s4   



z InfinoCallbackHandler.on_llm_endr4   c                 K   s
   d| _ dS )zSet the error flag.   N)r4   r#   r4   r1   r   r   r   on_llm_error   s   
z"InfinoCallbackHandler.on_llm_errorinputsc                 K   r8   )z!Do nothing when LLM chain starts.Nr   )r#   r/   rT   r1   r   r   r   on_chain_start   s   z$InfinoCallbackHandler.on_chain_startoutputsc                 K   r8   )zDo nothing when LLM chain ends.Nr   )r#   rV   r1   r   r   r   on_chain_end   r:   z"InfinoCallbackHandler.on_chain_endc                 K   r8   )zNeed to log the error.Nr   rR   r   r   r   on_chain_error   r:   z$InfinoCallbackHandler.on_chain_error	input_strc                 K   r8   )zDo nothing when tool starts.Nr   )r#   r/   rY   r1   r   r   r   on_tool_start   s   z#InfinoCallbackHandler.on_tool_startactionc                 K   r8   )z.Do nothing when agent takes a specific action.Nr   )r#   r[   r1   r   r   r   on_agent_action   r:   z%InfinoCallbackHandler.on_agent_actionoutputobservation_prefix
llm_prefixc                 K   r8   )zDo nothing when tool ends.Nr   )r#   r]   r^   r_   r1   r   r   r   on_tool_end   s   z!InfinoCallbackHandler.on_tool_endc                 K   r8   )z&Do nothing when tool outputs an error.Nr   rR   r   r   r   on_tool_error   r:   z#InfinoCallbackHandler.on_tool_errorrK   c                 K   r8   zDo nothing.Nr   )r#   rK   r1   r   r   r   on_text   r:   zInfinoCallbackHandler.on_textfinishc                 K   r8   rb   r   )r#   rd   r1   r   r   r   on_agent_finish   r:   z%InfinoCallbackHandler.on_agent_finishrO   c                 K   s   | d}|r|D ]}|dkrd| _ nq	| jrK| d}|rK| d}|rK|| _d}|D ]}	ddd	 |	D }
t|
| jd
}||7 }q-| d| | jrZtd| j d| j  ddd	 |D }| jd|dd d| _t		 | _
dS )zRun when LLM starts running.idZ
ChatOpenAITinvocation_params
model_namer   r@   c                 s   s    | ]	}t t|jV  qd S rA   r   rB   rD   )rE   msgr   r   r   rG      s    
z<InfinoCallbackHandler.on_chat_model_start.<locals>.<genexpr>rH   r=   z=on_chat_model_start: is_chat_openai_model=                   z+,                   chat_openai_model_name=c                 s   s&    | ]}|D ]	}t t|jV  qqd S rA   ri   )rE   Zsublistrj   r   r   r   rG      s    r2   Fr3   N)getr!   r"   rM   r   r.   r   r,   r4   r+   r5   )r#   r/   rO   r1   valuesr&   rg   rh   r=   Zmessage_listZmessage_stringr   r2   r   r   r   on_chat_model_start   sL   






z)InfinoCallbackHandler.on_chat_model_start)NNF)T)NN)__name__
__module____qualname____doc__r   rB   boolr$   r   r.   r   r   r6   r9   r   rP   BaseExceptionrS   rU   rW   rX   rZ   r   r\   r`   ra   rc   r   re   r
   rm   r   r   r   r   r   "   s    

 

%




	



r   )r+   typingr   r   r   r   r   Zlangchain_core.agentsr   r   Zlangchain_core.callbacksr	   Zlangchain_core.messagesr
   Zlangchain_core.outputsr   r   Zlangchain_core.utilsr   r   r   rB   r*   r   r   r   r   r   r   <module>   s    