o
    ß­jeU  ã                   @  s(  d dl mZ d dlZd dlZd dlZd dl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 d dlmZ d d	lmZ d d
lmZ d dlmZ d_dd„Zd`dd„Zdadd„Zdbdd „Zdcd"d#„Z	dddddd$œded,d-„Z	dddddd$œded.d/„Zddddddddd0œdfd;d<„Zd=Zd=ddddddddddd>œdgdDdE„Z e !e j"¡d=ddddddddddd>œdhdGdH„ƒZ#ej$j%ej$j&fdIkrÎdJdKiZ'ni Z'ej(e !ej)j"¡ej*dii e'¤dLdMi¤ŽG dNdO„ dOej)ƒƒƒƒZ)djdTdU„Z+		dkdldVdW„Z,		dkdmdXdY„Z-ddddedddZœdnd]d^„Z.dS )oé    )ÚannotationsN)ÚIterableÚList)Úget_default_discuss_client)Ú get_default_discuss_async_client)Ústring_utils)Úprotos)Údiscuss_types)Úhelper_types)Úmodel_types)Úpalm_safety_typesÚcontentúdiscuss_types.MessageOptionsÚreturnúprotos.Messagec                 C  s0   t | tjƒr| S t | tƒrtj| d�S t | ¡S )z<Creates a `protos.Message` object from the provided content.©r   )Ú
isinstancer   ÚMessageÚstrr   © r   úX/var/www/html/CropPilot/venv/lib/python3.10/site-packages/google/generativeai/discuss.pyÚ_make_message#   s
   

r   Úmessagesúdiscuss_types.MessagesOptionsúList[protos.Message]c                 C  sú   t | tttjfƒrt| ƒg} ndd„ | D ƒ} tdd„ | ddd… D ƒƒ}|s)d}nt|ƒdkr4| ¡ }nt	 
d	¡‚td
d„ | ddd… D ƒƒ}|sLd}nt|ƒdkrW| ¡ }nt	 
d	¡‚tdd„ | D ƒƒrg| S ||g}t| ƒD ]\}}||d  |_qo| S )a3  
    Creates a list of `protos.Message` objects from the provided messages.

    This function takes a variety of message content inputs, such as strings, dictionaries,
    or `protos.Message` objects, and creates a list of `protos.Message` objects. It ensures that
    the authors of the messages alternate appropriately. If authors are not provided,
    default authors are assigned based on their position in the list.

    Args:
        messages: The messages to convert.

    Returns:
        A list of `protos.Message` objects with alternating authors.
    c                 S  s   g | ]}t |ƒ‘qS r   )r   )Ú.0Úmessager   r   r   Ú
<listcomp>A   s    z"_make_messages.<locals>.<listcomp>c                 s  ó   � | ]	}|j r|j V  qd S ©N©Úauthor©r   Úmsgr   r   r   Ú	<genexpr>C   ó   € z!_make_messages.<locals>.<genexpr>Né   Ú0é   zDInvalid sequence: Authors in the discussion must alternate strictly.c                 s  r   r   r    r"   r   r   r   r$   M   r%   Ú1c                 s  s   � | ]}|j V  qd S r   r    r"   r   r   r   r$   W   s   € )r   r   Údictr   r   r   ÚsetÚlenÚpopr	   ÚAuthorErrorÚallÚ	enumerater!   )r   Úeven_authorsÚeven_authorÚodd_authorsÚ
odd_authorÚauthorsÚir#   r   r   r   Ú_make_messages-   s2   
ÿ
ÿr7   Úitemúdiscuss_types.ExampleOptionsúprotos.Examplec                 C  s‚   t | tjƒr| S t | tƒr&|  ¡ } t| d ƒ| d< t| d ƒ| d< t | ¡S t | tƒr<t| ƒ\}}tjt|ƒt|ƒd�S t | ¡S )z9Creates a `protos.Example` object from the provided item.ÚinputÚoutput©r;   r<   )r   r   ÚExampler*   Úcopyr   r   Úlist)r8   r;   r<   r   r   r   Ú_make_examplea   s   



rA   Úexamplesú"List[discuss_types.MessageOptions]úList[protos.Example]c                 C  sŒ   t | ƒd dkrtt dt | ƒ› d�¡ƒ‚g }g }t| ƒD ]&\}}t|ƒ}| |¡ |d dkr1qtj|d |d d�}| |¡ g }q|S )a  
    Creates a list of `protos.Example` objects from a list of message options.

    This function takes a list of `discuss_types.MessageOptions` and pairs them into
    `protos.Example` objects. The input examples must be in pairs to create valid examples.

    Args:
        examples: The list of `discuss_types.MessageOptions`.

    Returns:
        A list of `protos.Example objects` created by pairing up the provided messages.

    Raises:
        ValueError: If the provided list of examples is not of even length.
    r&   r   z”                Invalid input: You must pass either `Primer` objects, pairs of messages, or an even number of messages. 
                Currently, z0 messages were provided, which is an odd number.r(   r=   )	r,   Ú
ValueErrorÚtextwrapÚdedentr0   r   Úappendr   r>   )rB   ÚresultÚpairÚnr8   r#   Úprimerr   r   r   Ú_make_examples_from_flatt   s,   þÿÿ
þ
rM   údiscuss_types.ExamplesOptionsc                 C  s¦   t | tjƒr	| gS t | tƒrt| ƒgS t| ƒ} | s| S | d }t |tƒr9d|v r,t| ƒS d|v r4d|v s8tdƒ‚n
t |tj	ƒrCt| ƒS g }| D ]	}| 
t|ƒ¡ qG|S )aÒ  
    Creates a list of `protos.Example` objects from the provided examples.

    This function takes various types of example content inputs and creates a list
    of `protos.Example` objects. It handles the conversion of different input types and ensures
    the appropriate structure for creating valid examples.

    Args:
        examples: The examples to convert.

    Returns:
        A list of `protos.Example` objects created from the provided examples.
    r   r   r;   r<   zwInvalid dictionary format: To create an `Example` instance, the dictionary must contain both `input` and `output` keys.)r   r   r>   r*   rA   r@   rM   Ú	TypeErrorr	   ÚMESSAGE_OPTIONSrH   )rB   ÚfirstrI   r8   r   r   r   Ú_make_examplesž   s,   


ÿÿrR   ©ÚcontextrB   r   Úpromptú"discuss_types.MessagePromptOptionsrT   ú
str | Noneú$discuss_types.ExamplesOptions | Noneú$discuss_types.MessagesOptions | Noneúprotos.MessagePromptc                C  sä   | du rt |||d�} n$|dup|dup|du}|rtdƒ‚t| tjƒr&| S t| t ƒr,nd| i} t|  ¡ ƒ}| tj	¡sGt
d|tj	 › d�ƒ‚|  dd¡}|durWt|ƒ| d< |  dd¡}|durgt|ƒ| d< dd	„ |  ¡ D ƒ} | S )
a‘  
    Creates a `protos.MessagePrompt` object from the provided prompt components.

    This function constructs a `protos.MessagePrompt` object using the provided `context`, `examples`,
    or `messages`. It ensures the proper structure and handling of the input components.

    Either pass a `prompt` or it's component `context`, `examples`, `messages`.

    Args:
        prompt: The complete prompt components.
        context: The context for the prompt.
        examples: The examples for the prompt.
        messages: The messages for the prompt.

    Returns:
        A `protos.MessagePrompt` object created from the provided prompt components.
    NrS   z€Invalid configuration: Either `prompt` or its fields `(context, examples, messages)` should be set, but not both simultaneously.r   zHInvalid prompt dictionary: Extra entries found that are not recognized: z. Please check the keys.rB   c                 S  s   i | ]\}}|d ur||“qS r   r   )r   ÚkÚvr   r   r   Ú
<dictcomp>  s    z-_make_message_prompt_dict.<locals>.<dictcomp>)r*   rE   r   r   ÚMessagePromptr+   ÚkeysÚissubsetr	   ÚMESSAGE_PROMPT_KEYSÚKeyErrorÚgetrR   r7   Úitems)rU   rT   rB   r   Úflat_promptr_   r   r   r   Ú_make_message_prompt_dictÎ   s:   ýÿ
ÿrf   c                C  s   t | |||d�} t | ¡S )zLCreates a `protos.MessagePrompt` object from the provided prompt components.©rU   rT   rB   r   )rf   r   r^   rg   r   r   r   Ú_make_message_prompt
  s   ÿ
rh   )rT   rB   r   ÚtemperatureÚcandidate_countÚtop_pÚtop_krU   Úmodelú&model_types.AnyModelNameOptions | Noneri   úfloat | Nonerj   ú
int | Nonerk   rl   ú)discuss_types.MessagePromptOptions | Noneúprotos.GenerateMessageRequestc        	   	      C  s0   t  | ¡} t||||d�}tj| |||||d�S )zICreates a `protos.GenerateMessageRequest` object for generating messages.rg   )rm   rU   ri   rk   rl   rj   )r   Úmake_model_namerh   r   ÚGenerateMessageRequest©	rm   rT   rB   r   ri   rj   rk   rl   rU   r   r   r   Ú_make_generate_message_request  s   
ÿúrv   zmodels/chat-bison-001)rm   rT   rB   r   ri   rj   rk   rl   rU   ÚclientÚrequest_optionsrw   úglm.DiscussServiceClient | Nonerx   ú&helper_types.RequestOptionsType | Noneúdiscuss_types.ChatResponsec                 C  s(   t | ||||||||d�	}t|	||
d�S )aS  Calls the API to initiate a chat with a model using provided parameters

    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.
        request_options: Options for the request.

    Returns:
        A `types.ChatResponse` containing the model's reply.
    ru   ©rw   Úrequestrx   )rv   Ú_generate_response©rm   rT   rB   r   ri   rj   rk   rl   rU   rw   rx   r}   r   r   r   Úchat8  s   T÷r€   ú$glm.DiscussServiceAsyncClient | Nonec                 Ã  s0   �t | ||||||||d�	}t|	||
d�I dH S )zVCalls the API asynchronously to initiate a chat with a model using provided parametersru   r|   N)rv   Ú_generate_response_asyncr   r   r   r   Ú
chat_async›  s   €÷ÿrƒ   )é   é
   Úkw_onlyTÚinitFc                   @  s–   e Zd ZU ejdd„ dd�Zded< dd„ Zee	 
ejjj¡ddd„ƒƒZejddd„ƒZe	 
ejjj¡	dddd„ƒZe	 
ejjj¡ddd„ƒZdS )ÚChatResponsec                   C  s   d S r   r   r   r   r   r   Ú<lambda>Æ  s    zChatResponse.<lambda>F)ÚdefaultÚreprry   Ú_clientc                 K  s"   |  ¡ D ]
\}}t| ||ƒ qd S r   )rd   Úsetattr)ÚselfÚkwargsÚkeyÚvaluer   r   r   Ú__init__È  s   ÿzChatResponse.__init__r   rW   c                 C  s   | j d r| j d d S d S )Néÿÿÿÿr   )r   )rŽ   r   r   r   ÚlastÌ  s   
zChatResponse.lastr   r   c                 C  s$   t |ƒ}t|ƒ |¡}|| jd< d S )Nr“   )r   ÚtypeÚto_dictr   )rŽ   r   r   r   r   r”   Ô  s   Nrx   rz   r{   c                 C  sŽ   t | jtjƒrtdƒ‚| jd u rtd| j› �ƒ‚|  ¡ }| 	d¡ | 	dd ¡ t
|d ƒ|d< |d  t|ƒ¡ tdi |¤Ž}t|| j|d�S )Nz~Invalid operation: The 'reply' method cannot be called on an asynchronous client. Please use the 'reply_async' method instead.z²Invalid operation: No candidates returned from the model's last response. Please inspect the '.filters' attribute to understand why responses were filtered out. Current filters: Ú
candidatesÚfiltersr   )r}   rw   rx   r   )r   rŒ   ÚglmÚDiscussServiceAsyncClientrO   r”   rE   r˜   r–   r-   r@   rH   r   rv   r~   )rŽ   r   rx   r}   r   r   r   ÚreplyÚ  s&   ÿ
ÿÿ
ÿzChatResponse.replyc                 Ã  sz   �t | jtjƒrtdƒ‚|  ¡ }| d¡ | dd ¡ t|d ƒ|d< |d  t	|ƒ¡ t
di |¤Ž}t|| jd�I d H S )NzqInvalid method call: `reply_async` is not supported on a non-async client. Please use the `reply` method instead.r—   r˜   r   )r}   rw   r   )r   rŒ   r™   ÚDiscussServiceClientrO   r–   r-   r@   rH   r   rv   r‚   )rŽ   r   r}   r   r   r   Úreply_asyncô  s   €ÿ
zChatResponse.reply_async)r   rW   )r   r   r   )r   r   rx   rz   r   r{   )r   r   r   r{   )Ú__name__Ú
__module__Ú__qualname__ÚdataclassesÚfieldrŒ   Ú__annotations__r’   Úpropertyr   Úset_docr	   rˆ   r”   Ú__doc__Úsetterr›   r�   r   r   r   r   rˆ   Â  s   
 ýrˆ   r}   Úresponseúprotos.GenerateMessageResponseú;glm.DiscussServiceClient | protos.DiscussServiceAsyncClientc                 C  s¼   t | ƒ | ¡} |  d¡}|d | d< |d | d< |d | d< t |ƒ |¡}| d¡ t |d ¡|d< |d r>|d d }nd }| d  |¡ |  dd ¡ |  d	d ¡ tdd
|i|¤| ¤ŽS )NrU   rB   rT   r   r˜   r—   r   ri   rj   rŒ   r   )r•   r–   r-   r   Úconvert_filters_to_enumsrH   Ú
setdefaultrˆ   )r}   r¨   rw   rU   r”   r   r   r   Ú_build_chat_response  s   

r­   c                 C  s8   |d u ri }|d u rt ƒ }|j| fi |¤Ž}t| ||ƒS r   )r   Úgenerate_messager­   ©r}   rw   rx   r¨   r   r   r   r~      s   r~   c                 Ã  s@   �|d u ri }|d u rt ƒ }|j| fi |¤ŽI d H }t| ||ƒS r   )r   r®   r­   r¯   r   r   r   r‚   0  s   €r‚   )rU   rT   rB   r   rm   rw   rx   úmodel_types.AnyModelNameOptionsúdiscuss_types.TokenCountc                 C  sX   t  |¡}t| |||d�} |du ri }|du rtƒ }|jd|| dœ|¤Ž}t|ƒ |¡S )zCCalls the API to calculate the number of tokens used in the prompt.rS   N)rm   rU   r   )r   rs   rh   r   Úcount_message_tokensr•   r–   )rU   rT   rB   r   rm   rw   rx   rI   r   r   r   r²   @  s   
r²   )r   r   r   r   )r   r   r   r   )r8   r9   r   r:   )rB   rC   r   rD   )rB   rN   r   rD   r   )
rU   rV   rT   rW   rB   rX   r   rY   r   rZ   )rm   rn   rT   rW   rB   rX   r   rY   ri   ro   rj   rp   rk   ro   rl   ro   rU   rq   r   rr   )rm   rn   rT   rW   rB   rX   r   rY   ri   ro   rj   rp   rk   ro   rl   ro   rU   rq   rw   ry   rx   rz   r   r{   )rm   rn   rT   rW   rB   rX   r   rY   ri   ro   rj   rp   rk   ro   rl   ro   rU   rq   rw   r�   rx   rz   r   r{   r   )r}   rr   r¨   r©   rw   rª   r   rˆ   )NN)r}   rr   rw   ry   rx   rz   r   rˆ   )r}   rr   rw   r�   rx   rz   r   rˆ   )rU   rV   rT   rW   rB   rX   r   rY   rm   r°   rw   r�   rx   rz   r   r±   )/Ú
__future__r   r¡   ÚsysrF   Útypingr   r   Úgoogle.ai.generativelanguageÚaiÚgenerativelanguager™   Úgoogle.generativeai.clientr   r   Úgoogle.generativeair   r   Úgoogle.generativeai.typesr	   r
   r   r   r   r7   rA   rM   rR   rf   rh   rv   ÚDEFAULT_DISCUSS_MODELr€   r¥   r¦   rƒ   Úversion_infoÚmajorÚminorÚDATACLASS_KWARGSÚprettyprintrˆ   Ú	dataclassr­   r~   r‚   r²   r   r   r   r   Ú<module>   s°   



4

*1ÿû=ÿûöô
cô 

@ýýø