/images/hugo/avatar.png

LangChain chain

1. Chain

Chain 是 langchain 早期提供的链抽象。他正在被 LCEL 取代。但是 Chain 仍然是 langchain 中非常重要的一个组件。仍被广泛使用,所以我们也需要了解。Chain 的代码位于 langchain.chains 内。

1.1 BaseChain

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
    """Abstract base class for creating structured sequences of calls to components.

    Chains should be used to encode a sequence of calls to components like
    models, document retrievers, other chains, etc., and provide a simple interface
    to this sequence.

    The Chain interface makes it easy to create apps that are:
        - Stateful: add Memory to any Chain to give it state,
        - Observable: pass Callbacks to a Chain to execute additional functionality,
            like logging, outside the main sequence of component calls,
        - Composable: the Chain API is flexible enough that it is easy to combine
            Chains with other components, including other Chains.

    The main methods exposed by chains are:
        - `__call__`: Chains are callable. The `__call__` method is the primary way to
            execute a Chain. This takes inputs as a dictionary and returns a
            dictionary output.
        - `run`: A convenience method that takes inputs as args/kwargs and returns the
            output as a string or object. This method can only be used for a subset of
            chains and cannot return as rich of an output as `__call__`.
    """

    memory: Optional[BaseMemory] = None
    """Optional memory object. Defaults to None.
    Memory is a class that gets called at the start
    and at the end of every chain. At the start, memory loads variables and passes
    them along in the chain. At the end, it saves any returned variables.
    There are many different types of memory - please see memory docs
    for the full catalog."""
    callbacks: Callbacks = Field(default=None, exclude=True)
    """Optional list of callback handlers (or callback manager). Defaults to None.
    Callback handlers are called throughout the lifecycle of a call to a chain,
    starting with on_chain_start, ending with on_chain_end or on_chain_error.
    Each custom chain can optionally call additional callback methods, see Callback docs
    for full details."""
    verbose: bool = Field(default_factory=_get_verbosity)
    """Whether or not run in verbose mode. In verbose mode, some intermediate logs
    will be printed to the console. Defaults to the global `verbose` value,
    accessible via `langchain.globals.get_verbose()`."""
    tags: Optional[list[str]] = None
    """Optional list of tags associated with the chain. Defaults to None.
    These tags will be associated with each call to this chain,
    and passed as arguments to the handlers defined in `callbacks`.
    You can use these to eg identify a specific instance of a chain with its use case.
    """
    metadata: Optional[dict[str, Any]] = None
    """Optional metadata associated with the chain. Defaults to None.
    This metadata will be associated with each call to this chain,
    and passed as arguments to the handlers defined in `callbacks`.
    You can use these to eg identify a specific instance of a chain with its use case.
    """
    callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)
    """[DEPRECATED] Use `callbacks` instead."""

    model_config = ConfigDict(
        arbitrary_types_allowed=True,
    )
属性名 类型 默认值 说明
memory Optional[BaseMemory] None 链的记忆模块。用于在执行链时引入上下文记忆,自动在调用前加载变量、调用后保存变量。适用于多轮对话、Agent 状态持久化等。
callbacks Callbacks None 回调函数列表或回调管理器。贯穿链的生命周期(开始、结束、异常等),用于日志记录、追踪、调试、UI 更新等。
verbose bool langchain.globals.get_verbose() 控制是否开启“详细模式”。启用后会在控制台打印中间执行信息,便于调试。
tags Optional[list[str]] None 用于标记每一次链的调用,便于在日志或 trace 工具中识别用途或调用源(如 "qa_chain", "retriever_flow")。
metadata Optional[dict[str, Any]] None 附加元数据,用于跟踪链的调用上下文,可传给 callback。适合记录模型版本、实验标记等。
callback_manager Optional[BaseCallbackManager] None(已废弃) 已废弃的回调字段,请改用 callbacks。在旧版中用于管理回调函数。
model_config ConfigDict arbitrary_types_allowed=True Pydantic v2 配置,允许包含任意类型(如函数、类实例等),使链具备高度灵活性。

BaseChain 定义了如下抽象方法:

LangChain Language Model

这一节我们来看 Langchain 的 Language Model。

1. Language Model 的 UML 类图

/images/langchain/language_model.svg

Language Model 有如下基类:

  1. BaseLanguageModel
  2. BaseChatModel
  3. BaseLLM

Language Model 基类不多,让我们直接问大模型这些类的语义

1
2
3
4
5
6
我正在阅读  Language Model 子包的源代码,注意到包内,有如下类:
1. BaseLanguageModel
2. BaseChatModel
3. BaseLLM

请给我从语义上解释一下这些类的的作用

在 LangChain 中,language_models 子包是核心模块之一,负责抽象和实现对底层语言模型(如 OpenAI、Anthropic、Cohere 等)的调用逻辑。你提到的两个类:

LangChain Tools

1. Function Call

提问: 能不能想写给我介绍一下 OpenAI Function Calling

回答: 当然可以,下面我会从 初衷、语法结构、工作机制、代码示例、进阶用法和与 LangChain 结合方式 六个方面,全面介绍 OpenAI Function Calling 的机制。

LangChain Output Parser

1. OutPut Parser 的 UML 类图

/images/langchain/output_parser.svg

如图,OutPut Parser 有如下抽象基类:

  1. BaseLLMOutputParser
  2. BaseGenerationOutputParser
  3. BaseOutputParser
  4. BaseTransformOutputParser
  5. BaseCumulativeTransformOutputParser

1.1 提问

让我们问问大模型这三个基类代表的语义。

1
2
3
4
5
6
7
8
我正在阅读  langchain output parser 子包的源代码,注意到包内,有三个 base 的抽象类:
2. BaseGenerationOutputParser
3. BaseOutputParser
4. BaseTransformOutputParser
5. BaseCumulativeTransformOutputParser
请给我从语义上解释一下这些类的的作用

说明,最开始我是把 1. BaseLLMOutputParser 也作为内容之一提给了 ChatGPT 但是我觉得回答不太好所以删了

1.2 回答

langchain.output_parsers 子包中定义的这些 Base 抽象类(BaseOutputParserBaseGenerationOutputParserBaseTransformOutputParserBaseCumulativeTransformOutputParser)是 LangChain 中构建输出解析器(output parsers)的基础组件,用于将 LLM 的原始输出(字符串或结构化数据)解析为用户需要的特定结构或对象。