o
    Zh?                     @   sR  d dl Z d dlmZmZmZmZmZ ddlmZ	 ddlm
Z
 ddlmZmZ ddl
mZmZmZmZmZ e jdkr@d d	lmZ nd d	lmZ d
edefddZdee defddZdedefddZdee dee fddZG dd dZdeee ef dee	j fddZG dd deZG dd dZ G dd  d eZ!G d!d" d"Z"dS )#    N)AsyncIterator	AwaitableOptionalUnionget_args   )_transformers)types)AsyncModelsModels)ContentGenerateContentConfigOrDictGenerateContentResponsePartPartUnionDict)   
   )	TypeGuardcontentreturnc                 C   sD   | j sdS | j D ]}|t kr dS |jd ur|jdkr dS qdS )NF T)partsr   text)r   part r   I/var/www/html/lang_env/lib/python3.10/site-packages/google/genai/chats.py_validate_content   s   

r   contentsc                 C   s$   | sdS | D ]	}t |s dS qdS )NFT)r   )r   r   r   r   r   _validate_contents*   s   r   responsec                 C   s*   | j sdS | j d jsdS t| j d jS )NFr   )
candidatesr   r   )r   r   r   r   _validate_response3   s
   r!   comprehensive_historyc                 C   s   | sg S g }t | }d}| | }|jdkrtd||k r}| | jdvr.td| | j | | jdkr>| | }|d7 }n;g }d}||k rm| | jdkrm|| |  |r^t| | s^d	}|d7 }||k rm| | jdksM|ry|| || ||k s|S )
a  Extracts the curated (valid) history from a comprehensive history.

  The comprehensive history contains all turns (user input and model responses),
  including any invalid or rejected model outputs.  This function filters
  that history to return only the valid turns.

  A "turn" starts with one user input (a single content) and then follows by
  corresponding model response (which may consist of multiple contents).
  Turns are assumed to alternate: user input, model output, user input, model
  output, etc.

  Args:
      comprehensive_history: A list representing the complete chat history.
        Including invalid turns.

  Returns:
      curated history, which is a list of valid turns.
  r   userz$History must start with a user turn.)r#   modelz$Role must be user or model, but got r   Tr$   F)lenrole
ValueErrorappendr   extend)r"   Zcurated_historylengthiZcurrent_inputZcurrent_outputis_validr   r   r   _extract_curated_history;   s:   



r-   c                   @   sn   e Zd ZdZdddedee dee fddZ	d	ed
ee dee de
fddZdde
dee fddZdS )	_BaseChatzBase chat session.Nconfigr$   r0   historyc                C   s"   || _ || _|| _	 t|| _d S N)_model_config_comprehensive_historyr-   _curated_historyselfr$   r0   r1   r   r   r   __init__r   s   
z_BaseChat.__init__
user_inputmodel_output"automatic_function_calling_historyr,   c                 C   sn   |r|t | jd n|g}|r|ntdg dg}| j| | j| |r5| j| | j| dS dS )a/  Records the chat history.

    Maintaining both comprehensive and curated histories.

    Args:
      user_input: The user's input content.
      model_output: A list of `Content` from the model's response. This can be
        an empty list if the model produced no output.
      automatic_function_calling_history: A list of `Content` representing the
        history of automatic function calls, including the user input as the
        first entry.
      is_valid: A boolean flag indicating whether the current model output is
        considered valid.
    Nr$   )r&   r   )r%   r6   r   r5   r)   )r8   r:   r;   r<   r,   Zinput_contentsoutput_contentsr   r   r   record_history   s   z_BaseChat.record_historyFcuratedr   c                 C   s   |r| j S | jS )aH  Returns the chat history.

    Args:
        curated: A boolean flag indicating whether to return the curated (valid)
          history or the comprehensive (all turns) history. Defaults to False
          (returns the comprehensive history).

    Returns:
        A list of `Content` objects representing the chat history.
    )r6   r5   )r8   r?   r   r   r   get_history   s   z_BaseChat.get_history)F)__name__
__module____qualname____doc__strr   r   listr   r9   boolr>   r@   r   r   r   r   r.   o   s(    

(r.   c                 C   sT   t | trtdd | D S ttj}t| |v rdS tjd ur(t | tjr(dS dS )Nc                 s   s    | ]}t |V  qd S r2   )_is_part_type).0r   r   r   r   	<genexpr>   s    z _is_part_type.<locals>.<genexpr>TF)
isinstancerF   allr   r	   	PartUniontypeZ	PIL_Image)r   Zallowed_part_typesr   r   r   rH      s   

rH   c                
       s   e Zd ZdZdddededee dee	 f fdd	Z
	dd
eee ef dee defddZ	dd
eee ef dee fddZ  ZS )ChatzChat session.Nr/   modulesr$   r0   r1   c                      || _ t j|||d d S N)r$   r0   r1   _modulessuperr9   r8   rP   r$   r0   r1   	__class__r   r   r9         
zChat.__init__messager   c                 C   s   t |stdtj dtj dt| t| jj	|}| jj
| j| j|g |r+|n| jd}|jr@|jd jr@|jd jgng }|jrH|jng }| j|||t|d |S )a  Sends the conversation history with the additional message and returns the model's response.

    Args:
      message: The message to send to the model.
      config:  Optional config to override the default Chat config for this
        request.

    Returns:
      The model's response.

    Usage:

    .. code-block:: python

      chat = client.chats.create(model='gemini-1.5-flash')
      response = chat.send_message('tell me a story')
    #Message must be a valid part type:  or , got r$   r   r0   r   r:   r;   r<   r,   rH   r'   r	   rM   r   rN   t	t_contentrT   _api_clientZgenerate_contentr3   r6   r4   r    r   r<   r>   r!   r8   rZ   r0   input_contentr   r;   r<   r   r   r   send_message   s>   


zChat.send_messagec           	      c   s   t |stdtj dtj dt| t| jj	|}g }d}d}d}t
| jtr| jj| j| j|g |r:|n| jdD ],}t|sGd}|jrY|jd jrY||jd j |jrh|jd jrh|jd j}|V  q?|jrr|jng }| j||||o|duo|dud	 dS dS )
a  Sends the conversation history with the additional message and yields the model's response in chunks.

    Args:
      message: The message to send to the model.
      config: Optional config to override the default Chat config for this
        request.

    Yields:
      The model's response in chunks.

    Usage:

    .. code-block:: python

      chat = client.chats.create(model='gemini-1.5-flash')
      for chunk in chat.send_message_stream('tell me a story'):
        print(chunk.text)
    r[   r\   r]   NTr^   Fr   r_   )rH   r'   r	   rM   r   rN   ra   rb   rT   rc   rK   r   generate_content_streamr3   r6   r4   r!   r    r   r(   finish_reasonr<   r>   )	r8   rZ   r0   re   r=   rh   r,   chunkr<   r   r   r   send_message_stream  sR   



zChat.send_message_streamr2   )rA   rB   rC   rD   r   rE   r   r   rF   r   r9   r   r   r   rf   rj   __classcell__r   r   rW   r   rO      s4    
7rO   c                	   @   L   e Zd ZdZdefddZddddedee d	ee	e
  d
efddZdS )Chatsz%A util class to create chat sessions.rP   c                 C   
   || _ d S r2   rT   r8   rP   r   r   r   r9   S     
zChats.__init__Nr0   r1   r$   r0   r1   r   c                C      t | j|||r|dS g dS zCreates a new chat session.

    Args:
      model: The model to use for the chat.
      config: The configuration to use for the generate content request.
      history: The history to use for the chat.

    Returns:
      A new chat session.
    )rP   r$   r0   r1   )rO   rT   r7   r   r   r   createV     zChats.create)rA   rB   rC   rD   r   r9   rE   r   r   rF   r   rO   ru   r   r   r   r   rm   P      
rm   c                
       s   e Zd ZdZdddededee dee	 f fdd	Z
	dd
eee ef dee defddZ	dd
eee ef dee deee  fddZ  ZS )	AsyncChatzAsync chat session.Nr/   rP   r$   r0   r1   c                   rQ   rR   rS   rV   rW   r   r   r9   r  rY   zAsyncChat.__init__rZ   r   c                    s   t |stdtj dtj dt| t| jj	|}| jj
| j| j|g |r,|n| jdI dH }|jrD|jd jrD|jd jgng }|jrL|jng }| j|||t|d |S )a  Sends the conversation history with the additional message and returns model's response.

    Args:
      message: The message to send to the model.
      config: Optional config to override the default Chat config for this
        request.

    Returns:
      The model's response.

    Usage:

    .. code-block:: python

      chat = client.aio.chats.create(model='gemini-1.5-flash')
      response = await chat.send_message('tell me a story')
    r[   r\   r]   r^   Nr   r_   r`   rd   r   r   r   rf     s@   


zAsyncChat.send_messagec                    sR   t |stdtj dtj dt| tjj	| fdd}| S )a  Sends the conversation history with the additional message and yields the model's response in chunks.

    Args:
      message: The message to send to the model.
      config: Optional config to override the default Chat config for this
        request.

    Yields:
      The model's response in chunks.

    Usage:

    .. code-block:: python
      chat = client.aio.chats.create(model='gemini-1.5-flash')
      async for chunk in await chat.send_message_stream('tell me a story'):
        print(chunk.text)
    r[   r\   r]   c                    s   g } d }d}d }j jjjg  r njdI d H 2 z03 d H W }t|s+d}|jr=|jd jr=| |jd j |jrL|jd j	rL|jd j	}|V  q6 j
| |j|o\| o\|d d S )NTr^   Fr   r_   )rT   rg   r3   r6   r4   r!   r    r   r(   rh   r>   r<   )r=   rh   r,   ri   r0   re   r8   r   r   async_generator  s0   


z6AsyncChat.send_message_stream.<locals>.async_generator)
rH   r'   r	   rM   r   rN   ra   rb   rT   rc   )r8   rZ   r0   rz   r   ry   r   rj     s   
zAsyncChat.send_message_streamr2   )rA   rB   rC   rD   r
   rE   r   r   rF   r   r9   r   r   r   rf   r   r   rj   rk   r   r   rW   r   rx   o  s8    
6
rx   c                	   @   rl   )
AsyncChatsz+A util class to create async chat sessions.rP   c                 C   rn   r2   ro   rp   r   r   r   r9     rq   zAsyncChats.__init__Nrr   r$   r0   r1   r   c                C   rs   rt   )rx   rT   r7   r   r   r   ru     rv   zAsyncChats.create)rA   rB   rC   rD   r
   r9   rE   r   r   rF   r   rx   ru   r   r   r   r   r{     rw   r{   )#systypingr   r   r   r   r   r   r   ra   r	   modelsr
   r   r   r   r   r   r   version_infor   Ztyping_extensionsrG   r   rF   r   r!   r-   r.   ZContentTyperH   rO   rm   rx   r{   r   r   r   r   <module>   s8   
	
4L
 ~