
    Li>                        U 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Zddl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( ddl'm)Z* ejZ                  rddl.m/Z0 ddl1m2Z3 ddl4m5Z5 ddlm6Z6 nLeZ0ejn                  e8d<   eZ3ejn                  e8d<   eZ5ejn                  e8d<   	 ddl.m/Z0 ddl1m2Z3 ddl4m5Z5 ddlm6Z6  ejt                  d      Z;dZ< G d d      Z= G d d ej|                        Z?d!ed"e	ej                     d#ej                  fd$ZBy# e+$ r ddl,m(Z( ddl,m)Z* Y w xY w# e9$ r dZ0dZ3dZ5dZ6Y {w xY w)%z[Preview] Live API client.    N)AnyAsyncIteratorOptionalSequenceUnionget_args)ConnectionClosed   )_api_module)_common)_live_converters)
_mcp_utils)_transformers)errors)types)BaseApiClient)get_value_by_path)set_value_by_path)AsyncLiveMusic)_Content_to_mldev)ClientConnection)connect)ClientSession)Tool)McpToGenAiToolAdapter)mcp_to_gemini_toolMcpClientSessionMcpToolr   z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'dedede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   ddfdZddddee	e
j(                  e
j*                  ee	e
j(                  e
j*                  f      f      deddfdZdddddddddee
j0                     dee
j2                     dee   dee
j0                     dee   dee
j4                     dee
j6                     ddfdZde	e
j                   ee
j                      f   dd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$jJ                  dd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
jN                  fd%Z(d)d&Z)y)*AsyncSessionz[Preview] AsyncSession.N
api_client	websocket
session_idc                 .    || _         || _        || _        y N)_api_client_wsr#   )selfr!   r"   r#   s       O/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/google/genai/live.py__init__zAsyncSession.__init__T   s     "DDH DO    F)inputend_of_turnr,   r-   returnc                   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)   r7   zAsyncSession.send^   sV     P MM	B 	 //{CN
((--

>2
333s   A A*"A(#A*Tturnsturn_completer<   r=   c                V  K   t        j                  ||      j                  dd      }| j                  j                  rt        j                  |d      }nt        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:

    .. code-block:: python

      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-live-2.5-flash-preview';

      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)
    r8   Tmodeexclude_noneconvert_keysfrom_objectclient_contentN)tt_client_content
model_dumpr&   vertexair   convert_to_dictlive_converters_LiveClientContent_to_mldevr'   r7   r8   r9   )r(   r<   r=   rF   client_content_dicts        r)   send_client_contentz AsyncSession.send_client_content   s     V ''}=HH$ I N   #33
t ,GG$ ((--

$46I#JK
LLLs   BB)!B'"B))mediaaudioaudio_stream_endvideotextactivity_startactivity_endrP   rQ   rR   rS   rT   rU   rV   c          	      |  K   i }|||d<   |||d<   |||d<   |||d<   |||d<   |||d<   |||d<   t        |      d	k7  r1t        d
t        |       dt        |j                                      t        j
                  j                  |      }	| j                  j                  rt        j                  |	      }
nt        j                  |	      }
t        j                  |
      }
t        j                  |
      }
| j                  j!                  t#        j$                  d|
i             d{    y7 w)a  Send realtime input to the model, only send one argument per call.

    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:

    .. code-block:: python

      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-live-2.5-flash-preview';


      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}')
    NrP   rQ   rR   rS   rT   rU   rV   r
   z"Only one argument can be set, got z: rD   realtime_input)len
ValueErrorlistkeysr   LiveSendRealtimeInputParametersmodel_validater&   rJ   rL   *_LiveSendRealtimeInputParameters_to_vertex)_LiveSendRealtimeInputParameters_to_mldevr   rK   encode_unserializable_typesr'   r7   r8   r9   )r(   rP   rQ   rR   rS   rT   rU   rV   kwargsrX   realtime_input_dicts              r)   send_realtime_inputz AsyncSession.send_realtime_input   se    | "$FfWofWo##3f fWofVn!!/f+f^
6{a.s6{m <6;;=!"$  ::IIN   

D
D(  
C
C( 
 "112EF!== ((--

$46I#JK
LLLs   D2D<4D:5D<function_responsesc                  K   t        j                  |      }| j                  j                  rt	        j
                  |d      }nNt	        j
                  |d      }|j                  dg       D ]"  }|j                  d      t        t               | j                  j                  t        j                  d|i             d{    y7 w)aF  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:

    .. code-block:: python

      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-live-2.5-flash-preview';

      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-live-2.5-flash-preview',
          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)
    TrB   functionResponsesidNtool_response)rG   t_tool_responser&   rJ   r   rK   getrZ   _FUNCTION_RESPONSE_REQUIRES_IDr'   r7   r8   r9   )r(   re   ri   tool_response_dictresponses        r)   send_tool_responsezAsyncSession.send_tool_responseT  s     L %%&89M  "22
d #22
d ),,-@"E ;(<<%9:
:; ((--

O5G#HI
JJJs   BCACCCc                   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_contentr=   )r(   results     r)   receivezAsyncSession.receive  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.   r1   N)return_when-q=)r3   r4   r5   asyncioEventcreate_task
_send_loopis_setrq   waitFIRST_COMPLETEDdoners   sleepr	   cancelCancelledError)r(   ru   rv   
stop_event	recv_tasks        r)   start_streamzAsyncSession.start_stream  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                 2  K   t        j                         }	 | j                  j                  d       d {   }|r	 t        j                  |      }ni }| j                  j                  rt        j                  |      }n|}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decodeFailed to parse response: rn   rb   )r   LiveServerMessager'   recv	TypeErrorr8   loadsdecoderJSONDecodeErrorrZ   r&   rJ   rL   _LiveServerMessage_from_vertex_from_responserI   )r(   parameter_modelraw_responsern   response_dicts        r)   rq   zAsyncSession._receive  s     --/O+88===66l H::l+ h  %DDXNmm""11'A'A'C 2  ! 7 +88==?**l+
 \\)) H5l5EFGGHs[   DB6 B4B6 DC( A D4B6 6&C%CC%"D$C%%D(,DDdata_streamr   c                   K   |2 3 d {   }t        j                  t        j                  ||      g      }| j                  |       d {    t	        j
                  d       d {    m7 h7 $7 	6 |j                          y w)Ndatarv   media_chunks)r,   rz   )r   LiveClientRealtimeInputBlobr7   r{   r   set)r(   r   rv   r   r   model_inputs         r)   r~   zAsyncSession._send_loop%  s      " # #d11

	BC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              rJi }g }|D ]7  }t        |t5        t
        j6                              s'|j/                  |       9 | j                  j                  r8t9        j:                  |      D cg c]  }t=        j>                  |d       }}n,t9        j:                  |      D cg c]  }tA        ||       }}g }|D ]\  }	 t        jB                  d$i |}|j/                  t        jD                  |j                  dd	      d   |jF                               ^ t        j0                  t        jH                  ||            }
|
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        jJ                  |            }
|
S t        |t              r"d|v sd|v rKd|v r|d   }n|d   }t        j0                  t        jH                  ||j-                  d                  }
|
S d|v rV	 t        jL                  d$i |}t        j0                  t        jJ                  |j                  dd	      d               }
|
S d |v rV	 t        jN                  d$i |}t        j0                  t        j2                  |j                  dd	      d                }
|
S t        dt        |       d| d      t        |t
        jL                        rE|j                  dd	      }t        j0                  t        jJ                  |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        jP                  tS        jT                  |j                        |jV                  #              ||
d!   d<   |
S t        |t
        jX                        r^|j                  dd	      }t        j0                  t        jH                  |j-                  d      |j-                  d                  }
|
S t        |t
        jN                        r| j                  j                  s4|jZ                  (|jZ                  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.rF   r=   Tr   zUnsupported input type "z" or input content ""r8   r?   namern   rh   c              3   T   K   | ]   }t        |t              xr
 d |v xr d|v  " yw)r   rn   N
isinstancedict.0cs     r)   	<genexpr>z5AsyncSession._parse_client_message.<locals>.<genexpr>a  s4      5 	1d?!?
a?5s   &()rA   r@   )r   rn   )re   )ri   c              3   <   K   | ]  }t        |t                y wr%   )r   strr   s     r)   r   z5AsyncSession._parse_client_message.<locals>.<genexpr>  s      7 
1c7s   rB   parts)r   roler;   )rF   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>  s     BQz!UZZ(Bs   $&r   )rX   contentr<   r   re   rX   r   r    ).logginginfor   r   r   r   r   pydanticValidationErrorrZ   typer   bytesrI   r&   rJ   rl   r   anyFunctionResponserh   FunctionResponseDictrk   appendLiveClientMessageDictLiveClientToolResponseDictr   	PartUnionrG   
t_contentsr   rK   r   ContentContentDictr   LiveClientContentDictLiveClientRealtimeInputDictr   LiveClientToolResponseBlobDictbase64	b64decoderv   LiveClientContentre   )r(   r,   r-   formatted_input
blob_inputfunction_responses_inputitemfunction_response_inputfunction_response_dictfunction_response_typeddictr:   	to_objectcontent_input_partscontentscontent_dict_listcontent_inputr   content_turnsrX   tool_response_inputrc   formatted_media_chunksrN   function_response_lists                           r)   r6   z"AsyncSession._parse_client_message5  s     !OllEF$ 788%o	E4	 Vu_
ZZ(%(

 
J

	+

//51 !!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
*+ 
			"	" %89
 ##Dt<
 
 %89
 dI.
 

 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
 	

8 )) *4;- 8G1 J


 '' 	(e 6' 	.
> '' 	(e 6' 	 '' 	(e 6' 	J ++ ,T%[M :gQ  sZ   	h i	i7i<jj3,j8 k* %l/i/i4/j08/k'*/l/mc                 T   K   | j                   j                          d {    y 7 wr%   )r'   closer(   s    r)   r   zAsyncSession.closec  s     
((..
s   (&(r%   )NF)r.   N)*__name__
__module____qualname____doc__r   r   r   r   r*   r   r   ContentListUnionContentListUnionDictLiveClientContentOrDictLiveClientRealtimeInputOrDictLiveClientToolResponseOrDictFunctionResponseOrDictr   boolr7   r   r   r[   rO   BlobImageUnionDict
BlobOrDictActivityStartOrDictActivityEndOrDictrd   ro   r   r   rt   r   r   rq   r{   r|   r~   r   r6   r   r   r+   r)   r    r    Q   sH    #'	!! "! 3-	!. $)14 
$$((++1100**u3346
14 D>14 14x  XM 
mm5(9(99:;=XM XM XMz 37*.)-26 <@8<gM e../gM e&&'	gM
 !gM e../gM SMgM u889gM U445gM gMRSK  

&
&
5//
02SK SKj]5+B+BC :F$U+F8;FU,,-FPe55 . '  --	
 8 $)l
$$((++1100**u3346
l D>l ""l\	r+   r    c            	            e Zd ZdZdef fdZedefd       Ze	j                  ddded	eej                     dee   fd
       Z xZS )	AsyncLivez[Preview] AsyncLive.r!   c                 D    t         |   |       t        |      | _        y r%   )superr*   r   _music)r(   r!   	__class__s     r)   r*   zAsyncLive.__init__k  s    	GZ  ,DKr+   r.   c                     | j                   S r%   )r   r   s    r)   musiczAsyncLive.musico  s    ;;r+   N)configmodelr   c          	       K   t        |t              rt        j                  d'i |}|r|j                  rt        d      | j                  j                         }t        |t              r|j                  d      }t        j                  | j                  |      }t        | j                  |       d{   }| j                  j                  ry| j                  j                  sb| j                  j                  j                   }| j                  j                  }d}| j                  j                  j"                  }	|	|	j%                         ni }
|j'                  d      rYt)        j*                  dt,        j.                         d}d	| |
d
<   |dk7  r%t)        j*                  dt,        j.                         | d| d| }t1        j2                  t5        j6                  | j                  t        j8                  ||      j;                  d                  }|d= t=        |ddg|       t?        j@                  |      }n| j                  j                  r
| j                  j                  r| j                  j                  }| j                  j                  j                   }| d| d}| j                  j                  j"                  }	|	|	j%                         ni }
t1        j2                  t5        jB                  | j                  t        j8                  ||      j;                  d                  }|d= t=        |ddg|       t?        j@                  |      }n| j                  j                  j                   }| j                  jD                  xr | j                  jF                  }| j                  jH                  rP|sN| j                  jH                  }|}| j                  j                  j"                  }	|	|	j%                         ni }
n| d| d}| j                  jJ                  s%tL        jN                  jQ                  dg      \  }}n| j                  jJ                  }|jR                  r|jT                  sCtL        jN                  jV                  jX                  j[                         }|j]                  |       |jR                  }| j                  j                  j"                  }	|	|	j%                         ni }
|
j_                  d
      sd| |
d
<   | j                  jF                  }| j                  jD                  }|j'                  d      r|r|rd| d| d|z   }t1        j2                  t5        jB                  | j                  t        j8                  ||      j;                  d                  }|d= ta        |g d      	 t=        |g dd g       t?        j@                  |      }|jb                  r8te        jf                  |jb                        r|
i }
te        jh                  |
       tk        |fd!|
i| j                  jl                  4 d{   }|jo                  |       d{    	 |jq                  d"#       d{   }|r	 t?        jt                  |      }ni }| j                  j                  rt5        jz                  |      }n|}t        j|                  j                  ||j;                         %      }|j                  r|j                  j                  }nd}t        | j                  ||&       ddd      d{    y7 7 7 7 # tr        $ r |jq                          d{  7  }Y w xY w# t>        jv                  jx                  $ r t        d$|      w xY w7 f# 1 d{  7  sw Y   y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_client_content(
          turns=types.Content(
            role='user',
            parts=[types.Part(text='hello!')]
          ),
          turn_complete=True
        )
        async for message in session.receive():
          print(message)

    Args:
      model: The model to use for the live session.
      config: The configuration for the live session.
      **kwargs: additional keyword arguments.

    Yields:
      An AsyncSession object.
    zgoogle.genai.client.aio.live.connect() does not support http_options at request-level in LiveConnectConfig yet. Please use the client-level http_options configuration instead.zutf-8NBidiGenerateContentzauth_tokens/zUThe SDK's ephemeral token support is experimental, and may change in future versions.)messagecategoryBidiGenerateContentConstrainedzToken Authorizationv1alphazThe SDK's ephemeral token support is in v1alpha only.Please use client = genai.Client(api_key=token.name, http_options=types.HttpOptions(api_version="v1alpha")) before session connection.z!/ws/google.ai.generativelanguage.z.GenerativeService.)r   r   T)rA   )r!   rE   r   setupr   z/ws/google.cloud.aiplatform.z#.LlmBidiService/BidiGenerateContentz.https://www.googleapis.com/auth/cloud-platform)scopeszBearer zpublishers/z	projects/z/locations//)r  generationConfigresponseModalitiesAUDIOadditional_headersFr   r   r   )r!   r"   r#   r   )Cr   r   r   LiveConnectConfighttp_optionsrZ   r&   _websocket_base_urlr   r   rG   t_model_t_live_connect_configapi_keyrJ   _http_optionsapi_versionheaderscopy
startswithr3   r4   r   ExperimentalWarningr   rK   rL   _LiveConnectParameters_to_mldevLiveConnectParametersrI   setvr8   r9    _LiveConnectParameters_to_vertexprojectlocationcustom_base_url_credentialsgoogleauthdefaulttokenvalid	transportrequestsRequestrefreshrk   getvtoolsr   has_mcp_tool_usageset_mcp_usage_header
ws_connect_websocket_ssl_ctxr7   r   r   r   r   r   r   r   r   setup_completer#   r    )r(   r   r   base_urltransformed_modelr   versionr  methodoriginal_headersr  urirequest_dictrequesthas_sufficient_authcreds_auth_reqbearer_tokenr  r  wsr   rn   r   setup_responser#   s                              r)   r   zAsyncLive.connects  s>    J &$&&00f&%%B  335H(E")h		$"2"2E:243C3CVLLO(8(8(A(A  ..::g  ((g$f))77??+;+G %%'Rg			N	+. //	
 2%+G9#5 i
--0
 11 j9'BUV\U]^c,,

9
9))55)( 

-l x
 
<'7+->?

<(g				!	!d&6&6&?&?  ((g  ..::gj4WI=`ac))77??+;+G %%'Rg,,

:
:))55)( 

-l x
 
<'7+->?

<(g  ..::g



"
"
@t'7'7'@'@  
			)	)2E ..!++99AA'7'C!!# 	
 
6wi?bc,,[[((FG ) (% ""//% [[**33;;=(
--
!{{++99AA'7'C!!# 	 {{?+'.|n%='/
"!!**h  ((g		%	%m	4XyH:Q7:KK 	 ,,

:
:))55)( 

-l x
  O 
 	?I	
 

<(g!>!>" 
%%g. '+/+;+;+N+N ! !	GGG'WWEW22 
	JZZ-( 				"	"'FFxP ..== )C)C)E > n 
	&	&#22==

%% ;! ! !c Mb!  3 'WWY'
 ||++ 	J77GHI
I	J! ! ! !s   B3_-5]56V=_-3]84_-7_];_]?']=(]?,_/^'B _$_-/_0_-8_-;_=]??^$^^$!_#^$$_',___-_*_!_*&_-)r   r   r   r   r   r*   propertyr   r   
contextlibasynccontextmanagerr   r   r   LiveConnectConfigOrDictr   r    r   __classcell__)r   s   @r)   r   r   h  s    - - ^   !!
 9=	d d u445	d
 \"d "dr+   r   r!   r   r.   c                   K   |t        j                         }nt        |t              rMt	        |dg      !t        j                  t	        |dg            }nd }t        j                  di |}||_        n8|j                  d }n t        j                  t	        |dg            }|}||_        |j                  dd i      }|j                  rg |_	        |j                  D ]  }t        Xt        |t              rHt        ||j                          d {         }|j                  j                  |j                         at        5t        |t              r%|j                  j                  t!        |             |j                  j                  |        |j"                  t%        j&                  dt(        d       |S 7 w)Nsystem_instructionr'  )updatezSetting `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)rx   r1   r   )r   r	  r   r   r&  rG   	t_contentrB  
model_copyr'  r   r   
list_toolsextendr   r   r   generation_configr3   r4   r5   )r!   r   r   converted_system_instructionrB  parameter_model_copytoolmcp_to_genai_tool_adapters           r)   r  r  [  s    
 ^--/O&$F)*+7%&[[
v,-
.&" &*"--77O)EO&  (;;tF5I4J'KLO);O& )33GT?3K!#%% 
0		%*T;K*L$9))%
! 	""))*C*I*IJ:dG#<""))*<T*BC""))$/
0 ++7MM	C 	 
% *s   DGGB1G)Cr   r{   r   r=  r8   r   typingr   r   r   r   r   r   r3   google.authr  r   
websocketsr	    r   r   r   rL   r   r   rG   r   r   r&   r   r   r&  r   r  
live_musicr   modelsr   websockets.asyncio.clientr   r   r*  ModuleNotFoundErrorwebsockets.clientTYPE_CHECKINGmcpr   r   	mcp.typesr   r   	_adaptersr   r   Type__annotations__ImportError	getLoggerloggerrl   r    
BaseModuler   r?  r	  r  r   r+   r)   <module>r`     sa    !       J J    '   1      & . . & %68= 
3'.,"%FKK%'6;;'**	5)0. 
		.	/< T Tnp&& pf22U2232 2W!  6056& 
 G 	s$   E ,E0 E-,E-0F ?F 