
    Ng9                         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dS )	    N)AnyDictListOptionalcast)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   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responsec                     g | ]	}|j         
S  r   .0fields     j/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/callbacks/argilla_callback.py
<listcomp>z3ArgillaCallbackHandler.__init__.<locals>.<listcomp>   s    LLLu
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    AnAnAnQV%*AnAnAnr)   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 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d6J J J J   ?ry):;;CM>151E> > >   *G?ry):;;C -..x@@ #   M>151E> > >   *G	GGGWG5555 	 	 	!T T T (,T T T 
 	 ),B0@0@0B0B	JT)**U8__<<.(< . . .  
 -e4
:2-: &-   DLL
  	 	 	#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AnZ^ZfZmAnAnAnP P
 @D}P P P   .0AOA A A	
 	
 	
 	
 	
s:   4 A1E	 	
E4E//E4A2H 
I4II
serializedrB   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)rB   updatestr)rC   rI   rB   rJ   s       r'   on_llm_startz#ArgillaCallbackHandler.on_llm_start   s<     	S!8!LF8<LMMwWXXXXXr)   tokenc                     dS )z)Do nothing when a new token is generated.Nr"   )rC   rQ   rJ   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.rL   NrM   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   )
rB   rO   zipgenerationsr>   add_recordspopr   r0   push_to_argilla)rC   r    rJ   rB   r^   r   s        @r'   
on_llm_endz!ArgillaCallbackHandler.on_llm_end   s    /" 	F ,s6(#3445#&w0D#E#E 	 	FKL$$    '2   % 
 
 
 
 	VH-..///%&&x88L((***** 98r)   errorc                     dS )z%Do nothing when LLM outputs an error.Nr"   rC   rc   rJ   s      r'   on_llm_errorz#ArgillaCallbackHandler.on_llm_error   rT   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.
        inputrL   rM   N)rB   rN   rO   
isinstancelist)rC   rI   rg   rJ   s       r'   on_chain_startz%ArgillaCallbackHandler.on_chain_start   s     fL/C6(3CDD%fWot<</w$Wo.	     r)   outputsc           	      d    t           fdt          |d                   t          |d                   fD                       sdS  j                            t          |d                             p@t	          t
           j                            t          |d                   g                     }|                                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 )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 V  d S )N)rB   )r%   keyrC   s     r'   	<genexpr>z6ArgillaCallbackHandler.on_chain_end.<locals>.<genexpr>  s>       
 
 4<
 
 
 
 
 
r)   rL   rM   Nc                 R    g | ]$\  }}d ||d                                          di%S )r@   rX   rW   )rY   )r%   r   outputs      r'   r(   z7ArgillaCallbackHandler.on_chain_end.<locals>.<listcomp>  sS        +FF %*0,26N,@,@,B,B' '  r)   r[   r@    rW   r   )anyrO   rB   getr   r   itemsrj   rk   r>   r_   r]   joinrY   r`   r   r0   ra   )rC   rm   rJ   rB   chain_output_keychain_output_vals   `     r'   on_chain_endz#ArgillaCallbackHandler.on_chain_end  sS   
  
 
 
 
F?344c&:J6K6KL
 
 
 
 
 	 F((VO-D)E)EFF 
$$,""3vh'7#8#8"==K
 K
 3:--// 	 	..*D11 ((  /2';K.L.L   ) 
 
 
 
 (( %*-((7*;*;,<,B,B,D,D' ' ) 	 	 	 	 vo&''4<77LS!899:::vh  DL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"   re   s      r'   on_chain_errorz%ArgillaCallbackHandler.on_chain_error8  rT   r)   	input_strc                     dS )zDo nothing when tool starts.Nr"   )rC   rI   r~   rJ   s       r'   on_tool_startz$ArgillaCallbackHandler.on_tool_start<  s	     	r)   actionc                     dS )z.Do nothing when agent takes a specific action.Nr"   )rC   r   rJ   s      r'   on_agent_actionz&ArgillaCallbackHandler.on_agent_actionE  rT   r)   rs   observation_prefix
llm_prefixc                     dS )zDo nothing when tool ends.Nr"   )rC   rs   r   r   rJ   s        r'   on_tool_endz"ArgillaCallbackHandler.on_tool_endI  s	     	r)   c                     dS )z&Do nothing when tool outputs an error.Nr"   re   s      r'   on_tool_errorz$ArgillaCallbackHandler.on_tool_errorS  rT   r)   rX   c                     dS z
Do nothingNr"   )rC   rX   rJ   s      r'   on_textzArgillaCallbackHandler.on_textW  rT   r)   finishc                     dS r   r"   )rC   r   rJ   s      r'   on_agent_finishz&ArgillaCallbackHandler.on_agent_finish[  rT   r)   )NNN)NN)!__name__
__module____qualname____doc__r   rO   __annotations__r   r   r   r   r-   r   r   r   rP   rS   r   rb   BaseExceptionrf   rl   r{   r}   r   r   r   r   r   r   r	   r   __classcell__)rH   s   @r'   r   r      s        ) )V <Hc;;;!***J*** GHc  G  G  G2OS222
 )-!%!%I
 I
I
 !I
 #	I

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