
    }h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	 	 	 	 	 	 	 	 	 d"dZ6d#dZ7d$dZ8d e9e       e9e"      ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%dZ: eddd      d e9e       e9e"      ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&d       Z;d e9e       e9e"      dddd 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'd!Z<y)(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                  T    e Zd ZU dZded<   	 ddZe	 	 	 	 d	 	 	 	 	 	 	 	 	 d	d       Zy)
StructuredQueryOutputParserz-Output parser that parses a structured query.r   	ast_parsec           
        	 ddg}g d}t        ||      }|d   t        |d         dk(  rd|d<   |d   dk(  s|d   sd |d<   n| j                  |d         |d<   |j                  d      s|j	                  dd        t        d
i |j                         D ci c]  \  }}||v s|| c}}S c c}}w # t        $ r}t        d| d	|       d }~ww xY w)Nqueryfilter)r+   r,   limitr    	NO_FILTERr-   zParsing text
z
 raised following error:
 )	r   lenr)   getpopr   items	Exceptionr   )selftextexpected_keysallowed_keysparsedkves           a/var/www/html/engine/venv/lib/python3.12/site-packages/langchain/chains/query_constructor/base.pyparsez!StructuredQueryOutputParser.parse0   s    	$h/M7L24GFg&#fWo*>!*C"%wh;.fX6F#'x #'>>&2B#Cx ::g&

7D)" $*LLNHDAqa<6G1a4H H 	' &B1#F 	s0   BB6 B0%B0*B6 0B6 6	C?CCNc                `    |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
        c                    t        t        t           t               j	                  |             }t        |      }|S )Nallowed_comparatorsallowed_operatorsallowed_attributes)r   r   r   r   r?   fix_filter_directive)
raw_filterr,   fixedrE   rC   rD   s      r>   r)   z>StructuredQueryOutputParser.from_components.<locals>.ast_parseZ   s>    h79K9KJ9WX,(;&7'9	     rB   )r)   )rG   strreturnOptional[FilterDirective])r   r?   )clsrC   rD   rE   fix_invalidr)   s    ```  r>   from_componentsz+StructuredQueryOutputParser.from_componentsE   s>    &   #$7"3#5 e	 
 Y''rI   )r7   rJ   rK   r   )NNNF)
rC   Optional[Sequence[Comparator]]rD   Optional[Sequence[Operator]]rE   Optional[Sequence[str]]rN   boolrK   r(   )__name__
__module____qualname____doc____annotations__r?   classmethodrO   r0   rI   r>   r(   r(   *   sf    7S*  ?C:>6:!$(;$( 8$( 4	$(
 $( 
%$( $(rI   r(   rB   c                  |s|s|r| s| S t        | t              r$|r| j                  |vry|r| j                  |vry| S t        | t              r|r| j
                  |vry| j                  D cg c]!  }|t        t        t        ||||            # }}|syt        |      dk(  r1| j
                  t        j                  t        j                  fv r|d   S t	        | j
                  |      S | S c c}w )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.
    NrB      r   )operator	arguments)
isinstancer   
comparator	attributer   r\   r]   r   r   rF   r1   r   ANDOR)r,   rC   rD   rE   argargss         r>   rF   rF   m   s   & !$59K	FJ	'6#4#4<O#O&"2"2:L"L	FI	&8I!I ''
  $(;&7'9	
 
 Y!^HLL(++3N N7N 
 /
s   .&C1c                    i }| D ]!  }t        |      }|||j                  d      <   # t        j                  |d      j	                  dd      j	                  dd      S )Nname   indent{{{}}})dictr3   jsondumpsreplace)info
info_dictsii_dicts       r>   _format_attribute_inforv      s_    J 0a)/
6::f%&0 ::j+33C>FFsDQQrI   c                    g }t        |       D ]Y  \  }\  }}t        j                  |d      j                  dd      j                  dd      }|dz   ||d}|j	                  |       [ |S )	zConstruct examples from input-output pairs.

    Args:
        input_output_pairs: Sequence of input-output pairs.

    Returns:
        List of examples.
    rg   rh   rj   rk   rl   rm   r[   )rt   
user_querystructured_request)	enumeratero   rp   rq   append)input_output_pairsexamplesrt   _inputoutputry   examples          r>   construct_examplesr      s     H();< 	!FFJJva(00d;CCCN 	 Q "4

 	 	! OrI   Fr}   rC   rD   enable_limitschema_promptc          	     >   |rt         nt        }|xs |}t        |      }	|j                  dj	                  |      dj	                  |            }
|r_t        |d   t              rLt        |      }t        }t        j                  |
| |	      }t        j                  t        |      dz         }nR|xs |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 | )rC   rD   r   )schemacontent
attributesr[   )rt   )r   )rt   r   r   r+   )r}   example_promptinput_variablessuffixprefixr0   )r#   r   rv   formatjoinr^   tupler   r%   r"   r$   r1   r!   r   r    r   r   r   list)document_contentsattribute_infor}   rC   rD   r   r   kwargsdefault_schema_promptattribute_strr   r   r   r   s                 r>   get_query_constructor_promptr      s-   : %1 6K  ":%:M*>:M!!!JJ':;**%67 " F Jx{E2%h/6(//#4
 ,22S]Q5FG 
#/5E 	 (&&f5&&(ma):}
 ! h% 	  rI   z0.2.13load_query_constructor_runnablez1.0)sincealternativeremovalc           	         t        |||||||      }	g }
|D ]2  }|
j                  t        |t              r|j                  n|d          4 t
        j                  |||
      }||	_        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   rf   rB   )llmpromptoutput_parserr0   )	r   r{   r^   r&   rf   r(   rO   r   r   )r   r   r   r}   rC   rD   r   r   r   r   rE   ainfor   s                r>   load_query_constructor_chainr     s    D */+!#F  
!!$UM:EJJf	

 0??/+- @ M )FRF-R6RRrI   )r}   rC   rD   r   r   rN   c          	         t        ||f|||||d|	}
g }|D ]2  }|j                  t        |t              r|j                  n|d          4 t
        j                  ||||      }|
| 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   rf   )rC   rD   rE   rN   )r   r{   r^   r&   rf   r(   rO   )r   r   r   r}   rC   rD   r   r   rN   r   r   rE   r   r   s                 r>   r   r   ?  s    D *	 /+!#	 	F  
!!$UM:EJJf	

 0??/+-	 @ M C<-''rI   )
r,   rL   rC   rP   rD   rQ   rE   rR   rK   rL   )rr   $Sequence[Union[AttributeInfo, dict]]rK   rJ   )r|   zSequence[Tuple[str, dict]]rK   z
List[dict])r   rJ   r   r   r}   Optional[Sequence]rC   Sequence[Comparator]rD   Sequence[Operator]r   rS   r   Optional[BasePromptTemplate]r   r   rK   r   )r   r   r   rJ   r   r   r}   zOptional[List]rC   r   rD   r   r   rS   r   r   r   r   rK   r   )r   r   r   rJ   r   r   r}   r   rC   r   rD   r   r   rS   r   r   rN   rS   r   r   rK   r   )=rW   
__future__r   ro   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(   rF   rv   r   r   r   r   r   r0   rI   r>   <module>r      sb   F "  N N N * ; < : L 5 A -  * @   D@("2?"C @(L ;?6:267%7 87 4	7
 07 7tR6 $(05j0A,1(O26<<8< !	<
 .< *< < 0< < <~ 
1  $05j0A,1(O262S	2S2S 92S 	2S
 .2S *2S 2S 02S 2S 2S
2St $(05j0A,1(O267(	7(7( 97(
 !7( .7( *7( 7( 07( 7( 7( 7(rI   