
    NgG                        d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ erdd	lmZ dd
lmZ ddlmZ ddlmZ dZ d#dZ!d$dZ"	 d%d&dZ#	 	 d'd(dZ$d)dZ% G d d e          Z& G d! d"e          Z'dS )*zBA Tracer Implementation that records activity to Weights & Biases.    )annotationsN)
TYPE_CHECKINGAnyCallableDictListOptionalSequenceTuple	TypedDictUnion)warn_deprecated)PydanticBaseModel)
BaseTracer)Run)Settings)Trace)StrPathTrun_ioOptional[dict]returndictc                   | si S ddl m} ddlm} i }|                                 D ]\  }}t          ||          r ||          ||<   $t          |t                    r<t          |d          r|                                n|	                                ||<   u|dk    r-|
                    d t          |          D                        |||<   |S )zUtility to serialize the input and output of a run to store in wandb.
    Currently, supports serializing pydantic models and protobuf messages.

    :param run_io: The inputs and outputs of the run.
    :return: The serialized inputs and outputs.


    r   )MessageToJson)Messagemodel_dump_jsoninput_documentsc                D    i | ]\  }}d | |                                 S )input_document_)json).0idocs      g/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/callbacks/tracers/wandb.py
<dictcomp>z!_serialize_io.<locals>.<dictcomp>=   s/    RRRvq#&1&&

RRR    )google.protobuf.json_formatr   google.protobuf.messager   items
isinstancer   hasattrr   r    update	enumerate)r   r   r   serialized_inputskeyvalues         r$   _serialize_ior1   !   s+     	999999//////llnn + +
UeW%% 	+%2]5%9%9c""011 	+ 5"344"%%'''ZZ\\ c"" %%%$$RR5AQAQRRR    &+c""r&   runDict[str, Any]List[Dict[str, Any]]c                (    dfd | g          S )zUtility to flatten a nest run object into a list of runs.
    :param run: The base run to flatten.
    :return: The flattened list of runs.
    
child_runsr4   r   c                    | g S g }| D ]K}|                     dg           } |                    |           |                     |                      L|S )zUtility to recursively flatten a list of child runs in a run.
        :param child_runs: The list of child runs to flatten.
        :return: The flattened list of runs.
        Nr6   )popappendextend)r6   resultitemflattens      r$   r=   zflatten_run.<locals>.flattenJ   sm    
 I 	/ 	/D,33JMM$MM''*--....r&   )r6   r4   r   r4    )r2   r=   s    @r$   flatten_runr?   D   s3           7C5>>r&   r>   runs	keep_keysTuple[str, ...]c                J    dfd}t          t          ||                     S )zUtility to truncate a list of runs dictionaries to only keep the specified
        keys in each run.
    :param runs: The list of runs to truncate.
    :param keep_keys: The keys to keep in each run.
    :return: The truncated list of runs.
    r2   r3   r   c                N    i }| D ]}|v r|                      |          ||<   |S )zUtility to truncate a single run dictionary to only keep the specified
            keys.
        :param run: The run dictionary to truncate.
        :return: The truncated run dictionary
        )get)r2   new_dictr/   rA   s      r$   truncate_singlez/truncate_run_iterative.<locals>.truncate_singleg   s=      	- 	-Ci #r&   r2   r3   r   r3   listmap)r@   rA   rG   s    ` r$   truncate_run_iterativerL   ]   s;    
 
 
 
 
 
 OT**+++r&   
exact_keyspartial_keysc                ~    dfdddfddfd
dfd}t          t          ||                     S )a  Utility to modify the serialized field of a list of runs dictionaries.
    removes any keys that match the exact_keys and any keys that contain any of the
    partial_keys.
    recursively moves the dictionaries under the kwargs key to the top level.
    changes the "id" field to a string "_kind" field that tells WBTraceTree how to
    visualize the run. promotes the "serialized" field to the top level.
    :param runs: The list of runs to modify.
    :param exact_keys: A tuple of keys to remove from the serialized field.
    :param partial_keys: A tuple of partial keys to remove from the serialized
        field.
    :return: The modified list of runs.
    objr3   r   c                   t          | t                    rJfd|                                 D             } |                                 D ]\  }} |          | |<   n#t          | t                    rfd| D             } | S )zRecursively removes exact and partial keys from a dictionary.
        :param obj: The dictionary to remove keys from.
        :return: The modified dictionary.
        c                \    i | ]'\  }v	t          fd D                       $|(S )c              3      K   | ]}|v V  	d S Nr>   )r!   partialks     r$   	<genexpr>z`modify_serialized_iterative.<locals>.remove_exact_and_partial_keys.<locals>.<dictcomp>.<genexpr>   s'      EEWGqLEEEEEEr&   )any)r!   vrV   rM   rN   s     @r$   r%   zVmodify_serialized_iterative.<locals>.remove_exact_and_partial_keys.<locals>.<dictcomp>   sZ       AqJ&&EEEEEEEEE ' 1&&&r&   c                &    g | ]} |          S r>   r>   )r!   xremove_exact_and_partial_keyss     r$   
<listcomp>zVmodify_serialized_iterative.<locals>.remove_exact_and_partial_keys.<locals>.<listcomp>   s%    AAA0033AAAr&   )r*   r   r)   rJ   )rP   rV   rY   rM   rN   r\   s      r$   r\   zBmodify_serialized_iterative.<locals>.remove_exact_and_partial_keys   s    
 c4   
	B    IIKK  C 		 : :166q99A:T"" 	BAAAASAAAC
r&   Frootboolc                   t          | t                    rd| v r#t          | d         t                    r| d         } d| v sd| v r|s|                     d          }|s|                     d          g}t          |t                    r7|d         | d<   |                     dd           |                     dd           d| v r4|                     d          }|                                D ]
\  }}|| |<   |                                 D ]\  }} |          | |<   n#t          | t                    rfd| D             } | S )	a  Recursively handles the id and kwargs fields of a dictionary.
        changes the id field to a string "_kind" field that tells WBTraceTree how
        to visualize the run. recursively moves the dictionaries under the kwargs
        key to the top level.
        :param obj: a run dictionary with id and kwargs fields.
        :param root: whether this is the root dictionary or the serialized
            dictionary.
        :return: The modified dictionary.
        dataidname_kindNkwargsc                &    g | ]} |          S r>   r>   )r!   r[   handle_id_and_kwargss     r$   r]   zMmodify_serialized_iterative.<locals>.handle_id_and_kwargs.<locals>.<listcomp>   s%    888q''**888r&   )r*   r   rE   rJ   r8   r)   )rP   r^   re   rf   rV   rY   rh   s         r$   rh   z9modify_serialized_iterative.<locals>.handle_id_and_kwargs   sf    c4   	9}}CK!>!>}&kv}}d} . WWV__-EeT** *#(9CLGGD$'''GGFD)))s?? WWX..F & # #1!"A		 1 11--a00A1T"" 	98888C888C
r&   
serializedc                8     | d          }  |           } | S )zTransforms the serialized field of a run dictionary to be compatible
            with WBTraceTree.
        :param serialized: The serialized field of a run dictionary.
        :return: The transformed serialized field.
        T)r^   r>   )ri   rh   r\   s    r$   transform_serializedz9modify_serialized_iterative.<locals>.transform_serialized   s0     *)*4@@@
22:>>
r&   r2   c                     |           }|                     d          }|                                D ]
\  }}|||<   |                    dd          }|                     dd          }|s|}| |i}|S )zTransforms a run dictionary to be compatible with WBTraceTree.
        :param run: The run dictionary to transform.
        :return: The transformed run dictionary.
        ri   re   Nrc   )r8   r)   rE   )	r2   transformed_dictri   rV   rY   re   rc   output_dictrk   s	           r$   transform_runz2modify_serialized_iterative.<locals>.transform_run   s    
 0/44%)),77
$$&& 	$ 	$DAq"#Q $$Wd33##FD11 	D I'
 r&   )rP   r3   r   r3   F)rP   r3   r^   r_   r   r3   )ri   r3   r   r3   rH   rI   )r@   rM   rN   ro   rh   r\   rk   s    `` @@@r$   modify_serialized_iterativerq   v   s    $       $      >           , M4(()))r&   c           	     B   i }i | D ]V}|                                 D ]?\  }}|                    dd          }|                    dd          }||i||<   |r||<   @W                                 D ]~\  }}||         }	||         t          t          ||                                      |	t          t          |	                             t          t          ||                             <   t          fd|                                 D                       }
|
S )zBuilds a nested dictionary from a list of runs.
    :param runs: The list of runs to build the tree from.
    :return: The nested dictionary representing the langchain Run in a tree
        structure compatible with WBTraceTree.
    rb   Nparent_run_idc              3  *   K   | ]\  }}|v	|V  d S rT   r>   )r!   id_valra   child_to_parents      r$   rW   zbuild_tree.<locals>.<genexpr>   s:        v_7T7T7T7T7T7T r&   )r)   r8   nextiter)r@   
id_to_dataentityr/   ra   ru   rs   child_id	parent_idparent_dict	root_dictrv   s              @r$   
build_treer      sU    JO 8 8 	8 	8ICXXdD))F HH_d;;M"%tJv 8*7'	8  /4466 
 
) +x d:h+?&@&@!A!AB 	Dk**++,T$z(7K2L2L-M-MNN     !+!1!1!3!3    I r&   c                     e Zd ZU dZded<   ded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   d
ed<   ded<   d
ed<   d
ed<   d
ed<   d
ed<   d
ed<   ded <   d!ed"<   d#S )$WandbRunArgszArguments for the WandbTracer.zOptional[str]job_typezOptional[StrPath]dirzUnion[Dict, str, None]configprojectrz   zOptional[bool]reinitzOptional[Sequence]tagsgrouprc   notesz Optional[Union[dict, str, bool]]magiczOptional[List[str]]config_exclude_keysconfig_include_keys	anonymousmodeallow_val_changezOptional[Union[bool, str]]resumeforcetensorboardsync_tensorboardmonitor_gym	save_coderb   z'Union[WBSettings, Dict[str, Any], None]settingsN)__name__
__module____qualname____doc____annotations__r>   r&   r$   r   r      s8        ((""""++++,,,,,,,,$$$$&&&&$$$$555555r&   r   c                  r     e Zd ZU dZdZded<   dZded<   defd fdZddZ	dddZ
ddZd dZd!dZ xZS )"WandbTracerzCallback Handler that logs to Weights and Biases.

    This handler will log the model architecture and run traces to Weights and Biases.
    This will ensure that all LangChain activity is logged to W&B.
    NzOptional[WBRun]_runOptional[WandbRunArgs]	_run_argsrun_argsio_serializerr   rf   r   r   Nonec                .    t                      j        di | 	 ddl}ddlm} n"# t
          $ r}t          d          |d}~ww xY w|| _        || _        || _        | 	                    |j
        du            || _        t          dddd	
           dS )a  Initializes the WandbTracer.

        Parameters:
            run_args: (dict, optional) Arguments to pass to `wandb.init()`. If not
                provided, `wandb.init()` will be called with no arguments. Please
                refer to the `wandb.init` for more details.
            io_serializer: callable A function that serializes the input and outputs
             of a run to store in wandb. Defaults to "_serialize_io"

        To use W&B to monitor all LangChain activity, add this tracer like any other
        LangChain callback:
        ```
        from wandb.integration.langchain import WandbTracer

        tracer = WandbTracer()
        chain = LLMChain(llm, callbacks=[tracer])
        # ...end of notebook / script:
        tracer.finish()
        ```
        r   N)
trace_treezTCould not import wandb python package.Please install it with `pip install -U wandb`.)should_print_urlz0.3.8Fa   Please use the `WeaveTracer` from the `weave` package instead of this.The `WeaveTracer` is a more flexible and powerful tool for logging and tracing your LangChain callables.Find more information at https://weave-docs.wandb.ai/guides/integrations/langchainzPlease instantiate the WeaveTracer from `weave.integrations.langchain import WeaveTracer` .For autologging simply use `weave.init()` and log all traces from your LangChain callables.)pendingmessagealternativer>   )super__init__wandbwandb.sdk.data_typesr   ImportError_wandb_trace_treer   _ensure_runr2   _io_serializerr   )selfr   r   rf   r   r   e	__class__s          r$   r   zWandbTracer.__init__!  s    4 	""6"""	LLL7777777 	 	 	A  	
 %!59+<>>>+e1	
 	
 	
 	
 	
 	
s   
' 
AAAc                8    | j                                          dS )zpWaits for all asynchronous processes to finish and data to upload.

        Proxy for `wandb.finish()`.
        N)r   finish)r   s    r$   r   zWandbTracer.finishZ  s    
 	r&   Fr   r_   c                6   | j         j        (i | j        pi }d|vrddi|d<    | j         j        d	i | | j         j        X|r4| j         j        j        j        }| j                             d| d           | j         j                            d           dS dS )
zlEnsures an active W&B run exists.

        If not, will start a new run with the provided run_args.
        Nr   silentTz'Streaming LangChain activity to W&B at z
`WandbTracer` is currently in beta.
Please report any issues to https://github.com/wandb/wandb/issues with the tag `langchain`.	langchain)repor>   )r   r2   r   initr   run_urltermlog_label)r   r   r   r   s       r$   r   zWandbTracer._ensure_runa  s    
 ;?"7!527H))(0$'7$DK((x(((;?& +/2:###g # # #   KO"""44444 '&r&   r2   r   Optional[Dict[str, Any]]c                \   	 t          j        |                                           }t          |          }d}t          ||          }d\  }}t	          |||          }t          |          }|S # t          $ r/}t          r| j        	                    d|            Y d}~dS d}~ww xY w)zUtility to process a run for wandb model_dict serialization.
        :param run: The run to process.
        :return: The convert model_dict to pass to WBTraceTree.
        )rb   rc   ri   rs   )rA   ))lctypegraph)api_keyinputoutput)rM   rN   z$WARNING: Failed to serialize model: N)
r    loadsr?   rL   rq   r   	ExceptionPRINT_WARNINGSr   	termerror)	r   r2   ra   	processedrA   rM   rN   r   r   s	            r$   process_model_dictzWandbTracer.process_model_dictz  s    
	:chhjj))D#D))II /yINNNI($J 4j|  I  	**FM 	 	 	 R%%&PQ&P&PQQQ44444	s   A/A2 2
B+<$B&&B+c                                                        	 d	d
 fd |          }                     |          }|	|||_         j        j        ||                    d           dS dS dS )z+Logs a LangChain Run to W*B as a W&B Trace.Nr2   'Run'parentOptional['Trace']r   c                   dd}	 | j         dv r| j         }n-| j         dk    r d| j                                        v rdnd}nd	} ||           }	j                            | j        || j        rd
nd| j        )t          | j                                        dz            nd	| j	        )t          | j	                                        dz            nd	|	
                    | j                  	
                    | j                            }| j        D ]} ||           ||S |                    |           |S # t          $ r/}t           r	j                            d|            Y d	}~d	S d	}~ww xY w)a{  
            Create a trace for a given run and its child runs.

            Args:
                run (Run): The run for which to create a trace.
                parent (Optional[Trace]): The parent trace.
                If provided, the created trace is added as a child to the parent trace.

            Returns:
                Optional[Trace]: The created trace.
                 If an error occurs during the creation of the trace, None is returned.

            Raises:
                Exception: If an error occurs during the creation of the trace,
                no exception is raised and a warning is printed.
            rr   r   r3   c                f   t          j        |                                            }|                    di           }|                    d          |d<   |                    d          |d<   |                    d          |d<   |                    dd                              d          |d	<   |S )
a  
                Extract metadata from a given run.

                This function extracts metadata from a given run
                and returns it as a dictionary.

                Args:
                    r (Run): The run from which to extract metadata.

                Returns:
                    Dict[str, Any]: A dictionary containing the extracted metadata.
                metadatarb   run_idrs   r   dotted_order .execution_order)r    r   rE   count)r   run_dictmetadata_dicts      r$   get_metadata_dictzPWandbTracer._log_trace_from_run.<locals>.create_trace.<locals>.get_metadata_dict  s      :affhh// (Z < <*2,,t*<*<h'19o1N1No.(0V(<(<f%3;<<"B4 4%** /0 %$r&   )llmtoolchainagentNerrorsuccessi  )rc   kindstatus_codestart_time_msend_time_msr   inputsoutputsz3WARNING: Failed to serialize trace for run due to: )r   r   r   r3   )run_typerc   lowerr   r   r   
start_timeint	timestampend_timer   r   r   r6   	add_childr   r   r   termwarn)
r2   r   r   r   r   r   	child_runr   create_tracer   s
           r$   r   z5WandbTracer._log_trace_from_run.<locals>.create_trace  s   (% % % %.&<?22"|HH\W,,*1SX^^5E5E*E*Eww7HH#H,,S11!-33!+.9 C)~1 #&cn&>&>&@&@4&G"H"H"H|/ !$CL$:$:$<$<t$C D D D%..sz:: //<< 4  
  "% 8 8I LJ7777>%%$$Z000!M   ! K((QaQQ   ttttts   D"E *E 
E:$E55E:langchain_tracerT   )r2   r   r   r   r   r   )r   r   _model_dictr   r2   log)r   r2   	run_trace
model_dictr   s   `   @r$   _log_trace_from_runzWandbTracer._log_trace_from_run  s     59Q	 Q	 Q	 Q	 Q	 Q	 Q	 Q	f !L%%	,,S11
!i&;$.I!;?&9+@MM+,,,,, '&+@+@r&   r   c                0    |                      |           dS )zPersist a run.N)r   )r   r2   s     r$   _persist_runzWandbTracer._persist_run  s      %%%%%r&   )r   r   r   r   rf   r   r   r   )r   r   rp   )r   r_   r   r   )r2   r   r   r   )r2   r   r   r   )r2   r   r   r   )r   r   r   r   r   r   r   r1   r   r   r   r   r   r   __classcell__)r   s   @r$   r   r     s           !D    (,I,,,, ,0"/7
 7
 7
 7
 7
 7
 7
r   5 5 5 5 52   B\- \- \- \-|& & & & & & & &r&   r   )r   r   r   r   )r2   r3   r   r4   )r>   )r@   r4   rA   rB   r   r4   )r>   r>   )r@   r4   rM   rB   rN   rB   r   r4   )r@   r4   r   r3   )(r   
__future__r   r    typingr   r   r   r   r   r	   r
   r   r   r   langchain_core._apir   &langchain_core.output_parsers.pydanticr   langchain_core.tracers.baser   langchain_core.tracers.schemasr   r   r   
WBSettingswandb.sdk.data_types.trace_treer   wandb.sdk.lib.pathsr   wandb.wandb_runWBRunr   r1   r?   rL   rq   r   r   r   r>   r&   r$   <module>r	     s(   H H " " " " " "                         0 / / / / / D D D D D D 2 2 2 2 2 2 . . . . . . -,,,,,,555555++++++,,,,,,       F   4 >@, , , , ,6 #%$&c* c* c* c* c*L   <6 6 6 6 69 6 6 6:d& d& d& d& d&* d& d& d& d& d&r&   