o
    Jjg-                     @  s   d dl mZ d dl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mZ d dlmZmZ erBd dlmZ dddZG dd deZG dd deZ		d d!ddZdS )"    )annotations)TYPE_CHECKINGAnyDictListOptional	TypedDictUnion)BaseLanguageModel)StrOutputParser)BasePromptTemplate)RunnableRunnablePassthrough)PROMPTSQL_PROMPTS)SQLDatabasetextstrreturnc                 C  s   |   S )N)strip)r    r   [/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/chains/sql_database/query.py_strip   s   r   c                   @  s   e Zd ZU dZded< dS )SQLInputInput for a SQL Chain.r   questionN__name__
__module____qualname____doc____annotations__r   r   r   r   r      s   
 r   c                   @  s"   e Zd ZU dZded< ded< dS )SQLInputWithTablesr   r   r   z	List[str]table_names_to_useNr   r   r   r   r   r"      s   
 r"   N   llmr
   dbr   promptOptional[BasePromptTemplate]kintBRunnable[Union[SQLInput, SQLInputWithTables, Dict[str, Any]], str]c                   s   |dur|}n j tv rt j  }nt}h d|jt|j r,td|j d| d|jv r8|j j d}dd  fd	dd
}t	j
di |dd B |jt|dB | jdgdB t B tB S )a2  Create a chain that generates SQL queries.

    *Security Note*: This chain generates SQL queries for the given database.

        The SQLDatabase class provides a get_table_info method that can be used
        to get column information as well as sample data from the table.

        To mitigate risk of leaking sensitive data, limit permissions
        to read and scope to the tables that are needed.

        Optionally, use the SQLInputWithTables input type to specify which tables
        are allowed to be accessed.

        Control access to who can submit requests to this chain.

        See https://python.langchain.com/docs/security for more information.

    Args:
        llm: The language model to use.
        db: The SQLDatabase to generate the query for.
        prompt: The prompt to use. If none is provided, will choose one
            based on dialect. Defaults to None. See Prompt section below for more.
        k: The number of results per select statement to return. Defaults to 5.

    Returns:
        A chain that takes in a question and generates a SQL query that answers
        that question.

    Example:

        .. code-block:: python

            # pip install -U langchain langchain-community langchain-openai
            from langchain_openai import ChatOpenAI
            from langchain.chains import create_sql_query_chain
            from langchain_community.utilities import SQLDatabase

            db = SQLDatabase.from_uri("sqlite:///Chinook.db")
            llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
            chain = create_sql_query_chain(llm, db)
            response = chain.invoke({"question": "How many employees are there"})

    Prompt:
        If no prompt is provided, a default prompt is selected based on the SQLDatabase dialect. If one is provided, it must support input variables:
            * input: The user question plus suffix "
SQLQuery: " is passed here.
            * top_k: The number of results per select statement (the `k` argument to
                this function) is passed in here.
            * table_info: Table definitions and sample rows are passed in here. If the
                user specifies "table_names_to_use" when invoking chain, only those
                will be included. Otherwise, all tables are included.
            * dialect (optional): If dialect input variable is in prompt, the db
                dialect will be passed in here.

        Here's an example prompt:

        .. code-block:: python

            from langchain_core.prompts import PromptTemplate

            template = '''Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
            Use the following format:

            Question: "Question here"
            SQLQuery: "SQL Query to run"
            SQLResult: "Result of the SQLQuery"
            Answer: "Final answer here"

            Only use the following tables:

            {table_info}.

            Question: {input}'''
            prompt = PromptTemplate.from_template(template)
    N>   inputtop_k
table_infozhPrompt must have input variables: 'input', 'top_k', 'table_info'. Received prompt with input variables: z. Full prompt:

dialect)r/   c                 S  s   | d d S )Nr   z
SQLQuery: r   xr   r   r   <lambda>   s    z(create_sql_query_chain.<locals>.<lambda>c                   s    j | ddS )Nr#   )table_names)get_table_infogetr0   r&   r   r   r2      s    )r,   r.   c                 S  s   dd |   D S )Nc                 S  s   i | ]\}}|d vr||qS ))r   r#   r   ).0r)   vr   r   r   
<dictcomp>   s
    z<create_sql_query_chain.<locals>.<lambda>.<locals>.<dictcomp>)itemsr0   r   r   r   r2      s    )r-   z
SQLResult:)stopr   )r/   r   r   
differenceinput_variableslistpartial_variables
ValueErrorpartialr   assignr   bindr   r   )r%   r&   r'   r)   prompt_to_useinputsr   r6   r   create_sql_query_chain!   s@   P


	
rF   )r   r   r   r   )Nr$   )
r%   r
   r&   r   r'   r(   r)   r*   r   r+   )
__future__r   typingr   r   r   r   r   r   r	   langchain_core.language_modelsr
   langchain_core.output_parsersr   langchain_core.promptsr   langchain_core.runnablesr   r   $langchain.chains.sql_database.promptr   r   *langchain_community.utilities.sql_databaser   r   r   r"   rF   r   r   r   r   <module>   s    $

