o
    j6hO                     @  s  d Z ddlmZ ddlZ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 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 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ZdZdJddZdKddZdLd#d$Z dMd&d'Z!dKd(d)Z"dNd,d-Z#dOd0d1Z$dPd2d3Z%dOd4d5Z&dOd6d7Z'dOd8d9Z(dPd:d;Z)dOd<d=Z*dPd>d?Z+dPd@dAZ,dQdBdCZ-dRdFdGZ.G dHdI dIZ/dS )SzParses an LLM command line.    )annotationsN)AbstractSetAnyCallableMutableMappingSequence)argument_parser)flag_def)input_utils)model_registry)output_utils)parsed_args_lib)post_process_utils)py_utils)sheets_utils)llm_function)llmfn_inputs_source)llmfn_outputs)model      source%llmfn_inputs_source.LLMFnInputsSourceplaceholdersAbstractSet[str]returnNonec                 C  s2   |   D ]}|D ]}||vrtd|qqd S )Nz#Placeholder "{}" not found in input)to_normalized_inputs
ValueErrorformat)r   r   inputskeyword r"   {/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/generativeai/notebook/cmd_line_parser.py+_validate_input_source_against_placeholders*   s   r$   AbstractSet[str] | None6Callable[[str], llmfn_inputs_source.LLMFnInputsSource]c                      d fdd}|S )Nvar_namestrr   r   c                   s   t | } rt|  |S N)r
   get_inputs_source_from_py_varr$   )r(   r   r   r"   r#   _fn7   s   

z._get_resolve_input_from_py_var_fn.<locals>._fn)r(   r)   r   r   r"   r   r-   r"   r,   r#   !_get_resolve_input_from_py_var_fn4   s   r/   namer)   /tuple[str, parsed_args_lib.TextResultCompareFn]c                 C  s*   t | }t|tstd| | |fS )z*Resolves a value passed into --compare_fn.z0Variable "{}" does not contain a Callable object)r   
get_py_var
isinstancer   r   r   )r0   fnr"   r"   r#   _resolve_compare_fn_var@   s   

r5   Sequence[str]c                 C  s\   t | }t|trt|tst|trtd| |D ]}t|ts+td| q|S )z,Resolves a value passed into --ground_truth.z4Variable "{}" does not contain a Sequence of strings)r   r2   r3   r   r)   bytesr   r   )r0   valuexr"   r"   r#   _resolve_ground_truth_varK   s   

r:   c                   r'   )Nr8   r)   r   r   c                   s&   t | }t |} rt|  |S r*   )r   get_sheets_id_from_strSheetsInputsr$   )r8   	sheets_idr   r,   r"   r#   r-   \   s
   


z*_get_resolve_sheets_inputs_fn.<locals>._fn)r8   r)   r   r   r"   r.   r"   r,   r#   _get_resolve_sheets_inputs_fnY   s   r>   r8   llmfn_outputs.LLMFnOutputsSinkc                 C  s   t | }t |S r*   )r   r;   SheetsOutputs)r8   r=   r"   r"   r#   _resolve_sheets_outputsf   s   

rA   parserargparse.ArgumentParserc                 C  s   t jddtjtjjdd|  ddd	}t jd
dtd|dd|  t jddddd|  ddd}t jddt	d|dd|  t j
ddd|  dS )z:Adds flags that are related to model selection and config.
model_typemtzThe type of model to use.)r0   
short_name	enum_typedefault_valuehelp_msgr9   floatr   c                 S  s   | dk rt d| | S )Nr   z5Value should be greater than or equal to zero, got {})r   r   r9   r"   r"   r#   '_check_is_greater_than_or_equal_to_zerow   s   zA_add_model_flags.<locals>._check_is_greater_than_or_equal_to_zerotemperaturetNzControls the randomness of the output. Must be positive. Typical values are in the range: [0.0, 1.0]. Higher values produce a more random and varied response. A temperature of zero will be deterministic.)r0   rF   
parse_typerH   parse_to_dest_type_fnrI   r   mzLThe name of the model to use. If not provided, a default model will be used.)r0   rF   rH   rI   r   intc                 S  s*   | t k s| tkrtdt t| t| S )Nz-Value should be in the range [{}, {}], got {})_MIN_CANDIDATE_COUNT_MAX_CANDIDATE_COUNTr   r   rR   rK   r"   r"   r#   _check_candidate_count_range   s   z6_add_model_flags.<locals>._check_candidate_count_rangecandidate_countccz$The number of candidates to produce.uniquez3Whether to dedupe candidates returned by the model.)r0   rI   )r9   rJ   r   rJ   )r9   r   r   rR   )r	   EnumFlagDefr   	ModelNameModelRegistryDEFAULT_MODELadd_argument_to_parserSingleValueFlagDefrJ   rR   BooleanFlagDef)rB   rL   rU   r"   r"   r#   _add_model_flagsk   sP   

		r`   c                 C  sD   t jddtjt|dd|  t jddtjt|dd|  dS )	z;Adds flags to read inputs from a Python variable or Sheets.r    izOptional names of Python variables containing inputs to use to instantiate a prompt. The variable must be either: a dictionary {'key1': ['val1', 'val2'] ...}, or an instance of LLMFnInputsSource such as SheetsInput.r0   rF   	dest_typerP   rI   sheets_input_namessizOptional names of Google Sheets to read inputs from. This is equivalent to using --inputs with the names of variables that are instances of SheetsInputs, just more convenient to use.N)r	   MultiValuesFlagDefr   LLMFnInputsSourcer/   r]   r>   rB   r   r"   r"   r#   _add_input_flags   s    
ri   c                 C  s>   t jddtjtjdd|  t jddtjtdd|  dS )	z1Adds flags to write outputs to a Python variable.outputsoa  Optional names of Python variables to output to. If the Python variable has not already been defined, it will be created. If the variable is defined and is an instance of LLMFnOutputsSink, the outputs will be written through the sink's write_outputs() method.rb   sheets_output_namessozOptional names of Google Sheets to write inputs to. This is equivalent to using --outputs with the names of variables that are instances of SheetsOutputs, just more convenient to use.N)r	   rf   r   LLMFnOutputsSinkr   get_outputs_sink_from_py_varr]   rA   rB   r"   r"   r#   _add_output_flags   s    
rq   c                 C  s   t jdttdd|  d S )N
compare_fnzAn optional function that takes two inputs: (lhs_result, rhs_result) which are the results of the left- and right-hand side functions. Multiple comparison functions can be provided.)r0   rc   rP   rI   )r	   rf   tupler5   r]   rp   r"   r"   r#   _add_compare_flags   s   	rt   c                 C  s   t jddttdd|  d S )Nground_truthTzA variable containing a Sequence of strings representing the ground truth that the output of this cell will be compared against. It should have the same number of entries as inputs.)r0   requiredrc   rP   rI   )r	   r^   r   r:   r]   rp   r"   r"   r#   _add_eval_flags   s   
rw   c                 C  s   t |  t| | t|  dS )zAdds flags for the `run` command.

    `run` sends one or more prompts to a model.

    Args:
      parser: The parser to which flags will be added.
      placeholders: Placeholders from prompts in the cell contents.
    N)r`   ri   rq   rh   r"   r"   r#   _create_run_parser  s   
rx   c                 C  s*   d
dd}d}| j d||d t|  d	S )zAdds flags for the compile command.

    `compile` "compiles" a prompt and model call into a callable function.

    Args:
      parser: The parser to which flags will be added.
    r(   r)   r   c              
   S  s>   zt |  W | S  ty } z
td d||d }~ww )N{})r   validate_var_namer   argparseArgumentErrorr   )r(   er"   r"   r#   _compile_save_name_fn(  s   z5_create_compile_parser.<locals>._compile_save_name_fnz?The name of a Python variable to save the compiled function to.compile_save_namehelptypeN)r(   r)   r   r)   )add_argumentr`   )rB   r~   save_name_helpr"   r"   r#   _create_compile_parser  s   
r   c                 C  sL   ddd}d}| j d||d	 | j d
||d	 t| | t|  t|  dS )zAdds flags for the compare command.

    Args:
      parser: The parser to which flags will be added.
      placeholders: Placeholders from prompts in the compiled functions.
    r(   r)   r   $tuple[str, llm_function.LLMFunction]c              
   S  sl   zt |  W n ty } z
td d||d }~ww t | }t|tj	s2td d| | |fS )Nry   z7{} is not a function created with the "compile" command)
r   rz   r   r{   r|   r   r2   r3   r   LLMFunction)r(   r}   r4   r"   r"   r#   _resolve_llm_function_fnA  s   
z8_create_compare_parser.<locals>._resolve_llm_function_fnzbThe name of a Python variable containing a function previously created with the "compile" command.lhs_name_and_fnr   rhs_name_and_fnN)r(   r)   r   r   )r   ri   rq   rt   )rB   r   r   	name_helpr"   r"   r#   _create_compare_parser5  s   

r   c                 C  s.   t |  t| | t|  t|  t|  dS )zAdds flags for the eval command.

    Args:
      parser: The parser to which flags will be added.
      placeholders: Placeholders from prompts in the cell contents.
    N)r`   ri   rq   rt   rw   rh   r"   r"   r#   _create_eval_parser^  s
   

r   c                 C  s   d}d}d}t j|||d}|jdd}t|tjjj|  t	|tjj
j t|tjjj|  t|tjjj|  |S )zCreate the full parser.llmz#A system for interacting with LLMs. )progdescriptionepilogcmd)dest)r   ArgumentParseradd_subparsersrx   
add_parserr   CommandNameRUN_CMDr8   r   COMPILE_CMDr   COMPARE_CMDr   EVAL_CMD)r   system_namer   r   rB   
subparsersr"   r"   r#   _create_parsero  s.   r   parsed_argsparsed_args_lib.ParsedArgsc                 C  s2   | j r| jjd u s| jjdkrtd d S d S d S )Nr   zr"--unique" works across candidates only: it should be used with --candidate_count set to a value greater-than one.)rX   
model_argsrV   print)r   r"   r"   r#   _validate_parsed_args  s   r   c                   @  s^   e Zd ZdZejjZdZe	dddZ
e	dddZe	dddZ	ddddZd ddZdS )!CmdLineParserz-Implementation of Magics command line parser.|tokensr6   r   :tuple[Sequence[str], parsed_args_lib.PostProcessingTokens]c                 C  s   g }d}t |D ] \}}|du r|}|tjkr(||dur#||| ng  d}q||dur5||d ng  |d |dd fS )a  Splits inputs into the command and post processing tokens.

        The command is represented as a sequence of tokens.
        See comments on the PostProcessingTokens type alias.

        E.g. Given: "run --temperature 0.5 | add_score | to_lower_case"
        The command will be: ["run", "--temperature", "0.5"].
        The post processing tokens will be: [["add_score"], ["to_lower_case"]]

        Args:
          tokens: The command line tokens.

        Returns:
          A tuple of (command line, post processing tokens).
        Nr   r   )	enumerater   PIPE_OPappend)clsr   split_tokens	start_idx	token_numtokenr"   r"   r#   _split_post_processing_tokens  s   
z+CmdLineParser._split_post_processing_tokensliner)   c                 C  sL   t |}|stjjg}|d }|d  s!|dvr!tjjg| }t|S )zBParses `line` and returns command line and post processing tokens.r   )z-hz--help)shlexsplitr   DEFAULT_CMDr8   isalphar   )r   r   r   first_tokenr"   r"   r#   _tokenize_line  s   


zCmdLineParser._tokenize_lineparsed_resultsMutableMapping[str, Any]9tuple[MutableMapping[str, Any], model_lib.ModelArguments]c                 C  s<   | dd}| dd}| dd}tj|||d}||fS )al  Extracts fields for model args from `parsed_results`.

        Keys specific to model arguments will be removed from `parsed_results`.

        Args:
          parsed_results: A dictionary of parsed arguments (from ArgumentParser). It
            will be modified in place.

        Returns:
          A tuple of (updated parsed_results, model arguments).
        r   NrM   rV   )r   rM   rV   )pop	model_libModelArguments)r   r   r   rM   rV   r   r"   r"   r#   _get_model_args  s   zCmdLineParser._get_model_argsNr   r%   Gtuple[parsed_args_lib.ParsedArgs, parsed_args_lib.PostProcessingTokens]c           
      C  s   t |\}}| j||d}|jtjjkr=|jdusJ |jdus#J |j\}}|j\}}| j|t	|
 |
 d}t| |D ]}	t|	 qC||fS )a>  Parses the commandline and returns ParsedArgs and post-processing tokens.

        Args:
          line: The line to parse (usually contents from cell Magics).
          placeholders: Placeholders from prompts in the cell contents.

        Returns:
          A tuple of (parsed_args, post_processing_tokens).
        )r   r   N)r   r   %_get_parsed_args_from_cmd_line_tokensr   r   r   r   r   r   	frozensetget_placeholdersunionr   r   'validate_one_post_processing_expression)
selfr   r   r   post_processing_tokensr   _lhs_fnrhs_fnexprr"   r"   r#   
parse_line  s"   

zCmdLineParser.parse_liner   c                 C  sN   t ||}t|}t|d |d< t|\}}||d< tjdi |S )z1Returns ParsedArgs from a tokenized command line.r   r   Nr"   )r   
parse_argsvarsr   r   r   r   
ParsedArgs)r   r   r   resultsresults_dictr   r"   r"   r#   r     s   z3CmdLineParser._get_parsed_args_from_cmd_line_tokens)r   r6   r   r   )r   r)   r   r   )r   r   r   r   r*   )r   r)   r   r%   r   r   )r   r6   r   r%   r   r   )__name__
__module____qualname____doc__r   r   r   r   r   classmethodr   r   r   r   r   r"   r"   r"   r#   r     s    !,r   )r   r   r   r   r   r   )r   r%   r   r&   )r0   r)   r   r1   )r0   r)   r   r6   )r8   r)   r   r?   )rB   rC   r   r   )rB   rC   r   r%   r   r   )r   r%   r   rC   )r   r   r   r   )0r   
__future__r   r{   r   systypingr   r   r   r   r   google.generativeai.notebookr   r	   r
   r   r   r   r   r   r    google.generativeai.notebook.libr   r   r   r   r   rS   rT   r$   r/   r5   r:   r>   rA   r`   ri   rq   rt   rw   rx   r   r   r   r   r   r   r"   r"   r"   r#   <module>   sN   








D






)

