o
    ß­jé4  ã                   @  sº  d dl mZ d dlZd dlmZm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 d d	lmZ d d
lmZ d dlmZ d dlmZ dZdZzejZW n eyv   e
dƒZdNdd„ZY nw dOdd„Z edddddddddœ	dPd-d.„Z!edddddddddd/œ
dQd6d7„Z"ej#ej$d8d9�G d:d;„ d;ej%ƒƒƒZ%		dRdSd>d?„Z&		dRdTdAdB„Z'e			dRdUdFdG„ƒZ(e			dRdVdJdG„ƒZ(		dRdWdMdG„Z(dS )Xé    )ÚannotationsN)ÚIterableÚSequence)ÚAnyr   ÚoverloadÚTypeVar)Úprotos)Úget_default_text_client)Ústring_utils)Úhelper_types)Ú
text_types)Úmodel_types)Úmodels)Úpalm_safety_typeszmodels/text-bison-001éd   ÚTÚiterableúIterable[T]ÚnÚintÚreturnúIterable[list[T]]c                 c  sX   � |dk rt d|› �ƒ‚g }| D ]}| |¡ t|ƒ|kr"|V  g }q|r*|V  d S d S )Né   z Batch size `n` must be >1, got: )Ú
ValueErrorÚappendÚlen)r   r   ÚbatchÚitem© r   úU/var/www/html/CropPilot/venv/lib/python3.10/site-packages/google/generativeai/text.pyÚ_batched+   s   €
€
ÿr    Úpromptústr | dict[str, str]úprotos.TextPromptc                 C  s2   t | tƒrtj| d�S t | tƒrt | ¡S tdƒ‚)aV  
    Creates a `protos.TextPrompt` object based on the provided prompt input.

    Args:
        prompt: The prompt input, either a string or a dictionary.

    Returns:
        protos.TextPrompt: A TextPrompt object containing the prompt text.

    Raises:
        TypeError: If the provided prompt is neither a string nor a dictionary.
    )ÚtextzKInvalid argument type: Expected a string or dictionary for the text prompt.)Ú
isinstanceÚstrr   Ú
TextPromptÚdictÚ	TypeError©r!   r   r   r   Ú_make_text_prompt9   s   


ÿr+   ©	Úmodelr!   ÚtemperatureÚcandidate_countÚmax_output_tokensÚtop_pÚtop_kÚsafety_settingsÚstop_sequencesr-   úmodel_types.AnyModelNameOptionsú
str | Noner.   úfloat | Noner/   ú
int | Noner0   r1   r2   r3   ú-palm_safety_types.SafetySettingOptions | Noner4   ústr | Iterable[str] | Noneúprotos.GenerateTextRequestc        	   	      C  sV   t  | ¡} t|d�}t |¡}t|tƒr|g}|rt|ƒ}tj	| ||||||||d�	S )a�  
    Creates a `protos.GenerateTextRequest` object based on the provided parameters.

    This function generates a `protos.GenerateTextRequest` object with the specified
    parameters. It prepares the input parameters and creates a request that can be
    used for generating text using the chosen model.

    Args:
        model: The model to use for text generation.
        prompt: The prompt for text generation. Defaults to None.
        temperature: The temperature for randomness in generation. Defaults to None.
        candidate_count: The number of candidates to consider. Defaults to None.
        max_output_tokens: The maximum number of output tokens. Defaults to None.
        top_p: The nucleus sampling probability threshold. Defaults to None.
        top_k: The top-k sampling parameter. Defaults to None.
        safety_settings: Safety settings for generated text. Defaults to None.
        stop_sequences: Stop sequences to halt text generation. Can be a string
             or iterable of strings. Defaults to None.

    Returns:
        `protos.GenerateTextRequest`: A `GenerateTextRequest` object configured with the specified parameters.
    r*   r,   )
r   Úmake_model_namer+   r   Únormalize_safety_settingsr%   r&   Úlistr   ÚGenerateTextRequestr,   r   r   r   Ú_make_generate_text_requestP   s$   
"


÷r@   )
r-   r.   r/   r0   r1   r2   r3   r4   ÚclientÚrequest_optionsr&   rA   úglm.TextServiceClient | NonerB   ú&helper_types.RequestOptionsType | Noneútext_types.Completionc                 C  s(   t | ||||||||d�	}t|	||
d�S )ao  Calls the API to generate text based on the provided prompt.

    Args:
        model: Which model to call, as a string or a `types.Model`.
        prompt: Free-form input text given to the model. Given a prompt, the model will
                generate text that completes the input text.
        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`.
        max_output_tokens: Maximum number of tokens to include in a candidate. Must be greater
                           than zero. If unset, will default to 64.
        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]`.
        safety_settings: A list of unique `types.SafetySetting` instances for blocking unsafe content.
           These will be enforced on the `prompt` and
           `candidates`. There should not be more than one
           setting for each `types.SafetyCategory` type. The API will block any prompts and
           responses that fail to meet the thresholds set by these settings. This list
           overrides the default settings for each `SafetyCategory` specified in the
           safety_settings. If there is no `types.SafetySetting` for a given
           `SafetyCategory` provided in the list, the API will use the default safety
           setting for that category.
        stop_sequences: A set of up to 5 character sequences that will stop output generation.
          If specified, the API will stop at the first appearance of a stop
          sequence. The stop sequence will not be included as part of the response.
        client: If you're not relying on a default client, you pass a `glm.TextServiceClient` instead.
        request_options: Options for the request.

    Returns:
        A `types.Completion` containing the model's text completion response.
    r,   )rA   ÚrequestrB   )r@   Ú_generate_response)r-   r!   r.   r/   r0   r1   r2   r3   r4   rA   rB   rF   r   r   r   Úgenerate_text‡   s   :÷rH   F)Úinitc                   @  s   e Zd Zdd„ ZdS )Ú
Completionc                 K  sB   |  ¡ D ]
\}}t| ||ƒ qd | _| jr| jd d | _d S d S )Nr   Úoutput)ÚitemsÚsetattrÚresultÚ
candidates)ÚselfÚkwargsÚkeyÚvaluer   r   r   Ú__init__Ó   s   ÿzCompletion.__init__N)Ú__name__Ú
__module__Ú__qualname__rT   r   r   r   r   rJ   Ð   s    rJ   rF   úglm.TextServiceClientc                 C  s‚   |du ri }|du rt ƒ }|j| fi |¤Ž}t|ƒ |¡}t |d ¡|d< t |d ¡|d< t |d ¡|d< tdd|i|¤ŽS )aµ  
    Generates a response using the provided `protos.GenerateTextRequest` and client.

    Args:
        request: The text generation request.
        client: The client to use for text generation. Defaults to None, in which
            case the default text client is used.
        request_options: Options for the request.

    Returns:
        `Completion`: A `Completion` object with the generated text and response information.
    NÚfiltersÚsafety_feedbackrO   Ú_clientr   )	r	   rH   ÚtypeÚto_dictr   Úconvert_filters_to_enumsÚ convert_safety_feedback_to_enumsÚconvert_candidate_enumsrJ   )rF   rA   rB   Úresponser   r   r   rG   Ü   s   ÿrG   útext_types.TokenCountc                 C  sR   t  | ¡}|du ri }|du rtƒ }|jtj|d|id�fi |¤Ž}t|ƒ |¡S )z?Calls the API to count the number of tokens in the text prompt.Nr$   )r-   r!   )r   Úget_base_model_namer	   Úcount_text_tokensr   ÚCountTextTokensRequestr\   r]   )r-   r!   rA   rB   Ú
base_modelrN   r   r   r   rd   ÿ   s   
ÿþrd   ú model_types.BaseModelNameOptionsr$   útext_types.EmbeddingDictc                 C  ó   d S ©Nr   ©r-   r$   rA   rB   r   r   r   Úgenerate_embeddings  ó   rl   úSequence[str]útext_types.BatchEmbeddingDictc                 C  ri   rj   r   rk   r   r   r   rl      rm   ústr | Sequence[str]ú8text_types.EmbeddingDict | text_types.BatchEmbeddingDictc           	      C  sÖ   t  | ¡} |du ri }|du rtƒ }t|tƒr8tj| |d�}|j|fi |¤Ž}t|ƒ 	|¡}|d d |d< |S dg i}t
|tƒD ]'}tj| |d�}|j|fi |¤Ž}t|ƒ 	|¡}|d  dd„ |d D ƒ¡ qA|S )	a$  Calls the API to create an embedding for the text passed in.

    Args:
        model: Which model to call, as a string or a `types.Model`.

        text: Free-form input text given to the model. Given a string, the model will
              generate an embedding based on the input text.

        client: If you're not relying on a default client, you pass a `glm.TextServiceClient` instead.

        request_options: Options for the request.

    Returns:
        Dictionary containing the embedding (list of float values) for the input text.
    N)r-   r$   Ú	embeddingrS   )r-   Útextsc                 s  s   � | ]}|d  V  qdS )rS   Nr   )Ú.0Úer   r   r   Ú	<genexpr>X  s   € z&generate_embeddings.<locals>.<genexpr>Ú
embeddings)r   r<   r	   r%   r&   r   ÚEmbedTextRequestÚ
embed_textr\   r]   r    ÚEMBEDDING_MAX_BATCH_SIZEÚBatchEmbedTextRequestÚbatch_embed_textÚextend)	r-   r$   rA   rB   Úembedding_requestÚembedding_responseÚembedding_dictrN   r   r   r   r   rl   )  s4   

ÿþôÿþ)r   r   r   r   r   r   )r!   r"   r   r#   )r-   r5   r!   r6   r.   r7   r/   r8   r0   r8   r1   r8   r2   r8   r3   r9   r4   r:   r   r;   )r-   r5   r!   r&   r.   r7   r/   r8   r0   r8   r1   r7   r2   r7   r3   r9   r4   r:   rA   rC   rB   rD   r   rE   )NN)rF   r;   rA   rX   rB   rD   r   rJ   )
r-   r5   r!   r&   rA   rC   rB   rD   r   rb   )
r-   rg   r$   r&   rA   rX   rB   rD   r   rh   )
r-   rg   r$   rn   rA   rX   rB   rD   r   ro   )
r-   rg   r$   rp   rA   rX   rB   rD   r   rq   ))Ú
__future__r   ÚdataclassesÚcollections.abcr   r   Ú	itertoolsÚtypingr   r   r   Úgoogle.ai.generativelanguageÚaiÚgenerativelanguageÚglmÚgoogle.generativeair   Úgoogle.generativeai.clientr	   r
   Úgoogle.generativeai.typesr   r   r   r   r   ÚDEFAULT_TEXT_MODELrz   Úbatchedr    ÚAttributeErrorr   r+   r@   rH   ÚprettyprintÚ	dataclassrJ   rG   rd   rl   r   r   r   r   Ú<module>   s€   
ý
ö9ôI
ý&üüüü