o
    ưi<9                     @   s   d Z ddlZddl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 er?dd	lmZ neZd
dlmZmZ G dd deZdS )z
Dotprompt manager that integrates with LiteLLM's prompt management system.
Builds on top of PromptManagementBase to provide .prompt file support.
    N)TYPE_CHECKINGAnyDictListOptionalTupleUnion)CustomPromptManagement)PromptManagementClient)AllMessageValues)
PromptSpec)StandardCallbackDynamicParams)Logging   )PromptManagerPromptTemplatec                    @   s  e Zd ZdZ				d>dee dee deeeef  dee fddZe	d	efd
dZ
e	d	efddZdee dee ded	efddZ		d?dee dee dee dedee dee d	efddZ			d@dee dee dedee dee dee d	efddZ					dAd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d Z						dBdedee dedee dee ded!edee d"eee  dee dee dee dee d	eeee ef fd#d$Zd%ed	ee fd&d'Zd(ed)ed	efd*d+Zd,ed	efd-d.Zded	dfd/d0Z dCd1d2Z!ded3eee"f d	dfd4d5Z#d6eeeee"f f d	dfd7d8Z$d	eeeee"f f fd9d:Z%d;ed	eee"f fd<d=Z&dS )DDotpromptManageran  
    Dotprompt manager that integrates with LiteLLM's prompt management system.

    This class enables using .prompt files with the litellm completion() function
    by implementing the PromptManagementBase interface.

    Usage:
        # Set global prompt directory
        litellm.prompt_directory = "path/to/prompts"

        # Use with completion
        response = litellm.completion(
            model="dotprompt/gpt-4",
            prompt_id="my_prompt",
            prompt_variables={"variable": "value"},
            messages=[{"role": "user", "content": "This will be combined with the prompt"}]
        )
    Nprompt_directoryprompt_fileprompt_data	prompt_idc                 C   sL   dd l }|p|j| _t|trt|| _n|pi | _d | _|| _	|| _
d S )Nr   )litellmZglobal_prompt_directoryr   
isinstancestrjsonloadsr   _prompt_managerr   r   )selfr   r   r   r   r    r   g/home/app/Keep/.python/lib/python3.10/site-packages/litellm/integrations/dotprompt/dotprompt_manager.py__init__+   s   


zDotpromptManager.__init__returnc                 C   s   dS )z<Integration name used in model names like 'dotprompt/gpt-4'.Z	dotpromptr   r   r   r   r   integration_name?   s   z!DotpromptManager.integration_namec                 C   sH   | j du r!| jdu r| js| jstdt| j| j| j| jd| _ | j S )zLazy-load the prompt manager.NzEither prompt_directory or prompt_data must be set before using dotprompt manager. Set litellm.global_prompt_directory, initialize with prompt_directory parameter, or provide prompt_data.)r   r   r   r   )r   r   r   r   
ValueErrorr   r   r"   r   r   r   prompt_managerD   s    

zDotpromptManager.prompt_managerprompt_specdynamic_callback_paramsc                 C   s2   |du rdS z|| j  v W S  ty   Y dS w )z
        Determine if prompt management should run based on the prompt_id.

        Returns True if the prompt_id exists in our prompt manager.
        NF)r%   Zlist_prompts	Exception)r   r   r&   r'   r   r   r   should_run_prompt_managementY   s   z-DotpromptManager.should_run_prompt_managementprompt_variablesprompt_labelprompt_versionc              
   C   s   |du rt dzA| jj||d}|du r*|rd| dnd}t d| d| d	| jj|||d
}	| |	}
|j}| |}t||
||ddW S  ty_ } z
t d| d| d}~ww )ae  
        Compile a .prompt file into a PromptManagementClient structure.

        This method:
        1. Loads the prompt template from the .prompt file (with optional version)
        2. Renders it with the provided variables
        3. Converts the rendered text into chat messages
        4. Extracts model and optional parameters from metadata
        N+prompt_id is required for dotprompt manager)r   versionz
 (version ) zPrompt ''z not found in prompt directory)r   r*   r.   )r   Zprompt_templateZprompt_template_modelZprompt_template_optional_paramsZcompleted_messageszError compiling prompt 'z': )	r$   r%   Z
get_promptrender_convert_to_messagesmodel_extract_optional_paramsr
   r(   )r   r   r&   r*   r'   r+   r,   templateversion_strrendered_contentmessagesZtemplate_modeloptional_paramser   r   r   _compile_prompt_helperl   s<   

z'DotpromptManager._compile_prompt_helperc                    s(   |du r	t d| j||||||dS )z
        Async version of compile prompt helper. Since dotprompt operations are synchronous,
        this simply delegates to the sync version.
        Nr-   )r   r&   r*   r'   r+   r,   )r$   r<   )r   r   r*   r'   r&   r+   r,   r   r   r   async_compile_prompt_helper   s   z,DotpromptManager.async_compile_prompt_helperFr4   r9   non_default_paramsignore_prompt_manager_model%ignore_prompt_manager_optional_paramsc                 C   s*   ddl m} |j| |||||||||	d
S )Nr   PromptManagementBase)r&   r+   r,   )+litellm.integrations.prompt_management_baserB   get_chat_completion_prompt)r   r4   r9   r>   r   r*   r'   r&   r+   r,   r?   r@   rB   r   r   r   rD      s   z+DotpromptManager.get_chat_completion_promptlitellm_logging_objtoolsc                    s:   ddl m} |j| |||||||||	|
|||dI dH S )zY
        Async version - delegates to PromptManagementBase async implementation.
        r   rA   )
r   r*   rE   r'   r&   rF   r+   r,   r?   r@   N)rC   rB    async_get_chat_completion_prompt)r   r4   r9   r>   r   r*   r'   rE   r&   rF   r+   r,   r?   r@   rB   r   r   r   rG      s$   z1DotpromptManager.async_get_chat_completion_promptr8   c           	   	   C   sf  |  }g }d}g }|d}|D ]|}|  }|dr:|r.|r.|| |d|   d}|dd   g}q|dr]|rQ|rQ|| |d|   d}|dd   g}q|d	r|rt|rt|| |d|   d
}|dd   g}q|r|| qd}|g}q|r|rd|  }|r|| || |s|r|| d| |S )a9  
        Convert rendered prompt content to chat messages.

        This method supports multiple formats:
        1. Simple text -> converted to user message
        2. Text with role prefixes (System:, User:, Assistant:) -> parsed into separate messages
        3. Already formatted as a single message
        N
zSystem:system   zUser:user   z
Assistant:Z	assistant
   )stripsplit
startswithappend_create_messagejoin)	r   r8   contentr9   Zcurrent_roleZcurrent_contentlineslineZcontent_textr   r   r   r3     sZ   




z%DotpromptManager._convert_to_messagesrolerT   c                 C   s
   ||dS )z5Create a message with the specified role and content.)rW   rT   r   )r   rW   rT   r   r   r   rR   M  s   z DotpromptManager._create_messager6   c                 C   s   i }|j dur||j  |S )z
        Extract optional parameters from the prompt template metadata.

        Includes parameters like temperature, max_tokens, etc.
        N)r:   update)r   r6   r:   r   r   r   r5   T  s   
z)DotpromptManager._extract_optional_paramsc                 C   s   || _ d| _dS )z,Set the prompt directory and reload prompts.N)r   r   )r   r   r   r   r   set_prompt_directoryb  s   
z%DotpromptManager.set_prompt_directoryc                 C   s   | j r
| j   dS dS )z&Reload all prompts from the directory.N)r   reload_promptsr"   r   r   r   rZ   g  s   zDotpromptManager.reload_prompts	json_datac                 C   s,   | dd}| di }| j||| dS )zAdd a prompt from JSON data.rT   r0   metadataN)getr%   Z
add_prompt)r   r   r[   rT   r\   r   r   r   add_prompt_from_jsonl  s   z%DotpromptManager.add_prompt_from_jsonprompts_datac                 C   s   | j | dS )z%Load multiple prompts from JSON data.N)r%   Zload_prompts_from_json_data)r   r_   r   r   r   load_prompts_from_jsonr  s   z'DotpromptManager.load_prompts_from_jsonc                 C   s
   | j  S )zGet all prompts in JSON format.)r%   Zget_all_prompts_as_jsonr"   r   r   r   get_prompts_as_jsonv  s   
z$DotpromptManager.get_prompts_as_json	file_pathc                 C   s   | j |S )z&Convert a .prompt file to JSON format.)r%   Zprompt_file_to_json)r   rb   r   r   r   convert_prompt_file_to_jsonz  s   z,DotpromptManager.convert_prompt_file_to_json)NNNN)NN)NNN)NNNFF)NNNNFF)r!   N)'__name__
__module____qualname____doc__r   r   r   dictr    propertyr#   r   r%   r   r   boolr)   intr
   r<   r=   r   r   r   rD   LiteLLMLoggingObjr   rG   r3   rR   r   r5   rY   rZ   r   r^   r`   ra   rc   r   r   r   r   r      s   


B
!	

'	


&G
"r   )rg   r   typingr   r   r   r   r   r   r   Z-litellm.integrations.custom_prompt_managementr	   rC   r
   Zlitellm.types.llms.openair   Z"litellm.types.prompts.init_promptsr   Zlitellm.types.utilsr   Z*litellm.litellm_core_utils.litellm_loggingr   rl   r%   r   r   r   r   r   r   r   <module>   s    $