o
    貪gG                     @  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.)result_value)r   r    r   i/var/www/html/chatdoc2/venv/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   to_normalized_inputs	enumerateformatr&   )r2   r4   normalized_inputsr(   r*   r+   r,   r-   r   r   r   _generate_prompts]   s$   

r;   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   rA   r   r   r   get_placeholders       zLLMFunction.get_placeholdersr4   r5   (Sequence[llmfn_outputs.LLMFnOutputEntry]c                 C  rD   )z&Concrete implementation of __call__().Nr   )rA   r4   r   r   r   
_call_impl   rG   zLLMFunction._call_implllmfn_outputs.LLMFnOutputsc                 C  s   |  |}tj|| jdS )z+Runs and returns results based on `inputs`.)outputsipython_display_fn)rI   r   LLMFnOutputsr@   )rA   r4   rK   r   r   r   __call__   s   
zLLMFunction.__call__namer)   r   1llmfn_post_process.LLMFnPostProcessBatchReorderFnc                 C     | j tj||d | S NrO   r   )r?   appendr   LLMFnPostProcessReorderCommandrA   rO   r   r   r   r   add_post_process_reorder_fn   s   z'LLMFunction.add_post_process_reorder_fn-llmfn_post_process.LLMFnPostProcessBatchAddFnc                 C  rQ   rR   )r?   rT   r   LLMFnPostProcessAddCommandrV   r   r   r   add_post_process_add_fn      z#LLMFunction.add_post_process_add_fn1llmfn_post_process.LLMFnPostProcessBatchReplaceFnc                 C  rQ   rR   )r?   rT   r   LLMFnPostProcessReplaceCommandrV   r   r   r   add_post_process_replace_fn   r[   z'LLMFunction.add_post_process_replace_fnN)r=   r>   r   rC   r4   r5   r   rH   )r4   r5   r   rJ   )rO   r)   r   rP   r   r<   )rO   r)   r   rX   r   r<   )rO   r)   r   r\   r   r<   )r.   r/   r0   __doc__rB   abcabstractmethodrF   rI   rN   rW   rZ   r^   r   r   r   r   r<      s    



r<   )	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.AbstractModelr2   r3   
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)superrB   _model_prompts	model_libModelArguments_model_args	frozenset_placeholdersunionr   rF   )rA   r   r2   rh   r=   r*   	__class__r   r   rB      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   PostProcessExecutionErrorr9   typeRuntimeErrorrO   r.   )rA   rv   cmder   r   r   _run_post_processing_cmds   s"   
z)LLMFunctionImpl._run_post_processing_cmdsrC   c                 C     | j S r_   rr   rE   r   r   r   rF   
     z LLMFunctionImpl.get_placeholdersr4   r5   rH   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)r2   r4   )r-   rh   dataresult_type)r(   r+   r*   r,   r-   model_resultsoutput_rows)r;   rm   rl   
call_modelr-   rp   r8   text_resultsrT   r   LLMFnOutputRowr   ColumnNames
RESULT_NUMTEXT_RESULTr)   LLMFnOutputEntryr(   r+   r*   r,   r   )rA   r4   rv   infor   r   
result_numtext_resultr   r   r   rI     s6   	zLLMFunctionImpl._call_implNN)r   rg   r2   r3   rh   ri   r=   r>   )rv   rw   r   rw   r`   ra   )	r.   r/   r0   rb   rB   r   rF   rI   __classcell__r   r   rt   r   rf      s    

rf   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__().
        rj   r      is_equalNrS   )rk   rB   	_lhs_name_lhs_fn	_rhs_name_rhs_fnrq   rF   rs   rr   _result_namer   _result_compare_fnadd_compare_post_process_add_fnr%   )rA   r   r   r   r=   rO   r   cmp_fnrt   r   r   rB   5  s&   




zLLMCompareFunction.__init__lhs_output_rowsrw   rhs_output_rowsrv   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 rx   )r?   ry   r   rz   r{   LLMCompareFnPostProcessCommandlistzipr~   r9   r}   r   r|   rO   r.   )rA   r   r   rv   r   r   r   r   r   r   `  s&   
z,LLMCompareFunction._run_post_processing_cmdsrC   c                 C  r   r_   r   rE   r   r   r   rF   y  r   z#LLMCompareFunction.get_placeholdersr4   r5   rH   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   rv   )r(   r+   r,   r   )r   r   r   r(   r~   r9   r+   r,   minlenr   r8   r   r   r   r   r   r   r   r   addPROMPT_VARSr   r   itemsrT   r   r   )rA   r4   lhs_resultsrhs_resultsrK   	lhs_entry	rhs_entrynum_output_rowsr   r   r   r   lhs_and_rhs_output_rowlhs_output_rowrhs_output_rowrow_data
output_rowrO   rowkvr   r   r   rI   |  sn   

		zLLMCompareFunction._call_implrO   r)   r   r   r<   c                 C  rQ   rR   )r?   rT   r   !LLMCompareFnPostProcessAddCommandrV   r   r   r   r     r[   z2LLMCompareFunction.add_compare_post_process_add_fnr   )r   r   r   r   r   r   r=   r>   )r   rw   r   rw   rv   rw   r   rw   r`   ra   )rO   r)   r   r   r   r<   )
r.   r/   r0   rb   rB   r   rF   rI   r   r   r   r   rt   r   r   .  s    

+

Pr   )r   r   r   r   r   r   )r   r   r   r   )r2   r3   r4   r5   r   r6   )$rb   
__future__r   rc   dataclassestypingr   r   r   r   r   r   r	   r
    google.generativeai.notebook.libr   r   r   r   r   r   rn   r   LLMFnOutputRowView	CompareFnr   r%   	dataclassr&   r;   LLMFunctionInputsrM   ABCMetar<   rf   r   r   r   r   r   <module>   s@   (	




"Hg