目录1 结构化输出 OutputParser1.1 普通 JsonOutputParser提示约束1.2 原生结构化输出厂商接口能力1.3 其他解析器2 ChatPromptTemplate 提示词模板3 LCEL 链式表达式核心 Runnable3.1 Runnable 统一接口3.2 RunnableSequence 串行流水线最常用3.3 RunnableParallel 并行执行3.4 其他常用 Runnable4 本章小结1 结构化输出 OutputParser1.1 普通 JsonOutputParser提示约束流程 1 用 Pydantic 定义输出结构 2 解析器生成格式要求注入 System 提示 3 LLM 输出后自动转为 Python 对象frompydanticimportBaseModel,Fieldfromlangchain_openaiimportChatOpenAIfromlangchain_core.output_parsersimportJsonOutputParserclassPrimeModel(BaseModel):prime:list[int]Field(description1000-10000素数列表)count:intField(description素数个数)parserJsonOutputParser(pydantic_objectPrimeModel)llmChatOpenAI(temperature0)promptparser.get_format_instructions()resllm.invoke([(system,prompt),(user,生成5个1000~10000素数)])dataparser.invoke(res)print(type(data))1.2 原生结构化输出厂商接口能力OpenAI/Gemini 支持with_structured_output无需手写约束提示classEvent(BaseModel):name:strdate:strpeople:list[str]llmChatOpenAI(temperature0)new_llmllm.with_structured_output(Event)resnew_llm.invoke(Alice周五参加科技展)print(res.name)1.3 其他解析器内置解析器列表、XML、Markdown、纯文本 StrOutputParser2 ChatPromptTemplate 提示词模板支持变量占位动态拼接对话上下文fromlangchain_core.promptsimportChatPromptTemplate promptChatPromptTemplate.from_messages([(system,你是{product}专业评测师),(human,分析{aspect1}和{aspect2}优缺点)])msgprompt.invoke({product:iPhone16,aspect1:性能,aspect2:续航})3 LCEL 链式表达式核心 Runnable3.1 Runnable 统一接口所有组件提示 / 模型 / 解析器都拥有invoke/stream/batch/ainvoke支持管道|拼接3.2 RunnableSequence 串行流水线最常用提示模板 → LLM → 输出解析promptChatPromptTemplate.from_template(讲{topic}段子)llminit_chat_model(modelgpt-4o-mini,model_provideropenai)parserStrOutputParser()# LCEL管道chainprompt|llm|parser reschain.invoke({topic:大模型})print(res)3.3 RunnableParallel 并行执行同时运行多条链路合并结果trans_enPromptTemplate.from_template(翻译{text}为英文)|llm|StrOutputParser()trans_krPromptTemplate.from_template(翻译{text}为韩文)|llm|StrOutputParser()# 并行字典写法map_chain{en:trans_en,kr:trans_kr}resmap_chain.invoke({text:人工智能技术})print(res)3.4 其他常用 Runnable1 RunnableLambda普通函数包装进流水线 2 RunnableBranchif 分支路由 3 RunnablePassthrough透传原始输入 4 RunnableWithFallbacks异常降级兜底4 本章小结1 OutputParser 实现结构化 JSON 输出分提示约束、原生两种方案 2 ChatPromptTemplate 实现动态变量提示词 3 LCEL 管道|快速组装业务流程串行 / 并行是开发主流