/images/hugo/avatar.png

LangChain Output

1. Outputs 和 Output Parser

看代码会发现 langchain-core 有两个 outputs 和 output_parsers 两个包。

提问: langchain 源码包内 outputs 和 output_parsers 两个package,请从语义上解释下这两个包的作用 回答: 这两个包名称相近但语义和作用不同,在 LangChain 中分别承担着 “结构化输出” 的不同阶段。我们来逐一从语义、功能定位、关系与区别几个方面进行解释:

LangChain Message

1. Message 的 UML 类图

/images/langchain/messages-all.svg

从 UML 类图可以看出,Message 类是一个抽象类,它有三个子类:

  1. BaseMessage
  2. BaseMessageChunk
  3. BaseDataContentBlock

1.1 提问

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

LangChain Prompts

1. Prompts 的 UML 类图

/images/langchain/prompts-all.svg

从 UML 类图可以看出,Prompts 有如下 Base 抽象类:

  1. BasePromptTemplate
  2. BaseChatPromptTemplate
  3. BaseMessagePrompts

1.1 提问

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

1
2
3
4
5
我正在阅读  langchain Prompts 子包的源代码,注意到 Prompts 包内有如下 base 的抽象类:
1. BasePromptTemplate
2. BaseChatPromptTemplate
3. BaseMessagePrompts
请给我从语义上解释一下这三个类的的作用

1.2 回答

你提到的这三个类是 langchain.prompts 子包中的核心抽象类,它们分别定义了不同层级的提示(Prompt)结构,主要作用是 组织和渲染最终要发送给语言模型的 Prompt 数据结构,语义上可以这样理解:

LangChain Context 和 RunnableConfig

上一篇我们讲到了 RunnableSequence invoke 方法。这个方法里调用的 config_with_context 方法比较难理解。所以在讲解 invoke 方法之前,我们先来了解一下 langchain 中的 Context 和 RunnableConfig。

1. RunnableConfig

RunnableConfig 的定义很简单:

 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
class RunnableConfig(TypedDict, total=False):
    """Configuration for a Runnable."""

    tags: list[str]
    """
    Tags for this call and any sub-calls (eg. a Chain calling an LLM).
    You can use these to filter calls.
    """

    metadata: dict[str, Any]
    """
    Metadata for this call and any sub-calls (eg. a Chain calling an LLM).
    Keys should be strings, values should be JSON-serializable.
    """

    callbacks: Callbacks
    """
    Callbacks for this call and any sub-calls (eg. a Chain calling an LLM).
    Tags are passed to all callbacks, metadata is passed to handle*Start callbacks.
    """

    run_name: str
    """
    Name for the tracer run for this call. Defaults to the name of the class.
    """

    max_concurrency: Optional[int]
    """
    Maximum number of parallel calls to make. If not provided, defaults to
    ThreadPoolExecutor's default.
    """

    recursion_limit: int
    """
    Maximum number of times a call can recurse. If not provided, defaults to 25.
    """

    configurable: dict[str, Any]
    """
    Runtime values for attributes previously made configurable on this Runnable,
    or sub-Runnables, through .configurable_fields() or .configurable_alternatives().
    Check .output_schema() for a description of the attributes that have been made
    configurable.
    """

    run_id: Optional[uuid.UUID]
    """
    Unique identifier for the tracer run for this call. If not provided, a new UUID
        will be generated.
    """

这里面大多数是元数据和控制参数,其中最重要的是 configurable 属性。通过注释可以看到,configurable 与 Runnable 的 configurable_fields、configurable_alternatives 方法有关。