LangChain LCEL 链式表达式实战:从入门到生产级应用
作者:Crown_22 | AI Agent & 自动化工作流开发者 | 技术分享
前言
如果你还在用 chain.run() 这种老式写法来调用 LangChain,那这篇文章就是为你准备的。
LangChain Expression Language(LCEL)是 LangChain 0.1.0 引入的声明式链式调用语法,它彻底改变了我们构建 AI 应用的方式。不是简单的语法糖,而是架构层面的升级——支持流式输出、批量处理、异步调用、并行执行,而且所有组件都可以无缝组合。
我在实际项目中踩过不少 LCEL 的坑,今天把经验分享出来,帮你少走弯路。

一、LCEL 是什么?为什么用它?
1.1 老式写法的问题
# ❌ 老式写法(已废弃)
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(input="你好")
问题:
- 不支持流式输出
- 不支持异步
- 链式组合困难
- 错误处理复杂
- 无法批量处理
1.2 LCEL 写法
# ✅ LCEL 写法
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
chain = prompt | llm | StrOutputParser()
result = chain.invoke({
"input": "你好"})
优势:
|管道语法,直观易读- 自动支持
.invoke()、.stream()、.batch()、.ainvoke() - 可以任意组合组件
- 内置重试和回退机制
1.3 核心概念:Runnable 接口
LCEL 中所有组件都实现了 Runnable 接口:
class Runnable:
def invoke(self, input, config=None) -> output
async def ainvoke(self, input, config=None) -> output
def stream(self, input, config=None) -> Iterator[output]
def batch(self, inputs, config=None) -> List[output]
def __or__(self, other) -> RunnableSequence # | 管道语法
这意味着你可以对任何组件使用相同的方法,不需要记忆不同的 API。
二、基础组件实战
2.1 PromptTemplate
from langchain_core.prompts import ChatPromptTemplate
# 简单模板
prompt = ChatPromptTemplate.from_template(
"你是一个{role},请用{style}的方式回答:{question}"
)
# 多消息模板
system_prompt = ChatPromptTemplate.from_messages([
("system", "你是一个资深的{domain}专家,回答要简洁准确。"),
("human", "{question}")
])
# 格式化测试
messages = prompt.format_messages(
role="Python专家",
style="简洁",
question="什么是装饰器?"
)
print(messages)
2.2 OutputParser
from langchain_core.output_parsers import (
StrOutputParser, # 字符串输出
JsonOutputParser, # JSON输出
PydanticOutputParser, # Pydantic模型输出
)
# 字符串解析器(最常用)
str_parser = StrOutputParser()
# JSON解析器
json_parser = JsonOutputParser()
# Pydantic解析器(结构化输出)
from pydantic import BaseModel, Field
class CodeReview(BaseModel):
issues: list[str] = Field(description="发现的问题列表")
suggestions: list[str] = Field(description="改进建议")
score: int = Field(description="代码质量评分 1-10")
pydantic_parser = PydanticOutputParser(pydantic_object=CodeReview)


795

被折叠的 条评论
为什么被折叠?



