1. Runnable与LCEL联动机制解析
在LangChain生态中,Runnable作为基础执行单元与LCEL(LangChain Expression Language)的协同工作构成了框架的核心运作机制。这种设计模式类似于Unix系统中的管道(pipe)概念——每个Runnable相当于一个独立处理器,通过LCEL的声明式语法将这些处理器连接成完整的工作流。
1.1 Runnable的核心特性
Runnable接口定义了四种标准操作模式,这也是它能与LCEL无缝集成的基础:
python复制class Runnable(Generic[Input, Output]):
def invoke(self, input: Input) -> Output: ... # 同步调用
async def ainvoke(self, input: Input) -> Output: ... # 异步调用
def batch(self, inputs: List[Input]) -> List[Output]: ... # 批量处理
def stream(self, input: Input) -> Iterator[Output]: ... # 流式输出
实际开发中最常用的组合方式是通过LCEL的管道操作符(|)连接不同Runnable:
python复制chain = prompt | model | output_parser # 典型的LCEL表达式
这里的每个组件(prompt、model、output_parser)都是实现了Runnable接口的对象,管道符会自动将它们组合成新的RunnableSequence实例。
1.2 LCEL的编译时优化
当LCEL表达式被编译时,会进行以下关键优化:
- 操作融合:检测相邻的可合并操作(如连续的map操作)
- 并行化分析:识别可以并行执行的独立分支
- 流式传播:确定哪些节点支持流式输出
- 错误处理:自动插入fallback机制
通过chain.get_graph().print_ascii()可以查看优化后的执行计划:
code复制 [input]
|
[prompt]
|
[model]
|
[output_parser]
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 实战:构建生产级LCEL链
2.1 基础链构造
一个完整的LCEL链通常包含以下组件:
python复制from langchain_core.runnables i
