Ë
    µŒjë+  ã                  óâ   — d Z ddlm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
mZmZmZmZmZ ddlZddlmZmZ dd	lmZ dd
lmZ e
r
ddlZddlmZ dZdZdZdZdZ dd„Z! G d„ de«      Z"y)zArthurAI's Callback Handler.é    )ÚannotationsN)Údefaultdict)Údatetime)Útime)ÚTYPE_CHECKINGÚAnyÚDefaultDictÚDictÚListÚOptional)ÚAgentActionÚAgentFinish)ÚBaseCallbackHandler)Ú	LLMResult)ÚArthurModelÚprompt_tokensÚcompletion_tokensÚtoken_usageÚfinish_reasonÚdurationc                 óJ   — 	 ddl } | S # t        $ r}t        d|«      ‚d}~ww xY w)zLazy load Arthur.r   NzpTo use the ArthurCallbackHandler you need the `arthurai` package. Please install it with `pip install arthurai`.)ÚarthuraiÚImportError)r   Úes     úw/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain_community/callbacks/arthur_callback.pyÚ_lazy_load_arthurr      s:   € ð
Ûð €Oøô ò 
Üð'ð ó	
ð 	
ûð
ús   ‚ ˆ	"‘�"c                  ó  ‡ — e Zd ZdZ	 	 	 	 dˆ fd„Ze	 	 	 d	 	 	 	 	 	 	 	 	 dd„«       Z	 	 	 	 	 	 	 	 dd„Zdd„Z	 	 	 	 	 	 	 	 dd„Z	dd„Z
dd„Zdd	„Zdd
„Z	 	 	 	 	 	 	 	 dd„Zdd„Z	 	 d	 	 	 	 	 	 	 	 	 dd„Zdd„Zdd„Zdd„Zˆ xZS ) ÚArthurCallbackHandlera÷  Callback Handler that logs to Arthur platform.

    Arthur helps enterprise teams optimize model operations
    and performance at scale. The Arthur API tracks model
    performance, explainability, and fairness across tabular,
    NLP, and CV models. Our API is model- and platform-agnostic,
    and continuously scales with complex and dynamic enterprise needs.
    To learn more about Arthur, visit our website at
    https://www.arthur.ai/ or read the Arthur docs at
    https://docs.arthur.ai/
    c                óœ  •— t         ‰| �  «        t        «       }|j                  j                  j
                  }|j                  j                  j                  }|| _        t        | j                  j                  «       D �cg c]  }|j                  ‘Œ c}«      | _        | j                  j                  «       D �cg c]6  }|j                  |j                  k(  r|j                  |j                  k(  r|‘Œ8 c}d   j                  | _        | j                  j                  «       D �cg c]6  }|j                  |j"                  k(  r|j                  |j                  k(  r|‘Œ8 c}d   j                  | _        d| _        t)        | j                  j                  «       D �cg c]  }|j                  |j*                  k(  r|‘Œ c}«      dkD  rS| j                  j                  «       D �cg c]  }|j                  |j*                  k(  r|‘Œ c}d   j                  | _        t-        t.        «      | _        yc c}w c c}w c c}w c c}w c c}w )zInitialize callback handler.r   N)ÚsuperÚ__init__r   ÚcommonÚ	constantsÚStageÚ	ValueTypeÚarthur_modelÚsetÚget_attributesÚnameÚ
attr_namesÚstageÚModelPipelineInputÚ
value_typeÚUnstructured_TextÚ
input_attrÚPredictedValueÚoutput_attrÚtoken_likelihood_attrÚlenÚTokenLikelihoodsr   ÚdictÚrun_map)Úselfr&   r   r$   r%   ÚaÚxÚ	__class__s          €r   r!   zArthurCallbackHandler.__init__8   s&  ø€ ô
 	‰ÑÔÜ$Ó&ˆØ—‘×)Ñ)×/Ñ/ˆØ—O‘O×-Ñ-×7Ñ7ˆ	Ø(ˆÔô ¨t×/@Ñ/@×/OÑ/OÔ/QÓRÑ/Q¨!˜qŸv›vÐ/QÑRÓSˆŒð ×&Ñ&×5Ñ5Ô7ó
á7�Ø�w‰w˜%×2Ñ2Ò2Ø—‘ 	× ;Ñ ;Ò;ò Ø7ñ
ð
 ñ÷
 ‰Tð 	Œð ×&Ñ&×5Ñ5Ô7ó
á7�Ø�w‰w˜%×.Ñ.Ò.Ø—‘ 	× ;Ñ ;Ò;ò Ø7ñ
ð
 ñ÷
 ‰Tð 	Ôð &*ˆÔ"äð "×.Ñ.×=Ñ=Ô?óá?˜Ø—|‘| y×'AÑ'AÒAò Ø?ñóð òð ×*Ñ*×9Ñ9Ô;ó*á;�AØ—<‘< 9×#=Ñ#=Ò=ò Ø;ñ*ð ñ	*÷ ‘ð	 Ô&ô /:¼$Ó.?ˆ�ùò= Sùò
ùò
ùòùò*s   ÂH5Â=;H:Ä);H?Æ!"IÇ)"I	c                ót  — t        «       }|j                  }|j                  j                  j                  }|€	 t
        j                  d   } |||¬«      }	n|€ |||¬«      }	n ||||¬«      }		 |	j                  |«      }
 | |
«      S # t        $ r t        d«      ‚w xY w# |$ r t        d|› d�«      ‚w xY w)aX  Initialize callback handler from Arthur credentials.

        Args:
            model_id (str): The ID of the arthur model to log to.
            arthur_url (str, optional): The URL of the Arthur instance to log to.
                Defaults to "https://app.arthur.ai".
            arthur_login (str, optional): The login to use to connect to Arthur.
                Defaults to None.
            arthur_password (str, optional): The password to use to connect to
                Arthur. Defaults to None.

        Returns:
            ArthurCallbackHandler: The initialized callback handler.
        ÚARTHUR_API_KEYzˆNo Arthur authentication provided. Either give a login to the ArthurCallbackHandler or set an ARTHUR_API_KEY as an environment variable.)ÚurlÚ
access_key)r=   Úlogin)r=   r?   Úpasswordz%Was unable to retrieve model with id zl from Arthur. Make sure the ID corresponds to a model that is currently registered with your Arthur account.)
r   ÚArthurAIr"   Ú
exceptionsÚResponseClientErrorÚosÚenvironÚKeyErrorÚ
ValueErrorÚ	get_model)ÚclsÚmodel_idÚ
arthur_urlÚarthur_loginÚarthur_passwordr   rA   rC   Úarthur_api_keyÚarthurr&   s              r   Úfrom_credentialsz&ArthurCallbackHandler.from_credentialsd   sï   € ô, %Ó&ˆØ×$Ñ$ˆØ&Ÿo™o×8Ñ8×LÑLÐð ÐðÜ!#§¡Ð,<Ñ!=�ñ  *¸ÔH‰FàÐ&Ù! j¸ÔE‘á!Ø"¨,Àô�ð	Ø!×+Ñ+¨HÓ5ˆLñ �<Ó Ð øô/ ò Ü ðLóð ðûð" #ò 	ÜØ7¸°zð B8ð 8óð ð	ús   ºB
 Á1B" Â
BÂ"B7c                óf   — |d   }|| j                   |   d<   t        «       | j                   |   d<   y)z$On LLM start, save the input promptsÚrun_idÚinput_textsÚ
start_timeN)r6   r   )r7   Ú
serializedÚpromptsÚkwargsrR   s        r   Úon_llm_startz"ArthurCallbackHandler.on_llm_start›   s6   € ð ˜Ñ!ˆØ.5ˆ�‰�VÑ˜]Ñ+Ü-1«Vˆ�‰�VÑ˜\Ò*ó    c                ól  — 	 ddl }|d   }	 | j                  |   }t	        «       |d   z
  }g }t        |j                  «      D �]  \  }	}
|
D �]  }dt        t        j                  «       «      dt        j                  |j                  ¬	«      | j                  |d
   	   | j                  |j                  i}|j                   �Ìt"        |j                   v r,t"        | j$                  v r|j                   t"           |t"        <   |j                   d   }|�}| j&                  �q|d   }t)        t+        |«      «      D �	��cg c]<  }	||	   j-                  «       D ��ci c]  \  }}|t/        j0                  |«      “Œ c}}‘Œ> }}}	}||| j&                  <   t3        |j4                  t6        «      ryt8        |j4                  v rg|j4                  t8           }t:        |v r"t:        | j$                  v r|t:           |t:        <   t<        |v r"t<        | j$                  v r|t<           |t<        <   t>        | j$                  v r	||t>        <   |jA                  |«       �Œ �Œ | jB                  jE                  |«       y# t        $ r}t        d«      |‚d}~ww xY w# t        $ r}t        d«      |‚d}~ww xY wc c}}w c c}}}	w )z On LLM end, send data to Arthur.r   NzACould not import pytz. Please install it with 'pip install pytz'.rR   z~This function has been called with a run_id that was never registered in on_llm_start(). Restart and try running the LLM againrT   Úpartner_inference_idÚinference_timestamp)ÚtzrS   ÚlogprobsÚtop_logprobs)#Úpytzr   r6   rF   r   Ú	enumerateÚgenerationsÚstrÚuuidÚuuid4r   ÚnowÚUTCr/   r1   ÚtextÚgeneration_infoÚFINISH_REASONr*   r2   Úranger3   ÚitemsÚnpÚexpÚ
isinstanceÚ
llm_outputr5   ÚTOKEN_USAGEÚPROMPT_TOKENSÚCOMPLETION_TOKENSÚDURATIONÚappendr&   Úsend_inferences)r7   ÚresponserW   r`   r   rR   Úrun_map_dataÚtime_from_start_to_endÚ
inferencesÚirb   Ú
generationÚ	inferenceÚlogprobs_datar^   ÚkÚvÚlikelihoodsr   s                      r   Ú
on_llm_endz ArthurCallbackHandler.on_llm_end£   sž  € ð	Ûð ˜Ñ!ˆð	ØŸ<™<¨Ñ/ˆLô "&£¨,°|Ñ*DÑ!DÐð ˆ
Ü'¨×(<Ñ(<×=‰NˆAˆ{Ü)�
à*¬C´·
±
³Ó,=Ø)¬8¯<©<¸4¿8¹8Ô+DØ—O‘O \°-Ñ%@ÀÑ%CØ×$Ñ$ j§o¡oð	�	ð ×-Ñ-Ð9ô
 &¨×)CÑ)CÑCÜ)¨T¯_©_Ñ<à3=×3MÑ3MÜ)ñ4˜	¤-Ñ0ð %/×$>Ñ$>¸zÑ$J�Mà%Ð1Ø ×6Ñ6ÐBà#0°Ñ#@˜ô &+¬3¨x«=Ô%9õ'á%9 ð 7?¸q±k×6GÑ6GÔ6IÔJÑ6I©d¨a°˜Q¤§¡ q£	™\Ð6IÔJØ%9ð $ò 'ð AL˜	 $×"<Ñ"<Ñ=ô
 ˜x×2Ñ2´DÔ9Ü# x×':Ñ':Ñ:à"*×"5Ñ"5´kÑ"B�Kä%¨Ñ4Ü)¨T¯_©_Ñ<à3>¼}Ñ3M˜	¤-Ñ0ä)¨[Ñ8Ü-°·±Ñ@à7BÔCTÑ7U˜	Ô"3Ñ4ô ˜tŸ™Ñ.Ø*@�IœhÑ'à×!Ñ! )Ö,òs *ð >ðz 	×Ñ×)Ñ)¨*Õ5øôi ò 	ÜØSóàðûð	ûô ò 	Üð9óð ð	ûð	üóT Kùô'sF   ‚I/ ŒJ Ä:J/Å J)Å5J/É/	J	É8JÊJ	Ê	J&ÊJ!Ê!J&Ê)J/c                 ó   — y)zOn chain start, do nothing.N© )r7   rU   ÚinputsrW   s       r   Úon_chain_startz$ArthurCallbackHandler.on_chain_startý   ó   � rY   c                 ó   — y)zOn chain end, do nothing.Nr„   )r7   ÚoutputsrW   s      r   Úon_chain_endz"ArthurCallbackHandler.on_chain_end  r‡   rY   c                 ó   — y)z%Do nothing when LLM outputs an error.Nr„   ©r7   ÚerrorrW   s      r   Úon_llm_errorz"ArthurCallbackHandler.on_llm_error  r‡   rY   c                 ó   — y)zOn new token, pass.Nr„   )r7   ÚtokenrW   s      r   Úon_llm_new_tokenz&ArthurCallbackHandler.on_llm_new_token  r‡   rY   c                 ó   — y)z+Do nothing when LLM chain outputs an error.Nr„   rŒ   s      r   Úon_chain_errorz$ArthurCallbackHandler.on_chain_error  r‡   rY   c                 ó   — y)zDo nothing when tool starts.Nr„   )r7   rU   Ú	input_strrW   s       r   Úon_tool_startz#ArthurCallbackHandler.on_tool_start  r‡   rY   c                 ó   — y)z.Do nothing when agent takes a specific action.Nr„   )r7   ÚactionrW   s      r   Úon_agent_actionz%ArthurCallbackHandler.on_agent_action  r‡   rY   c                 ó   — y)zDo nothing when tool ends.Nr„   )r7   ÚoutputÚobservation_prefixÚ
llm_prefixrW   s        r   Úon_tool_endz!ArthurCallbackHandler.on_tool_end  r‡   rY   c                 ó   — y)z&Do nothing when tool outputs an error.Nr„   rŒ   s      r   Úon_tool_errorz#ArthurCallbackHandler.on_tool_error"  r‡   rY   c                 ó   — y©z
Do nothingNr„   )r7   rh   rW   s      r   Úon_textzArthurCallbackHandler.on_text%  r‡   rY   c                 ó   — yr¢   r„   )r7   ÚfinishrW   s      r   Úon_agent_finishz%ArthurCallbackHandler.on_agent_finish(  r‡   rY   )r&   r   ÚreturnÚNone)zhttps://app.arthur.aiNN)
rJ   rc   rK   úOptional[str]rL   r©   rM   r©   r§   r   )rU   úDict[str, Any]rV   z	List[str]rW   r   r§   r¨   )rw   r   rW   r   r§   r¨   )rU   rª   r…   rª   rW   r   r§   r¨   )r‰   rª   rW   r   r§   r¨   )r�   ÚBaseExceptionrW   r   r§   r¨   )r�   rc   rW   r   r§   r¨   )rU   rª   r•   rc   rW   r   r§   r¨   )r˜   r   rW   r   r§   r   )NN)
r›   r   rœ   r©   r�   r©   rW   r   r§   r¨   )rh   rc   rW   r   r§   r¨   )r¥   r   rW   r   r§   r¨   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   ÚclassmethodrP   rX   r‚   r†   rŠ   rŽ   r‘   r“   r–   r™   rž   r    r£   r¦   Ú__classcell__)r:   s   @r   r   r   +   sT  ø„ ñ
ð*@à!ð*@ð 
õ*@ðX ð %<Ø&*Ø)-ð4!àð4!ð "ð4!ð $ð	4!ð
 'ð4!ð 
ò4!ó ð4!ðl4Ø(ð4Ø3<ð4ØHKð4à	ó4óX6ðt*Ø(ð*Ø2@ð*ØLOð*à	ó*ó
(ó4ó"ó:ð+à"ð+ð ð+ð ð	+ð
 
ó+ó=ð -1Ø$(ð	)àð)ð *ð)ð "ð	)ð
 ð)ð 
ó)ó5ó÷rY   r   )r§   r   )#r¯   Ú
__future__r   rD   rd   Úcollectionsr   r   r   Útypingr   r   r	   r
   r   r   Únumpyrm   Úlangchain_core.agentsr   r   Úlangchain_core.callbacksr   Úlangchain_core.outputsr   r   Úarthurai.core.modelsr   rr   rs   rq   rj   rt   r   r   r„   rY   r   Ú<module>rº      sc   ðÙ "å "ã 	Û Ý #Ý Ý ß H× Hã ß :Ý 8Ý ,áÛÝ0à€Ø'Ð Ø€Ø€Ø€óô~Ð/õ ~rY   