
    imF                         d Z ddlmZmZmZmZmZmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZ ddlmZ ddlmZ ddlmZ d	d
lmZ  G d d      Z G d d      Z G d de      Zy)z
Arize Phoenix prompt manager that integrates with LiteLLM's prompt management system.
Fetches prompt versions from Arize Phoenix and provides workspace-based access control.
    )AnyDictListOptionalTupleUnion)
DictLoaderEnvironmentselect_autoescape)CustomPromptManagement)PromptManagementBasePromptManagementClient)AllMessageValues)
PromptSpec)StandardCallbackDynamicParams   )ArizePhoenixClientc            
       R    e Zd ZdZ	 d	dedeeeef      deeef   dee   fdZ	d Z
y)
ArizePhoenixPromptTemplatezA
    Represents a prompt template loaded from Arize Phoenix.
    Ntemplate_idmessagesmetadatamodelc                 p   || _         || _        || _        |xs |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  di       | _        |j                  dd      | _	        |j                  dd	      | _
        y )
N
model_namemodel_providertemperature
max_tokensinvocation_parametersdescription template_formatMUSTACHE)r   r   r   getr   r   r   r   r   r    r"   )selfr   r   r   r   s        /Users/manta/Documents/Projects/TheRoad-I1/.venv/lib/python3.12/site-packages/litellm/integrations/arize/arize_phoenix_prompt_manager.py__init__z#ArizePhoenixPromptTemplate.__init__   s     '  8hll<8
&ll+;<#<<6",,|4%-\\2I2%N"#<<r:'||,=zJ    c                 <    d| j                    d| j                   dS )NzArizePhoenixPromptTemplate(id='z
', model='z'))r   r   r%   s    r&   __repr__z#ArizePhoenixPromptTemplate.__repr__-   s%    -d.>.>-?z$**UWX	
r(   N)__name__
__module____qualname____doc__strr   r   r   r   r'   r+    r(   r&   r   r      sZ      $KK tCH~&K sCx.	K
 }K$
r(   r   c                       e Zd ZdZ	 	 	 ddee   dee   dee   fdZdeddfd	Zd
eee	f   dede
fdZ	 ddedeeee	f      dee   fdZdedee
   fdZdee   fdZy)ArizePhoenixTemplateManageram  
    Manager for loading and rendering prompt templates from Arize Phoenix.

    Supports:
    - Fetching prompt versions from Arize Phoenix API
    - Workspace-based access control through Arize Phoenix permissions
    - Mustache/Handlebars-style templating (using Jinja2)
    - Model configuration and invocation parameters
    - Multi-message chat templates
    Napi_keyapi_base	prompt_idc           
      0   || _         || _        || _        i | _        t	        | j                   | j                        | _        t        t        i       t        ddg      dddddd	
      | _	        | j                  r| j                  | j                         y y )N)r5   r6   htmlxmlz{{z}}z{%z%}z{#z#})loader
autoescapevariable_start_stringvariable_end_stringblock_start_stringblock_end_stringcomment_start_stringcomment_end_string)r5   r6   r7   promptsr   arize_clientr
   r	   r   	jinja_env_load_prompt_from_arize)r%   r5   r6   r7   s       r&   r'   z$ArizePhoenixTemplateManager.__init__?   s      ">@.LL4==
 %b>(&%9"& $#!!%#

 >>((8 r(   prompt_version_idreturnc                     	 | j                   j                  |      }|r"| j                  ||      }|| j                  |<   yt	        d| d      # t
        $ r}t        d| d|       d}~ww xY w)z2Load a specific prompt version from Arize Phoenix.zPrompt version '' not foundzFailed to load prompt version 'z' from Arize Phoenix: N)rD   get_prompt_version_parse_prompt_datarC   
ValueError	Exception)r%   rG   prompt_datatemplatees        r&   rF   z3ArizePhoenixTemplateManager._load_prompt_from_arize]   s    	++>>?PQK22;@QR2:./ #34E3Fk!RSS 	12C1DDZ[\Z]^ 	s   >A A 	A/A**A/datac           
         |j                  di       }|j                  dg       }|j                  di       }i }d|v r|d   }n6d|v r|d   }n,|j                         D ]  \  }}t        |t              s|} n |j                  d      |j                  d      |j                  dd	      |j                  d
      |j                  dd      ||j                  d      |j                  d      d}	t	        |||	      S )zBParse Arize Phoenix prompt data and extract messages and metadata.rP   r   r   openai	anthropicr   r   r    r!   template_typer"   r#   r   r   )r   r   r    rV   r"   r   r   r   )r   r   r   )r$   items
isinstancedictr   )
r%   rR   rG   template_datar   invocation_paramsprovider_paramskeyvaluer   s
             r&   rL   z.ArizePhoenixTemplateManager._parse_prompt_datam   s    R0 $$Z4 !HH%<bA ((/9O--/<O 0557
UeT*&+O 8 ((<0"hh'7888M26!XXo6#xx(9:F%6*..}=)--l;	
 *)
 	
r(   r   	variablesc                    || j                   vrt        d| d      | j                   |   }g }|j                  D ]  }|j                  dd      }|j                  dg       }g }|D ]|  }	|	j                  d      dk(  rU|	j                  dd      }
| j                  j                  |
      } |j                  di |xs i }|j                  |       l|j                  |	       ~ d	j                  |      }|j                  ||d
        |S )zIRender a template with the given variables and return formatted messages.z
Template 'rJ   roleusercontenttypetextr!    )ra   rc   r2   )	rC   rM   r   r$   rE   from_stringrenderappendjoin)r%   r   r_   rP   rendered_messagesmessagera   content_partsrendered_content_partspartre   jinja_templaterendered_textfinal_contents                 r&   render_templatez+ArizePhoenixTemplateManager.render_template   s    dll*z+kBCC<<,46((G;;vv.D#KK	26M &("%88F#v-88FB/D%)^^%?%?%EN$9N$9$9$NY_"$NM*11-@ +11$7 &  HH%;<M$$-8) )0 ! r(   c                 8    | j                   j                  |      S )zGet a template by ID.)rC   r$   )r%   r   s     r&   get_templatez(ArizePhoenixTemplateManager.get_template   s    ||,,r(   c                 H    t        | j                  j                               S )z List all available template IDs.)listrC   keysr*   s    r&   list_templatesz*ArizePhoenixTemplateManager.list_templates   s    DLL%%'((r(   NNNr,   )r-   r.   r/   r0   r   r1   r'   rF   r   r   r   rL   r   r   rs   ru   ry   r2   r(   r&   r4   r4   3   s    	 "&"&#'	9#9 3-9 C=	9<   '
cN'
7:'
	#'
T GK"!"!+3DcN+C"!		"!H- -9S0T -)S	 )r(   r4   c                       e Zd ZdZ	 	 	 ddee   dee   dee   f fdZedefd       Zede	fd       Z
	 dded	eeeef      deee   eeef   f   fd
Z	 	 	 	 d dee   dee   deeeeef   ef      deeeef      dee   d	eeeef      deee   eeeef      f   fdZdee   fdZd!dZdee   dee   dedefdZ	 	 d"dee   dee   d	ee   dedee   dee   defdZ	 	 	 ddee   d	ee   dedee   dee   dee   defdZ	 	 	 	 	 d#dedee   dedee   d	ee   dedee   dee   dee   dee   dee   deeee   ef   fdZ xZS )$ArizePhoenixPromptManagera	  
    Arize Phoenix prompt manager that integrates with LiteLLM's prompt management system.

    This class enables using prompt versions from Arize Phoenix with the
    litellm completion() function by implementing the PromptManagementBase interface.

    Usage:
        # Configure Arize Phoenix access
        arize_config = {
            "workspace": "your-workspace",
            "access_token": "your-token",
        }

        # Use with completion
        response = litellm.completion(
            model="arize/gpt-4o",
            prompt_id="UHJvbXB0VmVyc2lvbjox",
            prompt_variables={"question": "What is AI?"},
            arize_config=arize_config,
            messages=[{"role": "user", "content": "This will be combined with the prompt"}]
        )
    r5   r6   r7   c                 \    t        |   di | || _        || _        || _        d | _        y )Nr2   )superr'   r5   r6   r7   _prompt_manager)r%   r5   r6   r7   kwargs	__class__s        r&   r'   z"ArizePhoenixPromptManager.__init__   s2     	"6" "FJr(   rH   c                      y)z9Integration name used in model names like 'arize/gpt-4o'.arizer2   r*   s    r&   integration_namez*ArizePhoenixPromptManager.integration_name   s     r(   c                     | j                   1t        | j                  | j                  | j                        | _         | j                   S )z*Get or create the prompt manager instance.)r5   r6   r7   )r   r4   r5   r6   r7   r*   s    r&   prompt_managerz(ArizePhoenixPromptManager.prompt_manager   s@     '#>..$D 
 ###r(   prompt_variablesc                 p   | j                   j                  |      }|st        d| d      | j                   j                  ||xs i       }|j                  |j
                  |j                  d}|j                  }i }d|v r|d   }n	d|v r|d   }|j                         D ]  \  }}	||vs|	||<    ||fS )a  
        Get a prompt template and render it with variables.

        Args:
            prompt_id: The ID of the prompt version
            prompt_variables: Variables to substitute in the template

        Returns:
            Tuple of (rendered_messages, metadata)
        zPrompt template 'rJ   )r   r   r   rT   rU   )	r   ru   rM   rs   r   r   r   r   rW   )
r%   r7   r   rP   rk   r   r[   r\   r]   r^   s
             r&   get_prompt_templatez-ArizePhoenixPromptManager.get_prompt_template   s     &&33I>0;GHH !//??'-2
 ^^#//"--
 %::((/9O--/<O *//1JC(" % 2 !(**r(   user_idr   function_calllitellm_paramsc                 t   |s||fS 	 | j                  ||      \  }}	|r||z   }
n|}
|i }|	j                  d      r| j                  s|	d   |d<   | j                  sdD ]  }||	v s|	|   ||<    |
|fS # t        $ r:}ddl}|j                  j                  j                  d|        ||fcY d}~S d}~ww xY w)z^
        Pre-call hook that processes the prompt template before making the LLM call.
        Nr   r   r   top_pfrequency_penaltypresence_penaltyr   z-Error in Arize Phoenix prompt pre_call_hook: )	r   r$   ignore_prompt_manager_model%ignore_prompt_manager_optional_paramsrN   litellm_loggingverbose_proxy_loggererror)r%   r   r   r   r   r7   r   r   rk   prompt_metadatafinal_messagesparamrQ   r   s                 r&   pre_call_hookz'ArizePhoenixPromptManager.pre_call_hook'  s     ^++)	,151I1I+2.
 !!2X!=!) %!# ""7+D4T4T*9'*Bw'==E /0?0Fu- ">11 	,1177?sC ^++	,s$   AA4 &A4 4	B7=/B2,B72B7c                 6    | j                   j                         S )z!Get list of available prompt IDs.)r   ry   r*   s    r&   get_available_promptsz/ArizePhoenixPromptManager.get_available_promptsb  s    ""1133r(   c                 D    | j                   rd| _        | j                   yy)z"Reload prompts from Arize Phoenix.N)r7   r   r   r*   s    r&   reload_promptsz(ArizePhoenixPromptManager.reload_promptsf  s    >>#'D  r(   prompt_specdynamic_callback_paramsc                      y)z
        Determine if prompt management should run based on the prompt_id.

        For Arize Phoenix, we always return True and handle the prompt loading
        in the _compile_prompt_helper method.
        Tr2   )r%   r7   r   r   s       r&   should_run_prompt_managementz6ArizePhoenixPromptManager.should_run_prompt_managementl  s     r(   prompt_labelprompt_versionc                 `   |t        d      	 || j                  j                  vr| j                  j                  |       | j	                  ||      \  }}|j                  d      }	i }
dD ]  }||v s||   |
|<    t        |||	|
d      S # t        $ r}t        d| d|       d}~ww xY w)aM  
        Compile an Arize Phoenix prompt template into a PromptManagementClient structure.

        This method:
        1. Loads the prompt version from Arize Phoenix
        2. Renders it with the provided variables
        3. Returns formatted chat messages
        4. Extracts model and optional parameters from metadata
        N6prompt_id is required for Arize Phoenix prompt managerr   r   )r7   prompt_templateprompt_template_modelprompt_template_optional_paramscompleted_messageszError compiling prompt 'z': )rM   r   rC   rF   r   r$   r   rN   )r%   r7   r   r   r   r   r   rk   r   template_modeloptional_paramsr   rQ   s                r&   _compile_prompt_helperz0ArizePhoenixPromptManager._compile_prompt_helperz  s    $ UVV"	K 3 3 ; ;;##;;IF 261I1I+2.
 -009N !O O+-<U-COE* *# 1&40?#'   	K7	{#aSIJJ	Ks   A$B 4B 	B-B((B-c                 R   K   |t        d      | j                  ||||||      S w)z
        Async version of compile prompt helper. Since Arize Phoenix operations are synchronous,
        this simply delegates to the sync version.
        r   )r7   r   r   r   r   r   )rM   r   )r%   r7   r   r   r   r   r   s          r&   async_compile_prompt_helperz5ArizePhoenixPromptManager.async_compile_prompt_helper  sD      UVV**#-$;%) + 
 	
s   %'r   non_default_paramsr   r   c                 D    t        j                  | |||||||||	|
|      S )zu
        Get chat completion prompt from Arize Phoenix and return processed model, messages, and parameters.
        )r   r   r   r   r   )r   get_chat_completion_prompt)r%   r   r   r   r7   r   r   r   r   r   r   r   s               r&   r   z4ArizePhoenixPromptManager.get_chat_completion_prompt  s;    " $>>##%)(C2W
 	
r(   rz   r,   )NNNN)rH   N)NN)NNNFF) r-   r.   r/   r0   r   r1   r'   propertyr   r4   r   r   r   r   r   r   r   r   r   r   r   r   r   boolr   rY   intr   r   r   r   __classcell__)r   s   @r&   r|   r|      s_   2 "&"&#'	K#K 3-K C=	K #   $ ; $ $ 6:-+-+ #4S>2-+ 
t$%tCH~5	6	-+f ?C37#'599,#9, '(9,  d38nc&9 :;	9,
 !c3h09, C=9, #4S>29, 
t$%xS#X'??	@9,v4tCy 4 C= j) "?	
 
( '+(,6KC=6K j)6K #4.	6K
 "?6K sm6K !6K 
 6Kz -1&*(,
C=
 #4.
 "?	

 j)
 sm
 !
 
 
@ -1&*(,6;@E

 '(
 !	

 C=
 #4.
 "?
 j)
 sm
 !
 &.d^
 08~
 
sD)*D0	1
r(   r|   N)r0   typingr   r   r   r   r   r   jinja2r	   r
   r   -litellm.integrations.custom_prompt_managementr   +litellm.integrations.prompt_management_baser   r   litellm.types.llms.openair   "litellm.types.prompts.init_promptsr   litellm.types.utilsr   arize_phoenix_clientr   r   r4   r|   r2   r(   r&   <module>r      sT   
 ; : = = P 7 9 = 4
 
:M) M)`e
 6 e
r(   