
    ; i6              	         U d dl mZ d dlZd dlmZ 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c mZ d dlmZ d dlmZ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ej        j         Z ee!e"e f         Z#i e j$        e j$        d e j$        de j$        de j$        e j%        e j%        de j%        de j%        de j%        e j&        e j&        de j&        de j&        de j&        e j'        e j'        de j'        de j'        de j'        Z(de)d<   dEd Z*eej+        e,e"ej-        f         ej-        f         fZ.eej/        ee.         e	e"ej-        f         f         Z0dFd$Z1ee"ej2        ej2        ej3        ej3        f         Z4 G d% d&e          Z5ee4e5ej6        f         Z7dGd(Z8dHd-Z9edddddd.dId=Z:edddddddd>dJdCZ;edddddddd>dJdDZ<dS )K    )annotationsN)Iterable)Anyr   UnionMappingOptional)	TypedDict)protos)get_default_generative_client#get_default_generative_async_client)model_types)helper_types)safety_types)content_types)retriever_types)MetadataFilterz
models/aqaanswer_style_unspecifiedunspecified   answer_style_abstractiveabstractive   answer_style_extractive
extractive   answer_style_verboseverbosez%dict[AnswerStyleOptions, AnswerStyle]_ANSWER_STYLESxAnswerStyleOptionsreturnAnswerStylec                n    t          | t                    r|                                 } t          |          S N)
isinstancestrlowerr   )r   s    r/var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/google/generativeai/answer.pyto_answer_styler)   ?   s,    !S GGII!    sourceGroundingPassagesOptionsprotos.GroundingPassagesc                   t          | t          j                  r| S t          | t                    s%t	          dt          |           j         d          g }t          | t                    r|                                 } t          |           D ]\  }}t          |t          j
                  r|                    |           5t          |t                    r0|\  }}|                    |t          j        |          d           z|                    t          |          t          j        |          d           t          j        |          S )a  
    Converts the `source` into a `protos.GroundingPassage`. A `GroundingPassages` contains a list of
    `protos.GroundingPassage` objects, which each contain a `protos.Content` and a string `id`.

    Args:
        source: `Content` or a `GroundingPassagesOptions` that will be converted to protos.GroundingPassages.

    Return:
        `protos.GroundingPassages` to be passed into `protos.GenerateAnswer`.
    zdInvalid input: The 'source' argument must be an instance of 'GroundingPassagesOptions'. Received a 'z' object instead.)idcontent)passages)r%   r
   GroundingPassagesr   	TypeErrortype__name__r   items	enumerateGroundingPassageappendtupler   
to_contentr&   )r+   r1   ndatar/   r0   s         r(   _make_grounding_passagesr>   R   sa    &&233 fh'' 
 \swx~ss  tI  \  \  \
 
 	
 H&'""  V$$ W W4dF344 	WOOD!!!!e$$ 	WKBOO2-2J72S2STTUUUUOO3q66m6Nt6T6TUUVVVV#X6666r*   c                  B    e Zd ZU ded<   ded<   ded<   ded<   d	ed
<   dS )SemanticRetrieverConfigDictSourceNameTyper+   content_types.ContentsTypequeryz"Optional[Iterable[MetadataFilter]]metadata_filterzOptional[int]max_chunks_countzOptional[float]minimum_relevance_scoreN)r5   
__module____qualname____annotations__ r*   r(   r@   r@   z   sN         %%%%7777####,,,,,,r*   r@   
str | Nonec                    t          | t                    r| S t          | t          j        t          j        t          j        t          j        f          r| j        S d S r$   )r%   r&   r   Corpusr
   Documentname)r+   s    r(   _maybe_get_source_namerP      sT    &# 	'8PRXRab
 
  {tr*   SemanticRetrieverConfigOptionsrC   rB   protos.SemanticRetrieverConfigc                   t          | t          j                  r| S t          |           }|d|i} nUt          | t                    rt          | d                   | d<   n't          dt          |           j         d|            | d         || d<   n8t          | d         t                    rt          j
        | d                   | d<   t          j        |           S )Nr+   zlInvalid input: Failed to create a 'protos.SemanticRetrieverConfig' from the provided source. Received type: z, Received value: rC   )r%   r
   SemanticRetrieverConfigrP   dictr3   r4   r5   r&   r   r;   )r+   rC   rO   s      r(   _make_semantic_retriever_configrV      s     &&899 !&))DD!	FD	!	! 
1&2BCCx("6ll3( (%( (
 
 	
 gw	F7OS	)	) D'26'?CCw)&111r*   )modelinline_passagessemantic_retrieveranswer_stylesafety_settingstemperaturerW   model_types.AnyModelNameOptionscontentsrX   GroundingPassagesOptions | NonerY   %SemanticRetrieverConfigOptions | NonerZ   AnswerStyle | Noner[   (safety_types.SafetySettingOptions | Noner\   float | Noneprotos.GenerateAnswerRequestc           	        t          j        |           } t          j        |          }|rt	          j        |          }||t          d| d| d          |t          |          }n/|t          ||d                   }nt          d| d| d          |rt          |          }t          j        | ||||||          S )a  
    constructs a protos.GenerateAnswerRequest object by organizing the input parameters for the API call to generate a grounded answer from the model.

    Args:
        model: Name of the model used to generate the grounded response.
        contents: Content of the current conversation with the model. For single-turn query, this is a
            single question to answer. For multi-turn queries, this is a repeated field that contains
            conversation history and the last `Content` in the list containing the question.
        inline_passages: Grounding passages (a list of `Content`-like objects or `(id, content)` pairs,
            or a `protos.GroundingPassages`) to send inline with the request. Exclusive with `semantic_retriever`,
            one must be set, but not both.
        semantic_retriever: A Corpus, Document, or `protos.SemanticRetrieverConfig` to use for grounding. Exclusive with
             `inline_passages`, one must be set, but not both.
        answer_style: Style for grounded answers.
        safety_settings: Safety settings for generated output.
        temperature: The temperature for randomness in the output.

    Returns:
        Call for protos.GenerateAnswerRequest().
    NzInvalid configuration: Please set either 'inline_passages' or 'semantic_retriever_config', but not both. Received for inline_passages: z, and for semantic_retriever: .zInvalid configuration: Either 'inline_passages' or 'semantic_retriever_config' must be provided, but currently both are 'None'. Received for inline_passages: rW   r^   rX   rY   r[   r\   rZ   )r   make_model_namer   to_contentsr   normalize_safety_settings
ValueErrorr>   rV   r3   r)   r
   GenerateAnswerRequest)rW   r^   rX   rY   rZ   r[   r\   s          r(   _make_generate_answer_requestrn      s?   < '..E(22H R&@QQ"'9'Er-<r r\nr r r
 
 	
 
	$2?CC		'<=OQYZ\Q]^^r-<r r\nr r r
 
 	

  5&|44''-'!   r*   )rW   rX   rY   rZ   r[   r\   clientrequest_optionsro   "glm.GenerativeServiceClient | Nonerp   &helper_types.RequestOptionsType | Nonec        	   	     v    |i }|t                      }t          | ||||||          }	 |j        |	fi |}
|
S )a  Calls the GenerateAnswer API and returns a `types.Answer` containing the response.

    You can pass a literal list of text chunks:

    >>> from google.generativeai import answer
    >>> answer.generate_answer(
    ...     content=question,
    ...     inline_passages=splitter.split(document)
    ... )

    Or pass a reference to a retreiver Document or Corpus:

    >>> from google.generativeai import answer
    >>> from google.generativeai import retriever
    >>> my_corpus = retriever.get_corpus('my_corpus')
    >>> genai.generate_answer(
    ...     content=question,
    ...     semantic_retriever=my_corpus
    ... )


    Args:
        model: Which model to call, as a string or a `types.Model`.
        contents: The question to be answered by the model, grounded in the
                provided source.
        inline_passages: Grounding passages (a list of `Content`-like objects or (id, content) pairs,
            or a `protos.GroundingPassages`) to send inline with the request. Exclusive with `semantic_retriever`,
            one must be set, but not both.
        semantic_retriever: A Corpus, Document, or `protos.SemanticRetrieverConfig` to use for grounding. Exclusive with
             `inline_passages`, one must be set, but not both.
        answer_style: Style in which the grounded answer should be returned.
        safety_settings: Safety settings for generated output. Defaults to None.
        temperature: Controls the randomness of the output.
        client: If you're not relying on a default client, you pass a `glm.GenerativeServiceClient` instead.
        request_options: Options for the request.

    Returns:
        A `types.Answer` containing the model's text answer response.
    Nrh   )r   rn   generate_answerrW   r^   rX   rY   rZ   r[   r\   ro   rp   requestresponses              r(   rt   rt      sj    f ~.00+'-'!  G &v%gAAAAHOr*   c        	   	        K   |i }|t                      }t          | ||||||          }	 |j        |	fi | d{V }
|
S )a^  
    Calls the API and returns a `types.Answer` containing the answer.

    Args:
        model: Which model to call, as a string or a `types.Model`.
        contents: The question to be answered by the model, grounded in the
                provided source.
        inline_passages: Grounding passages (a list of `Content`-like objects or (id, content) pairs,
            or a `protos.GroundingPassages`) to send inline with the request. Exclusive with `semantic_retriever`,
            one must be set, but not both.
        semantic_retriever: A Corpus, Document, or `protos.SemanticRetrieverConfig` to use for grounding. Exclusive with
             `inline_passages`, one must be set, but not both.
        answer_style: Style in which the grounded answer should be returned.
        safety_settings: Safety settings for generated output. Defaults to None.
        temperature: Controls the randomness of the output.
        client: If you're not relying on a default client, you pass a `glm.GenerativeServiceClient` instead.

    Returns:
        A `types.Answer` containing the model's text answer response.
    Nrh   )r   rn   rt   ru   s              r(   generate_answer_asyncry   9  s      @ ~466+'-'!  G ,V+GGGGGGGGGGGHOr*   )r   r    r!   r"   )r+   r,   r!   r-   )r!   rK   )r+   rQ   rC   rB   r!   rR   )rW   r]   r^   rB   rX   r_   rY   r`   rZ   ra   r[   rb   r\   rc   r!   rd   )rW   r]   r^   rB   rX   r_   rY   r`   rZ   ra   r[   rb   r\   rc   ro   rq   rp   rr   )=
__future__r   dataclassescollections.abcr   	itertoolstypingr   r   r   r   typing_extensionsr	   google.ai.generativelanguageaigenerativelanguageglmgoogle.generativeair
   google.generativeai.clientr   r   google.generativeai.typesr   r   r   r   r   )google.generativeai.types.retriever_typesr   DEFAULT_ANSWER_MODELrm   r"   intr&   r    ANSWER_STYLE_UNSPECIFIEDABSTRACTIVE
EXTRACTIVEVERBOSEr   rI   r)   r8   r:   ContentTypeGroundingPassageOptionsr2   r,   r>   rM   rN   rA   r@   rT   rQ   rP   rV   rn   rt   ry   rJ   r*   r(   <module>r      sO   # " " " " " "     $ $ $ $ $ $     : : : : : : : : : : : : : : ' ' ' ' ' ' * * * * * * * * * & & & & & &        2 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 5 5 5 5 5 5 D D D D D D# *63[01 9(+*N9{+9  D9 ;7	9
 [49 {9  79 ;*9 K29 {9 {59 +(9 ,9 {9 K/9  {"!9    (    
sM,E'E!FHaa  !
$%C**+-  7  7  7  7F 	0H&/Y
- - - - -) - - - "'
"$"    2 2 2 2: .B7;@D'+@D $? ? ? ? ? ?H .B7;@D'+@D $15>BE E E E E ET .B7;@D'+@D $15>B2 2 2 2 2 2 2 2r*   