
    
@gq                    p   d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZ d dlmZmZmZ d dlmZ ddlmZmZmZ dd	lmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ d
dl%m&Z& ddlm'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z= ddl>m?Z?m@Z@mAZA ddlBmCZCmDZD ddlEmFZF ddlGmHZI ddlJmKZL  G d dee4                   ZM G d dee4                   ZN G d dee4                   ZO G d d ee4                   ZP G d! d"ee4                   ZQ G d# d$          ZRd*d)ZSdS )+    )annotationsN)TracebackType)TYPE_CHECKINGAnyGenericCallableIterable	AwaitableAsyncIteratorcast)SelfIteratorassert_never)	from_json   )ParsedChoiceSnapshotParsedChatCompletionSnapshot#ParsedChatCompletionMessageSnapshot)
ChunkEventContentDoneEventRefusalDoneEventContentDeltaEventRefusalDeltaEventLogprobsContentDoneEventLogprobsRefusalDoneEventChatCompletionStreamEventLogprobsContentDeltaEventLogprobsRefusalDeltaEvent"FunctionToolCallArgumentsDoneEvent#FunctionToolCallArgumentsDeltaEvent   )accumulate_delta   )	NOT_GIVENIncExNotGiven)is_givenconsume_sync_iteratorconsume_async_iterator)
model_dump)buildconstruct_type   )ResponseFormatThas_parseable_inputmaybe_parse_contentparse_chat_completionget_input_tool_by_namesolve_response_format_tparse_function_tool_arguments)StreamAsyncStream)ChatCompletionChunkParsedChatCompletionChatCompletionToolParam)LengthFinishReasonErrorContentFilterFinishReasonError)ChoiceLogprobs)Choice)ResponseFormatc                  r    e Zd ZdZd d
Zd!dZd"dZd#dZd$dZd%dZ	d&dZ
d#dZed'd            Zd"dZdS )(ChatCompletionStream+  Wrapper over the Chat Completions streaming API that adds helpful
    events such as `content.done`, supports automatically parsing
    responses & tool calls and accumulates a `ChatCompletion` object
    from each individual chunk.

    https://platform.openai.com/docs/api-reference/streaming
    
raw_streamStream[ChatCompletionChunk]response_format6type[ResponseFormatT] | ResponseFormatParam | NotGiveninput_tools,Iterable[ChatCompletionToolParam] | NotGivenreturnNonec                   || _         |j        | _        |                                 | _        t          ||          | _        d S NrD   rF   _raw_streamresponse	_response
__stream__	_iteratorChatCompletionStreamState_stateselfrB   rD   rF   s       Z/var/www/piapp/venv/lib/python3.11/site-packages/openai/lib/streaming/chat/_completions.py__init__zChatCompletionStream.__init__8   @     &#,**/]hiii    *ChatCompletionStreamEvent[ResponseFormatT]c                4    | j                                         S N)rR   __next__rV   s    rW   r^   zChatCompletionStream.__next__D   s    ~&&(((rZ   4Iterator[ChatCompletionStreamEvent[ResponseFormatT]]c              #  &   K   | j         D ]}|V  d S r]   rR   rV   items     rW   __iter__zChatCompletionStream.__iter__G   s,      N 	 	DJJJJ	 	rZ   r   c                    | S r]    r_   s    rW   	__enter__zChatCompletionStream.__enter__K   s    rZ   exc_typetype[BaseException] | NoneexcBaseException | Noneexc_tbTracebackType | Nonec                .    |                                   d S r]   closerV   ri   rk   rm   s       rW   __exit__zChatCompletionStream.__exit__N   s     	

rZ   c                8    | j                                          dS z
        Close the response and release the connection.

        Automatically called if the response body is read to completion.
        N)rP   rq   r_   s    rW   rq   zChatCompletionStream.closeV   s     	rZ   %ParsedChatCompletion[ResponseFormatT]c                \    |                                   | j                                        S )V  Waits until the stream has been read to completion and returns
        the accumulated `ParsedChatCompletion` object.

        If you passed a class type to `.stream()`, the `completion.choices[0].message.parsed`
        property will be the content deserialised into that class, if there was any content returned
        by the API.
        
until_donerT   get_final_completionr_   s    rW   r{   z)ChatCompletionStream.get_final_completion^   s(     	{//111rZ   c                $    t          |            | S )*Blocks until the stream has been consumed.)r(   r_   s    rW   rz   zChatCompletionStream.until_donei   s    d###rZ   r   c                    | j         j        S r]   rT   current_completion_snapshotr_   s    rW   r   z0ChatCompletionStream.current_completion_snapshotn       {66rZ   c              #  d   K   | j         D ]%}| j                            |          }|D ]}|V  &d S r]   rN   rT   handle_chunkrV   	sse_eventevents_to_fireevents       rW   rQ   zChatCompletionStream.__stream__r   sV      ) 	 	I![55i@@N'  	 	rZ   N)rB   rC   rD   rE   rF   rG   rH   rI   rH   r[   )rH   r`   rH   r   ri   rj   rk   rl   rm   rn   rH   rI   rH   rI   rH   rv   rH   r   )__name__
__module____qualname____doc__rX   r^   re   rh   rs   rq   r{   rz   propertyr   rQ   rg   rZ   rW   r@   r@   /   s         
j 
j 
j 
j) ) ) )            	2 	2 	2 	2   
 7 7 7 X7     rZ   r@   c                  *    e Zd ZdZdd
ZddZddZdS )ChatCompletionStreamManageraK  Context manager over a `ChatCompletionStream` that is returned by `.stream()`.

    This context manager ensures the response cannot be leaked if you don't read
    the stream to completion.

    Usage:
    ```py
    with client.beta.chat.completions.stream(...) as stream:
        for event in stream:
            ...
    ```
    api_request)Callable[[], Stream[ChatCompletionChunk]]rD   rE   rF   rG   rH   rI   c               >    d | _         || _        || _        || _        d S r]   )$_ChatCompletionStreamManager__stream)_ChatCompletionStreamManager__api_request-_ChatCompletionStreamManager__response_format)_ChatCompletionStreamManager__input_toolsrV   r   rD   rF   s       rW   rX   z$ChatCompletionStreamManager.__init__   s+     GK(!0(rZ   %ChatCompletionStream[ResponseFormatT]c                z    |                                  }t          || j        | j                  | _        | j        S N)rB   rD   rF   )r   r@   r   r   r   rV   rB   s     rW   rh   z%ChatCompletionStreamManager.__enter__   sB    ''))
,! 2*
 
 
 }rZ   ri   rj   rk   rl   rm   rn   c                J    | j         | j                                          d S d S r]   )r   rq   rr   s       rW   rs   z$ChatCompletionStreamManager.__exit__   s.     =$M!!!!! %$rZ   N)r   r   rD   rE   rF   rG   rH   rI   )rH   r   r   )r   r   r   r   rX   rh   rs   rg   rZ   rW   r   r   y   sZ         
) 
) 
) 
)	 	 	 	" " " " " "rZ   r   c                  r    e Zd ZdZd d
Zd!dZd"dZd#dZd$dZd%dZ	d&dZ
d#dZed'd            Zd"dZdS )(AsyncChatCompletionStreamrA   rB    AsyncStream[ChatCompletionChunk]rD   rE   rF   rG   rH   rI   c                   || _         |j        | _        |                                 | _        t          ||          | _        d S rK   rM   rU   s       rW   rX   z"AsyncChatCompletionStream.__init__   rY   rZ   r[   c                D   K   | j                                          d {V S r]   )rR   	__anext__r_   s    rW   r   z#AsyncChatCompletionStream.__anext__   s,      ^--/////////rZ   9AsyncIterator[ChatCompletionStreamEvent[ResponseFormatT]]c               4   K   | j         2 3 d {V }|W V  6 d S r]   rb   rc   s     rW   	__aiter__z#AsyncChatCompletionStream.__aiter__   sF      . 	 	 	 	 	 	 	$JJJJJ )..s   r   c                
   K   | S r]   rg   r_   s    rW   
__aenter__z$AsyncChatCompletionStream.__aenter__   s      rZ   ri   rj   rk   rl   rm   rn   c                >   K   |                                   d {V  d S r]   rp   rr   s       rW   	__aexit__z#AsyncChatCompletionStream.__aexit__   s.       jjllrZ   c                H   K   | j                                          d{V  dS ru   )rP   acloser_   s    rW   rq   zAsyncChatCompletionStream.close   s4       n##%%%%%%%%%%%rZ   rv   c                l   K   |                                   d{V  | j                                        S )rx   Nry   r_   s    rW   r{   z.AsyncChatCompletionStream.get_final_completion   s>       oo{//111rZ   c                4   K   t          |            d{V  | S )r}   N)r)   r_   s    rW   rz   z$AsyncChatCompletionStream.until_done   s+      $T*********rZ   r   c                    | j         j        S r]   r   r_   s    rW   r   z5AsyncChatCompletionStream.current_completion_snapshot   r   rZ   c               r   K   | j         2 3 d {V }| j                            |          }|D ]}|W V  ,6 d S r]   r   r   s       rW   rQ   z$AsyncChatCompletionStream.__stream__   sr      #/ 	 	 	 	 	 	 	)![55i@@N'    0//s   6N)rB   r   rD   rE   rF   rG   rH   rI   r   )rH   r   r   r   r   r   r   )r   r   r   r   rX   r   r   r   r   rq   r{   rz   r   r   rQ   rg   rZ   rW   r   r      s         
j 
j 
j 
j0 0 0 0         & & & &	2 	2 	2 	2   
 7 7 7 X7     rZ   r   c                  *    e Zd ZdZdd
ZddZddZdS ) AsyncChatCompletionStreamManageraV  Context manager over a `AsyncChatCompletionStream` that is returned by `.stream()`.

    This context manager ensures the response cannot be leaked if you don't read
    the stream to completion.

    Usage:
    ```py
    async with client.beta.chat.completions.stream(...) as stream:
        for event in stream:
            ...
    ```
    r   +Awaitable[AsyncStream[ChatCompletionChunk]]rD   rE   rF   rG   rH   rI   c               >    d | _         || _        || _        || _        d S r]   ))_AsyncChatCompletionStreamManager__stream._AsyncChatCompletionStreamManager__api_request2_AsyncChatCompletionStreamManager__response_format._AsyncChatCompletionStreamManager__input_toolsr   s       rW   rX   z)AsyncChatCompletionStreamManager.__init__   s+     LP(!0(rZ   *AsyncChatCompletionStream[ResponseFormatT]c                p   K   | j          d {V }t          || j        | j                  | _        | j        S r   )r   r   r   r   r   r   s     rW   r   z+AsyncChatCompletionStreamManager.__aenter__  sO      -------
1! 2*
 
 
 }rZ   ri   rj   rk   rl   rm   rn   c                Z   K   | j         !| j                                          d {V  d S d S r]   )r   rq   rr   s       rW   r   z*AsyncChatCompletionStreamManager.__aexit__  sD       =$-%%''''''''''' %$rZ   N)r   r   rD   rE   rF   rG   rH   rI   )rH   r   r   )r   r   r   r   rX   r   r   rg   rZ   rW   r   r      sZ         
) 
) 
) 
)	 	 	 	( ( ( ( ( (rZ   r   c                  V    e Zd ZddZdd	Zedd            ZddZddZddZ	ddZ
dS )rS   rF   rG   rD   rE   rH   rI   c                   d | _         g | _        t          |          rd |D             ng | _        || _        t          j        |          r|nt          | _        d S )Nc                    g | ]}|S rg   rg   ).0tools     rW   
<listcomp>z6ChatCompletionStreamState.__init__.<locals>.<listcomp>+  s    :::dT:::rZ   )	7_ChatCompletionStreamState__current_completion_snapshot/_ChatCompletionStreamState__choice_event_statesr'   _input_tools_response_formatinspectisclassr$   _rich_response_format)rV   rF   rD   s      rW   rX   z"ChatCompletionStreamState.__init__"  sk     SW*=?">F{>S>S[::k::::Y[ /IPYhIiIi6xooox"""rZ   rv   c                D    t          | j        | j        | j                  S )N)chat_completionrD   rF   )r1   r   r   r   r_   s    rW   r{   z.ChatCompletionStreamState.get_final_completion/  s+    $ < 6)
 
 
 	
rZ   r   c                "    | j         J | j         S r]   )r   r_   s    rW   r   z5ChatCompletionStreamState.current_completion_snapshot6  s    1===11rZ   chunkr7   0list[ChatCompletionStreamEvent[ResponseFormatT]]c                n    |                      |          | _        |                     || j                  S )zOAccumulate a new chunk into the snapshot and returns a list of events to yield.)r   completion_snapshot)_accumulate_chunkr   _build_events)rV   r   s     rW   r   z&ChatCompletionStreamState.handle_chunk;  s>    -1-C-CE-J-J*!! $ B " 
 
 	
rZ   choiceChoiceChunkChoiceEventStatec                    	 | j         |j                 S # t          $ r4 t          | j                  }| j                             |           |cY S w xY w)N)rF   )r   index
IndexErrorr   r   append)rV   r   choice_states      rW   _get_choice_statez+ChatCompletionStreamState._get_choice_stateD  sh    	 -fl;; 	  	  	 +8IJJJL&--l;;;	 s    ;AAc                	   | j         }|t          |          S |j        D ]F}	 |j        |j                 }|j        j        pg }t          t          t          t          t          t          dt          |j        t          t          dd t          |j        j        pg           D             d                              t          d|j                                                                                |_        t          |          D ]^\  }}|j        j        pg |         }|j        dk    r$|j        dk    sJ |j        j        |j        _        Ht$          rt'          |           _n# t(          $ ry t          t*          t          t*          i |
                    ddh	          d
|j                                        i                    }|j                            |           Y nw xY w|j        r[|j        |_        t1          | j        | j                  r4|j        dk    rt7          |          |j        dk    rt9                      |j        j        rS|j        j        sGt?          | j                   r3tC          tE          |j        j        d          d          |j        _#        |j        j        pg D ]}	|j        j        pg |	j                 }
|
j        dk    rtI          | j        |
j        j%                  }|rh|&                    di           &                    d          r?|
j        j'        r3tC          tE          |
j        j'        d          d          |
j        _        t$          rt'          |
           |j(        |j(        2tS          tT          |j(        j        |j(        j                  |_(        |j(        j        rA|j(        j        g |j(        _        |j(        j        +                    |j(        j                   |j(        j        rA|j(        j        g |j(        _        |j(        j        +                    |j(        j                   H|j,        |_,        |j-        |_-        |S )Nzdict[object, object]Tc                "    i | ]\  }}|d ddiiS )functionparsed_argumentsTrg   )r   idx_s      rW   
<dictcomp>z?ChatCompletionStreamState._accumulate_chunk.<locals>.<dictcomp>h  s:     ;. ;. ;.4:C 14jCUW[B\5];. ;. ;.rZ   )parsed
tool_calls)excludetype_valuer   deltaexclude_unsetr   messagerL   length)
completioncontent_filterzutf-8)partial_mode)rF   namestrict)contentrefusal).r   $_convert_initial_chunk_into_snapshotchoicesr   r   r   r   r   r,   r"   r*   r%   	enumerater   to_dicttyper   r   r   r   r   r   r   finish_reasonr/   r   r   r:   r;   r   r   r'   r   r   bytesr   r2   r   get	argumentslogprobsr+   r<   extendusagesystem_fingerprint)rV   r   r   r   choice_snapshotprevious_tool_calls
tool_index	prev_toolnew_tooltool_call_chunktool_call_snapshot
input_tools               rW   r   z+ChatCompletionStreamState._accumulate_chunkL  s   "@&7>>>m v	Y v	YF7D"5"=fl"K&5&=&H&NB#*.7"A.  6 *$3$; -1(-6:;. ;.>GH_HjHpnp>q>q;. ;. ;.)* )*
-& 
-&!" !" !" ( !!79M9M9O9OPP+   + +'@ .77J-K-K 0 0)J	 / 7 B Hb*UH ~33'}
::::=F=O=`)::& 0$Y///0  D D D"&("2$//dWI/VV%v|';';'='=   	# 	# $+22?CCCCCD # 
?060D-&t7LZ^Zklll ?+x77 6ATUUUU+/???<>>>  '/'/7 T788
 2;/197CC!%2 2 2'.
 $*<#:#@b 5 5&5&=&H&NBP_Pe%f"%*j88!7$($5<N<W<\" " "J
 #&NN:r::>>xHH /7A
 HQ!"4"="GQQ)-H H H*3D # 5 !3444*"+3/4& & 7 & 70 0 0O,, . Y*3;C?AO4<'08??@WXXX. Y*3;C?AO4<'08??@WXXX$)K!161I.""s   E
E//B G21G2r   c                  g }|                     t          t          d||                     |j        D ]}|                     |          }|j        |j                 }|j        j        V|j        j        J|                     t          t          d|j        j        |j        j        |j        j
                             |j        j        K|j        j        ?|                     t          t          d|j        j        |j        j                             |j        j        r|j        j        }|J |j        j        D ]}||j                 }	|	j        dk    rg|j        J |                     t          t           d|	j        j        |j        |	j        j        |	j        j        |j        j        pd	
                     t(          rt+          |	           |j        |j        |j        j        rK|j        j        r?|                     t          t.          d|j        j        |j        j                             |j        j        rK|j        j        r?|                     t          t0          d|j        j        |j        j                             |                    |                    ||| j                             |S )Nr   )r   r   snapshotzcontent.delta)r   r   r  r   zrefusal.delta)r   r   r  r   z#tool_calls.function.arguments.delta )r   r   r   r  r   arguments_deltazlogprobs.content.delta)r   r   r  zlogprobs.refusal.delta)r   r   r  )choice_chunkr  rD   )r   r+   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r  r   r   r   r  r   r   r  get_done_eventsr   )
rV   r   r   r   r   r   r  r   tool_call_delta	tool_calls
             rW   r   z'ChatCompletionStreamState._build_events  s    LN*7%BUVVV	
 	
 	
 m K	 K	F11&99L19&,GO|#/O4K4S4_%%),$l2!0!8!@.6=     |#/O4K4S4_%%),$l2!0!8!@	     |& 0,4?
!---'-|'> 0 0O *?+@ AI ~33.7CCC&--! C%J%.%7%<&5&;*3*<*F1:1C1T0?0H0R0XVX  
 
 
 
 ' 0$Y///*/G/S?* /G/O "))5!9$*O$;%4%=%E	     ?* /G/O "))5!9$*O$;%4%=%E	     !!,,!'$3$($9 -      rZ   N)rF   rG   rD   rE   rH   rI   r   r   )r   r7   rH   r   )r   r   rH   r   r   r7   rH   r   )r   r7   r   r   rH   r   )r   r   r   rX   r{   r   r   r   r   r   r   rg   rZ   rW   rS   rS   !  s        y y y y
 
 
 
 2 2 2 X2
 
 
 
       A# A# A# A#FY Y Y Y Y YrZ   rS   c                  .    e Zd ZddZddZddZddZdS )r   rF   list[ChatCompletionToolParam]rH   rI   c                   || _         d| _        d| _        d| _        d| _        t                      | _        d | _        d S )NF)r   _content_done_refusal_done_logprobs_content_done_logprobs_refusal_doneset_done_tool_calls*_ChoiceEventState__current_tool_call_index)rV   rF   s     rW   rX   zChoiceEventState.__init__,  sD    '""&+#&+#*-%%59&&&rZ   r  r   r  r   rD   rE   r   c                  g }|j         r\|                    |                     ||                     | j        +| j        | j        vr|                     ||| j                   |j        j        pg D ]l}| j        |j        k    rN|                    |                     ||                     | j        |                     ||| j                   |j        | _        m|S )N)r  rD   )r   r  r  )	r   r  _content_done_eventsr   r  _add_tool_done_eventr   r   r   )rV   r  r  rD   r   r  s         rW   r  z ChoiceEventState.get_done_events6  s.    LN( 	!!))/[j)kk  
 .:2$:OOO))#1$3#= *    &+6<" 	= 	=I-@@%%--o_n-oo   1=--'5(7#'#A .    .7_D**rZ   c               D   g }|j         j        r| j        sd| _        t          ||j                   }||j         _        |                    t          t          dt          t          t                    t          |                             d|j         j        |                     |j         j        B| j        s;d| _        |                    t          t          d|j         j                             |j        N|j        j        B| j        s;d| _        |                    t          t           d|j        j        	                     |j        N|j        j        B| j        s;d| _        |                    t          t$          d
|j        j                             |S )NT)rD   r   z'type[ContentDoneEvent[ResponseFormatT]]zcontent.done)r   r   r   zrefusal.done)r   r   zlogprobs.content.done)r   r   zlogprobs.refusal.done)r   r   r  r0   r   r   r+   r   r   r   r3   r   r  r   r  r  r   r  r   )rV   r  rD   r   r   s        rW   r"  z%ChoiceEventState._content_done_events_  s    LN"* 	43E 	!%D( /'/  F .4O#*!! AS"2334KO4\4\]  (+3;!     "*6t?Q6!%D!!&^_E\Edeee  
 $0(0</ = +/D'!!.5LVeVnVvwww  
 $0(0</ = +/D'!!.5LVeVnVvwww   rZ   r   r  intc          
        || j         v rd S | j                             |           |j        j        J |j        j        |         }|j        dk    rjt          | j        |j                  }||j        _        |	                    t          t          d||j        j        |j        j        |                     d S t          rt          |           d S d S )Nr   )rF   r   z"tool_calls.function.arguments.done)r   r   r   r  r   )r  addr   r   r   r4   r   r   r   r   r+   r   r   r  r   r   )rV   r   r  r  r  r   s         rW   r#  z%ChoiceEventState._add_tool_done_event  s
    ...F!!*---&1===,4?
K"j00< -8J8S      <L'8!!6=$+4909C%5  	 	 	 	 	  	-+,,,,,	- 	-rZ   N)rF   r  rH   rI   )r  r   r  r   rD   rE   rH   r   )r  r   rD   rE   rH   r   )r   r   r  r   r  r%  rH   rI   )r   r   r   rX   r  r"  r#  rg   rZ   rW   r   r   +  sf        : : : :' ' ' 'R> > > >@$- $- $- $- $- $-rZ   r   r   r7   rH   r   c           	     F   |                                  }t          d|d                   }| j        D ]?}i |                    ddh          d|j                                         i||j        <   @t          t          t          t          dd i|dd	i
                    S )Nzlist[object]r   Tr   r   r   r  objectzchat.completionr   )r   r   r   r*   r   r   r   r,   )r   datar   r   s       rW   r   r     s    ==??D>4	?33G- 
 
!
dWIFF!
v|++--!
 !

 $.$d + 	
 	
 	

 
 
rZ   r  )T
__future__r   r   typesr   typingr   r   r   r   r	   r
   r   r   typing_extensionsr   r   r   jiterr   _typesr   r   r   _eventsr   r   r   r   r   r   r   r   r   r   r   r    _deltasr"   r$   r%   r&   _utilsr'   r(   r)   _compatr*   _modelsr+   r,   _parsingr.   r/   r0   r1   r2   r3   r4   
_streamingr5   r6   
types.chatr7   r8   r9   _exceptionsr:   r;   types.chat.chat_completionr<    types.chat.chat_completion_chunkr=   r   #types.chat.completion_create_paramsr>   ResponseFormatParamr@   r   r   r   rS   r   r   rg   rZ   rW   <module>r>     s   " " " " " "        b b b b b b b b b b b b b b b b b b b b : : : : : : : : : :       k k k k k k k k k k                            ' & & & & & 1 1 1 1 1 1 1 1 1 1 N N N N N N N N N N " " " " " " - - - - - - - -                  / . . . . . . . ] ] ] ] ] ] ] ] ] ] S S S S S S S S 9 9 9 9 9 9 F F F F F F Y Y Y Y Y YG G G G G7?3 G G GT," ," ," ," ,"'/": ," ," ,"^G G G G G 8 G G GT,( ,( ,( ,( ,(w'? ,( ,( ,(^G G G G G 8 G G GTX- X- X- X- X- X- X- X-v     rZ   