
    Ng6                    :   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ee#                   Z5dddddDdZ6dEd"Z7dFd&Z8d e9e           e9e"          d'dd(dGd6Z: ed7d8d9:          d e9e           e9e"          d'dfdHd?            Z;d e9e           e9e"          d'dd'd@dIdCZ<dS )Jz@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                  J    e Zd ZU dZded<   	 ddZe	 	 	 	 ddd            Zd	S )StructuredQueryOutputParserz-Output parser that parses a structured query.r   	ast_parsetextstrreturnr   c                   	 ddg}g dt          ||          }|d         t          |d                   dk    rd|d<   |d         dk    s|d         sd |d<   n|                     |d                   |d<   |                    d          s|                    dd            t          di fd|                                D             S # t          $ r}t          d	| d
|           d }~ww xY w)Nqueryfilter)r.   r/   limitr    	NO_FILTERr0   c                $    i | ]\  }}|v 	||S  r4   ).0kvallowed_keyss      c/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/chains/query_constructor/base.py
<dictcomp>z5StructuredQueryOutputParser.parse.<locals>.<dictcomp>>   s)    HHHDAqa<6G6G1a6G6G6G    zParsing text
z
 raised following error:
r4   )	r   lenr)   getpopr   items	Exceptionr   )selfr*   expected_keysparseder8   s        @r9   parsez!StructuredQueryOutputParser.parse0   s@   	$h/M777L24GGFg&#fWo*>*>!*C*C"%wh;..fX6F.#'x  #'>>&2B#C#Cx ::g&& *

7D)))"  HHHHFLLNNHHH    	 	 	'FFF1FF  	s   C
C 
C2C--C2NFallowed_comparatorsOptional[Sequence[Comparator]]allowed_operatorsOptional[Sequence[Operator]]allowed_attributesOptional[Sequence[str]]fix_invalidboolc                d    |r	dfd}nt                    j        } | |          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
        
raw_filterr+   r,   Optional[FilterDirective]c                    t          t          t                   t                                          |                     }t          |          }|S NrF   rH   rJ   )r   r   r   r   rE   fix_filter_directive)rO   r/   fixedrJ   rF   rH   s      r9   r)   z>StructuredQueryOutputParser.from_components.<locals>.ast_parseZ   sP    h79K9KJ9W9WXX,(;&7'9	   r;   rS   )r)   )rO   r+   r,   rP   )r   rE   )clsrF   rH   rJ   rL   r)   s    ```  r9   from_componentsz+StructuredQueryOutputParser.from_componentsE   sx    &  	         #$7"3#5   	 
 sY''''r;   )r*   r+   r,   r   )NNNF)
rF   rG   rH   rI   rJ   rK   rL   rM   r,   r(   )__name__
__module____qualname____doc____annotations__rE   classmethodrW   r4   r;   r9   r(   r(   *   ss         77S   *  ?C:>6:!$( $( $( $( [$( $( $(r;   r(   rS   r/   rP   rF   rG   rH   rI   rJ   rK   r,   c                  ssr| s| S t          | t                    rr| j        vrdS r| j        vrdS | S t          | t                    rvr| j        vrdS fd| j        D             }|sdS t          |          dk    r'| j        t          j	        t          j
        fv r|d         S t	          | j        |          S | 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                `    g | ]*}|t          t          t          |                    +S rR   )r   r   rT   )r5   argrJ   rF   rH   s     r9   
<listcomp>z(fix_filter_directive.<locals>.<listcomp>   sU     
 
 
  $(;&7'9	    r;      r   )operator	arguments)
isinstancer   
comparator	attributer   rc   rd   r<   r   ANDOR)r/   rF   rH   rJ   argss    ``` r9   rT   rT   m   s@   & !%$5%9K%% 	FJ	'	'   	6#4<O#O#O4 	&"2:L"L"L4	FI	&	&  	8I!I!I4
 
 
 
 
 
 '
 
 
  	4YY!^^HL(+3N N N7N   
 r;   info$Sequence[Union[AttributeInfo, dict]]r+   c                    i }| D ])}t          |          }|||                    d          <   *t          j        |d                              dd                              dd          S )Nname   indent{{{}}})dictr>   jsondumpsreplace)rk   
info_dictsii_dicts       r9   _format_attribute_infor}      so    J 0 0a)/
6::f%%&&:j+++33C>>FFsDQQQr;   input_output_pairsSequence[Tuple[str, dict]]
List[dict]c                    g }t          |           D ]d\  }\  }}t          j        |d                              dd                              dd          }|dz   ||d}|                    |           e|S )	zConstruct examples from input-output pairs.

    Args:
        input_output_pairs: Sequence of input-output pairs.

    Returns:
        List of examples.
    ro   rp   rr   rs   rt   ru   rb   )r{   
user_querystructured_request)	enumeraterw   rx   ry   append)r~   examplesr{   _inputoutputr   examples          r9   construct_examplesr      s     H();<< 	! 	!FFJva(((00d;;CCCNN 	 Q "4
 

 	    Or;   Fr   rF   rH   enable_limitschema_promptdocument_contentsattribute_infor   Optional[Sequence]Sequence[Comparator]Sequence[Operator]r   rM   r   Optional[BasePromptTemplate]kwargsr   r   c          	        |rt           nt          }|p|}t          |          }	|                    d                    |          d                    |                    }
|rnt          |d         t                    rSt          |          }t          }t          j        |
| |	          }t          j        t          |          dz             }nU|p|rt          nt          }t          }t          j        |
          }t!          j        t          |          dz   | |	          }t#          d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 | )rF   rH   r   )schemacontent
attributesrb   )r{   )r   )r{   r   r   r.   )r   example_promptinput_variablessuffixprefixr4   )r#   r   r}   formatjoinre   tupler   r%   r"   r$   r<   r!   r   r    r   r   r   list)r   r   r   rF   rH   r   r   r   default_schema_promptattribute_strr   r   r   r   s                 r9   get_query_constructor_promptr      s}   : %1K  6K  ":%:M*>::M!!!JJ':;;**%677 "  F  
Jx{E22 
%h//6(/#4
 
 
 ,2S]]Q5FGGG 
#/E5E 	 (&f555&(mma):}
 
 
 ! h% 	    r;   z0.2.13load_query_constructor_runnablez1.0)sincealternativeremovalllmr   Optional[List]r   c           	        t          |||||||          }	g }
|D ]9}|
                    t          |t                    r|j        n|d                    :t
                              |||
          }||	_        t          d| |	|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.
    r   rn   rS   )r   promptoutput_parserr4   )	r   r   re   r&   rn   r(   rW   r   r   )r   r   r   r   rF   rH   r   r   r   r   rJ   ainfor   s                r9   load_query_constructor_chainr     s    D */+!#  F  
 
!!$UM::MEJJf	
 	
 	
 	
 0??/+- @  M )FRF-RR6RRRr;   )r   rF   rH   r   r   rL   rL   r   c          	         t          ||f|||||d|	}
g }|D ]9}|                    t          |t                    r|j        n|d                    :t
                              ||||          }|
| z  |z  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.
    r   rn   )rF   rH   rJ   rL   )r   r   re   r&   rn   r(   rW   )r   r   r   r   rF   rH   r   r   rL   r   r   rJ   r   r   s                 r9   r   r   ?  s    D *	 /+!#	 	 	 	F  
 
!!$UM::MEJJf	
 	
 	
 	
 0??/+-	 @  M C<-''r;   )
r/   rP   rF   rG   rH   rI   rJ   rK   r,   rP   )rk   rl   r,   r+   )r~   r   r,   r   )r   r+   r   rl   r   r   rF   r   rH   r   r   rM   r   r   r   r   r,   r   )r   r   r   r+   r   rl   r   r   rF   r   rH   r   r   rM   r   r   r   r   r,   r   )r   r   r   r+   r   rl   r   r   rF   r   rH   r   r   rM   r   r   rL   rM   r   r   r,   r   )=r[   
__future__r   rw   typingr   r   r   r   r   r	   r
   r   langchain_core._apir   langchain_core.exceptionsr   langchain_core.language_modelsr   langchain_core.output_parsersr   "langchain_core.output_parsers.jsonr   langchain_core.promptsr   langchain_core.prompts.few_shotr   langchain_core.runnablesr   langchain_core.structured_queryr   r   r   r   r   r   langchain.chains.llmr   )langchain.chains.query_constructor.parserr   )langchain.chains.query_constructor.promptr   r   r   r   r    r!   r"   r#   r$   r%   )langchain.chains.query_constructor.schemar&   r(   rT   r}   r   r   r   r   r   r4   r;   r9   <module>r      s   F F " " " " " "  N N N N N N N N N N N N N N N N N N N N * * * * * * ; ; ; ; ; ; < < < < < < : : : : : : L L L L L L 5 5 5 5 5 5 A A A A A A - - - - - -                * ) ) ) ) ) @ @ @ @ @ @                        D C C C C C@( @( @( @( @("2?"C @( @( @(L ;?6:267 7 7 7 7 7tR R R R   6 $(05j0A0A,1E(OO26< < < < < <~ 
1    $05j0A0A,1E(OO262S 2S 2S 2S 
2St $(05j0A0A,1E(OO267( 7( 7( 7( 7( 7( 7( 7(r;   