o
    ưi
                     @   s*   d Z ddlmZmZmZ G dd dZdS )zy
Streaming utilities for ChatGPT provider.

Normalizes non-spec-compliant tool_call chunks from the ChatGPT backend API.
    )AnyDictOptionalc                   @   sb   e Zd ZdZdefddZdedefddZd	d
 Zdd Z	dd Z
dd ZdedefddZdS )ChatGPTToolCallNormalizera  
    Wraps a streaming response and fixes tool_call index/dedup issues.

    The ChatGPT backend API (chatgpt.com/backend-api) sends non-spec-compliant
    streaming tool call chunks:
    1. `index` is always 0, even for multiple parallel tool calls
    2. `id` and `name` get repeated in "closing" chunks that shouldn't exist

    This wrapper normalizes the stream to match the OpenAI spec before yielding
    chunks to the consumer.
    streamc                 C   s   || _ i | _d| _d | _d S )Nr   )_stream	_seen_ids_next_index_last_id)selfr    r   `/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/chatgpt/chat/streaming_utils.py__init__   s   
z"ChatGPTToolCallNormalizer.__init__namereturnc                 C   s   t | j|S N)getattrr   )r   r   r   r   r   __getattr__   s   z%ChatGPTToolCallNormalizer.__getattr__c                 C      | S r   r   r   r   r   r   __iter__       z"ChatGPTToolCallNormalizer.__iter__c                 C   r   r   r   r   r   r   r   	__aiter__#   r   z#ChatGPTToolCallNormalizer.__aiter__c                 C   s$   	 t | j}| |}|d ur|S qr   )nextr   
_normalizer   chunkresultr   r   r   __next__&   s   

z"ChatGPTToolCallNormalizer.__next__c                    s,   	 | j  I d H }| |}|d ur|S qr   )r   	__anext__r   r   r   r   r   r   -   s   
z#ChatGPTToolCallNormalizer.__anext__r   c                 C   s   |j s|S |j d j}|du s|js|S g }|jD ]@}|jr@|j| jvr@| j| j|j< | j|_|j| _|  jd7  _|| q|jrJ|j| jv rJq| jrT| j| j |_|| q|s^dS ||_|S )zCFix tool_calls in the chunk. Returns None to skip duplicate chunks.r   N   )	choicesdeltaZ
tool_callsidr   r	   indexr
   append)r   r   r"   
normalizedZtcr   r   r   r   4   s,   
z$ChatGPTToolCallNormalizer._normalizeN)__name__
__module____qualname____doc__r   r   strr   r   r   r   r   r   r   r   r   r   r   
   s    r   N)r*   typingr   r   r   r   r   r   r   r   <module>   s    