
    7|h9                     z    d dl Z 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  G d de      Zy)	    N)AnyDictListOptionalcast)AgentActionAgentFinish)BaseCallbackHandler)	LLMResult)parsec                       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                 x   t         
|           	 ddl}|j                  | _        t        | j                        t        d      k  rt        d| j                   d      |Dt        j                  d      /t        j                  d| j                   d	       | j                  }|nt        j                  d
      Yt        | j                        t        d      k  rdnd| _        t        j                  d| j                   d       | j                  }	 |j                  ||       || _        |xs |j%                         | _        	 i }t        | j                        t        d      k  r,t        j                  d| j                   dt(               ddi} |j*                  j,                  d'| j"                  | j&                  d|| _        dd g}|| j.                  j4                  D 	cg c]  }	|	j6                   c}	k7  ret9        d!| j"                   d| j&                   d"| d#| j.                  j4                  D 	cg c]  }	|	j6                   c}	 d$| j2                   d%      i | _        t        j                  d&| j                    d       y# t
        $ r t        d      w xY w# t        $ r"}t        d| d| j                    d      |d}~ww xY w# t        $ rI}t1        d| d| j"                   d| j&                   d| j2                   d| j                    d      |d}~ww xY wc c}	w c c}	w )(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   NzTo 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responsez`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 zl. For more information on how to create a `langchain`-compatible `FeedbackDataset` in Argilla, please visit .zThe `ArgillaCallbackHandler` is currently in beta and is subject to change based on updates to `langchain`. Please report any issues to  )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   fieldsr   
ValueErrorprompts)selfr   r   r   r   rge
extra_argssupported_fieldsfield	__class__s             m/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/callbacks/argilla_callback.pyr$   zArgillaCallbackHandler.__init__=   s   < 		 #%>>D  %%&w75d6J6J5K LJ J  ?ryy):;CMM1151E1E0F G>> **G?ryy):;C --.x@ #   MM1151E1E0F G>> **G	GGGWG5 ),B0@0@0B	JT))*U8_<'(<(<'= >. .
 -e4
:2--:: &&-- DL %j18K8KLu

LL.t/@/@.AAS&&' (BBRAS TAZ^ZfZfZmZmAnQV%**An@o p??C}}oQP  .0OO$$?A	
}  	Y 	X  	!@ D' (,&77RT
 	6  	#RSTRU V==A=N=N<O P"112 3**.-- 9((,'88SU 	  M
 BosI   J J/ BK /L2L7J,/	K8KK	L/&AL**L/
serializedr9   kwargsc                 d    | j                   j                  t        |d   xs |d         |i       y)z.Save the prompts in memory when an LLM starts.parent_run_idrun_idN)r9   updatestr)r:   rB   r9   rC   s       rA   on_llm_startz#ArgillaCallbackHandler.on_llm_start   s/     	S!8!LF8<LMwWX    tokenc                      y)z)Do nothing when a new token is generated.Nr"   )r:   rK   rC   s      rA   on_llm_new_tokenz'ArgillaCallbackHandler.on_llm_new_token       rJ   r    c           
         |d   ry| j                   t        |d            }t        ||j                        D ]L  \  }}| j                  j                  |D cg c]!  }d||j                  j                         di# c}       N | j                   j                  t        |d                t        | j                        t        d      k  r| j                  j                          yyc c}w )z(Log records to Argilla when an LLM ends.rE   NrF   r7   r   r    recordsr   )r9   rH   zipgenerationsr5   add_recordstextstrippopr   r'   push_to_argilla)r:   r    rC   r9   r   rT   
generations          rA   
on_llm_endz!ArgillaCallbackHandler.on_llm_end   s     /" ,,s6(#345#&w0D0D#E 	FKLL$$ '2 # !&,(2(=(=(?# % 
	 	VH-./%%&x8LL((* 9s   &C+
errorc                      y)z%Do nothing when LLM outputs an error.Nr"   r:   r\   rC   s      rA   on_llm_errorz#ArgillaCallbackHandler.on_llm_error   rN   rJ   inputsc                     d|v rM| j                   j                  t        |d   xs |d         t        |d   t              r|d   n|d   gi       yy)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.
        inputrE   rF   N)r9   rG   rH   
isinstancelist)r:   rB   r`   rC   s       rA   on_chain_startz%ArgillaCallbackHandler.on_chain_start   s`     fLL/C6(3CD%fWot< w$Wo.	 rJ   outputsc                     t         fdt        |d         t        |d         fD              sy j                  j                  t        |d               xs6 t	        t
         j                  j                  t        |d         g             }|j                         D ]  \  }}t        |t              rP j                  j                  t        ||      D cg c]  \  }}d||d   j                         di c}}       f j                  j                  dd	j                  |      |j                         dig        t        |d          j                  v r' j                  j                  t        |d                t        |d          j                  v r' j                  j                  t        |d                t         j                         t        d
      k  r j                  j#                          yyc c}}w )zIf 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   y w)N)r9   ).0keyr:   s     rA   	<genexpr>z6ArgillaCallbackHandler.on_chain_end.<locals>.<genexpr>  s"      
 4<<
s   rE   rF   Nr7   rV   rP   rQ    r   )anyrH   r9   getr   r   itemsrc   rd   r5   rU   rS   rW   joinrX   r   r'   rY   )r:   rf   rC   r9   chain_output_keychain_output_valr   outputs   `       rA   on_chain_endz#ArgillaCallbackHandler.on_chain_end  s   
  
F?34c&:J6KL
 
 ((VO-D)EF 
$$,,""3vh'7#8"=K
 3:--/ 	..*D1(( /2';K.L +FF %*0,26N,@,@,B' ) 
 (( %*-((7*;,<,B,B,D' ) 	!	8 vo&'4<<7LLS!89:vh DLL0LLS!123%%&x8LL((* 9;s   "Hc                      y)z+Do nothing when LLM chain outputs an error.Nr"   r^   s      rA   on_chain_errorz%ArgillaCallbackHandler.on_chain_error8  rN   rJ   	input_strc                      y)zDo nothing when tool starts.Nr"   )r:   rB   rw   rC   s       rA   on_tool_startz$ArgillaCallbackHandler.on_tool_start<  s     	rJ   actionc                      y)z.Do nothing when agent takes a specific action.Nr"   )r:   rz   rC   s      rA   on_agent_actionz&ArgillaCallbackHandler.on_agent_actionE  rN   rJ   rs   observation_prefix
llm_prefixc                      y)zDo nothing when tool ends.Nr"   )r:   rs   r}   r~   rC   s        rA   on_tool_endz"ArgillaCallbackHandler.on_tool_endI  s     	rJ   c                      y)z&Do nothing when tool outputs an error.Nr"   r^   s      rA   on_tool_errorz$ArgillaCallbackHandler.on_tool_errorS  rN   rJ   rV   c                      yz
Do nothingNr"   )r:   rV   rC   s      rA   on_textzArgillaCallbackHandler.on_textW  rN   rJ   finishc                      yr   r"   )r:   r   rC   s      rA   on_agent_finishz&ArgillaCallbackHandler.on_agent_finish[  rN   rJ   )NNN)NN)!__name__
__module____qualname____doc__r   rH   __annotations__r   r   r   r   r$   r   r   r   rI   rM   r   r[   BaseExceptionr_   re   rt   rv   ry   r   r|   r   r   r   r	   r   __classcell__)r@   s   @rA   r   r      si   )V <Hc;!
'*J* GHc  G2OS2
 )-!%!%I
I
 !I
 #	I

 #I
 
I
VYsCx.Y379YHKY	Yc S T +9 + + +:- 3 4 sCx.26sCx.LO	&0+DcN 0+c 0+d 0+dM S T cN  	
 
k S S  -1$(	 %SM SM	
  
= C D C 3 4 k S T rJ   r   )r)   r+   typingr   r   r   r   r   langchain_core.agentsr   r	   langchain_core.callbacksr
   langchain_core.outputsr   packaging.versionr   r   r"   rJ   rA   <module>r      s,    	  2 2 : 8 , #R0 RrJ   