
    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}d| d	| }t        |      |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emsgs	            e/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain/chains/query_constructor/base.pyparsez!StructuredQueryOutputParser.parse1   s    	4$h/M7L24GFg&#fWo*>!*C"%wh;.fX6F#'x #'>>&2B#Cx ::g&

7D)" $*LLNHDAqa<6G1a4H H 	4"4&(DQCHC',!3	4s0   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_filterfilter_directiverD   rB   rC   s     r=   r'   z>StructuredQueryOutputParser.from_components.<locals>.ast_parseZ   sA    #'_-L&&z2$  ,$(;&7'9	     rA   )r'   )rF   strreturnOptional[FilterDirective])r   r>   )clsrB   rC   rD   fix_invalidr'   s    ```  r=   from_componentsz+StructuredQueryOutputParser.from_componentsE   s>    & 
 
 #$7"3#5 e	 
 Y''rH   )r5   rI   rJ   r   )NNNF)
rB   Optional[Sequence[Comparator]]rC   Optional[Sequence[Operator]]rD   Optional[Sequence[str]]rM   boolrJ   r&   )__name__
__module____qualname____doc____annotations__r>   classmethodrN   r.   rH   r=   r&   r&   +   sf    7S4(  ?C:>6:!&(;&( 8&( 4	&(
 &( 
%&( &(rH   r&   rA   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.
    NrA      r   )operator	arguments)
isinstancer   
comparator	attributer   r[   r\   r	   r   rE   r/   r   ANDOR)r*   rB   rC   rD   argargss         r=   rE   rE   o   s   & !$59K&*%6#4#4<O#O&"2"2:L"L&)$8I!I ''
  $(;&7'9	
 
 t9>foo(,,1LL7N__
 	
 M+
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_inforu      s_    J 0a)/
6::f%&0 ::j+33C>FFsDQQrH   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.
    rf   rg   ri   rj   rk   rl   rZ   )rs   
user_querystructured_request)	enumeratern   ro   rp   append)input_output_pairsexamplesrs   _inputoutputrx   examples          r=   construct_examplesr      s     H();< 	!FFJJva(00d;CCCN 	 Q "4

 	 	! OrH   Fr|   rB   rC   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 | )rB   rC   r   )schemacontent
attributesrZ   )rs   )r   )rs   r   r   r)   )r|   example_promptinput_variablessuffixprefixr.   )r!   r   ru   formatjoinr]   tupler   r#   r    r"   r/   r   r   r   r   r   r   list)document_contentsattribute_infor|   rB   rC   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(//%$

 ,22S]Q5FG 
#/5E 	 (&&f5&&(ma%$

 ! h% 	  rH   z0.2.13load_query_constructor_runnablez1.0)sincealternativeremovalc           	         t        |||||||      }	|D 
cg c]#  }
t        |
t              r|
j                  n|
d   % }}
t        j                  |||      }||	_        t        d| |	|d|S c c}
w )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   re   rA   )llmpromptoutput_parserr.   )r   r]   r$   re   r&   rN   r   r   )r   r   r   r|   rB   rC   r   r   r   r   ainforD   r   s                r=   load_query_constructor_chainr   	  s    D */+!#F $ !6

E&MI  0??/+- @ M )FRF-R6RRs   (A/)r|   rB   rC   r   r   rM   c          	         t        ||f|||||d|	}
|D cg c]#  }t        |t              r|j                  n|d   % }}t        j                  ||||      }|
| z  |z  S c c}w )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   re   )rB   rC   rD   rM   )r   r]   r$   re   r&   rN   )r   r   r   r|   rB   rC   r   r   rM   r   r   r   rD   r   s                 r=   r   r   B  s    D *	 /+!#	 	F $ !6

E&MI  0??/+-	 @ M C<-''s   (A#)
r*   rK   rB   rO   rC   rP   rD   rQ   rJ   rK   )rq   $Sequence[Union[AttributeInfo, dict]]rJ   rI   )r{   zSequence[tuple[str, dict]]rJ   z
list[dict])r   rI   r   r   r|   Optional[Sequence]rB   Sequence[Comparator]rC   Sequence[Operator]r   rR   r   Optional[BasePromptTemplate]r   r   rJ   r   )r   r   r   rI   r   r   r|   zOptional[list]rB   r   rC   r   r   rR   r   r   r   r   rJ   r   )r   r   r   rI   r   r   r|   r   rB   r   rC   r   r   rR   r   r   rM   rR   r   r   rJ   r   )<rV   
__future__r   rn   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&   rE   ru   r   r   r   r   r   r.   rH   r=   <module>r      sl   F "  $ 7 7 * ; < : L 5 A -  * @   DA("2?"C A(N ;?6:265%5 85 4	5
 05 5pR6 $(05j0A,1(O26@@8@ !	@
 .@ *@ @ 0@ @ @F 
1  $05j0A,1(O261S	1S1S 91S 	1S
 .1S *1S 1S 01S 1S 1S
1Sr $(05j0A,1(O266(	6(6( 96(
 !6( .6( *6( 6( 06( 6( 6( 6(rH   