o
    ZhG                     @  s2  d Z ddlmZ ddlZddlZddl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 dd	lmZ dd
lmZ ddlmZ eejejgef Zd(ddZd)ddZejG dd dZd*dd ZG d!d" d"eeejdf gejf ej d#Z!G d$d% d%e!Z"G d&d' d'e!Z#dS )+zLLMFunction.    )annotationsN)AbstractSetAnyCallableIterableMappingOptionalSequenceUnion)llmfn_input_utils)llmfn_output_row)llmfn_outputs)llmfn_post_process)llmfn_post_process_cmds)model)prompt_utilslhs#llmfn_output_row.LLMFnOutputRowViewrhsreturnboolc                 C  s   |   |  kS )z-Default function used when comparing outputs.)Zresult_value)r   r    r   d/var/www/html/lang_env/lib/python3.10/site-packages/google/generativeai/notebook/lib/llm_function.py_is_equal_fn4   s   r   fnYCallable[[llmfn_output_row.LLMFnOutputRowView, llmfn_output_row.LLMFnOutputRowView], Any]4llmfn_post_process.LLMCompareFnPostProcessBatchAddFnc                   s   d fdd}|S )	z1Vectorize a single-row-based comparison function.lhs_and_rhs_rowsYSequence[tuple[llmfn_output_row.LLMFnOutputRowView, llmfn_output_row.LLMFnOutputRowView]]r   Sequence[Any]c                   s    fdd| D S )Nc                   s   g | ]	\}} ||qS r   r   ).0r   r   r   r   r   
<listcomp>O   s    zD_convert_compare_fn_to_batch_add_fn.<locals>._fn.<locals>.<listcomp>r   )r   r!   r   r   _fnG   s   z0_convert_compare_fn_to_batch_add_fn.<locals>._fnN)r   r   r   r   r   )r   r#   r   r!   r   #_convert_compare_fn_to_batch_add_fn<   s   
r$   c                   @  s6   e Zd ZU ded< ded< ded< ded< ded< d	S )
_PromptInfoint
prompt_numstrprompt	input_numzMapping[str, str]prompt_varsmodel_inputN)__name__
__module____qualname____annotations__r   r   r   r   r%   T   s   
 r%   promptsSequence[str]inputs*llmfn_input_utils.LLMFunctionInputs | NoneIterable[_PromptInfo]c              	   c  sn    g }|durt |}|si g}t| D ]\}}t|D ]\}}|jdi |}t|||||dV  qqdS )a  Generate a tuple of fields needed for processing prompts.

    Args:
      prompts: A list of prompts, with optional keyword placeholders.
      inputs: A list of key/value pairs to substitute into placeholders in
        `prompts`.

    Yields:
      A _PromptInfo instance.
    N)r'   r)   r*   r+   r,   r   )r   Zto_normalized_inputs	enumerateformatr%   )r1   r3   Znormalized_inputsr'   r)   r*   r+   r,   r   r   r   _generate_prompts]   s$   

r8   c                   @  sj   e Zd ZdZ	dd ddZejd!d	d
Zejd"ddZ	dd#ddZ	d$ddZ
d%ddZd&ddZdS )'LLMFunctionz6Base class for LLMFunctionImpl and LLMCompareFunction.Noutputs_ipython_display_fn3Callable[[llmfn_outputs.LLMFnOutputs], None] | Nonec                 C  s   g | _ || _dS )a  Constructor.

        Args:
          outputs_ipython_display_fn: Optional function that will be used to
            override how the outputs of this LLMFunction will be displayed in a
            notebook (See further documentation in LLMFnOutputs.__init__().)
        N)_post_process_cmds_outputs_ipython_display_fn)selfr:   r   r   r   __init__   s   
zLLMFunction.__init__r   AbstractSet[str]c                 C     dS )zLReturns the placeholders that should be present in inputs for this function.Nr   r>   r   r   r   get_placeholders       zLLMFunction.get_placeholdersr3   r4   (Sequence[llmfn_outputs.LLMFnOutputEntry]c                 C  rA   )z&Concrete implementation of __call__().Nr   )r>   r3   r   r   r   
_call_impl   rD   zLLMFunction._call_implllmfn_outputs.LLMFnOutputsc                 C  s   |  |}tj|| jdS )z+Runs and returns results based on `inputs`.)outputsZipython_display_fn)rF   r   LLMFnOutputsr=   )r>   r3   rH   r   r   r   __call__   s   
zLLMFunction.__call__namer(   r   1llmfn_post_process.LLMFnPostProcessBatchReorderFnc                 C     | j tj||d | S NrK   r   )r<   appendr   ZLLMFnPostProcessReorderCommandr>   rK   r   r   r   r   add_post_process_reorder_fn   s   z'LLMFunction.add_post_process_reorder_fn-llmfn_post_process.LLMFnPostProcessBatchAddFnc                 C  rM   rN   )r<   rP   r   ZLLMFnPostProcessAddCommandrQ   r   r   r   add_post_process_add_fn      z#LLMFunction.add_post_process_add_fn1llmfn_post_process.LLMFnPostProcessBatchReplaceFnc                 C  rM   rN   )r<   rP   r   ZLLMFnPostProcessReplaceCommandrQ   r   r   r   add_post_process_replace_fn   rU   z'LLMFunction.add_post_process_replace_fnN)r:   r;   r   r@   r3   r4   r   rE   )r3   r4   r   rG   )rK   r(   r   rL   r   r9   )rK   r(   r   rS   r   r9   )rK   r(   r   rV   r   r9   )r-   r.   r/   __doc__r?   abcabstractmethodrC   rF   rJ   rR   rT   rW   r   r   r   r   r9      s    



r9   )	metaclassc                      sF   e Zd ZdZ		dd fddZdddZdddZdddZ  ZS )LLMFunctionImpla  Callable class that executes the contents of a Magics cell.

    An LLMFunction is constructed from the Magics command line and cell contents
    specified by the user. It is defined by:
    - A model instance,
    - Model arguments
    - A prompt template (e.g. "the opposite of hot is {word}") with an optional
      keyword placeholder.

    The LLMFunction takes as its input a sequence of dictionaries containing
    values for keyword replacement, e.g. [{"word": "hot"}, {"word": "tall"}].

    This will cause the model to be executed with the following prompts:
      "The opposite of hot is"
      "The opposite of tall is"

    The results will be returned in a LLMFnOutputs instance.
    Nr   model_lib.AbstractModelr1   r2   
model_argsmodel_lib.ModelArguments | Noner:   r;   c                   s^   t  j|d || _|| _|du rt n|| _ti | _| jD ]}| j	t
|| _q dS )a  Constructor.

        Args:
          model: The model that the prompts will execute on.
          prompts: A sequence of prompt templates with optional placeholders. The
            placeholders will be replaced by the inputs passed into this function.
          model_args: Optional set of model arguments to configure how the model
            executes the prompts.
          outputs_ipython_display_fn: See documentation in LLMFunction.__init__().
        r:   N)superr?   _model_prompts	model_libZModelArguments_model_args	frozenset_placeholdersunionr   rC   )r>   r   r1   ra   r:   r)   	__class__r   r   r?      s   

zLLMFunctionImpl.__init__results)Sequence[llmfn_output_row.LLMFnOutputRow]r   c                 C  s   | j D ]=}zt|tjr||}n
tdt|W q tjy&     t	y@ } ztd|
 t|j|d}~ww |S z-Runs post-processing commands over `results`.z)Unsupported post-process command type: {}z Error executing "{}", got {}: {}N)r<   
isinstancer   LLMFnImplPostProcessCommandrunr   PostProcessExecutionErrorr7   typeRuntimeErrorrK   r-   )r>   rn   cmder   r   r   _run_post_processing_cmds   s"   
z)LLMFunctionImpl._run_post_processing_cmdsr@   c                 C     | j S rX   rj   rB   r   r   r   rC   
     z LLMFunctionImpl.get_placeholdersr3   r4   rE   c                 C  s   g }t | j|dD ]A}| jj|j| jd}g }t|jD ]\}}|t	j
tjj|tjj|itd q|tj|j|j|j|j|j|| |d q	|S )N)r1   r3   )r,   ra   dataZresult_type)r'   r*   r)   r+   r,   model_resultsoutput_rows)r8   rf   re   Z
call_modelr,   rh   r6   Ztext_resultsrP   r   LLMFnOutputRowr   ColumnNames
RESULT_NUMZTEXT_RESULTr(   LLMFnOutputEntryr'   r*   r)   r+   ry   )r>   r3   rn   infor   r   
result_numZtext_resultr   r   r   rF     s6   	zLLMFunctionImpl._call_implNN)r   r`   r1   r2   ra   rb   r:   r;   )rn   ro   r   ro   rY   rZ   )	r-   r.   r/   r[   r?   ry   rC   rF   __classcell__r   r   rl   r   r_      s    

r_   c                      sP   e Zd ZdZ		d"d# fd
dZd$ddZd%ddZd&ddZd'd d!Z  Z	S )(LLMCompareFunctionzLLMFunction for comparisons.

    LLMCompareFunction runs an input over a pair of LLMFunctions and compares the
    result.
    Nlhs_name_and_fntuple[str, LLMFunction]rhs_name_and_fncompare_name_and_fns&Sequence[tuple[str, CompareFn]] | Noner:   r;   c                   s   t  j|d |d | _|d | _|d | _|d | _t| j | j | _	|s3d| _
t| _dS |d \}}|| _
|| _|dd D ]\}}| j|t|d qEdS )a  Constructor.

        Args:
          lhs_name_and_fn: Name and function for the left-hand side of the
            comparison.
          rhs_name_and_fn: Name and function for the right-hand side of the
            comparison.
          compare_name_and_fns: Optional names and functions for comparing the
            results of the left- and right-hand sides.
          outputs_ipython_display_fn: See documentation in LLMFunction.__init__().
        rc   r      Zis_equalNrO   )rd   r?   	_lhs_name_lhs_fn	_rhs_name_rhs_fnri   rC   rk   rj   _result_namer   _result_compare_fnadd_compare_post_process_add_fnr$   )r>   r   r   r   r:   rK   r   Zcmp_fnrl   r   r   r?   5  s&   




zLLMCompareFunction.__init__lhs_output_rowsro   rhs_output_rowsrn   r   c                 C  s   | j D ]N}z)t|tjr||}nt|tjr$|tt|||}n	td	t
|W q tjy7     tyQ } ztd	| t
|j|d}~ww |S rp   )r<   rq   r   rr   rs   ZLLMCompareFnPostProcessCommandlistziprv   r7   ru   r   rt   rK   r-   )r>   r   r   rn   rw   rx   r   r   r   ry   `  s&   
z,LLMCompareFunction._run_post_processing_cmdsr@   c                 C  rz   rX   r{   rB   r   r   r   rC   y  r|   z#LLMCompareFunction.get_placeholdersr3   r4   rE   c                 C  s  |  |}| |}g }t||D ]\}}|j|jkr%td|j|j|j|jkr5td|j|j|j|jkrEtd|j|jtt	|j
t	|j
}|j
d | }|j
d | }	g }
tt||	D ]R\}}|\}}tjj|| j| ||i}tj|td}|tjj|j | j|f| j|ffD ]\}}| D ]\}}|tjjkr|d||| qq|
| qg|tj|j|j|j| j||	|
dd q|S )NzPrompt num mismatch: {} vs {}zInput num mismatch: {} vs {}zPrompt vars mismatch: {} vs {}r}   z{}_{})r   r   rn   )r'   r*   r+   r   )r   r   r   r'   rv   r7   r*   r+   minlenr   r6   r   r   r   r   r   r   r   r   addZPROMPT_VARSr   r   itemsrP   r   ry   )r>   r3   Zlhs_resultsZrhs_resultsrH   Z	lhs_entryZ	rhs_entryZnum_output_rowsr   r   r   r   Zlhs_and_rhs_output_rowZlhs_output_rowZrhs_output_rowZrow_dataZ
output_rowrK   rowkvr   r   r   rF   |  sn   

		zLLMCompareFunction._call_implrK   r(   r   r   r9   c                 C  rM   rN   )r<   rP   r   Z!LLMCompareFnPostProcessAddCommandrQ   r   r   r   r     rU   z2LLMCompareFunction.add_compare_post_process_add_fnr   )r   r   r   r   r   r   r:   r;   )r   ro   r   ro   rn   ro   r   ro   rY   rZ   )rK   r(   r   r   r   r9   )
r-   r.   r/   r[   r?   ry   rC   rF   r   r   r   r   rl   r   r   .  s    

+

Pr   )r   r   r   r   r   r   )r   r   r   r   )r1   r2   r3   r4   r   r5   )$r[   
__future__r   r\   dataclassestypingr   r   r   r   r   r   r	   r
   Z google.generativeai.notebook.libr   r   r   r   r   r   rg   r   ZLLMFnOutputRowViewZ	CompareFnr   r$   	dataclassr%   r8   ZLLMFunctionInputsrI   ABCMetar9   r_   r   r   r   r   r   <module>   s@   (	




"Hg