U
    hEB                     @   s  d dl Z d dlZd dlZd dlmZmZmZmZ d dlm	  m
Z d dlmZ d dlmZ d dlmZ d dlmZ ejejddd	Zejeej d
ddZejejdddZeej eej dddZejeej dddZd:ddddejee eej eej ejdddZ d;ddddejee eej eej ejdddZ!dddddddddeej" ee eej eej ee# ee$ ee# ee# eej ej%d
ddZ&dd  Z'd!Z(d!dddddddddd"
eej" ee eej eej ee# ee$ ee# ee# eej eej) ej*d#d$d%Z+e'e+j,ddddddddddd"
eej" ee eej eej ee# ee$ ee# ee# eej eej- ej*d#d&d'Z.ej/j0ej/j1fd(krd)d*iZ2ni Z2e'ej*j,e j3f e2d+d,iG d-d. d.ej*Z*ej%ej4eej)ej-f e*d/d0d1Z5d<ej%eej) e*d2d3d4Z6d=ej%eej- e*d2d5d6Z7dddde(dd7ejee eej eej eeej- d7d8d9Z8dS )>    N)IterableListOptionalUnion)get_default_discuss_client) get_default_discuss_async_client)discuss_types)model_types)contentreturnc                 C   s4   t | tjr| S t | tr&tj| dS t| S d S )Nr
   )
isinstanceglmMessagestrr    r   ?/tmp/pip-unpacked-wheel-doshhd5e/google/generativeai/discuss.py_make_message   s
    
r   )messagesr   c                 C   s   t | tttjfrt| g} ndd | D } tdd | d d d D }|sRd}n t|dkrh| }n
t	
dtd	d | dd d D }|sd
}n t|dkr| }n
t	
dtdd | D r| S ||g}t| D ]\}}||d  |_q| S )Nc                 S   s   g | ]}t |qS r   )r   ).0messager   r   r   
<listcomp>+   s     z"_make_messages.<locals>.<listcomp>c                 s   s   | ]}|j r|j V  qd S Nauthorr   msgr   r   r   	<genexpr>-   s      z!_make_messages.<locals>.<genexpr>   0   z$Authors are not strictly alternatingc                 s   s   | ]}|j r|j V  qd S r   r   r   r   r   r   r   5   s      1c                 s   s   | ]}|j V  qd S r   r   r   r   r   r   r   =   s     )r   r   dictr   r   r   setlenpopr   ZAuthorErrorall	enumerater   )r   Zeven_authorsZeven_authorZodd_authorsZ
odd_authorZauthorsir   r   r   r   _make_messages'   s*    



r)   )itemr   c                 C   s   t | tjr| S t | trL|  } t| d | d< t| d | d< t| S t | trxt| \}}tjt|t|dS t| S )Ninputoutputr+   r,   )r   r   Exampler"   copyr   r   list)r*   r+   r,   r   r   r   _make_exampleG   s    


r1   )examplesr   c                 C   s   t | d dkrttdg }g }t| D ]L\}}t|}|| |d dkrVq.tj|d |d d}|| g }q.|S )Nr   r   z            You must pass `Primer` objects, pairs of messages, or an *even* number of messages, got: 
              {len(primers)} messagesr    r-   )	r$   
ValueErrortextwrapdedentr'   r   appendr   r.   )r2   resultpairnr*   r   Zprimerr   r   r   _make_examples_from_flatY   s(    

r:   c                 C   s   t | tjr| gS t | tr&t| gS t| } | s6| S | d }t |trrd|krXt| S d|krhd|kstdnt |tj	rt| S g }| D ]}|
t| q|S )Nr   r
   r+   r,   zTTo create an `Example` from a dict you must supply both `input` and an `output` keys)r   r   r.   r"   r1   r0   r:   	TypeErrorr   ZMESSAGE_OPTIONSr6   )r2   firstr7   r*   r   r   r   _make_examplest   s*    


r=   contextr2   r   )promptr?   r2   r   r   c                C   s   | d krt |||d} nH|d k	p.|d k	p.|d k	}|r<tdt| tjrL| S t| t rXnd| i} t|  }|tj	st
d|tj	  | dd }|d k	rt|| d< | dd }|d k	rt|| d< dd |  D } | S )Nr>   zWYou can't set `prompt`, and its fields `(context, examples, messages)` at the same timer   z.Found extra entries in the prompt dictionary: r2   c                 S   s   i | ]\}}|d k	r||qS r   r   )r   kvr   r   r   
<dictcomp>   s       z-_make_message_prompt_dict.<locals>.<dictcomp>)r"   r3   r   r   MessagePromptr#   keysissubsetr   ZMESSAGE_PROMPT_KEYSKeyErrorgetr=   r)   items)r@   r?   r2   r   Zflat_promptrE   r   r   r   _make_message_prompt_dict   s<    
rJ   c                C   s   t | |||d} t| S )Nr@   r?   r2   r   )rJ   r   rD   rK   r   r   r   _make_message_prompt   s       rL   )r?   r2   r   temperaturecandidate_counttop_ptop_kr@   )
modelr?   r2   r   rM   rN   rO   rP   r@   r   c        	   	      C   s0   t | } t||||d}tj| |||||dS )NrK   )rQ   r@   rM   rO   rP   rN   )r	   Zmake_model_namerL   r   GenerateMessageRequest	rQ   r?   r2   r   rM   rN   rO   rP   r@   r   r   r   _make_generate_message_request   s    
   rT   c                    s    fdd}|S )Nc                    s
    | _ | S r   )__doc__)fdocr   r   inner   s    zset_doc.<locals>.innerr   )rX   rY   r   rW   r   set_doc   s    rZ   zmodels/chat-bison-001)
rQ   r?   r2   r   rM   rN   rO   rP   r@   client)rQ   r?   r2   r   rM   rN   rO   rP   r@   r[   r   c        
         C   s&   t | ||||||||d	}
t|	|
dS )a"  Calls the API and returns a `types.ChatResponse` containing the response.

    Args:
        model: Which model to call, as a string or a `types.Model`.
        context: Text that should be provided to the model first, to ground the response.

            If not empty, this `context` will be given to the model first before the
            `examples` and `messages`.

            This field can be a description of your prompt to the model to help provide
            context and guide the responses.

            Examples:

            * "Translate the phrase from English to French."
            * "Given a statement, classify the sentiment as happy, sad or neutral."

            Anything included in this field will take precedence over history in `messages`
            if the total input size exceeds the model's `Model.input_token_limit`.
        examples: Examples of what the model should generate.

            This includes both the user input and the response that the model should
            emulate.

            These `examples` are treated identically to conversation messages except
            that they take precedence over the history in `messages`:
            If the total input size exceeds the model's `input_token_limit` the input
            will be truncated. Items will be dropped from `messages` before `examples`
        messages: A snapshot of the conversation history sorted chronologically.

            Turns alternate between two authors.

            If the total input size exceeds the model's `input_token_limit` the input
            will be truncated: The oldest items will be dropped from `messages`.
        temperature: Controls the randomness of the output. Must be positive.

            Typical values are in the range: `[0.0,1.0]`. Higher values produce a
            more random and varied response. A temperature of zero will be deterministic.
        candidate_count: The **maximum** number of generated response messages to return.

            This value must be between `[1, 8]`, inclusive. If unset, this
            will default to `1`.

            Note: Only unique candidates are returned. Higher temperatures are more
            likely to produce unique candidates. Setting `temperature=0.0` will always
            return 1 candidate regardless of the `candidate_count`.
        top_k: The API uses combined [nucleus](https://arxiv.org/abs/1904.09751) and
            top-k sampling.

            `top_k` sets the maximum number of tokens to sample from on each step.
        top_p: The API uses combined [nucleus](https://arxiv.org/abs/1904.09751) and
           top-k sampling.

           `top_p` configures the nucleus sampling. It sets the maximum cumulative
            probability of tokens to sample from.

            For example, if the sorted probabilities are
            `[0.5, 0.2, 0.1, 0.1, 0.05, 0.05]` a `top_p` of `0.8` will sample
            as `[0.625, 0.25, 0.125, 0, 0, 0].

            Typical values are in the `[0.9, 1.0]` range.
        prompt: You may pass a `types.MessagePromptOptions` **instead** of a
            setting `context`/`examples`/`messages`, but not both.
        client: If you're not relying on the default client, you pass a
            `glm.DiscussServiceClient` instead.

    Returns:
        A `types.ChatResponse` containing the model's reply.
    rS   r[   request)rT   _generate_responserQ   r?   r2   r   rM   rN   rO   rP   r@   r[   r]   r   r   r   chat   s    Rr`   c        
            s,   t | ||||||||d	}
t|	|
dI d H S )NrS   r\   )rT   _generate_response_asyncr_   r   r   r   
chat_asyncX  s    rb   )   
   Zkw_onlyTinitFc                   @   s   e Zd ZU ejdd ddZeej e	d< dd Z
eeejjjedd	d
Zejejddd
ZeejjjejejdddZeejjjejejdddZdS )ChatResponsec                   C   s   d S r   r   r   r   r   r   <lambda>      zChatResponse.<lambda>F)defaultrepr_clientc                 K   s"   |  D ]\}}t| || qd S r   )rI   setattr)selfkwargskeyvaluer   r   r   __init__  s    zChatResponse.__init__)r   c                 C   s   | j d d S )Nr
   )r   )rm   r   r   r   last  s    zChatResponse.last)r   c                 C   s   t |}|| jd< d S )Nrr   )r   r   )rm   r   r   r   r   rs     s    )r   r   c                 C   sb   t | jtjrtd|  }|d t|d |d< |d t	| t
f |}t|| jdS )NzBreply can't be called on an async client, use reply_async instead.
candidatesr   r]   r[   )r   rk   r   DiscussServiceAsyncClientr;   to_dictr%   r0   r6   r   rT   r^   rm   r   r]   r   r   r   reply  s    

zChatResponse.replyc                    sh   t | jtjrtd|  }|d t|d |d< |d t	| t
f |}t|| jdI d H S )NzEreply_async can't be called on a non-async client, use reply instead.rt   r   ru   )r   rk   r   DiscussServiceClientr;   rw   r%   r0   r6   r   rT   ra   rx   r   r   r   reply_async  s    

zChatResponse.reply_asyncN)__name__
__module____qualname__dataclassesfieldrk   r   r   rz   __annotations__rq   propertyrZ   r   rf   rs   rU   r   setterMessageOptionsry   r{   r   r   r   r   rf   {  s$   
 rf   )r]   responser[   r   c                 C   s   t | | } | d}|d | d< |d | d< |d | d< t ||}| d |d d  | dd  | dd  tf ||d d	| S )
Nr@   r2   r?   r   rt   r   rM   rN   )rk   rt   )typerw   r%   r6   
setdefaultrf   )r]   r   r[   r@   r   r   r   _build_chat_response  s    
 r   )r]   r[   r   c                 C   s$   |d krt  }|| }t| ||S r   )r   generate_messager   r]   r[   r   r   r   r   r^     s    
r^   c                    s*   |d krt  }|| I d H }t| ||S r   )r   r   r   r   r   r   r   ra     s    ra   )r@   r?   r2   r   rQ   r[   c                 C   s:   t | |||d} |d krt }|j|| d}t||S )Nr>   )rQ   r@   )rL   r   count_message_tokensr   rw   )r@   r?   r2   r   rQ   r[   r7   r   r   r   r     s    	   r   )N)N)N)N)9r   sysr4   typingr   r   r   r   Zgoogle.ai.generativelanguageZaiZgenerativelanguager   Zgoogle.generativeai.clientr   r   Zgoogle.generativeai.typesr   r	   r   r   r   ZMessagesOptionsr)   ZExampleOptionsr.   r1   r:   ZExamplesOptionsr=   ZMessagePromptOptionsr   rD   rJ   rL   ZModelNameOptionsfloatintrR   rT   rZ   ZDEFAULT_DISCUSS_MODELrz   rf   r`   rU   rv   rb   version_infomajorminorZDATACLASS_KWARGSZ	dataclassZGenerateMessageResponser   r^   ra   r   r   r   r   r   <module>   s"  	 " / a

3  