
    Oj                       U d dl mZ d dlZd dlZd dl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 d dlZd dlmZ ddlmZmZmZmZ dd	lmZmZmZmZ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*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC e	rd dlDmEZF d dlGmEZH ddlImJZJmKZK ddgZL ej                  eN      ZOdePd<    G d de'      ZQ G d  de(      ZR G d! d"      ZS G d# d$      ZT G d% d&      ZU G d' d(      ZV G d) d*      ZW G d+ d,eW      ZX G d- d.eW      ZY G d/ d0eW      ZZ G d1 d2eW      Z[ G d3 d4eW      Z\ G d5 d6eW      Z] G d7 d8eW      Z^ G d9 d:      Z_ G d; d<e_      Z` G d= d>e_      Za G d? d@e_      Zb G dA dBe_      Zc G dC dDe_      Zd G dE dFe_      Ze G dG dHe_      Zfy)I    )annotationsN)TracebackType)TYPE_CHECKINGAnyUnionCallableIteratorOptional	Awaitablecast)AsyncIterator)	BaseModel   )OmitQueryHeadersomit)is_givenpath_templatemaybe_transformstrip_not_givenasync_maybe_transform)cached_property)FinalRequestOptionsconstruct_type_unchecked)SyncAPIResourceAsyncAPIResource)OpenAIErrorWebSocketConnectionClosedError)	SendQueue)_merge_mappings)EventHandlerRegistry)
ErrorEvent)ReconnectingEventReconnectingOverridesis_recoverable_close)ConnectClientEvent)ConnectServerEvent)WebSocketConnectionOptions)ConnectClientEventParam)SessionUpdateConfigParam)ResponseInputItemParam)ClientConnection)OpenAIAsyncOpenAISidebandAsyncSidebandzlogging.Loggerlogc            
      T    e Zd Zei i i dddddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)	r0   N         ?       @   	graceful_closeextra_queryextra_headerswebsocket_connection_optionson_reconnectingmax_retriesinitial_delay	max_delaymax_queue_sizec       
        B    t        | j                  |||||||	|
||      S zVAttach to an existing Live session.

        Do not send session.start again.
        )clientr:   r;   r<   r=   r>   r?   r@   rA   
session_idr9   )SidebandConnectionManager_clientselfrE   r9   r:   r;   r<   r=   r>   r?   r@   rA   s              u/var/www/origus_pro_usr/data/www/origus.pro/core/.venv/lib/python3.12/site-packages/openai/resources/live/sideband.pyconnectzSideband.connect.   s6    $ )<<#')E+#')!)
 	
    )rE   strr9   bool | Omitr:   r   r;   r   r<   r)   r=   BCallable[[ReconnectingEvent], ReconnectingOverrides | None] | Noner>   intr?   floatr@   rQ   rA   rP   returnrF   __name__
__module____qualname__r   rK    rL   rJ   r0   r0   -   s    
 '+!#CE^b"'
 
 $	

 
 
 'A
 \
 
 
 
 
 
#
rL   c            
      T    e Zd Zei i i dddddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)	r1   Nr4   r5   r6   r7   r8   c       
        B    t        | j                  |||||||	|
||      S rC   )AsyncSidebandConnectionManagerrG   rH   s              rJ   rK   zAsyncSideband.connectP   s6    $ .<<#')E+#')!)
 	
rL   )rE   rM   r9   rN   r:   r   r;   r   r<   r)   r=   rO   r>   rP   r?   rQ   r@   rQ   rA   rP   rR   rZ   rS   rW   rL   rJ   r1   r1   O   s    
 '+!#CE^b"'
 
 $	

 
 
 'A
 \
 
 
 
 
 
(
rL   c            	          e Zd ZU dZded<   ded<   ded<   ddd	d
di i dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZd dZd!dZd"dZ	d#dZ
dddd$dZd%dZd&dZd'dZ	 d(	 	 	 	 	 d)dZd*dZ	 d(	 	 	 	 	 d)dZd'dZy)+AsyncSidebandConnection:Represents a live WebSocket connection to the Sideband APIAsyncSidebandSessionResourcesessionAsyncSidebandResponseResourceresponseAsyncWebSocketConnection_connectionNr4   r5   r6   make_wsr=   r>   r?   r@   r:   r;   
send_queuec               &   || _         || _        || _        || _        d| _        || _        || _        || _        || _        d| _	        d| _
        |	xs
 t               | _        t        d      | _        t        |       | _        t#        |       | _        y )Nr   Fuse_lock)rc   _make_ws_on_reconnecting_max_retries_reconnect_attempt_initial_delay
_max_delay_extra_query_extra_headers_intentionally_closed_is_reconnectingr    _send_queuer"   _event_handler_registryr^   r_   r`   ra   
rI   
connectionre   r=   r>   r?   r@   r:   r;   rf   s
             rJ   __init__z AsyncSidebandConnection.__init__y   s     & /'"#+#'+%*" %%4';U'K$3D95d;rL   c                 K   ddl m}m} 	 	 | j                          d{    7 # |$ r Y y|$ rO}| j	                  |       d{  7  s+| j
                  j                         }|rt        d|      | Y d}~Xd}~ww xY wwzq
        An infinite-iterator that will continue to yield events until
        the connection is closed.
        r   )ConnectionClosedOKConnectionClosedErrorNz0WebSocket connection closed with unsent messages)unsent_messageswebsockets.exceptionsr{   r|   recv
_reconnectrt   drainr   rI   r{   r|   excunsents        rJ   	__aiter__z!AsyncSidebandConnection.__aiter__   s     
 	T IIK'' '% ( !__S111!--335F<N,2  ##  2sL   
B+ )+ B+ BBBB 
A0B ;B BBc                (  K   | j                  | j                          d{         }t        t        t        |      t
              rt        d|      j                  d      nt        |dd      }t        |t              r|r|dk7  rd| _	        |S 7 nw)
        Receive the next message from the connection and parses it into a `ConnectServerEvent` object.

        Canceling this method is safe. There's no risk of losing data.
        Ndict[str, object]typeerrorr   
parse_event
recv_bytes
isinstancer   objectdictgetgetattrrM   rm   rI   event
event_types      rJ   r   zAsyncSidebandConnection.recv   s        t'8!89 $vu-t4 $e,008- 	 j#&:*:O&'D# "9s   BBA/Bc                  K   | j                   j                  d       d{   }t        j                  dt	        |             | j
                  ra	 t        j                  |      }t        |t              rt        d|      j                  d      nd}t        |t              r|r|dk7  rd| _        |S 7 # t        t        f$ r |cY S w xY ww)	  Receive the next message from the connection as raw bytes.

        Canceling this method is safe. There's no risk of losing data.

        If you want to parse the message into a `ConnectServerEvent` object like `.recv()` does,
        then you can call `.parse_event(data)`.
        FdecodeN$Received WebSocket message: %i bytesr   r   r   r   rc   r   r2   debuglenrm   jsonloads
ValueErrorRecursionErrorr   r   r   r   rM   rI   message
event_datar   s       rJ   r   z"AsyncSidebandConnection.recv_bytes   s      ((--U-;;		8#g,G""%)ZZ%8
 OYYceiNj1:>BB6JptJ*c*zjG>S*+' < / s4    CB5/CB7 (AC7CC
CCc                  K   t        |t              r|j                  ddd      n*t        j                  t        |t               d {         }| j                  r| j                  j                  |       y 	 | j                  j                  |       d {    y 7 U7 # t        $ r | j                  j                  |        w xY wwNTuse_api_namesexclude_defaultsexclude_unset)r   r   to_jsonr   dumpsr   r*   rs   rt   enqueuerc   send	ExceptionrI   r   datas      rJ   r   zAsyncSidebandConnection.send   s      %+ MMtSWMX"7?V"WWX 	
   $$T*	""''--- X . 	$$T*	s<   AC	B
0C;B# B!B# C!B# #&C		Cc                   K   | j                   r?t        |t              r|n|j                  d      }| j                  j                  |       y | j                  j                  |       d {    y 7 wNutf-8rs   r   rM   r   rt   r   rc   r   rI   r   raws      rJ   send_rawz AsyncSidebandConnection.send_raw   sY       $T3/$T[[5IC$$S)##D)))s   A*A4,A2-A4   codereasonc               h   K   d| _         | j                  j                  ||       d {    y 7 wNTr   rr   rc   closerI   r   r   s      rJ   r   zAsyncSidebandConnection.close   s-     %)"$$$v$>>>s   (202c           
         t        t        t        t        j                  |      t        t
        t                          S z
        Converts a raw `str` or `bytes` message into a `ConnectServerEvent` object.

        This is helpful if you're using `.recv_bytes()`.
        )valuetype_r   r(   r   r   r   r   rI   r   s     rJ   r   z#AsyncSidebandConnection.parse_event   1      8tzz$?OW[\_asWt u
 	
rL   c           	       K   ddl }| j                  | j                  yddlm} d}t        ||      r"|j                  |j                  j                  }t        |      syd| _	        t        | j                  dz   | j                  dz         D ]  }|| _        t        | j                  d|dz
  z  z  | j                        }d	t!        j                          d
z  z   }||z  }t#        || j                  ||| j$                  | j&                        }		 | j                  |	      }
|
|
j+                  d      r	d| _	         y|
d|
v r
|
d   | _        d|
v r
|
d   | _        t,        j/                  d|| j                  |       |j1                  |       d{    | j2                  r	d| _	         y	 | j                  | j$                  | j&                         d{   | _        t,        j/                  d       d| _	        | j7                          d{     y d| _	        y# t(        $ r d| _	        Y  yw xY w7 7 a7 *# t(        $ r Y w xY ww)Attempt to reconnect after a connection failure.

        Returns ``True`` if a new connection was established, ``False`` if the
        caller should re-raise the original exception.
        r   NFr|     T            ?      ?attemptmax_attemptsdelay
close_coder:   r;   abortr:   r;   ?Reconnecting to WebSocket API (attempt %d/%d) after %.1fs delayReconnected to WebSocket API)asynciork   rj   r   r|   r   rcvdr   r&   rs   rangerm   rl   minrn   ro   randomr$   rp   rq   r   r   r2   infosleeprr   rc   _flush_send_queue)rI   r   r   r|   r   r   
base_delayjitterr   r   results              rJ   r   z"AsyncSidebandConnection._reconnect   sM     	  (DMM,A?
c01chh6JJ#J/ $T44q8$:K:Ka:OP 2	G&-D#T00A'A+4FGYJFMMOd22F'E%!..% --"11E..u5
 !fjj&9(-%! F*(.}(=D%"f,*0*AD'HHQ!!	 --&&&))(-%)-t7H7H$J]J])^#^ 78(-%,,...a2	h !&I  (-%( ' $_ / s   DIH #A0IH7I.)H=H98H=H;H=I H40I3H44I9H=;H==	I
I	I

Ic                    K   d fd}	  j                   j                  |       d{    y7 # t        $ r t        j	                  d       Y yw xY ww)5Send all queued messages over the current connection.c                X   K   j                   j                  |        d {    y 7 wNrc   r   r   rI   s    rJ   _sendz8AsyncSidebandConnection._flush_send_queue.<locals>._sendH  s!     ""''---s   *(*N*Failed to flush send queue after reconnect)r   rM   rR   None)rt   flush_asyncr   r2   warning)rI   r   s   ` rJ   r   z)AsyncSidebandConnection._flush_send_queueE  sI     	.	F""..u555 	FKKDE	Fs1   A1 /1 A1 AAAAc                X     | j                   j                  |        S d fd}|S )a-  Adds the handler to the end of the handlers list for the given event type.

        No checks are made to see if the handler has already been added. Multiple calls
        passing the same combination of event type and handler will result in the handler
        being added, and called, multiple times.

        Can be used as a method (returns ``self`` for chaining)::

            connection.on("session.started", my_handler)

        Or as a decorator::

            @connection.on("session.started")
            async def my_handler(event): ...
        c                @    j                   j                  |        | S r   ru   addfnr   rI   s    rJ   	decoratorz-AsyncSidebandConnection.on.<locals>.decoratorf      ((,,Z<IrL   r   Callable[..., Any]rR   r   r   rI   r   handlerr   s   ``  rJ   onzAsyncSidebandConnection.onP  3    $ ((,,ZAK	 rL   c                >    | j                   j                  ||       | S z-Remove a previously registered event handler.ru   removerI   r   r   s      rJ   offzAsyncSidebandConnection.offl      $$++J@rL   c                \     |  j                   j                  |d        S d fd}|S )bRegister a one-time event handler.

        Automatically removed after first invocation.
        Toncec                D    j                   j                  | d       | S NTr  r   r   s    rJ   r   z/AsyncSidebandConnection.once.<locals>.decorator|  #    ((,,Z$,GIrL   r   r   r   s   ``  rJ   r	  zAsyncSidebandConnection.onceq  8     ((,,Zt,LK	 rL   c                  K   ddl }| 2 3 d{   }|j                  }| j                  j                  |      }| j                  j                  d      }|dk(  r"|s |st	        |t
              rt        d|       |D ]&  } ||      }|j                  |      s| d{    ( |D ]&  } ||      }|j                  |      s| d{    ( 7 7 47 6 yw)al  Run the event loop, dispatching received events to registered handlers.

        Blocks until the connection is closed. This is the push-based
        alternative to iterating with ``async for event in connection``.

        If an ``"error"`` event arrives and no handler is registered for
        ``"error"`` or ``"event"``, an ``OpenAIError`` is raised.
        r   Nr   r   WebSocket error: )r   r   ru   get_handlersr   r#   r   iscoroutine)rI   r   r   r   specificgenericr   r   s           rJ   dispatch_eventsz'AsyncSidebandConnection.dispatch_events  s      	 	! 	!%J33@@LH22??HGW$XgeZ0%(9%&ABB# ! &&v. LL!
 # ! &&v. LL!	! !
 !#  sV   CCCCBCCC $CC
CCCCCC)rw   rb   re   zFCallable[[Query, Headers], Awaitable[AsyncWebSocketConnection]] | Noner=   rO   r>   rP   r?   rQ   r@   rQ   r:   r   r;   r   rf   SendQueue | NonerR   r   )rR   z!AsyncIterator[ConnectServerEvent]rR   r(   rR   bytesr   z,ConnectClientEvent | ConnectClientEventParamrR   r   r   zbytes | strrR   r   r   rP   r   rM   rR   r   r   zstr | bytesrR   r(   r   r   rR   boolrR   r   r   )r   rM   r   Callable[..., Any] | NonerR   zRUnion[AsyncSidebandConnection, Callable[[Callable[..., Any]], Callable[..., Any]]])r   rM   r   r   rR   r\   )rT   rU   rV   __doc____annotations__rx   r   r   r   r   r   r   r   r   r   r   r  r	  r  rW   rL   rJ   r\   r\   q   s%   D))++)) [_^b"!#'+<,< X	<
 \< < < < < < %< 
<<,$** *.R ?
KZ	F EI(A	[8 EI(A	["!rL   r\   c                      e Zd ZdZedddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZdd	Z	 d	 	 	 	 	 dd
ZddZ	 d	 	 	 	 	 ddZ	ddZ
e
ZddZddZ	 	 	 	 	 	 	 	 ddZy)rZ   a3  
    Context manager over a `AsyncSidebandConnection` that is returned by `live.sideband.connect()`

    This context manager ensures that the connection will be closed when it exits.

    ---

    Note that if your application doesn't work well with the context manager approach then you
    can call the `.enter()` method directly to initiate a connection.

    **Warning**: You must remember to close the connection with `.close()`.

    ```py
    connection = await client.live.sideband.connect(...).enter()
    # ...
    await connection.close()
    ```
    Nr4   r5   r6   r7   r9   r=   r>   r?   r@   rA   c                   || _         || _        || _        d | _        || _        || _        || _        || _        || _        |	| _	        |
| _
        t        |      | _        t        d      | _        y )N	max_bytesFrh   )'_AsyncSidebandConnectionManager__client+_AsyncSidebandConnectionManager__session_id/_AsyncSidebandConnectionManager__graceful_close+_AsyncSidebandConnectionManager__connection,_AsyncSidebandConnectionManager__extra_query._AsyncSidebandConnectionManager__extra_headers=_AsyncSidebandConnectionManager__websocket_connection_options0_AsyncSidebandConnectionManager__on_reconnecting,_AsyncSidebandConnectionManager__max_retries._AsyncSidebandConnectionManager__initial_delay*_AsyncSidebandConnectionManager__max_delayr    +_AsyncSidebandConnectionManager__send_queuer"   7_AsyncSidebandConnectionManager__event_handler_registryrI   rD   rE   r9   r:   r;   r<   r=   r>   r?   r@   rA   s               rJ   rx   z'AsyncSidebandConnectionManager.__init__  su     & .<@(,.J+!0(,$%?(<e(L%rL   c                    t        |t              r|j                  ddd      n"t        j                  t        |t                    }| j                  j                  |       yzQueue a message to be sent when the connection is established.

        This can be called before entering the context manager. Queued messages
        are automatically sent once the WebSocket connection opens.
        Tr   N)	r   r   r   r   r   r   r*   r3  r   r   s      rJ   r   z#AsyncSidebandConnectionManager.send  R     %+ MMtSWMXOE3JKL 	
 	!!$'rL   c                X     | j                   j                  |        S d fd}|S )zRegister an event handler before the connection is established.

        Handlers are transferred to the connection on enter. Supports the
        same method and decorator forms as ``AsyncSidebandConnection.on``.
        c                @    j                   j                  |        | S r   r4  r   r   s    rJ   r   z4AsyncSidebandConnectionManager.on.<locals>.decorator      ))--j"=IrL   r   r;  r   s   ``  rJ   r   z!AsyncSidebandConnectionManager.on  3     ))--j'BK	 rL   c                >    | j                   j                  ||       | S r   )r4  r  r  s      rJ   r  z"AsyncSidebandConnectionManager.off      %%,,ZArL   c                \     |  j                   j                  |d        S d fd}|S )GRegister a one-time event handler before the connection is established.Tr  c                D    j                   j                  | d       | S r  r;  r   s    rJ   r   z6AsyncSidebandConnectionManager.once.<locals>.decorator  #    ))--j"4-HIrL   r   r;  r   s   ``  rJ   r	  z#AsyncSidebandConnectionManager.once  8     ))--j'-MK	 rL   c                  K   | j                  | j                  | j                         d{   }t        || j                  | j                   nd| j                  | j
                  | j                  | j                  | j                  | j                  | j                  	      | _	        | j                  j                  | j                  j                         | j                  j                          d{    | j                  S 7 7 w)a  
        If your application doesn't work well with the context manager approach then you
        can call this method directly to initiate a connection.

        **Warning**: You must remember to close the connection with `.close()`.

        ```py
        connection = await client.live.sideband.connect(...).enter()
        # ...
        await connection.close()
        ```
        Nrd   )_connect_wsr,  r-  r\   r/  r0  r1  r2  r3  r+  r4  
merge_intoru   r   rI   wss     rJ   
__aenter__z)AsyncSidebandConnectionManager.__aenter__  s      ##D$6$68L8LMM3(,(>(>(JD$$PT 22**..&&**..((

 	%%001B1B1Z1Z[11333   # N 	4s"   *D	DCD	4D5D	D	c           
       K   	 ddl m} | j	                         j                  i | j                  j                  j                  | j                  t        urd| j                  ini |      }|j                  dddj                  |j                  |j                        	      }| j                  j                  t        j                  d
t!        |      t#        |      ddi             d {   }| j                  j	                  |j$                        j'                  | j                  j(                  j+                  t-        t.        |j                                    }|j                  dddj                  |j                  |j                        	      }| j                  j0                  i | j                  j2                  t5        |j6                        r|j6                  ni fD 	ci c]-  }|j9                         D ]  \  }}	|j;                         ||	f / }
}}}	t<        j?                  d       | j@                  rt<        j?                  d        |t!        |      fd tC        t#        |
jE                               i       d| j@                   d {   S # t        $ r}t        d      |d }~ww xY w7 c c}	}}w 7 +w)Nr   )_WebSocketConnect9You need to install `openai[realtime]` to use this methodr9   paramsrI  wsshttphttpsschemer   bearer_authTmethodurlheaderssecurityConnecting to WebSocket API,Custom WebSocket connection options provideduser_agent_headeradditional_headers)#lib._websocketrL  ImportErrorr   _prepare_url	copy_withr(  base_urlrO  r*  r   r   rU  _prepare_optionsr   	constructrM   r   rY  copy_merge_paramsqs	stringifyr   r   auth_headersdefault_headersr   rZ  itemslowerr2   r   r.  r!   valuesrI   r:   r;   rK   r   rY  options
header_setkeyr   rZ  s              rJ   rF  z*AsyncSidebandConnectionManager._connect_ws&  s    	dF !++--((//@D@U@U]a@a$d&;&;<gi  , 
 mmD5#A#E#EcjjRUR\R\#]m^66))H]+'.	
 
 mm((5GGMM&&tC'@A
 mmD5#A#E#EcjjRUR\R\#]m^ **--#+GOO#<"		
 	
 )..0	
 U IIK#u%	
	
 	
 			/0..IIDEH
".tGNN4D/ErJ
 11	
 
 	
K  	dYZ`cc	d
	

sT   KJ$ C&K0K1C?K02K"A=KK K$	J>-J99J>>KKc                   | j                   j                  *t        j                  | j                   j                        }nO| j                   j                  j
                  }|dk(  rdnd}| j                   j                  j                  |      }|j                  j                  d      t        d| j                        j                  d      z   }|j                  |	      S 
NrR  rI  rP  rT     /z"/live/sessions/{session_id}/attach)rE   r   )raw_path)r(  websocket_base_urlhttpx2URL	_base_urlrU  rd  rw  rstripr   r)  encoderI   re  rU  	ws_schememerge_raw_paths        rJ   rc  z+AsyncSidebandConnectionManager._prepare_urlU      ==++7zz$--"B"BCH]],,33F && 0eI}}..88	8JH!**11$7-0T=N=N;

&/ !!>!::rL   c                n   K   | j                   #| j                   j                          d {    y y 7 wr   )r+  r   rI   exc_typer   exc_tbs       rJ   	__aexit__z(AsyncSidebandConnectionManager.__aexit__b  s4      (##))+++ )+s   *535)rD   r/   rE   rM   r9   rN   r:   r   r;   r   r<   r)   r=   rO   r>   rP   r?   rQ   r@   rQ   rA   rP   rR   r   r  r   )r   rM   r   r   rR   zYUnion[AsyncSidebandConnectionManager, Callable[[Callable[..., Any]], Callable[..., Any]]])r   rM   r   r   rR   rZ   )rR   r\   )r:   r   r;   r   rR   rb   rR   z
httpx2.URLr  ztype[BaseException] | Noner   zBaseException | Noner  zTracebackType | NonerR   r   )rT   rU   rV   r!  r   rx   r   r   r  r	  rJ  enterrF  rc  r  rW   rL   rJ   rZ   rZ     s:   0 '+ _c"'M M 	M
 $M M M 'AM \M M M M M 
M:( EI(A	b$ EI(A	b!@ E-
^;,2,9M,Wk,	,rL   rZ   c            	          e Zd ZU dZded<   ded<   ded<   ddd	d
di i dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZd dZd!dZd"dZ	d#dZ
dddd$dZd%dZd&dZd'dZ	 d(	 	 	 	 	 d)dZd*dZ	 d(	 	 	 	 	 d)dZd'dZy)+SidebandConnectionr]   SidebandSessionResourcer_   SidebandResponseResourcera   WebSocketConnectionrc   Nr4   r5   r6   rd   c               &   || _         || _        || _        || _        d| _        || _        || _        || _        || _        d| _	        d| _
        |	xs
 t               | _        t        d      | _        t        |       | _        t#        |       | _        y )Nr   FTrh   )rc   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   r    rt   r"   ru   r  r_   r  ra   rv   s
             rJ   rx   zSidebandConnection.__init__q  s     & /'"#+#'+%*" %%4';T'J$.t406rL   c              #     K   ddl m}m} 	 	 | j                          # |$ r Y y|$ rF}| j	                  |      s+| j
                  j                         }|rt        d|      | Y d}~Md}~ww xY wwrz   r~   r   s        rJ   __iter__zSidebandConnection.__iter__  s     
 	Tiik!  & ( s+!--335F<N,2  ##  ,s4   
A4  A4A1A4A1<A,'A4,A11A4c                   | j                  | j                               }t        t        t        |      t
              rt        d|      j                  d      nt        |dd      }t        |t              r|r|dk7  rd| _	        |S )r   r   r   Nr   r   r   r   s      rJ   r   zSidebandConnection.recv  sy       !23 $vu-t4 $e,008- 	 j#&:*:O&'D#rL   c                   | j                   j                  d      }t        j                  dt	        |             | j
                  ra	 t        j                  |      }t        |t              rt        d|      j                  d      nd}t        |t              r|r|dk7  rd| _        |S # t        t        f$ r |cY S w xY w)	r   Fr   r   r   r   Nr   r   r   r   s       rJ   r   zSidebandConnection.recv_bytes  s     ""''u'5		8#g,G""%)ZZ%8
 OYYceiNj1:>BB6JptJ*c*zjG>S*+' / s   	B+ +B?>B?c                l   t        |t              r|j                  ddd      n"t        j                  t        |t                    }| j                  r| j                  j                  |       y 	 | j                  j                  |       y # t        $ r | j                  j                  |        w xY wr   )r   r   r   r   r   r   r*   rs   rt   r   rc   r   r   r   s      rJ   r   zSidebandConnection.send  s     %+ MMtSWMXOE3JKL 	
   $$T*	!!$' 	$$T*	s   1B &B3c                    | j                   r?t        |t              r|n|j                  d      }| j                  j                  |       y | j                  j                  |       y r   r   r   s      rJ   r   zSidebandConnection.send_raw  sO      $T3/$T[[5IC$$S)d#rL   r   r   r   c               L    d| _         | j                  j                  ||       y r   r   r   s      rJ   r   zSidebandConnection.close  s#    %)"D8rL   c           
         t        t        t        t        j                  |      t        t
        t                          S r   r   r   s     rJ   r   zSidebandConnection.parse_event  r   rL   c           	     Z   | j                   | j                  yddlm} d}t	        ||      r"|j
                  |j
                  j                  }t        |      syd| _        t        | j                  dz   | j                  dz         D ]q  }|| _
        t        | j                  d|dz
  z  z  | j                        }dt        j                         d	z  z   }||z  }t!        || j                  ||| j"                  | j$                  
      }	 | j                  |      }	|	|	j)                  d      r	d| _         y|	d|	v r
|	d   | _        d|	v r
|	d   | _        t*        j-                  d|| j                  |       t/        j0                  |       | j2                  r	d| _         y	 | j                  | j"                  | j$                        | _        t*        j-                  d       d| _        | j7                           y d| _        y# t&        $ r d| _        Y  yw xY w# t&        $ r Y w xY w)r   Fr   r   r   Tr   r   r   r   r   r   r:   r;   r   r   )rk   rj   r   r|   r   r   r   r&   rs   r   rm   rl   r   rn   ro   r   r$   rp   rq   r   r   r2   r   timer   rr   rc   r   )
rI   r   r|   r   r   r   r   r   r   r   s
             rJ   r   zSidebandConnection._reconnect  s(      (DMM,A?
c01chh6JJ#J/ $T44q8$:K:Ka:OP 2	G&-D#T00A'A+4FGYJFMMOd22F'E%!..% --"11E..u5
 !fjj&9(-%! F*(.}(=D%"f,*0*AD'HHQ!!	 JJu))(-%#'==1B1BDDWDW#X 78(-%&&(a2	h !&I  (-%@  s%   H$AHHH	H*)H*c                     	  j                   j                   fd       y# t        $ r t        j	                  d       Y yw xY w)r   c                :    j                   j                  |       S r   r   r   s    rJ   <lambda>z6SidebandConnection._flush_send_queue.<locals>.<lambda>>  s    T5E5E5J5J45P rL   r   N)rt   
flush_syncr   r2   r   rI   s   `rJ   r   z$SidebandConnection._flush_send_queue;  s<    	F''(PQ 	FKKDE	Fs   " AAc                X     | j                   j                  |        S d fd}|S )a'  Adds the handler to the end of the handlers list for the given event type.

        No checks are made to see if the handler has already been added. Multiple calls
        passing the same combination of event type and handler will result in the handler
        being added, and called, multiple times.

        Can be used as a method (returns ``self`` for chaining)::

            connection.on("session.started", my_handler)

        Or as a decorator::

            @connection.on("session.started")
            def my_handler(event): ...
        c                @    j                   j                  |        | S r   r   r   s    rJ   r   z(SidebandConnection.on.<locals>.decoratorX  r   rL   r   r   r   s   ``  rJ   r   zSidebandConnection.onB  r   rL   c                >    | j                   j                  ||       | S r   r  r  s      rJ   r  zSidebandConnection.off^  r  rL   c                \     |  j                   j                  |d        S d fd}|S )r  Tr  c                D    j                   j                  | d       | S r  r   r   s    rJ   r   z*SidebandConnection.once.<locals>.decoratorn  r  rL   r   r   r   s   ``  rJ   r	  zSidebandConnection.oncec  r  rL   c                    | D ]  }|j                   }| j                  j                  |      }| j                  j                  d      }|dk(  r"|s |st        |t              rt        d|       |D ]
  } ||        |D ]
  } ||         y)ay  Run the event loop, dispatching received events to registered handlers.

        Blocks the current thread until the connection is closed. This is the push-based
        alternative to iterating with ``for event in connection``.

        If an ``"error"`` event arrives and no handler is registered for
        ``"error"`` or ``"event"``, an ``OpenAIError`` is raised.
        r   r   r  N)r   ru   r  r   r#   r   )rI   r   r   r  r  r   s         rJ   r  z"SidebandConnection.dispatch_eventst  s      	EJ33@@LH22??HGW$XgeZ0%(9%&ABB#  # 	rL   )rw   r  re   z6Callable[[Query, Headers], WebSocketConnection] | Noner=   rO   r>   rP   r?   rQ   r@   rQ   r:   r   r;   r   rf   r  rR   r   )rR   zIterator[ConnectServerEvent]r  r  r  r  r  r  r  r  r   )r   rM   r   r   rR   zMUnion[SidebandConnection, Callable[[Callable[..., Any]], Callable[..., Any]]])r   rM   r   r   rR   r  )rT   rU   rV   r!  r"  rx   r  r   r   r   r   r   r   r   r   r   r  r	  r  rW   rL   rJ   r  r  i  s%   D$$&&$$ KO^b"!#'+7'7 H	7
 \7 7 7 7 7 7 %7 
7<,$*$ $(r 9
IVF EI(A	V8 EI(A	V"rL   r  c                      e Zd ZdZedddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZdd	Z	 d	 	 	 	 	 dd
ZddZ	 d	 	 	 	 	 ddZ	ddZ
e
ZddZddZ	 	 	 	 	 	 	 	 ddZy)rF   a"  
    Context manager over a `SidebandConnection` that is returned by `live.sideband.connect()`

    This context manager ensures that the connection will be closed when it exits.

    ---

    Note that if your application doesn't work well with the context manager approach then you
    can call the `.enter()` method directly to initiate a connection.

    **Warning**: You must remember to close the connection with `.close()`.

    ```py
    connection = client.live.sideband.connect(...).enter()
    # ...
    connection.close()
    ```
    Nr4   r5   r6   r7   r$  c                   || _         || _        || _        d | _        || _        || _        || _        || _        || _        |	| _	        |
| _
        t        |      | _        t        d      | _        y )Nr&  Trh   )"_SidebandConnectionManager__client&_SidebandConnectionManager__session_id*_SidebandConnectionManager__graceful_close&_SidebandConnectionManager__connection'_SidebandConnectionManager__extra_query)_SidebandConnectionManager__extra_headers8_SidebandConnectionManager__websocket_connection_options+_SidebandConnectionManager__on_reconnecting'_SidebandConnectionManager__max_retries)_SidebandConnectionManager__initial_delay%_SidebandConnectionManager__max_delayr    &_SidebandConnectionManager__send_queuer"   2_SidebandConnectionManager__event_handler_registryr5  s               rJ   rx   z"SidebandConnectionManager.__init__  su     & .7;(,.J+!0(,$%?(<d(K%rL   c                    t        |t              r|j                  ddd      n"t        j                  t        |t                    }| j                  j                  |       yr7  )	r   r   r   r   r   r   r*   r  r   r   s      rJ   r   zSidebandConnectionManager.send  r8  rL   c                X     | j                   j                  |        S d fd}|S )zRegister an event handler before the connection is established.

        Handlers are transferred to the connection on enter. Supports the
        same method and decorator forms as ``SidebandConnection.on``.
        c                @    j                   j                  |        | S r   r  r   r   s    rJ   r   z/SidebandConnectionManager.on.<locals>.decorator  r<  rL   r   r  r   s   ``  rJ   r   zSidebandConnectionManager.on  r=  rL   c                >    | j                   j                  ||       | S r   )r  r  r  s      rJ   r  zSidebandConnectionManager.off  r?  rL   c                \     |  j                   j                  |d        S d fd}|S )rA  Tr  c                D    j                   j                  | d       | S r  r  r   s    rJ   r   z1SidebandConnectionManager.once.<locals>.decorator  rC  rL   r   r  r   s   ``  rJ   r	  zSidebandConnectionManager.once  rD  rL   c                   | j                  | j                  | j                        }t        || j                  | j                   nd| j                  | j
                  | j                  | j                  | j                  | j                  | j                  	      | _	        | j                  j                  | j                  j                         | j                  j                          | j                  S )av  
        If your application doesn't work well with the context manager approach then you
        can call this method directly to initiate a connection.

        **Warning**: You must remember to close the connection with `.close()`.

        ```py
        connection = client.live.sideband.connect(...).enter()
        # ...
        connection.close()
        ```
        Nrd   )rF  r  r  r  r  r  r  r  r  r  r  rG  ru   r   rH  s     rJ   	__enter__z#SidebandConnectionManager.__enter__  s     d00$2F2FG.(,(>(>(JD$$PT 22**..&&**..((

 	%%001B1B1Z1Z[++-   rL   c           
     l   	 ddl m} | j	                         j                  i | j                  j                  j                  | j                  t        urd| j                  ini |      }|j                  dddj                  |j                  |j                        	      }| j                  j                  t        j                  d
t!        |      t#        |      ddi            }| j                  j	                  |j$                        j'                  | j                  j(                  j+                  t-        t.        |j                                    }|j                  dddj                  |j                  |j                        	      }| j                  j0                  i | j                  j2                  t5        |j6                        r|j6                  ni fD 	ci c]-  }|j9                         D ]  \  }}	|j;                         ||	f / }
}}}	t<        j?                  d       | j@                  rt<        j?                  d        |t!        |      fd tC        t#        |
jE                               i       d| j@                  S # t        $ r}t        d      |d }~ww xY wc c}	}}w )Nr   )rK   rM  r9   rN  rI  rP  rQ  rT  r   rV  TrW  r\  r]  r^  )#websockets.sync.clientrK   rb  r   rc  rd  r  re  rO  r  r   r   rU  rf  r   rg  rM   r   rY  rh  ri  rj  r   r   rk  rl  r   rZ  rm  rn  r2   r   r  r!   ro  rp  s              rJ   rF  z%SidebandConnectionManager._connect_ws  sr   	d6 !++--((//@D@U@U]a@a$d&;&;<gi  , 
 mmD5#A#E#EcjjRUR\R\#]m^--00))H]+'.	
 mm((5GGMM&&tC'@A
 mmD5#A#E#EcjjRUR\R\#]m^ **--#+GOO#<"		
 	
 )..0	
 U IIK#u%	
	
 	
 			/0..IIDEH
".tGNN4D/ErJ
 11	
 	
K  	dYZ`cc	d.	
s   J &2J/	J,J''J,c                   | j                   j                  *t        j                  | j                   j                        }nO| j                   j                  j
                  }|dk(  rdnd}| j                   j                  j                  |      }|j                  j                  d      t        d| j                        j                  d      z   }|j                  |	      S ru  )r  rx  ry  rz  r{  rU  rd  rw  r|  r   r  r}  r~  s        rJ   rc  z&SidebandConnectionManager._prepare_urlA  r  rL   c                R    | j                   | j                   j                          y y r   )r  r   r  s       rJ   __exit__z"SidebandConnectionManager.__exit__N  s'     (##% )rL   )rD   r.   rE   rM   r9   rN   r:   r   r;   r   r<   r)   r=   rO   r>   rP   r?   rQ   r@   rQ   rA   rP   rR   r   r  r   )r   rM   r   r   rR   zTUnion[SidebandConnectionManager, Callable[[Callable[..., Any]], Callable[..., Any]]])r   rM   r   r   rR   rF   )rR   r  )r:   r   r;   r   rR   r  r  r  )rT   rU   rV   r!  r   rx   r   r   r  r	  r  r  rF  rc  r  rW   rL   rJ   rF   rF     s:   0 '+ _c"'L L 	L
 $L L L 'AL \L L L L L 
L:( EI(A	]$ EI(A	]!@ E-
^;&2&9M&Wk&	&rL   rF   c                      e Zd ZddZy)BaseSidebandConnectionResourcec                    || _         y r   rc   rI   rw   s     rJ   rx   z'BaseSidebandConnectionResource.__init__V  
    %rL   N)rw   r  rR   r   rT   rU   rV   rx   rW   rL   rJ   r  r  U      &rL   r  c                  p    e Zd Zed	d       Zed
d       Zedd       Zedd       ZedddZ	edddZ
y)r  c                ,    t        | j                        S r   )!SidebandSessionCommentaryResourcerc   r  s    rJ   
commentaryz"SidebandSessionResource.commentary[      01A1ABBrL   c                ,    t        | j                        S r   )!SidebandSessionInputAudioResourcerc   r  s    rJ   input_audioz#SidebandSessionResource.input_audio_  r  rL   c                ,    t        | j                        S r   )#SidebandSessionInstructionsResourcerc   r  s    rJ   instructionsz$SidebandSessionResource.instructionsc  s    243C3CDDrL   c                ,    t        | j                        S r   )SidebandSessionThinkingResourcerc   r  s    rJ   thinkingz SidebandSessionResource.thinkingg  s    .t/?/?@@rL   event_idc          
     n    | j                   j                  t        t        t	        d|d                   yzRequest that the Live session close.

        The terminal `session.closed` event contains the close reason and final usage.
        zsession.closer   r  Nrc   r   r   r*   r   rI   r  s     rJ   r   zSidebandSessionResource.closek  s.    
 	(/?`h:i*jk	
rL   c               p    | j                   j                  t        t        t	        d||d                   yzUpdate the delegation settings of an active Live session.

        The server acknowledges accepted changes with `session.updated`.
        zsession.update)r   r_   r  Nr  rI   r_   r  s      rJ   updatezSidebandSessionResource.updatet  s4    
 	')9g[c de	
rL   N)rR   r  )rR   r  )rR   r  )rR   r  r  Optional[str] | OmitrR   r   r_   r+   r  r  rR   r   rT   rU   rV   r   r  r  r  r  r   r   r  rW   rL   rJ   r  r  Z  sn    C C C C E E A A 9= 
 ]a 

rL   r  c                      e Zd ZedddZy)r  r  c               r    | j                   j                  t        t        t	        d|||d                   yz{
        Provide context the Live model can communicate to the user, optionally for an existing client delegation.
        zsession.commentary.appendr   contentdelegation_idr  Nr  rI   r  r  r  s       rJ   appendz(SidebandSessionCommentaryResource.append  s<     	' ;#*)6$,	
	
rL   Nr  rM   r  zOptional[str]r  r  rR   r   rT   rU   rV   r   r  rW   rL   rJ   r  r    
    ei 
rL   r  c                  (    e Zd ZedddZedddZy)r  r  c          
     n    | j                   j                  t        t        t	        d|d                   yzMute audio input to the Live model without closing the session.

        The server acknowledges with `session.input_audio.muted`.
        zsession.input_audio.muter  Nr  r  s     rJ   mutez&SidebandSessionInputAudioResource.mute  s/    
 	(/C]ks:t*uv	
rL   c          
     n    | j                   j                  t        t        t	        d|d                   yzResume audio input to a Live model after muting it.

        The server acknowledges with `session.input_audio.unmuted`.
        zsession.input_audio.unmuter  Nr  r  s     rJ   unmutez(SidebandSessionInputAudioResource.unmute  s/    
 	(/C_mu:v*wx	
rL   Nr  rT   rU   rV   r   r  r  rW   rL   rJ   r  r    s    7; 
 :> 
rL   r  c                      e Zd ZedddZy)r  r  c               r    | j                   j                  t        t        t	        d|||d                   yz
        Append instructions to the Live conversation while it is running, optionally associating them with an existing client delegation.
        zsession.instructions.appendr  Nr  r  s       rJ   r  z*SidebandSessionInstructionsResource.append  s<     	' =#*)6$,	
	
rL   Nr  r  rW   rL   rJ   r  r    r  rL   r  c                      e Zd ZedddZy)r  r  c               r    | j                   j                  t        t        t	        d|||d                   yz
        Provide silent reasoning or progress context to the Live model, optionally for an existing client delegation.
        zsession.thinking.appendr  Nr  r  s       rJ   r  z&SidebandSessionThinkingResource.append  s<     	' 9#*)6$,	
	
rL   Nr  r  rW   rL   rJ   r  r    r  rL   r  c                  ,    e Zd Zedd       ZedddZy)r  c                ,    t        | j                        S r   )SidebandResponseItemResourcerc   r  s    rJ   itemzSidebandResponseResource.item  s    +D,<,<==rL   r  c          
     n    | j                   j                  t        t        t	        d|d                   yu   
        Request a response from the Live session’s Responses backend, or continue a
        delegated response waiting for tool results.

        Requires Responses delegation.
        zresponse.creater  Nr  r  s     rJ   createzSidebandResponseResource.create  s/     	(/CTbj:k*lm	
rL   N)rR   r  r  rT   rU   rV   r   r  r   r  rW   rL   rJ   r  r    s    > > :> 	
rL   r  c                      e Zd ZedddZy)r  r  c               p    | j                   j                  t        t        t	        d||d                   yu   Add an input item to the Live session’s Responses backend.

        Requires Responses delegation; use `response.create` to request a response.
        zresponse.item.create)r   r  r  Nr  rI   r  r  s      rJ   r  z#SidebandResponseItemResource.create  s4    
 	')?[c de	
rL   Nr  r,   r  r  rR   r   rT   rU   rV   r   r  rW   rL   rJ   r  r    s
    W[ 

rL   r  c                      e Zd ZddZy)#BaseAsyncSidebandConnectionResourcec                    || _         y r   r  r  s     rJ   rx   z,BaseAsyncSidebandConnectionResource.__init__  r  rL   N)rw   r\   rR   r   r  rW   rL   rJ   r  r    r  rL   r  c                  p    e Zd Zed	d       Zed
d       Zedd       Zedd       ZedddZ	edddZ
y)r^   c                ,    t        | j                        S r   )&AsyncSidebandSessionCommentaryResourcerc   r  s    rJ   r  z'AsyncSidebandSessionResource.commentary      5d6F6FGGrL   c                ,    t        | j                        S r   )&AsyncSidebandSessionInputAudioResourcerc   r  s    rJ   r  z(AsyncSidebandSessionResource.input_audio  r  rL   c                ,    t        | j                        S r   )(AsyncSidebandSessionInstructionsResourcerc   r  s    rJ   r  z)AsyncSidebandSessionResource.instructions  s    78H8HIIrL   c                ,    t        | j                        S r   )$AsyncSidebandSessionThinkingResourcerc   r  s    rJ   r  z%AsyncSidebandSessionResource.thinking  s    3D4D4DEErL   r  c          
        K   | j                   j                  t        t        t	        d|d                   d{    y7 wr  r  r  s     rJ   r   z"AsyncSidebandSessionResource.close  s<     
 ##(/?`h:i*jk
 	
 	
   9AAAc                  K   | j                   j                  t        t        t	        d||d                   d{    y7 wr  r  r  s      rJ   r  z#AsyncSidebandSessionResource.update  sB     
 ##')9g[c de
 	
 	
   :AAAN)rR   r  )rR   r  )rR   r  )rR   r  r  r  r  rW   rL   rJ   r^   r^     so    H H H H J J F F ?C 
 cg 

rL   r^   c                  (    e Zd Zed	 	 	 	 	 	 	 ddZy)r  r  c                  K   | j                   j                  t        t        t	        d|||d                   d{    y7 wr  r  r  s       rJ   r  z-AsyncSidebandSessionCommentaryResource.append  sJ      ##' ;#*)6$,	

 	
 	
   ;AAANr  r  rW   rL   rJ   r  r    *    ^b

.;
G[
	
rL   r  c                  (    e Zd ZedddZedddZy)r  r  c          
        K   | j                   j                  t        t        t	        d|d                   d{    y7 wr  r  r  s     rJ   r  z+AsyncSidebandSessionInputAudioResource.mute3  s=     
 ##(/C]ks:t*uv
 	
 	
r  c          
        K   | j                   j                  t        t        t	        d|d                   d{    y7 wr  r  r  s     rJ   r  z-AsyncSidebandSessionInputAudioResource.unmute<  s=     
 ##(/C_mu:v*wx
 	
 	
r  Nr  r  rW   rL   rJ   r  r  2  s    =A 
 @D 
rL   r  c                  (    e Zd Zed	 	 	 	 	 	 	 ddZy)r  r  c                  K   | j                   j                  t        t        t	        d|||d                   d{    y7 wr  r  r  s       rJ   r  z/AsyncSidebandSessionInstructionsResource.appendG  sJ      ##' =#*)6$,	

 	
 	
r!  Nr  r  rW   rL   rJ   r  r  F  r"  rL   r  c                  (    e Zd Zed	 	 	 	 	 	 	 ddZy)r  r  c                  K   | j                   j                  t        t        t	        d|||d                   d{    y7 wr  r  r  s       rJ   r  z+AsyncSidebandSessionThinkingResource.append]  sJ      ##' 9#*)6$,	

 	
 	
r!  Nr  r  rW   rL   rJ   r  r  \  r"  rL   r  c                  ,    e Zd Zedd       ZedddZy)r`   c                ,    t        | j                        S r   )!AsyncSidebandResponseItemResourcerc   r  s    rJ   r  z"AsyncSidebandResponseResource.items  r  rL   r  c          
        K   | j                   j                  t        t        t	        d|d                   d{    y7 wr  r  r  s     rJ   r  z$AsyncSidebandResponseResource.createw  s=      ##(/CTbj:k*lm
 	
 	
r  N)rR   r,  r  r  rW   rL   rJ   r`   r`   r  s"    C C @D 	
rL   r`   c                      e Zd ZedddZy)r,  r  c                  K   | j                   j                  t        t        t	        d||d                   d{    y7 wr
  r  r  s      rJ   r  z(AsyncSidebandResponseItemResource.create  sB     
 ##')?[c de
 	
 	
r  Nr  r  rW   rL   rJ   r,  r,    s
    ]a 

rL   r,  )g
__future__r   r   r  r   loggingtypesr   typingr   r   r   r   r	   r
   r   r   typing_extensionsr   ry  pydanticr   _typesr   r   r   r   _utilsr   r   r   r   r   _compatr   _modelsr   r   	_resourcer   r   _exceptionsr   r   rt   r    _base_clientr!   _event_handlerr"   types.live.error_eventr#   types.websocket_reconnectionr$   r%   r&   types.live.connect_client_eventr'   types.live.connect_server_eventr(   "types.websocket_connection_optionsr)   %types.live.connect_client_event_paramr*   &types.live.session_update_config_paramr+   )types.responses.response_input_item_paramr,   r  r-   r  websockets.asyncio.clientrb   rG   r.   r/   __all__	getLoggerrT   r2   r"  r0   r1   r\   rZ   r  rF   r  r  r  r  r  r  r  r  r  r^   r  r  r  r  r`   r,  rW   rL   rJ   <module>rI     s   #      [ [ [ +   0 0 f f & D : F $ + 2 0 j j A A L L N ONV.
''g''1^ 1
 
D
$ 
Dm! m!`	E, E,Pa aH	E& E&P& &
$
< $
N
(F 
(
(F 
(
*H 
(
&D 
(
= 
"
#A 
& &
$
#F $
N
-P 
,
-P 
(
/R 
,
+N 
,
$G 
"
(K 
rL   