o
    -iJ&                     @   s   d dl Z d dl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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 d dlmZ d dlmZ eeZG dd dZG dd dZ dS )    N)CallableSequence)cached_property)"ResponseFormatTextJSONSchemaConfig)ChatCompletionRequest)DeltaMessageExtractedToolCallInformation)ResponsesRequestResponseTextConfig)init_logger)StructuredOutputsParams)TokenizerLike)get_json_schema_from_tools)
is_list_of)import_from_pathc                   @   s   e Zd ZdZdefddZedeee	f fddZ
dedefd	d
ZdededefddZdedededee	 dee	 dee	 dededB fddZdS )
ToolParserz
    Abstract ToolParser class that should not be used directly. Provided
    properties and methods should be used in
    derived classes.
    	tokenizerc                 C   s"   g | _ d| _d| _g | _|| _d S )NF)prev_tool_call_arrcurrent_tool_idcurrent_tool_name_sentstreamed_args_for_toolmodel_tokenizer)selfr    r   c/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/vllm/tool_parsers/abstract_tool_parser.py__init__)   s
   
zToolParser.__init__returnc                 C   s
   | j  S N)r   	get_vocab)r   r   r   r   vocab2   s   
zToolParser.vocabrequestc                 C   sj   |j s|S t|j|j d}|dur3t|trt|d|_d|_t|tr3t	 |_
td|dddd|j
_|S )	zK
        Static method that used to adjust the request parameters.
        )tool_choicetoolsN)jsontool_calling_responsejson_schemaz Response format for tool callingT)nameschematypedescriptionstrict)r#   r   r"   
isinstancer   r   structured_outputsresponse_formatr	   r
   textr   format)r   r!   json_schema_from_toolr   r   r   adjust_request8   s*   


zToolParser.adjust_requestmodel_outputc                 C      t d)a,  
        Static method that should be implemented for extracting tool calls from
        a complete model-generated string.
        Used for non-streaming responses where we have the entire model response
        available before sending to the client.
        Static because it's stateless.
        z?AbstractToolParser.extract_tool_calls has not been implemented!NotImplementedError)r   r3   r!   r   r   r   extract_tool_callsV   s   
zToolParser.extract_tool_callsprevious_textcurrent_text
delta_textprevious_token_idscurrent_token_idsdelta_token_idsNc                 C   r4   )av  
        Instance method that should be implemented for extracting tool calls
        from an incomplete response; for use when handling tool 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)
        zIAbstractToolParser.extract_tool_calls_streaming has not been implemented!r5   )r   r8   r9   r:   r;   r<   r=   r!   r   r   r   extract_tool_calls_streamingd   s   z'ToolParser.extract_tool_calls_streaming)__name__
__module____qualname____doc__r   r   r   dictstrintr    r   r2   r   r7   r   r   r>   r   r   r   r   r   "   s<    	
	r   c                   @   sL  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dZededee fdd	Ze	
	ddee deee B d
B dedd
fddZededededd
fddZe	
		
ddeee B d
B dedee d
B dee eee gee f B fddZedee fddZededd
fddZd
S )ToolParserManagerz
    Central registry for ToolParser implementations.

    Supports two modes:
      - Eager (immediate) registration via `register_module`
      - Lazy registration via `register_lazy_module`
    tool_parserslazy_parsersr'   r   c                 C   s8   || j v r
| j | S || jv r| |S td| d)z
        Retrieve a registered or lazily registered ToolParser class.

        If the parser is lazily registered,
        it will be imported and cached on first access.
        Raises KeyError if not found.
        zTool parser 'z' not found.)rG   rH   _load_lazy_parserKeyErrorclsr'   r   r   r   get_tool_parser   s
   
	


z!ToolParserManager.get_tool_parserc              
   C   s|   | j | \}}z!t|}t||}t|ts!t| d| d|| j|< |W S  ty= } z	t	
d|||  d}~ww )z+Import and register a lazily loaded parser.z in z is not a ToolParser subclass.z2Failed to import lazy tool parser '%s' from %s: %sN)rH   	importlibimport_modulegetattr
issubclassr   	TypeErrorrG   	Exceptionlogger	exception)rL   r'   module_path
class_namemod
parser_clser   r   r   rI      s(   



z#ToolParserManager._load_lazy_parserNTmodulemodule_nameforcec                 C   s   t |tstdt| |du r|j}t|tr|g}nt|tr&|}ntd|D ]}|sD|| jv rD| j| }t	| d|j
 || j|< q,dS )z(Register a ToolParser class immediately.z/module must be subclass of ToolParser, but got Nz,module_name must be str, list[str], or None.z is already registered at )rQ   r   rR   r)   r?   r,   rD   r   rG   rJ   r@   )rL   r[   r\   r]   module_namesr'   existedr   r   r   _register_module   s"   



z"ToolParserManager._register_modulerV   rW   c                 C   s   ||f| j |< dS )a  
        Register a lazy module mapping.

        Example:
            ToolParserManager.register_lazy_module(
                name="kimi_k2",
                module_path="vllm.tool_parsers.kimi_k2_parser",
                class_name="KimiK2ToolParser",
            )
        N)rH   )rL   r'   rV   rW   r   r   r   register_lazy_module   s   z&ToolParserManager.register_lazy_modulec                    s\   t |tstdt| |dur j||d |S dtt dtt f fdd}|S )a)  
        Register module immediately or lazily (as a decorator).

        Usage:
            @ToolParserManager.register_module("kimi_k2")
            class KimiK2ToolParser(ToolParser):
                ...

        Or:
            ToolParserManager.register_module(module=SomeToolParser)
        z!force must be a boolean, but got N)r[   r\   r]   objr   c                    sX   | j }| j}ttrg}nd urttr}n|g}|D ]	}||f j|< q | S r   )r@   r?   r,   rD   r   rH   )rb   rV   rW   namesnrK   r   r   
_decorator   s   
z5ToolParserManager.register_module.<locals>._decorator)r,   boolrR   r)   r`   r   )rL   r'   r]   r[   re   r   rK   r   register_module   s   
 z!ToolParserManager.register_modulec                 C   s    t t| j t| j B S )z?Return names of all eagerly and lazily registered tool parsers.)sortedsetrG   keysrH   )rL   r   r   r   list_registered  s    z!ToolParserManager.list_registeredplugin_pathc                 C   sL   t jt j|d }zt|| W dS  ty%   td|| Y dS w )z6Import a user-defined parser file from arbitrary path.r   z#Failed to load module '%s' from %s.N)ospathsplitextbasenamer   rS   rT   rU   )rL   rl   r\   r   r   r   import_tool_parser  s   
z$ToolParserManager.import_tool_parser)NT)NTN)r?   r@   rA   rB   rG   rC   rD   r)   r   __annotations__rH   tupleclassmethodrM   rI   listrf   r`   ra   r   rg   rk   rq   r   r   r   r   rF   z   sN   
 
-rF   )!rN   rm   collections.abcr   r   	functoolsr   >openai.types.responses.response_format_text_json_schema_configr   0vllm.entrypoints.openai.chat_completion.protocolr   'vllm.entrypoints.openai.engine.protocolr   r   *vllm.entrypoints.openai.responses.protocolr	   r
   vllm.loggerr   vllm.sampling_paramsr   vllm.tokenizersr   vllm.tool_parsers.utilsr   vllm.utils.collection_utilsr   vllm.utils.import_utilsr   r?   rT   r   rF   r   r   r   r   <module>   s"   X