o
    پi                     @   s&  d dl mZmZ d dlmZ d dlmZmZmZm	Z	m
Z
mZmZ d dlZd dlZd dlmZ d dlmZmZ deded	efd
dZdeded	eeef fddZded	efddZdee d	efddZded	efddZdeeef d	e
e fddZdee deee	d f d	e
e fddZdS )    )JSONDecodeErrorJSONDecoder)
WHITESPACE)AnyDictListLiteralOptionalTupleUnionN)Allow)Tool
ToolChoices1s2returnc                 C   sL   d}t t| t|}td|D ]}| | || kr!|| | 7 }q |S |S )N r   )minlenrange)r   r   prefix
min_lengthi r   R/home/ubuntu/.local/lib/python3.10/site-packages/sglang/srt/function_call/utils.py_find_common_prefix   s   r   	input_strflagsc              
   C   s   zt | |t| fW S  ttfyE } z,t|dt|}d|v s%d|v r@t| d	 }t
 | |\}}||fW  Y d}~S  d}~ww )a  
    Parse incomplete or partial JSON strings commonly encountered during streaming.

    Args:
        input_str (str): The potentially incomplete JSON string to parse.
        flags (Allow): Bitwise flags controlling what types of partial data are allowed.
            Common flags include:
            - Allow.STR: Allow partial strings (e.g., '"hello wo' -> 'hello wo')
            - Allow.OBJ: Allow partial objects (e.g., '{"key":' -> {'key': None})
            - Allow.ARR: Allow partial arrays (e.g., '[1, 2,' -> [1, 2])
            - Allow.ALL: Allow all types of partial data

    Returns:
        Tuple[Any, int]: A tuple containing:
            - parsed_object: The Python object parsed from the JSON
            - consumed_length: Number of characters consumed from input_str
    msgz
Extra datazpop from empty listr   N)partial_json_parserloadsr   r   
IndexErrorgetattrstrr   matchendr   
raw_decode)r   r   er   startobjr%   r   r   r   _partial_json_loads   s   r*   c                 C   s&   zt |  W dS  ty   Y dS w )NTF)orjsonr    r   )r   r   r   r   _is_complete_json4   s   
r,   toolsc                 C   sn   i }| D ]0}|j jdu rq|j jdi }| D ]\}}||v r/|| |kr/td| d|||< qq|S )a  
    Get consolidated $defs from all tools, validating for conflicts.

    Args:
        tools: List of tools to process

    Returns:
        Dictionary of consolidated $defs from all tools

    Raises:
        ValueError: If conflicting $defs are found
    N$defszTool definition 'z/' has multiple schemas, which is not supported.)function
parametersgetitems
ValueError)r-   all_defstooldefsdef_name
def_schemar   r   r   _get_tool_schema_defs<   s   

	r9   r5   c                 C   s6   d| j jgd| j jr| j jndi ddddgdS )	Nstring)typeenumobject)r;   
properties)namer0   r?   r0   )r>   required)r/   r?   r0   )r5   r   r   r   _get_tool_schemaZ   s   
rA   schemac           	      C   s.  t | tsdS d| v r,| d }t |tr|S t |tr,|r,dd |D }|r*|d S dS d| v s4d| v rm| dp=| d}g }t |trm|D ]}t|}|rT|| qG|rmtt|d	krc|d S d|v ridS |d S d
| v rt | d
 tr| d
 s~dS t }| d
 D ]M}|du r|	d qt |t
r|	d qt |tr|	d qt |tr|	d qt |tr|	d qt |tr|	d qt |tr|	d qt|d	kr| S dS d| v rt | d tr| d }|D ]}t|}|r|dkr|  S qdS d| v rdS d| v rdS dS )a'  
    Infer the primary type of a parameter from JSON Schema.

    Supports complex JSON Schema structures including:
    - Direct type field (including type arrays)
    - anyOf/oneOf: parameter can be any of multiple types
    - enum: parameter must be one of enum values
    - allOf: parameter must satisfy all type definitions
    - properties: inferred as object type
    - items: inferred as array type

    Args:
        schema: JSON Schema definition

    Returns:
        Inferred type ('string', 'number', 'object', 'array', etc.) or None
    Nr;   c                 S   s   g | ]}|d kr|qS )nullr   ).0tr   r   r   
<listcomp>   s    z/infer_type_from_json_schema.<locals>.<listcomp>r   r:   anyOfoneOf   r<   rC   booleanintegernumberarrayr=   allOfr>   r2   )
isinstancedictr#   listr1   infer_type_from_json_schemaappendr   setaddboolintfloatpop)	rB   
type_valuenon_null_typesschemastypes
sub_schemainferred_type
enum_typesvaluer   r   r   rR   h   s|   












rR   tool_choicer@   c                 C   s   t |tr!|jj}| D ]}|jj|krdddt|d  S qdS |dkr?ddddd | D d	d
}t| }|r=||d< |S dS )z
    Get the JSON schema constraint for the specified tool choice.

    Args:
        tool_choice: The tool choice specification

    Returns:
        JSON schema dict, or None if no valid tools found
    rM   rI   )r;   minItemsmaxItemsr2   Nr@   r=   c                 S   s   g | ]}t |qS r   )rA   )rD   r5   r   r   r   rF      s    z.get_json_schema_constraint.<locals>.<listcomp>)r;   rG   )r;   rc   r2   r.   )rO   r   r/   r?   rA   r9   )r-   rb   fn_namer5   json_schemajson_schema_defsr   r   r   get_json_schema_constraint   s.   

rh   )jsonr   r   json.decoderr   typingr   r   r   r   r	   r
   r   r+   r    partial_json_parser.core.optionsr   &sglang.srt.entrypoints.openai.protocolr   r   r#   r   rW   r*   rV   r,   rP   r9   rA   rR   rh   r   r   r   r   <module>   s(    $g