《60天AI学习计划启动 | Day 21: LangChain 高级特性(LCEL + Structured Output》

Day 21:LangChain 高级特性(LCEL + Structured Output)

学习目标

  • 掌握 LangChain Expression Language(LCEL)基础用法
  • 会用 RunnableSequence / RunnableParallel 组合链路
  • 了解 结构化输出(Structured Output)+ zod 校验
  • 实战:把之前的 RAG / Chat 流程用 LCEL 重写一版

核心知识点

  • LCEL 核心思想

    • 一切都是 RunnablePromptTemplate、LLM、Parser、Retrievers 等
    • .pipe() / RunnableSequence.from() 串联;RunnableParallel 并行
    • 好处:声明式、可组合、易复用、易调试
  • 顺序链(RunnableSequence)

    • 典型链路:input → Prompt → LLM → Parser
    • 用法(伪代码):
      const chain = RunnableSequence.from([
        prompt,
        llm,
        outputParser
      ])
      const res = await chain.invoke({ question })
      
  • 并行链(RunnableParallel)

    • 同时跑多个子任务,比如:
      • 一个链做「总结」,一个链做「提取关键字」
    • 用法(伪代码):
      const parallel = RunnableParallel.from({
        summary: summaryChain,
        keywords: keywordChain
      })
      const res = await parallel.invoke({ text })
      
  • 结构化输出(Structured Output)

    • 使用 zod 定义 schema,确保 LLM 输出 JSON 符合类型
    • 适合:配置、提取字段、结构化分析结果
    • 用法(伪代码):
      const schema = z.object({
        title: z.string(),
        score: z.number().min(0).max(10)
      })
      const parser = StructuredOutputParser.fromZodSchema(schema)
      const chain = prompt.pipe(llm).pipe(parser)
      const res = await chain.invoke({ code })
      
  • LCEL + RAG 简写

    • 链路:question → retriever → context → prompt → llm → parser
    • 用一个 RunnableSequence 串起来,替代手写 try/await 流程

实战作业

  • 作业 1:用 LCEL 重写基础 Chat 链

    • 把原来 prompt + llm + 自己 parse 的逻辑改成:prompt.pipe(llm).pipe(parser)
    • 要求:保留原有功能,代码更短、更易读
  • 作业 2:实现一个「代码审查 + 打分」结构化输出链

    • zod 定义:
      const ReviewSchema = z.object({
        issues: z.array(z.string()),
        score: z.number().min(0).max(10),
        suggestion: z.string()
      })
      
    • 用 LCEL:prompt → llm → StructuredOutputParser,返回严格结构化对象
  • 作业 3:给 RAG 做一个 LCEL 版本

    • retriever.pipe(ragPrompt).pipe(llm).pipe(parser)
    • 对比:老版手写 await vs LCEL 写法,体会可组合性差异

思考/笔记要点(可写进博客)

  • 记录:传统 imperative 写法 vs LCEL 声明式写法代码对比
  • 总结:什么时候用 LCEL(复杂链路、多处复用)更合适
  • 反思:自己项目里哪些地方可以逐步替换成 LCEL
posted @ 2025-12-17 09:16  XiaoZhengTou  阅读(2)  评论(0)    收藏  举报