o
    ß­j‹G  ã                   @  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   új/var/www/html/CropPilot/venv/lib/python3.10/site-packages/google/generativeai/notebook/lib/llm_function.pyÚ_is_equal_fn4   s   r   ÚfnúYCallable[[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_rowsúYSequence[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_fnú3Callable[[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_fnú1llmfn_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 )(ÚLLMCompareFunctionz€LLMFunction 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_equaléÿÿÿÿNrS   )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 ||¡|¡ qžq–|
 |¡ 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