o
    Jjg=R                     @  s  d Z ddlmZ ddlZddl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 ddlmZ ddl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'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 eee7e7f ef Z8dddZ9d,ddZ:G d d! d!e'Z;G d"d# d#e,Z<ed$d%d&d'G d(d) d)e<Z=G d*d+ d+e<Z>dS )-*Chain for chatting with a vector database.    )annotationsN)abstractmethod)Path)AnyCallableDictListOptionalTupleTypeUnion)
deprecated)AsyncCallbackManagerForChainRunCallbackManagerForChainRun	Callbacks)Document)BaseLanguageModel)BaseMessage)BasePromptTemplate)BaseRetriever)RunnableConfig)VectorStore)	BaseModel
ConfigDictFieldmodel_validator)Chain)BaseCombineDocumentsChain)StuffDocumentsChain)CONDENSE_QUESTION_PROMPT)LLMChain)load_qa_chainHuman: Assistant: )humanaichat_historyList[CHAT_TURN_TYPE]returnstrc                 C  s   d}| D ]M}t |tr(t|jdkr't|j|j d}|d| |j 7 }qt |trEd|d  }d|d  }|dd||g 7 }qt	dt| d	|  d
|S )N r   z: 
r#   r$      z!Unsupported chat history format: z. Full chat history:  )

isinstancer   lencontent	_ROLE_MAPgettypetuplejoin
ValueError)r'   bufferdialogue_turnrole_prefixr%   r&    r;   f/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/chains/conversational_retrieval/base.py_get_chat_history)   s&   

r=   c                   @  s.   e Zd ZU dZded< 	 eedZded< dS )	InputTypez,Input type for ConversationalRetrievalChain.r*   questiondefault_factoryr(   r'   N)__name__
__module____qualname____doc____annotations__r   listr'   r;   r;   r;   r<   r>   >   s   
 r>   c                      s   e Zd ZU dZded< 	 ded< 	 dZded< 	 d	Zd
ed< 	 dZd
ed< 	 dZd
ed< 	 dZ	ded< 	 dZ
ded< 	 ed	d	ddZed7ddZ	d8d9ddZed7dd Zed:d'd(Z	d8d;d*d+Zed<d-d.Z	d8d=d0d1Zd> fd5d6Z  ZS )? BaseConversationalRetrievalChainz!Chain for chatting with an index.r   combine_docs_chainr!   question_generatoranswerr*   
output_keyTboolrephrase_questionFreturn_source_documentsreturn_generated_questionNz/Optional[Callable[[List[CHAT_TURN_TYPE]], str]]get_chat_historyzOptional[str]response_if_no_docs_foundforbid)populate_by_namearbitrary_types_allowedextrar)   	List[str]c                 C  s   ddgS )zInput keys.r?   r'   r;   selfr;   r;   r<   
input_keysi   s   z+BaseConversationalRetrievalChain.input_keysconfigOptional[RunnableConfig]Type[BaseModel]c                 C  s   t S N)r>   )rY   r[   r;   r;   r<   get_input_scheman   s   z1BaseConversationalRetrievalChain.get_input_schemac                 C  s,   | j g}| jr|dg }| jr|dg }|S )z8Return the output keys.

        :meta private:
        source_documentsgenerated_question)rL   rO   rP   )rY   _output_keysr;   r;   r<   output_keyss   s   

z,BaseConversationalRetrievalChain.output_keysr?   inputsDict[str, Any]run_managerr   List[Document]c                C     dS 	Get docs.Nr;   rY   r?   rd   rf   r;   r;   r<   	_get_docs   s    z*BaseConversationalRetrievalChain._get_docs$Optional[CallbackManagerForChainRun]c                 C  s  |pt  }|d }| jpt}||d }|r%| }| jj|||d}n|}dt| j	j
v }	|	r;| j	|||d}
n| 	||}
i }| jd urUt|
dkrU| j|| j< n"| }| jr`||d< ||d< | jjd
|
| d|}||| j< | jr~|
|d< | jr||d	< |S Nr?   r'   )r?   r'   	callbacksrf   )rf   r   )input_documentsro   r`   ra   r;   )r   get_noop_managerrQ   r=   	get_childrJ   runinspect	signaturerl   
parametersrR   r0   rL   copyrN   rI   rO   rP   rY   rd   rf   _run_managerr?   rQ   chat_history_strro   new_questionaccepts_run_managerdocsoutput
new_inputsrK   r;   r;   r<   _call   sB   

z&BaseConversationalRetrievalChain._callr   c                  s   dS ri   r;   rk   r;   r;   r<   
_aget_docs   s    z+BaseConversationalRetrievalChain._aget_docs)Optional[AsyncCallbackManagerForChainRun]c                   s(  |pt  }|d }| jpt}||d }|r)| }| jj|||dI d H }n|}dt| j	j
v }	|	rB| j	|||dI d H }
n	| 	||I d H }
i }| jd ur_t|
dkr_| j|| j< n%| }| jrj||d< ||d< | jjd
|
| d|I d H }||| j< | jr|
|d< | jr||d	< |S rn   )r   rq   rQ   r=   rr   rJ   arunrt   ru   r   rv   rR   r0   rL   rw   rN   rI   rO   rP   rx   r;   r;   r<   _acall   sD   

z'BaseConversationalRetrievalChain._acall	file_pathUnion[Path, str]Nonec                   s   | j rtdt | d S )Nz7Chain not saveable when `get_chat_history` is not None.)rQ   r7   supersave)rY   r   	__class__r;   r<   r      s   z%BaseConversationalRetrievalChain.save)r)   rW   r^   )r[   r\   r)   r]   r?   r*   rd   re   rf   r   r)   rg   )rd   re   rf   rm   r)   re   r?   r*   rd   re   rf   r   r)   rg   )rd   re   rf   r   r)   re   )r   r   r)   r   )rB   rC   rD   rE   rF   rL   rN   rO   rP   rQ   rR   r   model_configpropertyrZ   r_   rc   r   rl   r   r   r   r   __classcell__r;   r;   r   r<   rH   G   sL   
 ++rH   z0.1.17z^create_history_aware_retriever together with create_retrieval_chain (see example in docstring)z1.0)sincealternativeremovalc                   @  sd   e Zd ZU dZded< 	 dZded< 	 d+d
dZd,ddZd-ddZe	e
dddddfd.d)d*ZdS )/ConversationalRetrievalChaina  Chain for having a conversation based on retrieved documents.

    This class is deprecated. See below for an example implementation using
    `create_retrieval_chain`. Additional walkthroughs can be found at
    https://python.langchain.com/docs/use_cases/question_answering/chat_history

        .. code-block:: python

            from langchain.chains import (
                create_history_aware_retriever,
                create_retrieval_chain,
            )
            from langchain.chains.combine_documents import create_stuff_documents_chain
            from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
            from langchain_openai import ChatOpenAI


            retriever = ...  # Your retriever

            llm = ChatOpenAI()

            # Contextualize question
            contextualize_q_system_prompt = (
                "Given a chat history and the latest user question "
                "which might reference context in the chat history, "
                "formulate a standalone question which can be understood "
                "without the chat history. Do NOT answer the question, just "
                "reformulate it if needed and otherwise return it as is."
            )
            contextualize_q_prompt = ChatPromptTemplate.from_messages(
                [
                    ("system", contextualize_q_system_prompt),
                    MessagesPlaceholder("chat_history"),
                    ("human", "{input}"),
                ]
            )
            history_aware_retriever = create_history_aware_retriever(
                llm, retriever, contextualize_q_prompt
            )

            # Answer question
            qa_system_prompt = (
                "You are an assistant for question-answering tasks. Use "
                "the following pieces of retrieved context to answer the "
                "question. If you don't know the answer, just say that you "
                "don't know. Use three sentences maximum and keep the answer "
                "concise."
                "

"
                "{context}"
            )
            qa_prompt = ChatPromptTemplate.from_messages(
                [
                    ("system", qa_system_prompt),
                    MessagesPlaceholder("chat_history"),
                    ("human", "{input}"),
                ]
            )
            # Below we use create_stuff_documents_chain to feed all retrieved context
            # into the LLM. Note that we can also use StuffDocumentsChain and other
            # instances of BaseCombineDocumentsChain.
            question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)
            rag_chain = create_retrieval_chain(
                history_aware_retriever, question_answer_chain
            )

            # Usage:
            chat_history = []  # Collect chat history here (a sequence of messages)
            rag_chain.invoke({"input": query, "chat_history": chat_history})

    This chain takes in chat history (a list of messages) and new questions,
    and then returns an answer to that question.
    The algorithm for this chain consists of three parts:

    1. Use the chat history and the new question to create a "standalone question".
    This is done so that this question can be passed into the retrieval step to fetch
    relevant documents. If only the new question was passed in, then relevant context
    may be lacking. If the whole conversation was passed into retrieval, there may
    be unnecessary information there that would distract from retrieval.

    2. This new question is passed to the retriever and relevant documents are
    returned.

    3. The retrieved documents are passed to an LLM along with either the new question
    (default behavior) or the original question and chat history to generate a final
    response.

    Example:
        .. code-block:: python

            from langchain.chains import (
                StuffDocumentsChain, LLMChain, ConversationalRetrievalChain
            )
            from langchain_core.prompts import PromptTemplate
            from langchain_community.llms import OpenAI

            combine_docs_chain = StuffDocumentsChain(...)
            vectorstore = ...
            retriever = vectorstore.as_retriever()

            # This controls how the standalone question is generated.
            # Should take `chat_history` and `question` as input variables.
            template = (
                "Combine the chat history and follow up question into "
                "a standalone question. Chat History: {chat_history}"
                "Follow up question: {question}"
            )
            prompt = PromptTemplate.from_template(template)
            llm = OpenAI()
            question_generator_chain = LLMChain(llm=llm, prompt=prompt)
            chain = ConversationalRetrievalChain(
                combine_docs_chain=combine_docs_chain,
                retriever=retriever,
                question_generator=question_generator_chain,
            )
    r   	retrieverNzOptional[int]max_tokens_limitr}   rg   r)   c                   sp   t |} jr2t jtr2 fdd|D }t|d | }| jkr2|d8 }||| 8 }| jks#|d | S )Nc                   s   g | ]
} j j|jqS r;   )rI   	llm_chain_get_num_tokenspage_content).0docrX   r;   r<   
<listcomp>y  s    zKConversationalRetrievalChain._reduce_tokens_below_limit.<locals>.<listcomp>r-   )r0   r   r/   rI   r   sum)rY   r}   num_docstokenstoken_countr;   rX   r<   _reduce_tokens_below_limits  s   


z7ConversationalRetrievalChain._reduce_tokens_below_limitr?   r*   rd   re   rf   r   c                C  s"   | j j|d| id}| |S )rj   ro   r[   )r   invokerr   r   rY   r?   rd   rf   r}   r;   r;   r<   rl     s   
z&ConversationalRetrievalChain._get_docsr   c                  s*   | j j|d| idI dH }| |S )rj   ro   r   N)r   ainvokerr   r   r   r;   r;   r<   r     s
   
z'ConversationalRetrievalChain._aget_docsstuffFllmr   condense_question_promptr   
chain_typeverboserM   condense_question_llmOptional[BaseLanguageModel]combine_docs_chain_kwargsOptional[Dict]ro   r   kwargsr   rH   c	                 K  sP   |pi }t |f|||d|}
|p|}t||||d}| d||
||d|	S )a  Convenience method to load chain from LLM and retriever.

        This provides some logic to create the `question_generator` chain
        as well as the combine_docs_chain.

        Args:
            llm: The default language model to use at every part of this chain
                (eg in both the question generation and the answering)
            retriever: The retriever to use to fetch relevant documents from.
            condense_question_prompt: The prompt to use to condense the chat history
                and new question into a standalone question.
            chain_type: The chain type to use to create the combine_docs_chain, will
                be sent to `load_qa_chain`.
            verbose: Verbosity flag for logging to stdout.
            condense_question_llm: The language model to use for condensing the chat
                history and new question into a standalone question. If none is
                provided, will default to `llm`.
            combine_docs_chain_kwargs: Parameters to pass as kwargs to `load_qa_chain`
                when constructing the combine_docs_chain.
            callbacks: Callbacks to pass to all subchains.
            kwargs: Additional parameters to pass when initializing
                ConversationalRetrievalChain
        )r   r   ro   )r   promptr   ro   )r   rI   rJ   ro   Nr;   r"   r!   )clsr   r   r   r   r   r   r   ro   r   	doc_chain_llmcondense_question_chainr;   r;   r<   from_llm  s2   $z%ConversationalRetrievalChain.from_llm)r}   rg   r)   rg   r   r   )r   r   r   r   r   r   r   r*   r   rM   r   r   r   r   ro   r   r   r   r)   rH   )rB   rC   rD   rE   rF   r   r   rl   r   classmethodr    r   r;   r;   r;   r<   r      s"   
 	t


r   c                   @  s   e Zd ZU dZeddZded< dZded< eedZ	d	ed
< e
d0ddZedded1ddZd2ddZd3dd Zeed!d"d"fd4d.d/Zd"S )5ChatVectorDBChainr   vectorstore)aliasr      inttop_k_docs_for_contextr@   dictsearch_kwargsr)   r*   c                 C  rh   )Nzchat-vector-dbr;   rX   r;   r;   r<   _chain_type  s   zChatVectorDBChain._chain_typebefore)modevaluesr   r   c                 C  s   t d |S )Nzj`ChatVectorDBChain` is deprecated - please use `from langchain.chains import ConversationalRetrievalChain`)warningswarn)r   r   r;   r;   r<   raise_deprecation  s   z#ChatVectorDBChain.raise_deprecationr?   rd   re   rf   r   rg   c                C  s4   | di }i | j|}| jj|fd| ji|S )rj   vectordbkwargsk)r3   r   r   similarity_searchr   )rY   r?   rd   rf   r   full_kwargsr;   r;   r<   rl     s   zChatVectorDBChain._get_docsr   c                  s
   t d)rj   z(ChatVectorDBChain does not support async)NotImplementedErrorrk   r;   r;   r<   r     s   zChatVectorDBChain._aget_docsr   Nr   r   r   r   r   r   r   ro   r   r   rH   c           
      K  sD   |pi }t |f||d|}t|||d}	| d|||	|d|S )zLoad chain from LLM.)r   ro   )r   r   ro   )r   rI   rJ   ro   Nr;   r   )
r   r   r   r   r   r   ro   r   r   r   r;   r;   r<   r     s(   zChatVectorDBChain.from_llm)r)   r*   )r   r   r)   r   r   r   )r   r   r   r   r   r   r   r*   r   r   ro   r   r   r   r)   rH   )rB   rC   rD   rE   r   r   rF   r   r   r   r   r   r   r   r   rl   r   r    r   r;   r;   r;   r<   r     s$   
 


r   )r'   r(   r)   r*   )?rE   
__future__r   rt   r   abcr   pathlibr   typingr   r   r   r	   r
   r   r   r   langchain_core._apir   langchain_core.callbacksr   r   r   langchain_core.documentsr   langchain_core.language_modelsr   langchain_core.messagesr   langchain_core.promptsr   langchain_core.retrieversr   langchain_core.runnablesr   langchain_core.vectorstoresr   pydanticr   r   r   r   langchain.chains.baser   'langchain.chains.combine_documents.baser   (langchain.chains.combine_documents.stuffr   1langchain.chains.conversational_retrieval.promptsr    langchain.chains.llmr!   #langchain.chains.question_answeringr"   r*   CHAT_TURN_TYPEr2   r=   r>   rH   r   r   r;   r;   r;   r<   <module>   sJ    (

	 * d