
    `i                        d Z ddlZddlZddlZddlZddlZddlmZ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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 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% 	 ddl&m'Z' ddl&m(Z(  ejV                  d      Z,dZ- G d d      Z. G d dej^                        Z0dede
ejb                     dejd                  fdZ3y# e)$ r ddl*m'Z' ddl*m(Z( Y hw xY w)z[Preview] Live API client.    N)AnyAsyncIteratorDictOptionalSequenceUnioncastget_args)ConnectionClosed   )_api_module)_common)_transformers)client)types)BaseApiClient)get_value_by_path)set_value_by_path)live_converters)_Content_to_mldev)_Content_to_vertex)ClientConnection)connectzgoogle_genai.liveznFunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.c                   |   e Zd ZdZdej
                  defdZddddee	e
j                  e
j                  e
j                  e
j                  e
j                  e
j                   ee
j                      f      d	ee   fd
Zddddee	e
j(                  e
j*                  ee	e
j(                  e
j*                  f      f      defdZdej2                  fdZde	e
j                   ee
j                      f   fdZdee
j:                     fdZdee   de dee
j:                     fdZ!de
j:                  fdZ"dee   de de#jH                  fdZ%	 	 ddee	e
j                  e
j                  e
j                  e
j                  e
j                  e
j                   ee
j                      f      d	ee   de
jL                  fdZ'd dZ(y)!AsyncSessionz[Preview] AsyncSession.
api_client	websocketc                      || _         || _        y N)_api_client_ws)selfr   r   s      V/var/www/html/ts-aiml.yecor.com/venv/lib/python3.12/site-packages/google/genai/live.py__init__zAsyncSession.__init__>   s     "DDH    NF)inputend_of_turnr&   r'   c                   K   t        j                  dt        d       | j                  ||      }| j                  j                  t        j                  |             d{    y7 w)a  [Deprecated] Send input to the model.

    > **Warning**: This method is deprecated and will be removed in a future
    version (not before Q3 2025). Please use one of the more specific methods:
    `send_client_content`, `send_realtime_input`, or `send_tool_response`
    instead.

    The method will send the input request to the server.

    Args:
      input: The input request to the model.
      end_of_turn: Whether the input is the last message in a turn.

    Example usage:

    .. code-block:: python

      client = genai.Client(api_key=API_KEY)

      async with client.aio.live.connect(model='...') as session:
        await session.send(input='Hello world!', end_of_turn=True)
        async for message in session.receive():
          print(message)
    zThe `session.send` method is deprecated and will be removed in a future version (not before Q3 2025).
Please use one of the more specific methods: `send_client_content`, `send_realtime_input`, or `send_tool_response` instead.   
stacklevelN)warningswarnDeprecationWarning_parse_client_messager!   sendjsondumps)r"   r&   r'   client_messages       r#   r0   zAsyncSession.sendD   sV     P MM	B 	 //{CN
((--

>2
333s   A A*"A(#A*Tturnsturn_completer5   r6   c                ^  K   t        j                  ||      }| j                  j                  r"t	        j
                  | j                  |      }n!t	        j                  | j                  |      }| j                  j                  t        j                  d|i             d{    y7 w)a	  Send non-realtime, turn based content to the model.

    There are two ways to send messages to the live API:
    `send_client_content` and `send_realtime_input`.

    `send_client_content` messages are added to the model context **in order**.
    Having a conversation using `send_client_content` messages is roughly
    equivalent to using the `Chat.send_message_stream` method, except that the
    state of the `chat` history is stored on the API server.

    Because of `send_client_content`'s order guarantee, the model cannot
    respond as quickly to `send_client_content` messages as to
    `send_realtime_input` messages. This makes the biggest difference when
    sending objects that have significant preprocessing time (typically images).

    The `send_client_content` message sends a list of `Content` objects,
    which has more options than the `media:Blob` sent by `send_realtime_input`.

    The main use-cases for `send_client_content` over `send_realtime_input` are:

    - Prefilling a conversation context (including sending anything that can't
      be represented as a realtime message), before starting a realtime
      conversation.
    - Conducting a non-realtime conversation, similar to `client.chat`, using
      the live api.

    Caution: Interleaving `send_client_content` and `send_realtime_input`
      in the same conversation is not recommended and can lead to unexpected
      results.

    Args:
      turns: A `Content` object or list of `Content` objects (or equivalent
        dicts).
      turn_complete: if true (the default) the model will reply immediately. If
        false, the model will wait for you to send additional client_content,
        and will not return until you send `turn_complete=True`.

    Example:
    ```
    import google.genai
    from google.genai import types
    import os

    if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'):
      MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09'
    else:
      MODEL_NAME = 'gemini-2.0-flash-live-001';

    client = genai.Client()
    async with client.aio.live.connect(
        model=MODEL_NAME,
        config={"response_modalities": ["TEXT"]}
    ) as session:
      await session.send_client_content(
          turns=types.Content(
              role='user',
              parts=[types.Part(text="Hello world!")]))
      async for msg in session.receive():
        if msg.text:
          print(msg.text)
    ```
    r   from_objectclient_contentN)tt_client_contentr    vertexair   _LiveClientContent_to_vertex_LiveClientContent_to_mldevr!   r0   r1   r2   )r"   r5   r6   r:   client_content_dicts        r#   send_client_contentz AsyncSession.send_client_contentw   s     T ''}=N  +HH%%> ,GG%%> ((--

$46I#JK
LLLs   B#B-%B+&B-mediac                   K   t        j                  |      }|j                  dd      }| j                  j	                  t        j                  d|i             d{    y7 w)a_  Send realtime media chunks to the model.

    Use `send_realtime_input` for realtime audio chunks and video
    frames(images).

    With `send_realtime_input` the api will respond to audio automatically
    based on voice activity detection (VAD).

    `send_realtime_input` is optimized for responsivness at the expense of
    deterministic ordering. Audio and video tokens are added to the
    context when they become available.

    Args:
      media: A `Blob`-like object, the realtime media to send.

    Example:
    ```
    from pathlib import Path

    from google import genai
    from google.genai import types

    import PIL.Image
    
    import os

    if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'):
      MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09'
    else:
      MODEL_NAME = 'gemini-2.0-flash-live-001';


    client = genai.Client()

    async with client.aio.live.connect(
        model=MODEL_NAME,
        config={"response_modalities": ["TEXT"]},
    ) as session:
      await session.send_realtime_input(
          media=PIL.Image.open('image.jpg'))

      audio_bytes = Path('audio.pcm').read_bytes()
      await session.send_realtime_input(
          media=types.Blob(data=audio_bytes, mime_type='audio/pcm;rate=16000'))

      async for msg in session.receive():
        if msg.text is not None:
          print(f'{msg.text}')
    ```
    Tr1   exclude_nonemoderealtime_inputN)r;   t_realtime_input
model_dumpr!   r0   r1   r2   )r"   rB   rG   realtime_input_dicts       r#   send_realtime_inputz AsyncSession.send_realtime_input   s\     f ''.N(33 4  ((--

$46I#JK
LLLs   AA&A$A&function_responsesc                \  K   t        j                  |      }| j                  j                  r"t	        j
                  | j                  |      }n!t	        j                  | j                  |      }| j                  j                  t        j                  d|i             d{    y7 w)a  Send a tool response to the session.

    Use `send_tool_response` to reply to `LiveServerToolCall` messages
    from the server.

    To set the available tools, use the `config.tools` argument
    when you connect to the session (`client.live.connect`).

    Args:
      function_responses: A `FunctionResponse`-like object or list of
        `FunctionResponse`-like objects.

    Example:
    ```
    from google import genai
    from google.genai import types

    import os

    if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'):
      MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09'
    else:
      MODEL_NAME = 'gemini-2.0-flash-live-001';

    client = genai.Client()

    tools = [{'function_declarations': [{'name': 'turn_on_the_lights'}]}]
    config = {
        "tools": tools,
        "response_modalities": ['TEXT']
    }

    async with client.aio.live.connect(
        model='models/gemini-2.0-flash-live-001',
        config=config
    ) as session:
      prompt = "Turn on the lights please"
      await session.send_client_content(
          turns={"parts": [{'text': prompt}]}
      )

      async for chunk in session.receive():
          if chunk.server_content:
            if chunk.text is not None:
              print(chunk.text)
          elif chunk.tool_call:
            print(chunk.tool_call)
            print('_'*80)
            function_response=types.FunctionResponse(
                    name='turn_on_the_lights',
                    response={'result': 'ok'},
                    id=chunk.tool_call.function_calls[0].id,
                )
            print(function_response)
            await session.send_tool_response(
                function_responses=function_response
            )

            print('_'*80)
    r8   tool_responseN)r;   t_tool_responser    r=   r   !_LiveClientToolResponse_to_vertex _LiveClientToolResponse_to_mldevr!   r0   r1   r2   )r"   rL   rN   tool_response_dicts       r#   send_tool_responsezAsyncSession.send_tool_response  s     H %%&89M  *LL%%= +KK%%= ((--

O5G#HI
JJJs   B"B,$B*%B,returnc                   K   | j                          d{   x}rI|j                  r|j                  j                  r| y| | j                          d{   x}rHyy7 P7 w)a  Receive model responses from the server.

    The method will yield the model responses from the server. The returned
    responses will represent a complete model turn. When the returned message
    is function call, user must call `send` with the function response to
    continue the turn.

    Yields:
      The model responses from the server.

    Example usage:

    .. code-block:: python

      client = genai.Client(api_key=API_KEY)

      async with client.aio.live.connect(model='...') as session:
        await session.send(input='Hello world!', end_of_turn=True)
        async for message in session.receive():
          print(message)
    N)_receiveserver_contentr6   )r"   results     r#   receivezAsyncSession.receiveV  s]     . --/)
)&
)			6#8#8#F#Fl	 --/)
)&
)))s(   A+A'AA+A)A+%A+)A+stream	mime_typec                  K   t        j                  dt        d       t        j                         }t        j
                  | j                  |||             d}|j                         s	 t        j
                  | j                               }t        j                  |t        j
                  |j                               gt        j                         d{    |j                         r0|j                          t        j                  d       d{    |j                         s|-|j                         s|j                          	 | d{    yyy7 7 G# t        $ r Y ?w xY w7 # t        j                   $ r Y yw xY ww)a  [Deprecated] Start a live session from a data stream.

    > **Warning**: This method is deprecated and will be removed in a future
    version (not before Q2 2025). Please use one of the more specific methods:
    `send_client_content`, `send_realtime_input`, or `send_tool_response`
    instead.

    The interaction terminates when the input stream is complete.
    This method will start two async tasks. One task will be used to send the
    input stream to the model and the other task will be used to receive the
    responses from the model.

    Args:
      stream: An iterator that yields the model response.
      mime_type: The MIME type of the data in the stream.

    Yields:
      The audio bytes received from the model and server response messages.

    Example usage:

    .. code-block:: python

      client = genai.Client(api_key=API_KEY)
      config = {'response_modalities': ['AUDIO']}
      async def audio_stream():
        stream = read_audio()
        for data in stream:
          yield data
      async with client.aio.live.connect(model='...', config=config) as session:
        for audio in session.start_stream(stream = audio_stream(),
        mime_type = 'audio/pcm'):
          play_audio_chunk(audio.data)
    zSetting `AsyncSession.start_stream` is deprecated, and will be removed in a future release (not before Q3 2025). Please use the `receive`, and `send_realtime_input`, methods instead.   r*   N)return_when-q=)r,   r-   r.   asyncioEventcreate_task
_send_loopis_setrV   waitFIRST_COMPLETEDdonerX   sleepr   cancelCancelledError)r"   rZ   r[   
stop_event	recv_tasks        r#   start_streamzAsyncSession.start_streams  sZ    J MM	P 	 J	:FGI!''8	ll##JOO$56  //
 	
 	
 >>  "
"g&
&
& !  Y^^%5	 &6	
 '  	## s   A)F,A.E$ E ?E$ E"E$ F0"FE5 E3E5 F E$ "E$ $	E0-F/E00F3E5 5FF
FFc                   K   t        j                         }	 | j                  j                  d       d {   }|r	 t        j                  |      }ni }| j                  j                  r!t        j                  | j                  |      }n t        j                  | j                  |      }t         j                  j                  ||j!                               S 7 # t        $ r& | j                  j                          d {  7  }Y w xY w# t
        j                  j                  $ r t        d|      w xY ww)NFdecodezFailed to parse response: )responsekwargs)r   LiveServerMessager!   recv	TypeErrorr1   loadsdecoderJSONDecodeError
ValueErrorr    r=   r   _LiveServerMessage_from_vertex_LiveServerMessage_from_mldev_from_responserI   )r"   parameter_modelraw_responserq   response_dicts        r#   rV   zAsyncSession._receive  s    --/O+88===66l H::l+ h  %DDTEUEUW_`m%CCDDTDTV^_m""11'A'A'C 2  ! 7 +88==?**l+
 \\)) H5l5EFGGHs[   E C CC E D B	E C &DDDE DE ,D==E data_streamrk   c                   K   |2 3 d {   }t        j                  t        j                  ||      g      }| j                  |       d {    t	        j
                  d       d {    m7 h7 $7 	6 |j                          y w)Ndatar[   media_chunks)r&   r_   )r   LiveClientRealtimeInputBlobr0   r`   rh   set)r"   r   r[   rk   r   model_inputs         r#   rc   zAsyncSession._send_loop  s      " # #d11jjdi@Ak IIKI(((MM'"""# )" " NNsJ   B
A8A2A8AB
A4B
,A6-B
2A84B
6B
8B
c           	         |}|st        j                  d       dddiiS t        |t              r|g}nt        |t              rcd|v r_	 t        j                  d#i |}t        |t
        j                        rt        |j                  t              rw|j                  d	d
      g}nbt        |t
        j                        r|g}nDt        |t              r4d|v r0d|v r,| j                  j                  sd|vrt        t               |g}t        |t"              rt%        d |D              rg }|D ]  }t        |t              s	 t        j&                  d#i |}|j(                  %| j                  j                  st        t               |j                  dd	      }t        j*                  |j-                  d      |j-                  d            }	|j-                  d      r|j-                  d      |	d<   |j/                  |	        t        j0                  t        j2                  |            }
|
S t        |t"              r~t%        d |D              rki }g }|D ]7  }t        |t5        t
        j6                              s'|j/                  |       9 | j                  j                  rCt9        j:                  | j                  |      D cg c]  }t=        | j                  ||       }}nBt9        j:                  | j                  |      D cg c]  }t?        | j                  ||       }}g }|D ]\  }	 t        j@                  d#i |}|j/                  t        jB                  |j                  dd	      d   |jD                               ^ t        j0                  t        jF                  ||            }
|
S t        |t"              rt%        d |D              rnNt%        d |D              r!|D cg c]  }|j                  dd	       }}nt        dt        |       d| d      t        j0                  t        jH                  |            }
|
S t        |t              r"d|v sd|v rKd|v r|d   }n|d   }t        j0                  t        jF                  ||j-                  d                  }
|
S d|v rV	 t        jJ                  d#i |}t        j0                  t        jH                  |j                  dd	      d               }
|
S d|v rV	 t        jL                  d#i |}t        j0                  t        j2                  |j                  dd	      d               }
|
S t        dt        |       d| d      t        |t
        jJ                        rE|j                  dd	      }t        j0                  t        jH                  |j-                  d                  }
|
d    |
d    d   t        |
d    d   d!   d   t              rg }|
d    d   D ]  }t        |t              s	 t        j                  d#i |}t        |t
        j                        sEt        |j                  t              s`|j                  m|j/                  t        jN                  tQ        jR                  |j                        |jT                  "              ||
d    d<   |
S t        |t
        jV                        r^|j                  dd	      }t        j0                  t        jF                  |j-                  d      |j-                  d                  }
|
S t        |t
        jL                        r| j                  j                  s4|jX                  (|jX                  d!   j(                  st        t               t        j0                  t        j2                  |j                  dd	      j-                  d                  }
|
S t        |t
        j&                        r| j                  j                  s|j(                  st        t               |j                  dd	      }t        j*                  |j-                  d      |j-                  d            }	|j-                  d      r|j-                  d      |	d<   t        j0                  t        j2                  |	g            }
|
S t        |t"              rt        |d!   t
        j&                        r| j                  j                  s|d!   j(                  st        t               g }|D ]  }|j                  dd	      }t        j*                  |j-                  d      |j-                  d            }	|j-                  d      r|j-                  d      |	d<   |j/                  |	        t        j0                  t        j2                  |            }
|
S t        dt        |       d| d      # t        j                  $ r t        dt        |       d| d      w xY w# t        j                  $ r t        dt        |       d| d      w xY wc c}w c c}w # t        j                  $ r t        dt        |       d| d      w xY wc c}w # t        j                  $ r t        dt        |       d| d      w xY w# t        j                  $ r t        dt        |       d| d      w xY w# t        j                  $ r t        dt        |       d| d      w xY w)$Nz0No input provided. Assume it is the end of turn.r:   r6   Tr   zUnsupported input type "z" or input content ""r1   )rF   rE   namerq   idc              3   T   K   | ]   }t        |t              xr
 d |v xr d|v  " yw)r   rq   N
isinstancedict.0cs     r#   	<genexpr>z5AsyncSession._parse_client_message.<locals>.<genexpr>  s4      5 	1d?!?
a?5s   &(rD   )r   rq   )rL   )rN   c              3   <   K   | ]  }t        |t                y wr   )r   strr   s     r#   r   z5AsyncSession._parse_client_message.<locals>.<genexpr>5  s      7 
1c7s   parts)r   roler4   )r:   c              3   H   K   | ]  }t        |t              xr d |v   yw)r   Nr   r   bs     r#   r   z5AsyncSession._parse_client_message.<locals>.<genexpr>`  s#     LqjD!1fk1Ls    "c              3   P   K   | ]  }t        |t        j                           y wr   )r   r   r   r   s     r#   r   z5AsyncSession._parse_client_message.<locals>.<genexpr>b  s     BQz!UZZ(Bs   $&r   )rG   contentr5   r   rL   rG   r   r    )-logginginfor   r   r   r   r   pydanticValidationErrorry   typer   bytesrI   r    r=   _FUNCTION_RESPONSE_REQUIRES_IDr   anyFunctionResponser   FunctionResponseDictgetappendLiveClientMessageDictLiveClientToolResponseDictr
   	PartUnionr;   
t_contentsr   r   ContentContentDictr   LiveClientContentDictLiveClientRealtimeInputDictr   LiveClientToolResponseBlobDictbase64	b64decoder[   LiveClientContentrL   )r"   r&   r'   formatted_input
blob_inputfunction_responses_inputitemfunction_response_inputfunction_response_dictfunction_response_typeddictr3   	to_objectcontent_input_partscontentscontent_dict_listcontent_inputr   content_turnsrG   tool_response_inputrJ   formatted_media_chunksr@   function_response_lists                           r#   r/   z"AsyncSession._parse_client_message  s     !OllEF$ 788%o	E4	 Vu_
ZZ(%(
 Z
,%0 !!vD!A
 
E5::	&o	E4	 Vu_u9L''T->788o/8, 5 5 2
 "$! I$dD!&+&<&<&Dt&D# &((0&&//;<<%<%G%G! &H &" +0*D*D+//7/33J?+' &))$/2H2L2L3)$/ %++,GH5I6 2288!9n~ u 
OX	.3 7$37 4 #%i35! +$dHU__56

$
$T
*+ 
			"	" T%5%57JK
 t//yA
 
 T%5%57JK
 d..i@
 

 46 
$	--/$/- 	  #..Dv.N #''		

" 2244%[nj a 
OX	.	LOL	LB/BB %
 LLdL8
 

 &tE{m3GwaP
 	
 22::*nF { 
OT	*	o	%O)Co%)'2-))4-44 66#-11/B
l a _,	 88K?K. 44 <<+66!%F 7  "
P C  ?2	 % < < O O
 44::#6#A#A!%F $B $&$(
r c &tE{m3GwaP
 	
 
OU%B%B	C+66& 7  22::.22>Bn )
*
6-.~>J-.~>qA&I5 8:"#34^D 	Dd# ::--j :uzz2z6OO/$++..!++JOO< * 4 4	. # 	'(	
P I 
OU%<%<	=+66& 7  2244'++G4/33ODn@ u 
OU%A%A	B ((00<"55a8;;7882288!0!;!;#& "< "()nd W 
OU%;%;	<''/2D2D788.99&  :   %*$>$>%))&1)--j9%! 
 	#	#D	),B,F,Ft,L#D)2288"=!>n> 5 
OX	.:E224 ''/!2D2G2G788AC! C$!%d!P&+&@&@'++F3+//
;'
# "%%d+.D.H.H.N
%d
+%%&ABC 2288!7n 	 $T%[M1EeWA
N _ %% 
&tE{m3GwaP
 	

: )) *4;- 8G1 J


 '' 	(e 6' 	.
> '' 	(e 6' 	 '' 	(e 6' 	J ++ ,T%[M :gQ  sZ   	h4 i&jj?j" kk 'l l=4/i#&/j"/k/l/l:=/m,c                 T   K   | j                   j                          d {    y 7 wr   )r!   close)r"   s    r#   r   zAsyncSession.close  s     
((..
s   (&()NF)rT   N))__name__
__module____qualname____doc__r   r   r   r$   r   r   r   ContentListUnionContentListUnionDictLiveClientContentOrDictLiveClientRealtimeInputOrDictLiveClientToolResponseOrDictFunctionResponseOrDictr   boolr0   r   r   listrA   r;   	BlobUnionrK   rS   r   rs   rY   r   r   rm   rV   r`   ra   rc   r   r/   r   r   r%   r#   r   r   ;   sb   ,,9I& $)14 
$$((++1100**u3346
14 D>14x  UM 
mm5(9(99:;<UM UMn7M 7MrMK  

&
&
5//
02MK^]5+B+BC :F$U+F8;FU,,-FPe55 . '  --	8 $)m
$$((++1100**u3346
m D>m ""m^	r%   r   c            	       h    e Zd ZdZej
                  dddedeej                     de
e   fd       Zy)	AsyncLivez[Preview] AsyncLive.N)configmodelr   rT   c          	       K   | j                   j                         }t        j                  | j                   |      }t	        | j                   |      }| j                   j
                  r| j                   j
                  }| j                   j                  j                  }| d| d| }| j                   j                  j                  }	t        j                  t        j                  | j                   t        j                  ||      j                  d                  }
|
d= t!        |
dd	g|       t#        j$                  |
      }nt&        j(                  j+                  d
g      \  }}t&        j(                  j,                  j.                  j1                         }|j3                  |       |j4                  }| j                   j                  j                  }	|	"|	j7                  ddj9                  |      i       | j                   j                  j                  }| d| d}| j                   j:                  }| j                   j<                  }|j?                  d      rd| d| d|z   }t        j                  t        j@                  | j                   t        j                  ||      j                  d                  }
|
d= tC        |
g d      t!        |
g ddg       t#        j$                  |
      }	 tE        ||	      4 d{   }|jG                  |       d{    tH        jK                  |jM                  d       d{          tO        | j                   |       ddd      d{    y7 u7 ^7 77 # 1 d{  7  sw Y   yxY w# tP        $ r tE        ||	      4 d{  7  }|jG                  |       d{  7   tH        jK                  |jM                          d{  7         tO        | j                   |       ddd      d{  7   Y y# 1 d{  7  sw Y   Y yxY ww xY ww)a  [Preview] Connect to the live server.

    Note: the live API is currently in preview.

    Usage:

    .. code-block:: python

      client = genai.Client(api_key=API_KEY)
      config = {}
      async with client.aio.live.connect(model='...', config=config) as session:
        await session.send(input='Hello world!', end_of_turn=True)
        async for message in session.receive():
          print(message)
    z!/ws/google.ai.generativelanguage.z+.GenerativeService.BidiGenerateContent?key=)r   r   T)rE   r8   r   setupr   z.https://www.googleapis.com/auth/cloud-platform)scopesNAuthorizationz	Bearer {}z/ws/google.cloud.aiplatform.z#.LlmBidiService/BidiGenerateContentzpublishers/z	projects/z/locations//)r   generationConfigresponseModalitiesAUDIO)additional_headersFro   )r   r   )extra_headers))r    _websocket_base_urlr;   t_model_t_live_connect_configapi_key_http_optionsapi_versionheadersr   convert_to_dictr   _LiveConnectParameters_to_mldevr   LiveConnectParametersrI   setvr1   r2   googleauthdefault	transportrequestsRequestrefreshtokenupdateformatlocationproject
startswith _LiveConnectParameters_to_vertexgetvr   r0   loggerr   rt   r   ru   )r"   r   r   base_urltransformed_modelr}   r   versionurir   request_dictrequestcreds_auth_reqbearer_tokenr   r   wss                      r#   r   zAsyncLive.connect  s    , 335H		$"2"2E:,T-=-=vFO  ((g  ..::gj9'Bmnumvwc  ..66g,,

9
9))55'& 

-l x
 
<'7+->?

<(g $$BC % heQ &&//779hmmH[[l  ..66g		[//=
 	   ..::gj4WI=`ac!!**h  ((g		%	%m	4yH:Q7:KK 	 ,,

:
:))55'& 

-l x
 	lO	P	X\NQXPYZ

<(gF9 F FRggg"'''//0d&6&6"EE	F F F/F F F F
  FG4 F Fggg"'')OO$d&6&6"EE	F F F F FFs   L QN' N
N' N-N.(NN
"N9N' NN' 	Q
N' NNN' N$NN$ N' #Q$N' 'QOQP:O'P:P#P:'Q2P53Q8Q:Q	 QQ	QQQQ)r   r   r   r   
contextlibasynccontextmanagerr   r   r   LiveConnectConfigOrDictr   r   r   r   r%   r#   r   r     s\     !!
 9=	bF bF u445	bF
 \"bF "bFr%   r   r   r   rT   c                    |t        j                         }nt        |t              rNt	        |dg      "t        j                  | t	        |dg            }nd }t        j                  di |}||_        n9|j                  d }n!t        j                  | t	        |dg            }|}||_        |j                  t        j                  dt        d       |S )Nsystem_instructionzSetting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025)r]   r*   r   )r   LiveConnectConfigr   r   r   r;   	t_contentr  generation_configr,   r-   r.   )r   r   r}   converted_system_instructionr  s        r#   r   r     s    
 ^--/O&$F)*+7%&[[
d6$8#9:&" &*"--77O)EO&  (;;
d6$8#9: O);O&&&2MM	C 	 
r%   )4r   r`   r   r  r1   r   typingr   r   r   r   r   r   r	   r
   r,   google.authr   r   
websocketsr    r   r   r   r;   r   r   r    r   r   r   r   r   r   modelsr   r   websockets.asyncio.clientr   r   ModuleNotFoundErrorwebsockets.client	getLoggerr   r   r   
BaseModuler   r  r  r   r   r%   r#   <module>r     s     !      V V V    '       & . .  % &(8/ 
		.	/< X XxgF&& gFT##U223# #g  (0'(s    C! !C54C5