a
    bgX1                     @  s  d dl mZ d dlZd dlZd dlmZmZmZmZm	Z	m
Z
mZmZmZmZ d dlmZ d dlmZmZmZ d dlmZmZmZmZ d dlmZmZmZmZmZm Z  e!e"Z#dd	d
ddZ$ddd
ddZ%dddddZ&ddddddZ'ddddddZ(G dd deeZ)dS )    )annotationsN)
AnyCallableDictListLiteralOptionalSequenceSetTupleUnion)
Embeddings)get_from_dict_or_envget_pydantic_field_namespre_init)	BaseModel
ConfigDictFieldmodel_validator)AsyncRetryingbefore_sleep_logretryretry_if_exception_typestop_after_attemptwait_exponentialLocalAIEmbeddingszCallable[[Any], Any])
embeddingsreturnc                 C  sr   dd l }d}d}tdt| jtd||dt|jjt|jjB t|jj	B t|jj
B t|jjB tttjdS )Nr      
   T   
multiplierminmaxreraisestopwaitr   before_sleep)openair   r   max_retriesr   r   errorTimeoutAPIErrorAPIConnectionErrorRateLimitErrorServiceUnavailableErrorr   loggerloggingWARNING)r   r*   min_secondsmax_seconds r7   t/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain_community/embeddings/localai.py_create_retry_decorator%   s$    





r9   r   c                   s   dd l }d}d}tdt| jtd||dt|jjt|jjB t|jj	B t|jj
B t|jjB tttjd ddd	 fd
d}|S )Nr   r   r   Tr    r!   r%   r   )funcr   c                   s   dddd fdd}|S )Nr   r   )argskwargsr   c                    s6    2 z"3 d H W }| i |I d H   S 6 t dd S )Nzthis is unreachable)AssertionError)r;   r<   _)async_retryingr:   r7   r8   	wrapped_fQ   s    z7_async_retry_decorator.<locals>.wrap.<locals>.wrapped_fr7   )r:   r@   r?   )r:   r8   wrapP   s    z$_async_retry_decorator.<locals>.wrap)r*   r   r   r+   r   r   r,   r-   r.   r/   r0   r1   r   r2   r3   r4   )r   r*   r5   r6   rB   r7   rA   r8   _async_retry_decorator;   s(    





rC   dict)responser   c                 C  s.   t dd | d D r*dd l}|jd| S )Nc                 s  s   | ]}t |d  dkV  qdS )	embeddingr    N)len).0dr7   r7   r8   	<genexpr>]       z"_check_response.<locals>.<genexpr>datar   z'LocalAI API returned an empty embedding)anyr*   r,   r.   )rE   r*   r7   r7   r8   _check_response\   s    rN   )r   r<   r   c                   s.   t  }|ddd fdd}|f i |S ))Use tenacity to retry the embedding call.r   r<   r   c                    s    j jf i | }t|S N)clientcreaterN   r<   rE   r   r7   r8   _embed_with_retryh   s    z+embed_with_retry.<locals>._embed_with_retry)r9   )r   r<   Zretry_decoratorrV   r7   rU   r8   embed_with_retryd   s    rW   c                   s0   t  ddd fdd}|f i |I dH S )rO   r   rP   c                    s     j jf i | I d H }t|S rQ   )rR   ZacreaterN   rT   rU   r7   r8   _async_embed_with_retrys   s    z7async_embed_with_retry.<locals>._async_embed_with_retryN)rC   )r   r<   rX   r7   rU   r8   async_embed_with_retryp   s    rY   c                   @  s  e Zd ZU dZdZded< dZded< eZded< dZd	ed
< dZ	d	ed< dZ
d	ed< dZded< dZd	ed< dZd	ed< e Zded< dZded< dZded< dZded< dZded< dZded< dZded < eed!Zd"ed#< ed$d%d&Zed'd(ed"dd)d*d+Zed,d,d)d-d.Ze d,d/d0d1Z!ddd2d3d4d5Z"ddd2d3d6d7Z#dFd9d:d;d<d=d>Z$dGd9d:d;d<d?d@Z%dd2dAdBdCZ&dd2dAdDdEZ'dS )Hr   a  LocalAI embedding models.

    Since LocalAI and OpenAI have 1:1 compatibility between APIs, this class
    uses the ``openai`` Python package's ``openai.Embedding`` as its client.
    Thus, you should have the ``openai`` python package installed, and defeat
    the environment variable ``OPENAI_API_KEY`` by setting to a random string.
    You also need to specify ``OPENAI_API_BASE`` to point to your LocalAI
    service endpoint.

    Example:
        .. code-block:: python

            from langchain_community.embeddings import LocalAIEmbeddings
            openai = LocalAIEmbeddings(
                openai_api_key="random-string",
                openai_api_base="http://localhost:8080"
            )

    Nr   rR   ztext-embedding-ada-002strmodel
deploymentzOptional[str]openai_api_versionopenai_api_baseopenai_proxyi  intembedding_ctx_lengthopenai_api_keyopenai_organizationzUnion[Literal['all'], Set[str]]allowed_specialallz.Union[Literal['all'], Set[str], Sequence[str]]disallowed_speciali  
chunk_size   r+   z+Optional[Union[float, Tuple[float, float]]]request_timeoutheadersFboolshow_progress_bar)default_factoryzDict[str, Any]model_kwargsZforbidr7   )extraZprotected_namespacesbefore)mode)valuesr   c              
   C  s   t | }|di }t|D ]P}||v r8td| d||vrtd| d| d| d ||||< q|| }|rtd| d	||d< |S )
z>Build extra kwargs from additional params that were passed in.rn   zFound z supplied twice.z	WARNING! z/ is not default parameter.
                    zJ was transferred to model_kwargs.
                    Please confirm that z is what you intended.zParameters za should be specified explicitly. Instead they were passed in as part of `model_kwargs` parameter.)	r   getlist
ValueErrorwarningswarnpopintersectionkeys)clsrr   Zall_required_field_namesro   
field_nameZinvalid_model_kwargsr7   r7   r8   build_extra   s*    
zLocalAIEmbeddings.build_extrar   c                 C  s   t |dd|d< t |dddd|d< t |dddd|d< d}t |d	d
|d|d	< t |dddd|d< zddl}|j|d< W n ty   tdY n0 |S )z?Validate that api key and python package exists in environment.rb   ZOPENAI_API_KEYr^   ZOPENAI_API_BASE )defaultr_   ZOPENAI_PROXYr]   ZOPENAI_API_VERSIONrc   ZOPENAI_ORGANIZATIONr   NrR   zTCould not import openai python package. Please install it with `pip install openai`.)r   r*   Z	EmbeddingImportError)r{   rr   Zdefault_api_versionr*   r7   r7   r8   validate_environment   sH    




z&LocalAIEmbeddings.validate_environment)r   c                 C  sJ   | j | j| j| j| j| j| jd| j}| jrFdd l	}| j| jd|_
|S )N)r[   ri   rj   Zapi_keyZorganizationZapi_baseapi_versionr   )httphttps)r[   ri   rj   rb   rc   r^   r]   rn   r_   r*   proxy)selfZopenai_argsr*   r7   r7   r8   _invocation_params   s     
z$LocalAIEmbeddings._invocation_paramszList[float])textenginer   c                C  s<   | j dr|dd}t| fd|gi| jd d d S ))Call out to LocalAI's embedding endpoint.001
 inputrL   r   rF   )r[   endswithreplacerW   r   r   r   r   r7   r7   r8   _embedding_func  s    z!LocalAIEmbeddings._embedding_funcc                  sB   | j dr|dd}t| fd|gi| jI dH d d d S )	r   r   r   r   r   NrL   r   rF   )r[   r   r   rY   r   r   r7   r7   r8   _aembedding_func  s    
z"LocalAIEmbeddings._aembedding_funcr   z	List[str]zOptional[int]zList[List[float]])textsrg   r   c                   s    fdd|D S )aN  Call out to LocalAI's embedding endpoint for embedding search docs.

        Args:
            texts: The list of texts to embed.
            chunk_size: The chunk size of embeddings. If None, will use the chunk size
                specified by the class.

        Returns:
            List of embeddings, one for each text.
        c                   s   g | ]} j | jd qS )r   r   r\   )rH   r   r   r7   r8   
<listcomp>0  rK   z5LocalAIEmbeddings.embed_documents.<locals>.<listcomp>r7   )r   r   rg   r7   r   r8   embed_documents"  s    z!LocalAIEmbeddings.embed_documentsc                   s2   g }|D ]$}| j || jdI dH }|| q|S )aT  Call out to LocalAI's embedding endpoint async for embedding search docs.

        Args:
            texts: The list of texts to embed.
            chunk_size: The chunk size of embeddings. If None, will use the chunk size
                specified by the class.

        Returns:
            List of embeddings, one for each text.
        r   N)r   r\   append)r   r   rg   r   r   rE   r7   r7   r8   aembed_documents2  s
    z"LocalAIEmbeddings.aembed_documents)r   r   c                 C  s   | j || jd}|S )zCall out to LocalAI's embedding endpoint for embedding query text.

        Args:
            text: The text to embed.

        Returns:
            Embedding for the text.
        r   r   r   r   rF   r7   r7   r8   embed_queryE  s    	zLocalAIEmbeddings.embed_queryc                   s   | j || jdI dH }|S )zCall out to LocalAI's embedding endpoint async for embedding query text.

        Args:
            text: The text to embed.

        Returns:
            Embedding for the text.
        r   N)r   r\   r   r7   r7   r8   aembed_queryQ  s    	zLocalAIEmbeddings.aembed_query)r   )r   )(__name__
__module____qualname____doc__rR   __annotations__r[   r\   r]   r^   r_   ra   rb   rc   setrd   rf   rg   r+   ri   rj   rl   r   rD   rn   r   Zmodel_configr   classmethodr}   r   r   propertyr   r   r   r   r   r   r   r7   r7   r7   r8   r   {   sD   
*  )*
__future__r   r3   rv   typingr   r   r   r   r   r   r	   r
   r   r   Zlangchain_core.embeddingsr   Zlangchain_core.utilsr   r   r   Zpydanticr   r   r   r   tenacityr   r   r   r   r   r   	getLoggerr   r2   r9   rC   rN   rW   rY   r   r7   r7   r7   r8   <module>   s   0 	
!