o
    ưiu&                     @   s\   d Z ddlmZmZmZ ddlZddlmZ ddlm	Z	m
Z
 ddlmZ G dd deZdS )	au  
RAGFlow provider configuration for OpenAI-compatible API.

RAGFlow provides OpenAI-compatible APIs with unique path structures:
- Chat endpoint: /api/v1/chats_openai/{chat_id}/chat/completions
- Agent endpoint: /api/v1/agents_openai/{agent_id}/chat/completions

Model name format:
- Chat: ragflow/chat/{chat_id}/{model_name}
- Agent: ragflow/agent/{agent_id}/{model_name}
    )ListOptionalTupleN)OpenAIConfig)
get_secretget_secret_str)AllMessageValuesc                       s  e Zd ZdZdedeeeef fddZ	ddee dee ded	ed
edee	 defddZ
dedee dee dedeee ee ef f
ddZ		ddededee d	ed
edee dee defddZdedee d	ed
ededef fddZ  ZS )RAGFlowConfiga  
    Configuration for RAGFlow OpenAI-compatible API.
    
    Handles both chat and agent endpoints by parsing the model name format:
    - ragflow/chat/{chat_id}/{model_name} for chat endpoints
    - ragflow/agent/{agent_id}/{model_name} for agent endpoints
    modelreturnc                 C   s   | d}t|dk rtd| d|d dkr!td| d|d }|d	vr1td
| d|d }d|dd }|||fS )a  
        Parse RAGFlow model name format: ragflow/{endpoint_type}/{id}/{model_name}
        
        Args:
            model: Model name in format ragflow/chat/{chat_id}/{model} or ragflow/agent/{agent_id}/{model}
            
        Returns:
            Tuple of (endpoint_type, id, model_name)
            
        Raises:
            ValueError: If model format is invalid
        /   zInvalid RAGFlow model format: zU. Expected format: ragflow/chat/{chat_id}/{model} or ragflow/agent/{agent_id}/{model}r   Zragflowz. Must start with 'ragflow/'   )chatZagentzInvalid RAGFlow endpoint type: z. Must be 'chat' or 'agent'      N)splitlen
ValueErrorjoin)selfr
   partsendpoint_type	entity_idZ
model_name r   _/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/ragflow/chat/transformation.py_parse_ragflow_model   s"   




z"RAGFlowConfig._parse_ragflow_modelNapi_baseapi_keyoptional_paramslitellm_paramsstreamc                 C   s   |rt |dr|jr|p|j}|ptjptdptd}|du r$td| |\}}}	|d}|dr=|dd }n|drH|dd	 }|d
krSd| d}
nd| d}
|
	dsbd|
 }
| |
 S )a  
        Get the complete URL for the RAGFlow API call.
        
        Constructs URL based on endpoint type:
        - Chat: /api/v1/chats_openai/{chat_id}/chat/completions
        - Agent: /api/v1/agents_openai/{agent_id}/chat/completions
        
        Args:
            api_base: Base API URL (e.g., http://ragflow-server:port or http://ragflow-server:port/v1)
            api_key: API key (not used in URL construction)
            model: Model name in format ragflow/{endpoint_type}/{id}/{model}
            optional_params: Optional parameters
            litellm_params: LiteLLM parameters (may contain api_base)
            stream: Whether streaming is enabled
            
        Returns:
            Complete URL for the API call
        r   RAGFLOW_API_BASENzapi_base is required for RAGFlow provider. Set it via api_base parameter, RAGFLOW_API_BASE environment variable, or litellm.api_baser   z/api/v1iz/v1r   z/api/v1/chats_openai/z/chat/completionsz/api/v1/agents_openai/)
hasattrr   litellmr   r   r   r   rstripendswith
startswith)r   r   r   r
   r   r    r!   r   r   _pathr   r   r   get_complete_urlB   s.   




zRAGFlowConfig.get_complete_urlcustom_llm_providerc           	      C   sF   |  |\}}}|ptjptdptd}|ptjptd}|||fS )a  
        Get OpenAI-compatible provider information for RAGFlow.
        
        Args:
            model: Model name (will be parsed to extract actual model name)
            api_base: Base API URL (from input params)
            api_key: API key (from input params)
            custom_llm_provider: Custom LLM provider name
            
        Returns:
            Tuple of (api_base, api_key, custom_llm_provider)
        r"   RAGFLOW_API_KEY)r   r%   r   r   r   r   )	r   r
   r   r   r,   r)   actual_modelZdynamic_api_baseZdynamic_api_keyr   r   r   $_get_openai_compatible_provider_info   s   	
z2RAGFlowConfig._get_openai_compatible_provider_infoheadersmessagesc           
      C   s   |rt |dr|jr|p|j}|ptjptd}|dur#d| |d< d|vr/d|vr/d|d< z| |\}}}	|	|d	< W |S  tyH   Y |S w )
a  
        Validate environment and set up headers for RAGFlow API.
        
        Args:
            headers: Request headers
            model: Model name
            messages: Chat messages
            optional_params: Optional parameters
            litellm_params: LiteLLM parameters (may contain api_key)
            api_key: API key (from input params)
            api_base: Base API URL
            
        Returns:
            Updated headers dictionary
        r   r-   NzBearer Authorizationzcontent-typezContent-Typezapplication/json_ragflow_actual_model)r$   r   r%   r   r   r   )
r   r0   r
   r1   r   r    r   r   r)   r.   r   r   r   validate_environment   s&   

z"RAGFlowConfig.validate_environmentc                    sR   | d}|du rz
| |\}}}W n ty   |}Y nw t |||||S )a  
        Transform request for RAGFlow API.
        
        Uses the actual model name extracted from the RAGFlow model format.
        
        Args:
            model: Model name in RAGFlow format
            messages: Chat messages
            optional_params: Optional parameters
            litellm_params: LiteLLM parameters (may contain _ragflow_actual_model)
            headers: Request headers
            
        Returns:
            Transformed request dictionary
        r3   N)getr   r   supertransform_request)r   r
   r1   r   r    r0   r.   r)   	__class__r   r   r7      s   

zRAGFlowConfig.transform_request)N)NN)__name__
__module____qualname____doc__strr   r   r   dictboolr+   r/   r   r   r4   r7   __classcell__r   r   r8   r   r	      s|    +
B
/	
7r	   )r=   typingr   r   r   r%   Zlitellm.llms.openai.openair   Zlitellm.secret_managers.mainr   r   Zlitellm.types.llms.openair   r	   r   r   r   r   <module>   s    