Ë
    ´Œj~1  ã                   óº   — 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¬«       G d„ de«      «       Zy)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)ÚsinceÚmessageÚremovalc                   ó2  — 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d	eee      d
ee   fd„«       Ze
eefdededededed
d fd„«       Zed
ee   fd„«       Zed
ee   fd„«       Z	 ddeeef   dee   d
eeef   fd„Zeded
efd„«       Zy)ÚConstitutionalChainaG  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                 óx   — |€t        t        j                  «       «      S |D �cg c]  }t        |   ‘Œ c}S c c}w ©N)Úlistr   Úvalues)Úclsr   Únames      úq/var/www/html/Fitness-lenito-AI-main/venv/lib/python3.12/site-packages/langchain/chains/constitutional_ai/base.pyÚget_principlesz"ConstitutionalChain.get_principlesÆ   s:   € ð
 ˆ=Üœ
×)Ñ)Ó+Ó,Ð,Ù-2Ó3©U T”
˜4Ó ¨UÑ3Ð3ùÒ3s   ¤7ÚllmÚcritique_promptÚrevision_promptÚkwargsc                 óN   — t        ||¬«      }t        ||¬«      } | d|||dœ|¤ŽS )zCreate a chain from an LLM.)r$   Úprompt)r   r   r   © r   )r    r$   r   r%   r&   r'   r   r   s           r"   Úfrom_llmzConstitutionalChain.from_llmÏ   sA   € ô " c°/ÔBˆÜ! c°/ÔBˆÙð 
ØØ)Ø)ñ
ð ñ	
ð 	
ó    c                 ó.   — | j                   j                  S )zInput keys.)r   Ú
input_keys©Úselfs    r"   r.   zConstitutionalChain.input_keysâ   s   € ð �z‰z×$Ñ$Ð$r,   c                 ó(   — | j                   rg d¢S dgS )zOutput keys.)ÚoutputÚcritiques_and_revisionsÚinitial_outputr2   )r   r/   s    r"   Úoutput_keyszConstitutionalChain.output_keysç   s   € ð ×)Ò)ÚJÐJØˆzÐr,   ÚinputsÚrun_managerc                 óB  — |xs t        j                  «       } | j                  j                  di |¤d|j	                  d«      i¤Ž}|} | j                  j
                  j                  di |¤Ž}|j                  d|z   dz   | j                  d¬«       g }| j                  D �]_  }| j                  j                  |||j                  |j	                  d«      ¬«      }	| j                  |	¬	«      j                  «       }
d
|
j                  «       v r|j                  |
df«       Œ‚| j                   j                  |||j                  |
|j"                  |j	                  d«      ¬«      j                  «       }|}|j                  |
|f«       |j                  d|j$                  › d�dz   | j                  d¬«       |j                  d|
z   dz   | j                  d¬«       |j                  d|z   dz   | j                  d¬«       �Œb d|i}| j&                  r
||d<   ||d<   |S )NÚ	callbacksÚoriginalzInitial response: ú

Úyellow)ÚtextÚverboseÚcolorÚcritique)Úinput_promptÚoutput_from_modelÚcritique_requestr9   ©Úoutput_stringzno critique neededÚ Úrevision)rA   rB   rC   r@   Úrevision_requestr9   z	Applying z...Úgreenz
Critique: ÚbluezUpdated response: r2   r4   r3   r*   )r   Úget_noop_managerr   ÚrunÚ	get_childr)   ÚformatÚon_textr>   r   r   rC   Ú_parse_critiqueÚstripÚlowerÚappendr   rH   r!   r   )r0   r6   r7   Ú_run_managerÚresponseÚinitial_responserA   r3   Úconstitutional_principleÚraw_critiquer@   rG   Úfinal_outputs                r"   Ú_callzConstitutionalChain._callî   sc  € ð
 #ÒSÔ&@×&QÑ&QÓ&SˆØ!�4—:‘:—>‘>ñ 
Øñ
à"×,Ñ,¨ZÓ8ò
ˆð $ÐØ/�t—z‘z×(Ñ(×/Ñ/Ñ9°&Ñ9ˆà×ÑØ%¨Ñ0°6Ñ9Ø—L‘LØð 	ô 	
ð
 #%ÐØ(,×(FÕ(FÐ$ð  ×.Ñ.×2Ñ2Ø)Ø"*Ø!9×!JÑ!JØ&×0Ñ0°Ó<ð	 3ó ˆLð ×+Ñ+Ø*ð ,ó ç‰e‹gð ð $ x§~¡~Ó'7Ñ7Ø'×.Ñ.°¸"¨~Ô>Øð ×*Ñ*×.Ñ.Ø)Ø"*Ø!9×!JÑ!JØ!Ø!9×!JÑ!JØ&×0Ñ0°Ó<ð /ó ÷ ‰e‹gð ð  ˆHØ#×*Ñ*¨H°hÐ+?Ô@à× Ñ Ø Ð!9×!>Ñ!>Ð ?¸sÐCÀfÑLØŸ™Øð !ô ð × Ñ Ø! HÑ,¨vÑ5ØŸ™Øð !ô ð × Ñ Ø)¨HÑ4°vÑ=ØŸ™Øð !ö ð[ )Gðf )1°(Ð';ˆØ×)Ò)Ø-=ˆLÐ)Ñ*Ø6MˆLÐ2Ñ3ØÐr,   rE   c                 ój   — d| vr| S | j                  d«      d   } d| v r| j                  d«      d   } | S )NzRevision request:r   r;   )ÚsplitrD   s    r"   rP   z#ConstitutionalChain._parse_critique:  sI   € à mÑ3Ø Ð Ø%×+Ñ+Ð,?Ó@ÀÑCˆØ�]Ñ"Ø)×/Ñ/°Ó7¸Ñ:ˆMØÐr,   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r
   r   ÚboolÚclassmethodr   Ústrr#   r   r   r   r   r   r+   Úpropertyr.   r5   Údictr   rZ   ÚstaticmethodrP   r*   r,   r"   r   r      sc  … ñcðJ ƒOØ#Ð$;Ñ<Ó<ØÓØÓØ&+Ð˜tÓ+àð &*ñ4à˜˜S™	Ñ"ð4ð 
Ð%Ñ	&ò4ó ð4ð ð
 />Ø.=ñ
àð
ð ð
ð ,ð	
ð
 ,ð
ð ð
ð 
ò
ó ð
ð$ ð%˜D ™Iò %ó ð%ð ð˜T #™Yò ó ðð =AñJà�S˜#�X‘ðJð Ð8Ñ9ðJð 
ˆc�3ˆh‰ó	JðX ð sð ¨sò ó ñr,   r   N)r`   Útypingr   r   Úlangchain_core._apir   Úlangchain_core.callbacksr   Úlangchain_core.language_modelsr   Úlangchain_core.promptsr   Úlangchain.chains.baser	   Ú)langchain.chains.constitutional_ai.modelsr
   Ú-langchain.chains.constitutional_ai.principlesr   Ú*langchain.chains.constitutional_ai.promptsr   r   Úlangchain.chains.llmr   r   r*   r,   r"   Ú<module>rr      sW   ðÙ Sç  å *Ý ?Ý <Ý 5å 'Ý MÝ Dß WÝ )ñ Ø
ð	}ð ôôg˜%ó góñgr,   