§
    æ˜ºh:  ã                   ó~   — d dl Z d dlZd dl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  G d„ de¦  «        ZdS )	é    N)ÚAnyÚDictÚListÚOptional)ÚAgentActionÚAgentFinish)ÚBaseCallbackHandler)Ú	LLMResult)Úparsec                   ó6  ‡ — e Zd ZU dZdZeed<   e› d�Zeed<   dZeed<   dZ	eed	<   	 	 	 d-dede
e         de
e         de
e         dd
f
ˆ fd„Zdeeef         dee         dedd
fd„Zdededd
fd„Zdededd
fd„Zdededd
fd„Zdeeef         deeef         dedd
fd„Zdeeef         dedd
fd„Zdededd
fd„Zdeeef         d ededd
fd!„Zd"ededefd#„Z	 	 d.d$ed%e
e         d&e
e         dedd
f
d'„Zdededd
fd(„Zd)ededd
fd*„Zd+ededd
fd,„Zˆ xZ S )/ÚArgillaCallbackHandleraÐ  Callback Handler that logs into Argilla.

    Args:
        dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
            exist in advance. If you need help on how to create a `FeedbackDataset` in
            Argilla, please visit
            https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
        workspace_name: name of the workspace in Argilla where the specified
            `FeedbackDataset` lives in. Defaults to `None`, which means that the
            default workspace will be used.
        api_url: URL of the Argilla Server that we want to use, and where the
            `FeedbackDataset` lives in. Defaults to `None`, which means that either
            `ARGILLA_API_URL` environment variable or the default will be used.
        api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
            means that either `ARGILLA_API_KEY` environment variable or the default
            will be used.

    Raises:
        ImportError: if the `argilla` package is not installed.
        ConnectionError: if the connection to Argilla fails.
        FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.

    Examples:
        >>> from langchain_community.llms import OpenAI
        >>> from langchain_community.callbacks import ArgillaCallbackHandler
        >>> argilla_callback = ArgillaCallbackHandler(
        ...     dataset_name="my-dataset",
        ...     workspace_name="my-workspace",
        ...     api_url="http://localhost:6900",
        ...     api_key="argilla.apikey",
        ... )
        >>> llm = OpenAI(
        ...     temperature=0,
        ...     callbacks=[argilla_callback],
        ...     verbose=True,
        ...     openai_api_key="API_KEY_HERE",
        ... )
        >>> llm.generate([
        ...     "What is the best NLP-annotation tool out there? (no bias at all)",
        ... ])
        "Argilla, no doubt about it."
    z%https://github.com/argilla-io/argillaÚREPO_URLz/issuesÚ
ISSUES_URLzphttps://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.htmlÚBLOG_URLzhttp://localhost:6900ÚDEFAULT_API_URLNÚdataset_nameÚworkspace_nameÚapi_urlÚapi_keyÚreturnc                 ó²  •— t          ¦   «                              ¦   «          	 ddl}|j        | _        n# t
          $ r t          d¦  «        ‚w xY wt          | j        ¦  «        t          d¦  «        k     rt          d| j        › d�¦  «        ‚|€8t          j        d¦  «        €$t          j
        d| j        › d	�¦  «         | j        }|€ft          j        d
¦  «        €Rt          | j        ¦  «        t          d¦  «        k     rdnd| _        t          j
        d| j        › d�¦  «         | j        }	 |                     ||¬¦  «         n.# t          $ r!}t          d|› d| j        › d�¦  «        |‚d}~ww xY w|| _        |p|                     ¦   «         | _        	 i }t          | j        ¦  «        t          d¦  «        k     r't          j
        d| j        › d�t(          ¦  «         ddi} |j        j        d)| j        | j        dœ|¤Ž| _        nF# t          $ r9}t1          d|› d| j        › d| j        › d| j        › d| j        › d�¦  «        |‚d}~ww xY wdd g}|d!„ | j        j        D ¦   «         k    rBt7          d"| j        › d| j        › d#|› d$d%„ | j        j        D ¦   «         › d&| j        › d'�¦  «        ‚i | _        t          j
        d(| j        › d�¦  «         dS )*a)  Initializes the `ArgillaCallbackHandler`.

        Args:
            dataset_name: name of the `FeedbackDataset` in Argilla. Note that it must
                exist in advance. If you need help on how to create a `FeedbackDataset`
                in Argilla, please visit
                https://docs.argilla.io/en/latest/tutorials_and_integrations/integrations/use_argilla_callback_in_langchain.html.
            workspace_name: name of the workspace in Argilla where the specified
                `FeedbackDataset` lives in. Defaults to `None`, which means that the
                default workspace will be used.
            api_url: URL of the Argilla Server that we want to use, and where the
                `FeedbackDataset` lives in. Defaults to `None`, which means that either
                `ARGILLA_API_URL` environment variable or the default will be used.
            api_key: API Key to connect to the Argilla Server. Defaults to `None`, which
                means that either `ARGILLA_API_KEY` environment variable or the default
                will be used.

        Raises:
            ImportError: if the `argilla` package is not installed.
            ConnectionError: if the connection to Argilla fails.
            FileNotFoundError: if the `FeedbackDataset` retrieval from Argilla fails.
        r   Nz‰To use the Argilla callback manager you need to have the `argilla` Python package installed. Please install it with `pip install argilla`z1.8.0z#The installed `argilla` version is z} but `ArgillaCallbackHandler` requires at least version 1.8.0. Please upgrade `argilla` with `pip install --upgrade argilla`.ÚARGILLA_API_URLz[Since `api_url` is None, and the env var `ARGILLA_API_URL` is not set, it will default to `z6`, which is the default API URL in Argilla Quickstart.ÚARGILLA_API_KEYz1.11.0zadmin.apikeyzowner.apikeyz[Since `api_key` is None, and the env var `ARGILLA_API_KEY` is not set, it will default to `z6`, which is the default API key in Argilla Quickstart.)r   r   z.Could not connect to Argilla with exception: 'z“'.
Please check your `api_key` and `api_url`, and make sure that the Argilla server is up and running. If the problem persists please report it to z as an `integration` issue.ú1.14.0zYou have Argilla z., but Argilla 1.14.0 or higher is recommended.Úwith_recordsF)ÚnameÚ	workspacez@`FeedbackDataset` retrieval from Argilla failed with exception `z+`.
Please check that the dataset with name=z in the workspace=zz exists in advance. If you need help on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit z.. If the problem persists please report it to ÚpromptÚresponsec                 ó   — g | ]	}|j         ‘Œ
S © ©r   ©Ú.0Úfields     úv/var/www/html/services/rag-service/venv/lib/python3.11/site-packages/langchain_community/callbacks/argilla_callback.pyú
<listcomp>z3ArgillaCallbackHandler.__init__.<locals>.<listcomp>´   s   € ÐLÐLÐL¨u ¤
ÐLÐLÐLó    z`FeedbackDataset` with name=z] had fields that are not supported yet for the`langchain` integration. Supported fields are: z/, and the current `FeedbackDataset` fields are c                 ó   — g | ]	}|j         ‘Œ
S r!   r"   r#   s     r&   r'   z3ArgillaCallbackHandler.__init__.<locals>.<listcomp>¹   s   € ÐAnÐAnÐAnÐQVÀ%Ä*ÐAnÐAnÐAnr(   zl. For more information on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit ú.zˆThe `ArgillaCallbackHandler` is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to r!   )ÚsuperÚ__init__ÚargillaÚ__version__ÚARGILLA_VERSIONÚImportErrorr   ÚosÚgetenvÚwarningsÚwarnr   ÚDEFAULT_API_KEYÚinitÚ	ExceptionÚConnectionErrorr   r   Úget_workspacer   ÚUserWarningÚFeedbackDatasetÚfrom_argillaÚdatasetÚFileNotFoundErrorr   ÚfieldsÚ
ValueErrorÚprompts)
Úselfr   r   r   r   ÚrgÚeÚ
extra_argsÚsupported_fieldsÚ	__class__s
            €r&   r,   zArgillaCallbackHandler.__init__=   sb  ø€ õ< 	‰Œ×ÒÑÔÐð	Ø Ð Ð Ð à#%¤>ˆDÔ Ð øÝð 	ð 	ð 	ÝðYñô ð ð	øøøõ �Ô%Ñ&Ô&­¨w©¬Ò7Ð7ÝðJ°dÔ6Jð Jð Jð Jñô ð ð ˆ?�rœyÐ):Ñ;Ô;ÐCÝŒMð>Ø15Ô1Eð>ð >ð >ñô ð ð Ô*ˆGàˆ?�rœyÐ):Ñ;Ô;ÐCõ ˜Ô-Ñ.Ô.µ°x±´Ò@Ð@ð �à#ð Ô õ ŒMð>Ø15Ô1Eð>ð >ð >ñô ð ð Ô*ˆGð	Ø�GŠG˜G¨WˆGÑ5Ô5Ð5Ð5øÝð 	ð 	ð 	Ý!ðTÀð Tð Tð (,¤ðTð Tð Tñô ð
 ðøøøøð	øøøð )ˆÔØ,ÐB°×0@Ò0@Ñ0BÔ0BˆÔð	ØˆJÝ�TÔ)Ñ*Ô*­U°8©_¬_Ò<Ð<Ý”ð.¨Ô(<ð .ð .ð .åñô ð ð
 -¨eÐ4�
Ø:˜2Ô-Ô:ð ØÔ&ØÔ-ðð ð ðð ˆDŒLˆLøõ
 ð 	ð 	ð 	Ý#ðUÐSTð Uð UØ=AÔ=NðUð Uà"Ô1ðUð Uð +/¬-ð	Uð Uð
 )-¬ðUð Uð Uñô ð ðøøøøð	øøøð % jÐ1ÐØÐLÐL¸¼Ô8KÐLÑLÔLÒLÐLÝðP¨tÔ/@ð Pð PØÔ&ðPð PàBRðPð Pð BoÐAnÐZ^ÔZfÔZmÐAnÑAnÔAnðPð Pð
 @D¼}ðPð Pð Pñô ð ð .0ˆŒåŒðAà”OðAð Að Añ	
ô 	
ð 	
ð 	
ð 	
s:   £4 ´AÄ1E	 Å	
E4ÅE/Å/E4ÆA2H È
IÈ4IÉIÚ
serializedrA   Úkwargsc                 ót   — | j                              t          |d         p|d         ¦  «        |i¦  «         dS )z.Save the prompts in memory when an LLM starts.Úparent_run_idÚrun_idN)rA   ÚupdateÚstr)rB   rH   rA   rI   s       r&   Úon_llm_startz#ArgillaCallbackHandler.on_llm_startÈ   s<   € ð 	Œ×Ò�S ¨Ô!8Ð!L¸FÀ8Ô<LÑMÔMÈwÐWÑXÔXÐXÐXÐXr(   Útokenc                 ó   — dS )z)Do nothing when a new token is generated.Nr!   )rB   rP   rI   s      r&   Úon_llm_new_tokenz'ArgillaCallbackHandler.on_llm_new_tokenÎ   ó   € àˆr(   r   c                 óº  ‡— |d         rdS | j         t          |d         ¦  «                 }t          ||j        ¦  «        D ],\  Š}| j                             ˆfd„|D ¦   «         ¬¦  «         Œ-| j                              t          |d         ¦  «        ¦  «         t          | j        ¦  «        t          d¦  «        k     r| j         	                    ¦   «          dS dS )z(Log records to Argilla when an LLM ends.rK   NrL   c                 óL   •— g | ] }d ‰|j                              ¦   «         dœi‘Œ!S )r?   ©r   r   )ÚtextÚstrip)r$   Ú
generationr   s     €r&   r'   z5ArgillaCallbackHandler.on_llm_end.<locals>.<listcomp>Ý   sN   ø€ ð ð ð ð #ð !Ø&,Ø(2¬×(=Ò(=Ñ(?Ô(?ð#ð #ððð ð r(   ©Úrecordsr   )
rA   rN   ÚzipÚgenerationsr=   Úadd_recordsÚpopr   r/   Úpush_to_argilla)rB   r   rI   rA   r]   r   s        @r&   Ú
on_llm_endz!ArgillaCallbackHandler.on_llm_endÒ   s  ø€ ð �/Ô"ð 	ØˆFð ”,�s 6¨(Ô#3Ñ4Ô4Ô5ˆÝ#& w°Ô0DÑ#EÔ#Eð 	ð 	ÑˆF�KØŒL×$Ò$ðð ð ð ð '2ðñ ô ð %ñ 
ô 
ð 
ð 
ð 	Œ×Ò�˜V HÔ-Ñ.Ô.Ñ/Ô/Ð/å�Ô%Ñ&Ô&­¨x©¬Ò8Ð8àŒL×(Ò(Ñ*Ô*Ð*Ð*Ð*ð 9Ð8r(   Úerrorc                 ó   — dS )z%Do nothing when LLM outputs an error.Nr!   ©rB   rb   rI   s      r&   Úon_llm_errorz#ArgillaCallbackHandler.on_llm_errorï   rS   r(   Úinputsc                 óÔ   — d|v rc| j                              t          |d         p|d         ¦  «        t          |d         t          ¦  «        r|d         n|d         gi¦  «         dS dS )a  If the key `input` is in `inputs`, then save it in `self.prompts` using
        either the `parent_run_id` or the `run_id` as the key. This is done so that
        we don't log the same input prompt twice, once when the LLM starts and once
        when the chain starts.
        ÚinputrK   rL   N)rA   rM   rN   Ú
isinstanceÚlist)rB   rH   rf   rI   s       r&   Úon_chain_startz%ArgillaCallbackHandler.on_chain_startó   s‚   € ð �fÐÐØŒL×Òå˜˜Ô/ÐC°6¸(Ô3CÑDÔDå% f¨W¤oµtÑ<Ô<ð/˜˜wœ˜à$ WœoÐ.ð	ñô ð ð ð ð Ðr(   Úoutputsc                 ó<  ‡ — t          ˆ fd„t          |d         ¦  «        t          |d         ¦  «        fD ¦   «         ¦  «        sdS ‰ j                             t          |d         ¦  «        ¦  «        p,‰ j                             t          |d         ¦  «        ¦  «        }|                     ¦   «         D ]”\  }}t          |t          ¦  «        r4‰ j                             d„ t          ||¦  «        D ¦   «         ¬¦  «         ŒN‰ j                             dd 
                    |¦  «        |                     ¦   «         d	œig¬¦  «         Œ•t          |d         ¦  «        ‰ j        v r-‰ j                             t          |d         ¦  «        ¦  «         t          |d         ¦  «        ‰ j        v r-‰ j                             t          |d         ¦  «        ¦  «         t          ‰ j        ¦  «        t          d
¦  «        k     r‰ j                             ¦   «          dS dS )z×If either the `parent_run_id` or the `run_id` is in `self.prompts`, then
        log the outputs to Argilla, and pop the run from `self.prompts`. The behavior
        differs if the output is a list or not.
        c              3   ó*   •K  — | ]}|‰j         v V — Œd S )N)rA   )r$   ÚkeyrB   s     €r&   ú	<genexpr>z6ArgillaCallbackHandler.on_chain_end.<locals>.<genexpr>  s>   øè è € ð 
ð 
àð �4”<Ðð
ð 
ð 
ð 
ð 
ð 
r(   rK   rL   Nc                 óR   — g | ]$\  }}d ||d                               ¦   «         dœi‘Œ%S )r?   rW   rV   )rX   )r$   r   Úoutputs      r&   r'   z7ArgillaCallbackHandler.on_chain_end.<locals>.<listcomp>  sS   € ð ð ð ñ +˜F Fð %Ø*0Ø,2°6¬N×,@Ò,@Ñ,BÔ,Bð'ð 'ððð ð r(   rZ   r?   ú rV   r   )ÚanyrN   rA   ÚgetÚitemsri   rj   r=   r^   r\   ÚjoinrX   r_   r   r/   r`   )rB   rl   rI   rA   Úchain_output_keyÚchain_output_vals   `     r&   Úon_chain_endz#ArgillaCallbackHandler.on_chain_end  sL  ø€ õ
 ð 
ð 
ð 
ð 
å˜F ?Ô3Ñ4Ô4µc¸&ÀÔ:JÑ6KÔ6KÐLð
ñ 
ô 
ñ 
ô 
ð 	ð ˆFØ”,×"Ò"¥3 v¨oÔ'>Ñ#?Ô#?Ñ@Ô@ð 
ÀDÄL×DTÒDTÝ��xÔ Ñ!Ô!ñE
ô E
ˆð 3:·-²-±/´/ð 	ð 	Ñ.ÐÐ.ÝÐ*­DÑ1Ô1ð à”×(Ò(ðð õ /2Ø#Ø,ñ/ô /ðñ ô ð )ñ ô ð ð ð  ”×(Ò(ð %Ø*-¯(ª(°7Ñ*;Ô*;Ø,<×,BÒ,BÑ,DÔ,Dð'ð 'ððð )ñ 	ô 	ð 	ð 	õ ˆv�oÔ&Ñ'Ô'¨4¬<Ð7Ð7ØŒL×Ò�S ¨Ô!8Ñ9Ô9Ñ:Ô:Ð:Ýˆv�hÔÑ Ô  D¤LÐ0Ð0ØŒL×Ò�S ¨Ô!1Ñ2Ô2Ñ3Ô3Ð3å�Ô%Ñ&Ô&­¨x©¬Ò8Ð8àŒL×(Ò(Ñ*Ô*Ð*Ð*Ð*ð 9Ð8r(   c                 ó   — dS )z+Do nothing when LLM chain outputs an error.Nr!   rd   s      r&   Úon_chain_errorz%ArgillaCallbackHandler.on_chain_error;  rS   r(   Ú	input_strc                 ó   — dS )zDo nothing when tool starts.Nr!   )rB   rH   r}   rI   s       r&   Úon_tool_startz$ArgillaCallbackHandler.on_tool_start?  s	   € ð 	ˆr(   Úactionc                 ó   — dS )z.Do nothing when agent takes a specific action.Nr!   )rB   r€   rI   s      r&   Úon_agent_actionz&ArgillaCallbackHandler.on_agent_actionH  rS   r(   rr   Úobservation_prefixÚ
llm_prefixc                 ó   — dS )zDo nothing when tool ends.Nr!   )rB   rr   rƒ   r„   rI   s        r&   Úon_tool_endz"ArgillaCallbackHandler.on_tool_endL  s	   € ð 	ˆr(   c                 ó   — dS )z&Do nothing when tool outputs an error.Nr!   rd   s      r&   Úon_tool_errorz$ArgillaCallbackHandler.on_tool_errorV  rS   r(   rW   c                 ó   — dS ©z
Do nothingNr!   )rB   rW   rI   s      r&   Úon_textzArgillaCallbackHandler.on_textZ  rS   r(   Úfinishc                 ó   — dS rŠ   r!   )rB   rŒ   rI   s      r&   Úon_agent_finishz&ArgillaCallbackHandler.on_agent_finish^  rS   r(   )NNN)NN)!Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rN   Ú__annotations__r   r   r   r   r,   r   r   r   rO   rR   r
   ra   ÚBaseExceptionre   rk   rz   r|   r   r   r‚   r†   rˆ   r‹   r   rŽ   Ú__classcell__)rG   s   @r&   r   r      s›  ø€ € € € € € ð)ð )ðV <€HˆcÐ;Ð;Ñ;Ø!Ð*Ð*Ð*€J�Ð*Ð*Ñ*ð G€Hˆcð  Gð  Gñ  Gà2€O�SÐ2Ð2Ñ2ð
 )-Ø!%Ø!%ðI
ð I
àðI
ð ! œðI
ð ˜#”ð	I
ð
 ˜#”ðI
ð 
ðI
ð I
ð I
ð I
ð I
ð I
ðVYØ˜s C˜xœ.ðYØ37¸´9ðYØHKðYà	ðYð Yð Yð Yð cð °Sð ¸Tð ð ð ð ð+ 9ð +¸ð +Àð +ð +ð +ð +ð: -ð ¸3ð À4ð ð ð ð ðØ˜s C˜xœ.ðØ26°s¸C°x´.ðØLOðà	ðð ð ð ð&3+ D¨¨c¨¤Nð 3+¸cð 3+Àdð 3+ð 3+ð 3+ð 3+ðj Mð ¸Sð ÀTð ð ð ð ðà˜˜c˜”Nðð ðð ð	ð
 
ðð ð ð ð kð ¸Sð ÀSð ð ð ð ð -1Ø$(ð	ð àðð % SœMðð ˜S”Mð	ð
 ðð 
ðð ð ð ð =ð ¸Cð ÀDð ð ð ð ð˜Cð ¨3ð °4ð ð ð ð ð kð ¸Sð ÀTð ð ð ð ð ð ð ð r(   r   )r1   r3   Útypingr   r   r   r   Úlangchain_core.agentsr   r   Úlangchain_core.callbacksr	   Úlangchain_core.outputsr
   Úpackaging.versionr   r   r!   r(   r&   ú<module>r›      sÈ   ðØ 	€	€	€	Ø €€€Ø ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,Ð ,à :Ð :Ð :Ð :Ð :Ð :Ð :Ð :Ø 8Ð 8Ð 8Ð 8Ð 8Ð 8Ø ,Ð ,Ð ,Ð ,Ð ,Ð ,Ø #Ð #Ð #Ð #Ð #Ð #ðUð Uð Uð Uð UÐ0ñ Uô Uð Uð Uð Ur(   