蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行值班简报工作流和批准记录

PYTHONCPython 3.12,langchain-core 1.7.6、LangGraph 1.2.20、Tenacity 9.2.1 与 CrewAI 1.15.39。chain_review.py
chain_review.py87 行
"""Exercise a real Runnable sequence and a LangGraph review gate without model calls."""
import operator
from importlib.metadata import version
from typing import TypedDict

from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langgraph.graph import END, START, StateGraph

from lab_tools import run_exercise


def compose_chain():
    normalize = RunnableLambda(lambda fields: " ".join(fields["article"].split()))
    summarize = RunnableLambda(lambda text: text.split("。",1)[0])
    title = RunnableLambda(lambda fields: "值班简报 · " + fields["summary"])
    return ({"text": normalize}
        | RunnablePassthrough.assign(summary=RunnableLambda(operator.itemgetter("text")) | summarize)
        | RunnablePassthrough.assign(title=title))


class Review(TypedDict,total=False):
    outcomes: list[str]
    passes: int
    draft: str
    verdict: str
    status: str


def compile_review():
    def write(state):
        count=state.get("passes",0)+1
        return {"draft":f"draft-{count}","passes":count}

    def review(state):
        number=state["passes"]-1
        return {"verdict":state["outcomes"][number] if number<len(state["outcomes"]) else "missing"}

    def route(state):
        if state["verdict"]=="approved":
            return "accept"
        if state["verdict"]=="revise" and state["passes"]<3:
            return "write"
        return "manual"

    graph=StateGraph(Review)
    graph.add_node("write",write)
    graph.add_node("review",review)
    graph.add_node("accept",lambda _:{"status":"approved"})
    graph.add_node("manual",lambda _:{"status":"manual_review"})
    graph.add_edge(START,"write")
    graph.add_edge("write","review")
    graph.add_conditional_edges("review",route,["write","accept","manual"])
    graph.add_edge("accept",END)
    graph.add_edge("manual",END)
    return graph.compile()


def exercise(checks,_):
    chain=compose_chain()
    raw={"article":" 码头开放。   无故障 "}
    checks.expect("workflow_chain_shape",raw,"Invoke real Runnable branches and preserve intermediate values",
        {"text":"码头开放。 无故障","summary":"码头开放","title":"值班简报 · 码头开放"},chain.invoke(raw))
    try:
        chain.invoke({})
    except KeyError as error:
        checks.expect("workflow_chain_missing",{},"Check missing input before deriving output",
            ("article",),error.args)
    else:
        raise AssertionError("missing input accepted")

    app=compile_review()
    for key,verdicts,expected in (
        ("workflow_graph_approved",["approved"],["approved",1,"draft-1"]),
        ("workflow_graph_revised",["revise","approved"],["approved",2,"draft-2"]),
        ("workflow_graph_negated",["NOT APPROVED"],["manual_review",1,"draft-1"]),
        ("workflow_graph_budget",["revise","revise","revise","approved"],["manual_review",3,"draft-3"]),
    ):
        actual=app.invoke({"outcomes":verdicts})
        checks.expect(key,verdicts,"Route using exact status and a three-draft limit",
            expected,[actual[k] for k in ("status","passes","draft")])
    checks.expect("workflow_packages","local metadata","Report actual installed packages",
        ["1.7.6","1.2.20"],[version("langchain-core"),version("langgraph")])


if __name__=="__main__":
    run_exercise(exercise)
本例需在 CPython 3.12,langchain-core 1.7.6、LangGraph 1.2.20、Tenacity 9.2.1 与 CrewAI 1.15.39。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12,langchain-core 1.7.6、LangGraph 1.2.20、Tenacity 9.2.1 与 CrewAI 1.15.39。

入口文件:projects/ai-agent-workflow/chain_review.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 chain_review.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12,langchain-core 1.7.6、LangGraph 1.2.20、Tenacity 9.2.1 与 CrewAI 1.15.39。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3113.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习