
    ci                        U d Z ddlZddlmZmZmZ ddlmZ ddlm	Z	 ddl
mZ 	 ddlZej                  Zeed<   dd	d
ededededededee   defdZdedej(                  defdZdej,                  defdZdedee   fdZdedeej2                  j4                  ej2                  j6                  f   fdZy# e$ r dZeZY w xY w)z'Utility functions for prompt optimizer.    N)AnyOptionalUnion)	TypeAlias)ValidationError   )typesPandasDataFrame)system_instruction
example_dfprompt_col_namemodel_response_col_namerubrics_col_namerubrics_evaluations_col_nametarget_response_col_namer   returnc                4   g }| j                  d      D ]W  }||   ||   d}	|r||   |	d<   |r||   |	d<   |r||   |	d<   t        j                  |	d      }
|j                  d	|
 d
       Y dj	                  |      }|d}dj	                  d|d|dg      S )z=Construct the input prompt for the few shot prompt optimizer.records)orient)promptmodel_responserubricsrubrics_evaluationstarget_response   )indentz```JSON
z
```z

 
zOriginal System Instructions:
z
Examples:
z
New Output:
)to_dictjsondumpsappendjoin)r   r   r   r   r   r   r   all_promptsrowexample_datajson_strall_prompts_strs               N/tmp/pip-target-z3e9_cxr/lib/python/vertexai/_genai/_prompt_optimizer_utils.py_construct_input_promptr*   "   s     K!!!3 8/*!"9:
 &)*:&;L#'256R2SL./#.12J.KL*+::l15Yxj678 kk+.O!99-	
     configc           	      B   |j                   t        d      d|j                   j                  vrt        d      d|j                   j                  vrt        d      d}d|j                   j                  vrt        d      d}d}d}d}|j                  t        j
                  j                  k(  rHd|j                   j                  vrt        d      d}d	|j                   j                  v rt        d
      |j                  t        j
                  j                  k(  rYd	dhj                  |j                   j                        st        d      d	}d}d|j                   j                  v rt        d      t        d      t        |j                   ||||||       S )zBuilds the few shot prompt.z3The 'examples_dataframe' is required in the config.r   z/'prompt' is required in the examples_dataframe.r   z/'model_response' is required in the example_df.r   r   z8'target_response' is required in the examples_dataframe.r   zvOnly 'target_response' should be provided for OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE but 'rubrics' was provided.r   zYrubrics and rubrics_evaluations is required in theexamples_dataframe when rubrics is set.zOnly 'rubrics' and 'rubrics_evaluations' should be provided for OPTIMIZATION_TARGET_FEW_SHOT_RUBRICS but target_response was provided.z7One of 'target_response' or 'rubrics' must be provided.)r   r   r   r   r   r   )
examples_dataframe
ValueErrorcolumnsoptimization_targetr	   OptimizeTarget,OPTIMIZATION_TARGET_FEW_SHOT_TARGET_RESPONSE$OPTIMIZATION_TARGET_FEW_SHOT_RUBRICSissubsetr*   )r   r,   r   r   r   r   r   s          r)   _get_few_shot_promptr6   N   s      (NOOv00888JKKv00888JKKOv88@@@JKK.!#%  	""LL	M F$=$=$E$EEWXX#4 11999.  	""DD	E 01::%%--
 : 
 %'<$ 9 9 A AA4  RSS"!!' 7)%A!9- r+   c                 "   t        | t              rt        j                  j	                  |       } | j
                  r| j                  rt        d      | j
                  r| j
                  S | j                  r| j                   dS t        d      )z;Get the service account from the config for the custom job.zNOnly one of service_account or service_account_project_number can be provided.z&-compute@developer.gserviceaccount.comzEEither service_account or service_account_project_number is required.)
isinstancedictr	   PromptOptimizerConfigmodel_validateservice_accountservice_account_project_numberr/   )r,   s    r)   _get_service_accountr>      s     &$,,;;FC 	6#H#H>
 	
 
		%%%		.	.7788^__V
 	
r+   
output_strc                    | j                         j                  d      }|r7|d   j                         j                  d      rdj                  |dd       }n| }|j                         j                  d      r!|j                         dd j                         }	 t	        j
                  |      S # t        j                  $ r}t        d	|       |d}~ww xY w)
a*  Cleans a string response returned from the prompt optimizer endpoint.

    Args:
        output_str: The optimized prompt string containing the JSON data,
          potentially with markdown formatting like ```json ... ```.

    Returns:
        The parsed JSON data, or None if parsing fails.
    r   r   z```r   r       Nz=Failed to parse the response from prompt optimizer endpoint. )stripsplit
startswithr#   r    loadsJSONDecodeErrorr/   )r?   linescleaned_stringes       r)   !_clean_and_parse_optimized_promptrK      s     $$T*Eq!,,U352;/# ((0'--/399;zz.)) KA3O
	s   B1 1CCCc                     t        |       }	 t        j                  j                  di |S # t        $ r" t        j                  j
                  di |cY S w xY w)z<Parses the output string from the prompt optimizer endpoint. )rK   r	   promptsParsedResponser   ParsedResponseFewShot)r?   
parsed_outs     r)   _parserR      sU     3:>JA}}++9j99 A}}22@Z@@As   , (AA)__doc__r    typingr   r   r   typing_extensionsr   pydanticr   r   r	   pandaspd	DataFramer
   __annotations__ImportErrorstrr*   OptimizeConfigr6   PromptOptimizerConfigOrDictr>   rK   rN   rO   rP   rR   rM   r+   r)   <module>r_      sC   .  ' ' ' $ !#OY- )-)) ) !	)
 ) #&) ") !) 	)XEE  E 	EP
--

0# (3- <AA
	MM  	MM'')A_  	BOs   B; ;	CC