a
    ag6                     @  s  d Z ddlmZ ddlZddl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 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mZm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 G dd dee# Z5ddddddddddddZ6ddddd Z7d!d"d#d$d%Z8de9ee9e"d&dd'ddd(d)d*d+d,d-d.d/	d0d1Z:ed2d3d4d5de9ee9e"d&dfd6ddd7d)d*d+d,d-d8d9
d:d;Z;de9ee9e"d&dd&d<d6ddd(d)d*d+d,d+d-d=d>d?d3Z<dS )@z@LLM Chain for turning a user text query into a structured query.    )annotationsN)AnyCallableListOptionalSequenceTupleUnioncast)
deprecated)OutputParserException)BaseLanguageModel)BaseOutputParser)parse_and_check_json_markdown)BasePromptTemplate)FewShotPromptTemplate)Runnable)
Comparator
ComparisonFilterDirective	OperationOperatorStructuredQuery)LLMChain)
get_parser)
DEFAULT_EXAMPLESDEFAULT_PREFIXDEFAULT_SCHEMA_PROMPTDEFAULT_SUFFIXEXAMPLE_PROMPTEXAMPLES_WITH_LIMITPREFIX_WITH_DATA_SOURCESCHEMA_WITH_LIMIT_PROMPTSUFFIX_WITHOUT_DATA_SOURCEUSER_SPECIFIED_EXAMPLE_PROMPT)AttributeInfoc                   @  sF   e Zd ZU dZded< dddddZedddddd dddZd	S )StructuredQueryOutputParserz-Output parser that parses a structured query.r   	ast_parsestrr   )textreturnc              
     s   zddg}g d t ||}|d d u s8t|d dkr@d|d< |d dksT|d s^d |d< n| |d |d< |ds|dd  tf i  fdd	| D W S  ty } z td
| d| W Y d }~n
d }~0 0 d S )Nqueryfilter)r+   r,   limitr    Z	NO_FILTERr-   c                   s   i | ]\}}| v r||qS  r/   ).0kvZallowed_keysr/   u/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain/chains/query_constructor/base.py
<dictcomp>>       z5StructuredQueryOutputParser.parse.<locals>.<dictcomp>zParsing text
z
 raised following error:
)	r   lenr'   getpopr   items	Exceptionr   )selfr)   Zexpected_keysparseder/   r3   r4   parse0   s$    


z!StructuredQueryOutputParser.parseNFOptional[Sequence[Comparator]]Optional[Sequence[Operator]]Optional[Sequence[str]]bool)allowed_comparatorsallowed_operatorsallowed_attributesfix_invalidr*   c                   s8   |rddd fdd}nt  dj}| |dS )z
        Create a structured query output parser from components.

        Args:
            allowed_comparators: allowed comparators
            allowed_operators: allowed operators

        Returns:
            a structured query output parser
        r(   Optional[FilterDirective])
raw_filterr*   c                   s*   t tt t | }t| d}|S NrD   rE   rF   )r
   r   r   r   r?   fix_filter_directive)rI   r,   fixedrF   rD   rE   r/   r4   r'   Z   s    z>StructuredQueryOutputParser.from_components.<locals>.ast_parserK   )r'   )r   r?   )clsrD   rE   rF   rG   r'   r/   rN   r4   from_componentsE   s    z+StructuredQueryOutputParser.from_components)NNNF)__name__
__module____qualname____doc____annotations__r?   classmethodrP   r/   r/   r/   r4   r&   *   s   
    r&   rK   rH   r@   rA   rB   )r,   rD   rE   rF   r*   c                  s   ss r| s| S t | trFr0| jvr0dS  rB| j vrBdS | S t | trrb| jvrbdS  fdd| jD }|sdS t|dkr| jtj	tj
fv r|d S t| j|dS n| S dS )ah  Fix invalid filter directive.

    Args:
        filter: Filter directive to fix.
        allowed_comparators: allowed comparators. Defaults to all comparators.
        allowed_operators: allowed operators. Defaults to all operators.
        allowed_attributes: allowed attributes. Defaults to all attributes.

    Returns:
        Fixed filter directive.
    Nc              
     s*   g | ]"}|d urt tt| dqS rJ   )r
   r   rL   )r0   argrN   r/   r4   
<listcomp>   s   
z(fix_filter_directive.<locals>.<listcomp>   r   )operator	arguments)
isinstancer   Z
comparator	attributer   rZ   r[   r7   r   ANDOR)r,   rD   rE   rF   argsr/   rN   r4   rL   m   s<    


rL   z$Sequence[Union[AttributeInfo, dict]]r(   )infor*   c                 C  sB   i }| D ]}t |}|||d< qtj|ddddddS )Nname   indent{{{}}})dictr9   jsondumpsreplace)ra   Z
info_dictsiZi_dictr/   r/   r4   _format_attribute_info   s
    ro   zSequence[Tuple[str, dict]]z
List[dict])input_output_pairsr*   c                 C  sV   g }t | D ]D\}\}}tj|dddddd}|d ||d}|| q|S )	zConstruct examples from input-output pairs.

    Args:
        input_output_pairs: Sequence of input-output pairs.

    Returns:
        List of examples.
    rc   rd   rf   rg   rh   ri   rY   )rn   Z
user_querystructured_request)	enumeraterk   rl   rm   append)rp   examplesrn   _inputoutputrq   Zexampler/   r/   r4   construct_examples   s    	rw   Frt   rD   rE   enable_limitschema_promptzOptional[Sequence]zSequence[Comparator]zSequence[Operator]rC   zOptional[BasePromptTemplate]r   r   )	document_contentsattribute_infort   rD   rE   ry   rz   kwargsr*   c                K  s   |rt nt}|p|}t|}	|jd|d|d}
|rzt|d trzt|}t}t	j|
| |	d}t
jt|d d}n8|p|rtnt}t}tj|
d}tjt|d | |	d}tf t||d	g||d
|S )a#  Create query construction prompt.

    Args:
        document_contents: The contents of the document to be queried.
        attribute_info: A list of AttributeInfo objects describing
            the attributes of the document.
        examples: Optional list of examples to use for the chain.
        allowed_comparators: Sequence of allowed comparators.
        allowed_operators: Sequence of allowed operators.
        enable_limit: Whether to enable the limit operator. Defaults to False.
        schema_prompt: Prompt for describing query schema. Should have string input
            variables allowed_comparators and allowed_operators.
        kwargs: Additional named params to pass to FewShotPromptTemplate init.

    Returns:
        A prompt template that can be used to construct queries.
    z | )rD   rE   r   )schemacontent
attributesrY   )rn   )r~   )rn   r   r   r+   )rt   example_promptZinput_variablessuffixprefix)r"   r   ro   formatjoinr\   tuplerw   r$   r!   r#   r7   r    r   r   r   r   r   list)r{   r|   rt   rD   rE   ry   rz   r}   Zdefault_schema_promptZattribute_strr~   r   r   r   r/   r/   r4   get_query_constructor_prompt   s@    

r   z0.2.13load_query_constructor_runnablez1.0)ZsincealternativeZremovalr   zOptional[List]r   )
llmr{   r|   rt   rD   rE   ry   rz   r}   r*   c              	   K  sn   t |||||||d}	g }
|D ]"}|
t|tr6|jn|d  qtj|||
d}||	_tf | |	|d|S )aS  Load a query constructor chain.

    Args:
        llm: BaseLanguageModel to use for the chain.
        document_contents: The contents of the document to be queried.
        attribute_info: Sequence of attributes in the document.
        examples: Optional list of examples to use for the chain.
        allowed_comparators: Sequence of allowed comparators. Defaults to all
            Comparators.
        allowed_operators: Sequence of allowed operators. Defaults to all Operators.
        enable_limit: Whether to enable the limit operator. Defaults to False.
        schema_prompt: Prompt for describing query schema. Should have string input
            variables allowed_comparators and allowed_operators.
        **kwargs: Arbitrary named params to pass to LLMChain.

    Returns:
        A LLMChain that can be used to construct queries.
    rx   rb   rK   )r   promptoutput_parser)	r   rs   r\   r%   rb   r&   rP   r   r   )r   r{   r|   rt   rD   rE   ry   rz   r}   r   rF   ainfor   r/   r/   r4   load_query_constructor_chain  s*    "	r   )rt   rD   rE   ry   rz   rG   r   )r   r{   r|   rt   rD   rE   ry   rz   rG   r}   r*   c                K  sh   t ||f|||||d|	}
g }|D ]"}|t|tr>|jn|d  q&tj||||d}|
| B |B S )a  Load a query constructor runnable chain.

    Args:
        llm: BaseLanguageModel to use for the chain.
        document_contents: Description of the page contents of the document to be
            queried.
        attribute_info: Sequence of attributes in the document.
        examples: Optional list of examples to use for the chain.
        allowed_comparators: Sequence of allowed comparators. Defaults to all
            Comparators.
        allowed_operators: Sequence of allowed operators. Defaults to all Operators.
        enable_limit: Whether to enable the limit operator. Defaults to False.
        schema_prompt: Prompt for describing query schema. Should have string input
            variables allowed_comparators and allowed_operators.
        fix_invalid: Whether to fix invalid filter directives by ignoring invalid
            operators, comparators and attributes.
        kwargs: Additional named params to pass to FewShotPromptTemplate init.

    Returns:
        A Runnable that can be used to construct queries.
    rx   rb   )rD   rE   rF   rG   )r   rs   r\   r%   rb   r&   rP   )r   r{   r|   rt   rD   rE   ry   rz   rG   r}   r   rF   r   r   r/   r/   r4   r   ?  s0    "
)=rT   
__future__r   rk   typingr   r   r   r   r   r   r	   r
   Zlangchain_core._apir   Zlangchain_core.exceptionsr   Zlangchain_core.language_modelsr   Zlangchain_core.output_parsersr   Z"langchain_core.output_parsers.jsonr   Zlangchain_core.promptsr   Zlangchain_core.prompts.few_shotr   Zlangchain_core.runnablesr   Zlangchain_core.structured_queryr   r   r   r   r   r   Zlangchain.chains.llmr   Z)langchain.chains.query_constructor.parserr   Z)langchain.chains.query_constructor.promptr   r   r   r   r   r    r!   r"   r#   r$   Z)langchain.chains.query_constructor.schemar%   r&   rL   ro   rw   r   r   r   r   r/   r/   r/   r4   <module>   s^   ( 	0F:"?	$: