
    @'h6                       d Z ddlmZ ddlZddlmZ ddl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.m/Z/m0Z0m1Z1 ddl2m3Z3  G d dee"         Z4dddd	 	 	 	 	 	 	 	 	 d#dZ5d$dZ6d%dZ7d e8e       e8e!      ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ9 eddd      d e8e       e8e!      ddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'd        Z:d e8e       e8e!      dddd!	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(d"Z;y))z@LLM Chain for turning a user text query into a structured query.    )annotationsN)Sequence)AnyCallableOptional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           n/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langchain/chains/query_constructor/base.pyparsez!StructuredQueryOutputParser.parse1   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*   fixedrC   rA   rB   s      r<   r'   z>StructuredQueryOutputParser.from_components.<locals>.ast_parse[   s>    h79K9KJ9WX,(;&7'9	     r@   )r'   )rE   strreturnOptional[FilterDirective])r   r=   )clsrA   rB   rC   fix_invalidr'   s    ```  r<   from_componentsz+StructuredQueryOutputParser.from_componentsF   s>    &   #$7"3#5 e	 
 Y''rG   )r5   rH   rI   r   )NNNF)
rA   Optional[Sequence[Comparator]]rB   Optional[Sequence[Operator]]rC   Optional[Sequence[str]]rL   boolrI   r&   )__name__
__module____qualname____doc____annotations__r=   classmethodrM   r.   rG   r<   r&   r&   +   sf    7S*  ?C:>6:!$(;$( 8$( 4	$(
 $( 
%$( $(rG   r&   r@   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.
    Nr@      r   )operator	arguments)
isinstancer   
comparator	attributer   rZ   r[   r	   r   rD   r/   r   ANDOR)r*   rA   rB   rC   argargss         r<   rD   rD   n   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{{{}}})dictr1   jsondumpsreplace)info
info_dictsii_dicts       r<   _format_attribute_infort      s_    J 0a)/
6::f%&0 ::j+33C>FFsDQQrG   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.
    re   rf   rh   ri   rj   rk   rY   )rr   
user_querystructured_request)	enumeraterm   rn   ro   append)input_output_pairsexamplesrr   _inputoutputrw   examples          r<   construct_examplesr      s     H();< 	!FFJJva(00d;CCCN 	 Q "4

 	 	! OrG   Fr{   rA   rB   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 | )rA   rB   r   )schemacontent
attributesrY   )rr   )r   )rr   r   r   r)   )r{   example_promptinput_variablessuffixprefixr.   )r!   r   rt   formatjoinr\   tupler   r#   r    r"   r/   r   r   r   r   r   r   list)document_contentsattribute_infor{   rA   rB   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% 	  rG   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   rd   r@   )llmpromptoutput_parserr.   )	r   ry   r\   r$   rd   r&   rM   r   r   )r   r   r   r{   rA   rB   r   r   r   r   rC   ainfor   s                r<   load_query_constructor_chainr     s    D */+!#F  
!!$UM:EJJf	

 0??/+- @ M )FRF-R6RRrG   )r{   rA   rB   r   r   rL   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   rd   )rA   rB   rC   rL   )r   ry   r\   r$   rd   r&   rM   )r   r   r   r{   rA   rB   r   r   rL   r   r   rC   r   r   s                 r<   r   r   @  s    D *	 /+!#	 	F  
!!$UM:EJJf	

 0??/+-	 @ M C<-''rG   )
r*   rJ   rA   rN   rB   rO   rC   rP   rI   rJ   )rp   $Sequence[Union[AttributeInfo, dict]]rI   rH   )rz   zSequence[tuple[str, dict]]rI   z
list[dict])r   rH   r   r   r{   Optional[Sequence]rA   Sequence[Comparator]rB   Sequence[Operator]r   rQ   r   Optional[BasePromptTemplate]r   r   rI   r   )r   r   r   rH   r   r   r{   zOptional[list]rA   r   rB   r   r   rQ   r   r   r   r   rI   r   )r   r   r   rH   r   r   r{   r   rA   r   rB   r   r   rQ   r   r   rL   rQ   r   r   rI   r   )<rU   
__future__r   rm   collections.abcr   typingr   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&   rD   rt   r   r   r   r   r   r.   rG   r<   <module>r      sb   F "  $ 7 7 * ; < : 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(rG   