Home / Class/ ConstitutionalChain Class — langchain Architecture

ConstitutionalChain Class — langchain Architecture

Architecture documentation for the ConstitutionalChain class in base.py from the langchain codebase.

Entity Profile

Dependency Diagram

graph TD
  3418945f_37b1_dea9_34e6_ecb594bbeb4a["ConstitutionalChain"]
  097a4781_5519_0b5d_6244_98c64eadc0d6["Chain"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|extends| 097a4781_5519_0b5d_6244_98c64eadc0d6
  25f7cd75_c8f9_676b_c260_99637213d86a["base.py"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|defined in| 25f7cd75_c8f9_676b_c260_99637213d86a
  ca609c0b_c11f_7a53_0198_ade2e1401f74["get_principles()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| ca609c0b_c11f_7a53_0198_ade2e1401f74
  36e7e237_494b_8342_f636_bbc431239626["from_llm()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| 36e7e237_494b_8342_f636_bbc431239626
  d4292b8b_6f9a_18d8_359b_64ad1f38df50["input_keys()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| d4292b8b_6f9a_18d8_359b_64ad1f38df50
  97dd142c_1d6e_d85b_7f93_58ef5c246b9d["output_keys()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| 97dd142c_1d6e_d85b_7f93_58ef5c246b9d
  05bcf462_011d_0acb_2eb6_16c2645f8874["_call()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| 05bcf462_011d_0acb_2eb6_16c2645f8874
  dc332d71_0421_20c9_3ac4_f96219ab2f1c["_parse_critique()"]
  3418945f_37b1_dea9_34e6_ecb594bbeb4a -->|method| dc332d71_0421_20c9_3ac4_f96219ab2f1c

Relationship Graph

Source Code

libs/langchain/langchain_classic/chains/constitutional_ai/base.py lines 29–332

class ConstitutionalChain(Chain):
    r'''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:

        ```bash
        pip install -U langgraph
        ```

        ```python
        from typing import List, Optional, Tuple

        from langchain_classic.chains.constitutional_ai.prompts import (
            CRITIQUE_PROMPT,
            REVISION_PROMPT,
        )
        from langchain_classic.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

        model = 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 = model | StrOutputParser()
        critique_chain = critique_prompt | model.with_structured_output(Critique)
        revision_chain = revision_prompt | model | 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 = []

Extends

Frequently Asked Questions

What is the ConstitutionalChain class?
ConstitutionalChain is a class in the langchain codebase, defined in libs/langchain/langchain_classic/chains/constitutional_ai/base.py.
Where is ConstitutionalChain defined?
ConstitutionalChain is defined in libs/langchain/langchain_classic/chains/constitutional_ai/base.py at line 29.
What does ConstitutionalChain extend?
ConstitutionalChain extends Chain.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free