
    .`i)                        d dl Z d dlZd dlmZ d dl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 e
rd d
lmZ d dlmZ d dlmZ d dlmZ neZeZeZeZ ee          Z G d d          Z G d d          ZdS )    N)abstractmethod)CallableSequence)cached_property)TYPE_CHECKINGAny)
ToolServer)init_logger)
is_list_of)import_from_path)ChatCompletionRequest)DeltaMessage)ResponsesRequest)TokenizerLikec                      e Zd ZdZdefdZedeee	f         fd            Z
edee	         defd            Zdee	         dee	         defd	Zedee	         dee	         fd
            Zededeez  deedz  edz  f         fd            Zededededee	         dee	         dee	         dedz  fd            Zdedz  dedz  dedz  fdZdS )ReasoningParserz
    Abstract reasoning parser class that should not be used directly.
    Provided and methods should be used in derived classes.

    It is used to extract reasoning content from the model output.
    	tokenizerc                     || _         d S N)model_tokenizer)selfr   argskwargss       x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/reasoning/abs_reasoning_parsers.py__init__zReasoningParser.__init__,   s    (    returnc                 4    | j                                         S r   )r   	get_vocab)r   s    r   vocabzReasoningParser.vocab/   s     #--///r   	input_idsc                     dS )a  
        Check if the reasoning content ends in the input_ids.

        It is used in structured engines like `xgrammar` to check if the
        reasoning content ends in the model output.

        Parameters:
        input_ids: list[int]
            The input_ids of the model output.

        Returns:
        bool
            True if the reasoning content ends in the input_ids.
        N r   r!   s     r   is_reasoning_endz ReasoningParser.is_reasoning_end5         r   	delta_idsc                 ,    |                      |          S )a  
        Check if the reasoning content ends in the input_ids on a
        decode step.

        It is used in structured engines like `xgrammar` to check if the
        reasoning content ends in the model output during a decode step.
        `input_ids` the entire model output and `delta_ids` are the last few
        computed tokens of the model output (like during a decode step).

        Parameters:
        input_ids: list[int]
            The entire model output.
        delta_ids: list[int]
            The last few computed tokens of the model output at the current decode step.

        Returns:
        bool
            True if the reasoning content ends in the `delta_ids` on a
            decode step.
        )r%   )r   r!   r'   s      r   is_reasoning_end_streamingz*ReasoningParser.is_reasoning_end_streamingF   s    . $$Y///r   c                     dS )z
        Extract content token ids from the input_ids.
        Parameters:
        input_ids: list[int]
            The input_ids of the model output.
        Returns:
        list[int]
            The extracted content from the input_ids.
        Nr#   r$   s     r   extract_content_idsz#ReasoningParser.extract_content_ids_   r&   r   model_outputrequestNc                     dS )aE  
        Extract reasoning content from a complete model-generated string.

        Used for non-streaming responses where we have the entire model response
        available before sending to the client.

        Parameters:
        model_output: str
            The model-generated string to extract reasoning content from.

        request: ChatCompletionRequest
            The request object that was used to generate the model_output.

        Returns:
        tuple[Optional[str], Optional[str]]
            A tuple containing the reasoning content and the content.
        Nr#   )r   r,   r-   s      r   extract_reasoningz!ReasoningParser.extract_reasoningk   r&   r   previous_textcurrent_text
delta_textprevious_token_idscurrent_token_idsdelta_token_idsc                     dS )az  
        Instance method that should be implemented for extracting reasoning
        from an incomplete response; for use when handling reasoning calls and
        streaming. Has to be an instance method because  it requires state -
        the current tokens/diffs, but also the information about what has
        previously been parsed and extracted (see constructor)
        Nr#   )r   r0   r1   r2   r3   r4   r5   s          r   extract_reasoning_streamingz+ReasoningParser.extract_reasoning_streaming   r&   r   original_tagtool_serverc                     dS )zz
        Instance method that is implemented for preparing the structured tag
        Otherwise, None is returned
        Nr#   )r   r8   r9   s      r   prepare_structured_tagz&ReasoningParser.prepare_structured_tag   s	     tr   )__name__
__module____qualname____doc__r   r   r   dictstrintr    r   r   boolr%   r)   listr+   r   r   tupler/   r   r7   r	   r;   r#   r   r   r   r   $   s
        )- ) ) ) ) 0tCH~ 0 0 0 _0
 (3- D    ^ 0!#03;C=0	0 0 0 02 	T#Y 	49 	 	 	 ^	  ')99 
sTz3:%	&	   ^.   	
 %SM $C= "# 
	   ^"	Dj	  $&	 
t		 	 	 	 	 	r   r   c                      e Zd ZU dZi Zeeee         f         e	d<   i Z
eeeeef         f         e	d<   ededee         fd            Zedee         fd            Zededee         fd            Ze	 	 ddee         deee         z  d	z  dedd	fd            Zededededd	fd            Ze	 	 	 ddeee         z  d	z  dedee         d	z  dee         eee         gee         f         z  fd            Zededd	fd            Zd	S )ReasoningParserManagera  
    Central registry for ReasoningParser implementations.

    Supports two registration modes:
      - Eager registration via `register_module`
      - Lazy registration via `register_lazy_module`

    Each reasoning parser must inherit from `ReasoningParser`.
    reasoning_parserslazy_parsersnamer   c                     || j         v r| j         |         S || j        v r|                     |          S d                    |                                           }t          d| d|           )a  
        Retrieve a registered or lazily registered ReasoningParser class.

        If the parser is lazily registered, it will be imported and cached
        on first access.

        Raises:
            KeyError: if no parser is found under the given name.
        z, zReasoning parser 'z ' not found. Available parsers: )rH   rI   _load_lazy_parserjoinlist_registeredKeyError)clsrJ   
registereds      r   get_reasoning_parserz+ReasoningParserManager.get_reasoning_parser   s     3((((..3###((...YYs224455
SSSzSS
 
 	
r   c                     t          t          | j                                                  t          | j                                                  z            S )zDReturn names of all eagerly and lazily registered reasoning parsers.)sortedsetrH   keysrI   )rP   s    r   rN   z&ReasoningParserManager.list_registered   sE     c#/446677#c>N>S>S>U>U:V:VVWWWr   c                 8   | j         |         \  }}	 t          j        |          }t          ||          }t	          |t
                    st          | d| d          || j        |<   |S # t          $ r#}t          
                    d|||            d}~ww xY w)z5Import and register a lazily loaded reasoning parser.z in z# is not a ReasoningParser subclass.z7Failed to import lazy reasoning parser '%s' from %s: %sN)rI   	importlibimport_modulegetattr
issubclassr   	TypeErrorrH   	Exceptionlogger	exception)rP   rJ   module_path
class_namemod
parser_clses          r   rL   z(ReasoningParserManager._load_lazy_parser   s     #&"24"8Z	)+66C j11Jj/:: !WW{WWW   +5C!$' 	 	 	I	   	s   AA, ,
B6BBNTmodulemodule_nameforcec                    t          |t                    st          dt          |                     |	|j        g}n@t          |t                    r|g}n't          |t                    r|}nt          d          |D ]=}|s/|| j        v r&| j        |         }t          | d|j
                   || j        |<   >dS )z-Register a ReasoningParser class immediately.z4module must be subclass of ReasoningParser, but got Nz,module_name must be str, list[str], or None.z is already registered at )r[   r   r\   typer<   
isinstancerA   r   rH   rO   r=   )rP   re   rf   rg   module_namesrJ   existeds          r   _register_modulez'ReasoningParserManager._register_module   s     &/22 	UtF||UU   "O,LLS)) 	L'=LLS)) 	L&LLJKKK  	1 	1D XTS%:::/5$VV'BTVVWWW*0C!$''		1 	1r   r`   ra   c                     ||f| j         |<   dS )a;  
        Register a lazy module mapping for delayed import.

        Example:
            ReasoningParserManager.register_lazy_module(
                name="qwen3",
                module_path="vllm.reasoning.parsers.qwen3_reasoning_parser",
                class_name="Qwen3ReasoningParser",
            )
        N)rI   )rP   rJ   r`   ra   s       r   register_lazy_modulez+ReasoningParserManager.register_lazy_module   s     #.z!:r   c                      t          |t                    st          dt          |                     |                     ||           |S dt          t
                   dt          t
                   f fd}|S )z
        Register module with the given name or name list. it can be used as a
        decoder(with module as None) or normal function(with module as not
        None).
        z!force must be a boolean, but got N)re   rf   rg   objr   c                     | j         }| j        }t          t                    rg}nt	          t                    r}n|g}|D ]}||fj        |<   | S r   )r=   r<   rj   rA   r   rI   )rq   r`   ra   namesnrP   rJ   s        r   
_decoratorz:ReasoningParserManager.register_module.<locals>._decorator"  sw    .KJ$$$ %D#&& %# @ @'2J&? ##Jr   )rj   rC   r\   ri   rm   r   )rP   rJ   rg   re   ru   s   ``   r   register_modulez&ReasoningParserManager.register_module  s     %&& 	OMUMMNNN   D NNNM	D1 	d?6K 	 	 	 	 	 	 	  r   plugin_pathc                    t           j                            t           j                            |                    d         }	 t	          ||           dS # t
          $ r  t                              d||           Y dS w xY w)zq
        Import a user-defined reasoning parser by the path
        of the reasoning parser define file.
        r   z#Failed to load module '%s' from %s.N)ospathsplitextbasenamer   r]   r^   r_   )rP   rw   rf   s      r   import_reasoning_parserz.ReasoningParserManager.import_reasoning_parser4  s     g&&rw'7'7'D'DEEaH	[+66666 	 	 	5{K   FF		s   A &B ?B )NT)NTN)r<   r=   r>   r?   rH   r@   rA   ri   r   __annotations__rI   rE   classmethodrR   rD   rN   rL   rC   rm   ro   r   rv   r}   r#   r   r   rG   rG      sW          ;=tCo!667<<</1L$sE#s(O+,111
 
_0E 
 
 
 [
* XS	 X X X [X S T/-B    [,  /3	1 1_%1 49_t+1 	1
 
1 1 1 [16 ; ;# ;3 ;SW ; ; ; [;  (,/3	& &DIo$& & _%,	& 	_$*?)@$BW)W XX& & & [&P # $    [  r   rG   ) rX   ry   abcr   collections.abcr   r   	functoolsr   typingr   r    vllm.entrypoints.mcp.tool_serverr	   vllm.loggerr
   vllm.utils.collection_utilsr   vllm.utils.import_utilsr   0vllm.entrypoints.openai.chat_completion.protocolr   'vllm.entrypoints.openai.engine.protocolr   *vllm.entrypoints.openai.responses.protocolr   vllm.tokenizersr   r<   r^   r   rG   r#   r   r   <module>r      s       				       . . . . . . . . % % % % % % % % % % % % % % 7 7 7 7 7 7 # # # # # # 2 2 2 2 2 2 4 4 4 4 4 4                 .------LM	X		z z z z z z z zza a a a a a a a a ar   