a
    •˜ëj   ã                   @  sÐ   d Z ddlmZ ddlmZmZmZ ddl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mZ ddlmZ ddlmZ ddlmZmZ er¸ddlmZ dZ G dd„ deƒZ!dS )z2Chain for interacting with Elasticsearch Database.é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚOptional)ÚCallbackManagerForChainRun)ÚBaseLanguageModel)ÚBaseOutputParserÚStrOutputParser)ÚSimpleJsonOutputParser)ÚBasePromptTemplate)ÚRunnable)Ú
ConfigDictÚmodel_validator)ÚSelf)ÚChain)ÚANSWER_PROMPTÚ
DSL_PROMPT)ÚElasticsearchÚintermediate_stepsc                
   @  sH  e Zd ZU dZded< 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< dZd	ed< dZded< eddd�Zedd�ddœdd „ƒZed!dœd"d#„ƒZed!dœd$d%„ƒZd!dœd&d'„Zd!dd(œd)d*„Zd!ddd+œd,d-„Zd=d.d/d.d0œd1d2„Zeddœd3d4„ƒZedddd5œd6d7d8d8d9dd d:œd;d<„ƒZdS )>ÚElasticsearchDatabaseChaina¤  Chain for interacting with Elasticsearch Database.

    Example:
        .. code-block:: python

            from langchain.chains import ElasticsearchDatabaseChain
            from langchain_community.llms import OpenAI
            from elasticsearch import Elasticsearch

            database = Elasticsearch("http://localhost:9200")
            db_chain = ElasticsearchDatabaseChain.from_llm(OpenAI(), database)

    r   Úquery_chainÚanswer_chainNr   Údatabaseé
   ÚintÚtop_kzOptional[list[str]]Úignore_indicesÚinclude_indicesZquestionÚstrÚ	input_keyÚresultÚ
output_keyé   Úsample_documents_in_index_infoFÚboolÚreturn_intermediate_stepsTZforbid)Zarbitrary_types_allowedÚextraÚafter)Úmoder   )Úreturnc                 C  s   | j r| jrd}t|ƒ‚| S )Nz;Cannot specify both 'include_indices' and 'ignore_indices'.)r   r   Ú
ValueError)ÚselfÚmsg© r-   úk/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/chains/elasticsearch_database/base.pyÚ_validate_indices=   s    z,ElasticsearchDatabaseChain._validate_indicesz	list[str]c                 C  s   | j gS )z?Return the singular input key.

        :meta private:
        )r   ©r+   r-   r-   r.   Ú
input_keysD   s    z%ElasticsearchDatabaseChain.input_keysc                 C  s   | j s| jgS | jtgS )z@Return the singular output key.

        :meta private:
        )r%   r!   ÚINTERMEDIATE_STEPS_KEYr0   r-   r-   r.   Úoutput_keysL   s    z&ElasticsearchDatabaseChain.output_keysc                   sN   dd„ ˆ j jjdd�D ƒ}ˆ jr2‡ fdd„|D ƒ}ˆ jrJ‡ fdd„|D ƒ}|S )Nc                 S  s   g | ]}|d  ‘qS ©Úindexr-   ©Ú.0r5   r-   r-   r.   Ú
<listcomp>W   s   z<ElasticsearchDatabaseChain._list_indices.<locals>.<listcomp>Újson©Úformatc                   s   g | ]}|ˆ j v r|‘qS r-   )r   ©r7   Úir0   r-   r.   r8   \   ó    c                   s   g | ]}|ˆ j vr|‘qS r-   )r   r<   r0   r-   r.   r8   ^   r>   )r   ÚcatÚindicesr   r   )r+   Zall_indicesr-   r0   r.   Ú_list_indicesV   s    ÿz(ElasticsearchDatabaseChain._list_indices)r@   r)   c                   sš   | j jjd |¡d�‰ | jdkr‚ˆ  ¡ D ]X\}}| j j|di i| jd�d d }dd„ |D ƒ}t|ƒd	 d
 |¡ d ˆ | d< q(d ‡ fdd„ˆ D ƒ¡S )Nú,r4   r   Z	match_all)r5   ÚqueryÚsizeÚhitsc                 S  s   g | ]}t |d  ƒ‘qS )Ú_source)r   )r7   Úhitr-   r-   r.   r8   k   r>   zAElasticsearchDatabaseChain._get_indices_infos.<locals>.<listcomp>z

/*
Ú
z
*/Úmappingsz

c                   s    g | ]}d   |ˆ | d ¡‘qS )zMapping for index {}:
{}rI   r:   r6   ©rI   r-   r.   r8   n   s   ÿ)r   r@   Zget_mappingÚjoinr#   ÚitemsÚsearchr   )r+   r@   ÚkÚvrE   r-   rJ   r.   Ú_get_indices_infosb   s&    
ýüü$
þÿz-ElasticsearchDatabaseChain._get_indices_infos)r@   rC   r)   c                 C  s   | j jd |¡|d�}t|ƒS )NrB   )r5   Úbody)r   rM   rK   r   )r+   r@   rC   r    r-   r-   r.   Ú_searcht   s    z"ElasticsearchDatabaseChain._searchzdict[str, Any]z$Optional[CallbackManagerForChainRun])ÚinputsÚrun_managerr)   c              
   C  sŽ  |p
t  ¡ }|| j › d�}|j|| jd� |  ¡ }|  |¡}|t| jƒ|dgdœ}g }�z | 	|¡ | j
j|d| ¡ id�}	|j|	d| jd� | 	|	¡ | 	d	|	i¡ | j||	d
�}
| 	t|
ƒ¡ |jd| jd� |j|
d| jd� |jd| jd� |
|dœ}| 	|¡ | jj|d| ¡ id�}| 	|¡ |j|d| jd� | j|i}| j�rX||t< W n. t�yˆ } z||_‚ W Y d }~n
d }~0 0 |S )Nz	
ESQuery:)Úverbosez

ESResult:)Úinputr   Úindices_infoÚstopÚ	callbacks)ÚconfigZgreen)ÚcolorrU   Úes_cmd)r@   rC   z
ESResult: Zyellowz
Answer:)ÚdatarV   )r   Zget_noop_managerr   Zon_textrU   rA   rP   r   r   Úappendr   ZinvokeZ	get_childrR   r   r!   r%   r2   Ú	Exceptionr   )r+   rS   rT   Z_run_managerZ
input_textr@   rW   Zquery_inputsr   r\   r    Zanswer_inputsZfinal_resultZchain_resultÚexcr-   r-   r.   Ú_callx   sT    
ü

þÿ


þ

z ElasticsearchDatabaseChain._callc                 C  s   dS )NZelasticsearch_database_chainr-   r0   r-   r-   r.   Ú_chain_type°   s    z&ElasticsearchDatabaseChain._chain_type)Úquery_promptÚanswer_promptÚquery_output_parserr   r   zOptional[BasePromptTemplate]zOptional[BaseOutputParser])Úllmr   rc   rd   re   Úkwargsr)   c          	      K  sJ   |pt }|ptƒ }||B |B }|p$t}||B tƒ B }| f |||dœ|¤ŽS )a)  Convenience method to construct ElasticsearchDatabaseChain from an LLM.

        Args:
            llm: The language model to use.
            database: The Elasticsearch db.
            query_prompt: The prompt to use for query construction.
            answer_prompt: The prompt to use for answering user question given data.
            query_output_parser: The output parser to use for parsing model-generated
                ES query. Defaults to SimpleJsonOutputParser.
            kwargs: Additional arguments to pass to the constructor.
        )r   r   r   )r   r
   r   r	   )	Úclsrf   r   rc   rd   re   rg   r   r   r-   r-   r.   Úfrom_llm´   s    
ýüz#ElasticsearchDatabaseChain.from_llm)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r   r   r   r!   r#   r%   r   Zmodel_configr   r/   Úpropertyr1   r3   rA   rP   rR   ra   rb   Úclassmethodri   r-   r-   r-   r.   r      sB   
þ	 ý8ùr   N)"rm   Ú
__future__r   Útypingr   r   r   Zlangchain_core.callbacksr   Zlangchain_core.language_modelsr   Zlangchain_core.output_parsersr   r	   Z"langchain_core.output_parsers.jsonr
   Zlangchain_core.promptsr   Zlangchain_core.runnablesr   Zpydanticr   r   Ztyping_extensionsr   Zlangchain.chains.baser   Z/langchain.chains.elasticsearch_database.promptsr   r   Zelasticsearchr   r2   r   r-   r-   r-   r.   Ú<module>   s    