a
    •˜ëj@2  ã                   @   s¦   d Z ddl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 ddlmZ edddd�G dd„ deƒƒZdS )zMChain for applying constitutional principles to the outputs of another chain.é    )ÚAnyÚOptional)Ú
deprecated)ÚCallbackManagerForChainRun)ÚBaseLanguageModel)ÚBasePromptTemplate)ÚChain)ÚConstitutionalPrinciple©Ú
PRINCIPLES)ÚCRITIQUE_PROMPTÚREVISION_PROMPT©ÚLLMChainz0.2.13zÔThis class is deprecated and will be removed in langchain 1.0. See API reference for replacement: https://api.python.langchain.com/en/latest/chains/langchain.chains.constitutional_ai.base.ConstitutionalChain.htmlz1.0)ZsinceÚmessageZremovalc                	   @   sî   e Zd ZU dZeed< ee ed< eed< eed< dZe	ed< e
deee  ee d	œd
d„ƒZe
eefeeeeed dœdd„ƒZeee dœdd„ƒZeee dœdd„ƒZdeeef ee eeef dœdd„Zeeedœdd„ƒZdS )ÚConstitutionalChainaV  Chain for applying constitutional principles.

    .. note::
        This class is deprecated. See below for a replacement implementation using
        LangGraph. The benefits of this implementation are:

        - Uses LLM tool calling features instead of parsing string responses;
        - Support for both token-by-token and step-by-step streaming;
        - Support for checkpointing and memory of chat history;
        - Easier to modify or extend (e.g., with additional tools, structured responses, etc.)

        Install LangGraph with:

        .. code-block:: bash

            pip install -U langgraph

        .. code-block:: python

            from typing import List, Optional, Tuple

            from langchain.chains.constitutional_ai.prompts import (
                CRITIQUE_PROMPT,
                REVISION_PROMPT,
            )
            from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
            from langchain_core.output_parsers import StrOutputParser
            from langchain_core.prompts import ChatPromptTemplate
            from langchain_openai import ChatOpenAI
            from langgraph.graph import END, START, StateGraph
            from typing_extensions import Annotated, TypedDict

            llm = ChatOpenAI(model="gpt-4o-mini")

            class Critique(TypedDict):
                """Generate a critique, if needed."""
                critique_needed: Annotated[bool, ..., "Whether or not a critique is needed."]
                critique: Annotated[str, ..., "If needed, the critique."]

            critique_prompt = ChatPromptTemplate.from_template(
                "Critique this response according to the critique request. "
                "If no critique is needed, specify that.\n\n"
                "Query: {query}\n\n"
                "Response: {response}\n\n"
                "Critique request: {critique_request}"
            )

            revision_prompt = ChatPromptTemplate.from_template(
                "Revise this response according to the critique and reivsion request.\n\n"
                "Query: {query}\n\n"
                "Response: {response}\n\n"
                "Critique request: {critique_request}\n\n"
                "Critique: {critique}\n\n"
                "If the critique does not identify anything worth changing, ignore the "
                "revision request and return 'No revisions needed'. If the critique "
                "does identify something worth changing, revise the response based on "
                "the revision request.\n\n"
                "Revision Request: {revision_request}"
            )

            chain = llm | StrOutputParser()
            critique_chain = critique_prompt | llm.with_structured_output(Critique)
            revision_chain = revision_prompt | llm | StrOutputParser()


            class State(TypedDict):
                query: str
                constitutional_principles: List[ConstitutionalPrinciple]
                initial_response: str
                critiques_and_revisions: List[Tuple[str, str]]
                response: str


            async def generate_response(state: State):
                """Generate initial response."""
                response = await chain.ainvoke(state["query"])
                return {"response": response, "initial_response": response}

            async def critique_and_revise(state: State):
                """Critique and revise response according to principles."""
                critiques_and_revisions = []
                response = state["initial_response"]
                for principle in state["constitutional_principles"]:
                    critique = await critique_chain.ainvoke(
                        {
                            "query": state["query"],
                            "response": response,
                            "critique_request": principle.critique_request,
                        }
                    )
                    if critique["critique_needed"]:
                        revision = await revision_chain.ainvoke(
                            {
                                "query": state["query"],
                                "response": response,
                                "critique_request": principle.critique_request,
                                "critique": critique["critique"],
                                "revision_request": principle.revision_request,
                            }
                        )
                        response = revision
                        critiques_and_revisions.append((critique["critique"], revision))
                    else:
                        critiques_and_revisions.append((critique["critique"], ""))
                return {
                    "critiques_and_revisions": critiques_and_revisions,
                    "response": response,
                }

            graph = StateGraph(State)
            graph.add_node("generate_response", generate_response)
            graph.add_node("critique_and_revise", critique_and_revise)

            graph.add_edge(START, "generate_response")
            graph.add_edge("generate_response", "critique_and_revise")
            graph.add_edge("critique_and_revise", END)
            app = graph.compile()

        .. code-block:: python

            constitutional_principles=[
                ConstitutionalPrinciple(
                    critique_request="Tell if this answer is good.",
                    revision_request="Give a better answer.",
                )
            ]

            query = "What is the meaning of life? Answer in 10 words or fewer."

            async for step in app.astream(
                {"query": query, "constitutional_principles": constitutional_principles},
                stream_mode="values",
            ):
                subset = ["initial_response", "critiques_and_revisions", "response"]
                print({k: v for k, v in step.items() if k in subset})

    Example:
        .. code-block:: python

            from langchain_community.llms import OpenAI
            from langchain.chains import LLMChain, ConstitutionalChain
            from langchain.chains.constitutional_ai.models \
                import ConstitutionalPrinciple

            llm = OpenAI()

            qa_prompt = PromptTemplate(
                template="Q: {question} A:",
                input_variables=["question"],
            )
            qa_chain = LLMChain(llm=llm, prompt=qa_prompt)

            constitutional_chain = ConstitutionalChain.from_llm(
                llm=llm,
                chain=qa_chain,
                constitutional_principles=[
                    ConstitutionalPrinciple(
                        critique_request="Tell if this answer is good.",
                        revision_request="Give a better answer.",
                    )
                ],
            )

            constitutional_chain.run(question="What is the meaning of life?")

    ÚchainÚconstitutional_principlesÚcritique_chainÚrevision_chainFÚreturn_intermediate_stepsN)ÚnamesÚreturnc                 C   s"   |du rt t ¡ ƒS dd„ |D ƒS )zÉGet constitutional principles by name.

        Args:
            names: List of names of constitutional principles to retrieve.
                If None (default), all principles are returned.
        Nc                 S   s   g | ]}t | ‘qS © r
   )Ú.0Únamer   r   úf/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain/chains/constitutional_ai/base.pyÚ
<listcomp>Õ   ó    z6ConstitutionalChain.get_principles.<locals>.<listcomp>)Úlistr   Úvalues)Úclsr   r   r   r   Úget_principlesÈ   s    z"ConstitutionalChain.get_principles)Úllmr   Úcritique_promptÚrevision_promptÚkwargsr   c                 K   s.   t ||d�}t ||d�}| f |||dœ|¤ŽS )zCreate a chain from an LLM.)r#   Úprompt)r   r   r   r   )r!   r#   r   r$   r%   r&   r   r   r   r   r   Úfrom_llm×   s    
ýüzConstitutionalChain.from_llm)r   c                 C   s   | j jS )zInput keys.)r   Ú
input_keys©Úselfr   r   r   r)   ê   s    zConstitutionalChain.input_keysc                 C   s   | j rg d¢S dgS )zOutput keys.)ÚoutputÚcritiques_and_revisionsÚinitial_outputr,   )r   r*   r   r   r   Úoutput_keysï   s    zConstitutionalChain.output_keys)ÚinputsÚrun_managerr   c              
   C   sf  |p
t  ¡ }| jjf i |¤d| d¡i¤Ž}|}| jjjf i |¤Ž}|jd| d | jdd� g }| j	D ]Ø}| j
j|||j| d¡d�}	| j|	d	� ¡ }
d
|
 ¡ v r´| |
df¡ qh| jj|||j|
|j| d¡d� ¡ }|}| |
|f¡ |jd|j› d�d | jdd� |jd|
 d | jdd� |jd| d | jdd� qhd|i}| j�rb||d< ||d< |S )NÚ	callbacksÚoriginalzInitial response: ú

Zyellow)ÚtextÚverboseÚcolorÚcritique)Úinput_promptÚoutput_from_modelÚcritique_requestr2   ©Úoutput_stringzno critique neededÚ Úrevision)r9   r:   r;   r8   Úrevision_requestr2   z	Applying z...Zgreenz
Critique: ZbluezUpdated response: r,   r.   r-   )r   Zget_noop_managerr   ÚrunZ	get_childr'   ÚformatZon_textr6   r   r   r;   Ú_parse_critiqueÚstripÚlowerÚappendr   r@   r   r   )r+   r0   r1   Z_run_managerÚresponseZinitial_responser9   r-   Zconstitutional_principleZraw_critiquer8   r?   Zfinal_outputr   r   r   Ú_callö   sr    
ÿþ
ý
üÿ
ú
ý
ý
ýzConstitutionalChain._call)r=   r   c                 C   s4   d| vr| S |   d¡d } d| v r0|   d¡d } | S )NzRevision request:r   r4   )Úsplitr<   r   r   r   rC   B  s    z#ConstitutionalChain._parse_critique)N)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r	   r   ÚboolÚclassmethodr   Ústrr"   r   r   r   r   r   r(   Úpropertyr)   r/   Údictr   rH   ÚstaticmethodrC   r   r   r   r   r      sH   

 ( þ
ýûù	 ý

üLr   N)rM   Útypingr   r   Zlangchain_core._apir   Zlangchain_core.callbacksr   Zlangchain_core.language_modelsr   Zlangchain_core.promptsr   Zlangchain.chains.baser   Z)langchain.chains.constitutional_ai.modelsr	   Z-langchain.chains.constitutional_ai.principlesr   Z*langchain.chains.constitutional_ai.promptsr   r   Zlangchain.chains.llmr   r   r   r   r   r   Ú<module>   s    ù	