最近在帮团队搭建自动化邮件系统时,发现LangGraph这个工具对新手特别友好。它用节点(Nodes)和边(Edges)这种直观的图形化思维来组织工作流,比传统代码更符合人类思考逻辑。今天我就用最接地气的方式,带大家从零实现一个能自动分析需求、生成专业邮件的智能Bot。
这个教程会先拆解LangGraph最核心的Nodes和Edges概念,然后手把手带大家搭建完整流程。最终实现的Bot能做到:根据用户输入的关键词自动判断邮件类型(如询价、投诉、合作邀约),匹配对应的模板,生成结构清晰、语气得体的邮件草稿。整个过程不需要任何AI算法基础,会用if-else语句就能上手。
想象Nodes就像工厂的各个工作站。在我们的邮件Bot里,每个Node负责一个具体任务:
python复制# 示例:一个简单的模板选择Node
def template_selector(state):
if state["intent"] == "complaint":
return {"template": "complaint_template.md"}
elif state["intent"] == "inquiry":
return {"template": "inquiry_template.md"}
else:
return {"template": "general_template.md"}
Edges决定了工作流的走向,常见的有三种类型:
实战经验:设计Edges时建议先画流程图。我习惯先用白板画出所有可能的路径,再转化成代码逻辑,这样能避免遗漏分支情况。
需要安装:
bash复制pip install langgraph
建议目录结构:
code复制/mail_bot
│── templates/
│ ├── complaint_template.md
│ ├── inquiry_template.md
│── nodes.py # 存放所有Node函数
│── workflow.py # 主流程文件
以内容填充Node为例,需要处理三个特殊场景:
python复制def content_filler(state):
template = open(f"templates/{state['template']}").read()
# 变量替换安全处理
for key in ["product", "issue"]:
if key not in state:
state[key] = f"[{key}待补充]"
# 敏感词检测(实际项目建议用专业库)
if "垃圾" in state.get("issue", ""):
state["needs_review"] = True
return {"draft": template.format(**state)}
通过LangGraph的Graph对象串联Nodes:
python复制from langgraph.graph import Graph
workflow = Graph()
workflow.add_node("input_parser", input_parser)
workflow.add_node("intent_detector", intent_detector)
workflow.add_node("template_selector", template_selector)
# 设置跳转条件
workflow.add_conditional_edges(
"intent_detector",
lambda x: "complaint" if x["intent"] == "complaint" else "continue",
{"complaint": "urgent_process", "continue": "template_selector"}
)
parser_product vs template_product)python复制# 缓存实现示例
template_cache = {}
def cached_template_selector(state):
if state["intent"] in template_cache:
return template_cache[state["intent"]]
# ...正常选择逻辑...
template_cache[state["intent"]] = result
return result
测试输入:
json复制{
"text": "你们的新款耳机续航根本达不到宣传的8小时,才用3天就充不进电了!"
}
输出结果:
code复制主题:关于XX耳机质量问题的投诉
尊敬的客服主管:
您好!我是贵公司新款耳机的用户。非常遗憾地向您反馈...
扩展方向:
这个项目最让我惊喜的是,用LangGraph之后调试效率提升了至少3倍。因为每个Node可以独立测试,通过可视化工具能清晰看到数据流动轨迹。建议大家在复杂业务场景中优先考虑这种图形化编程范式