欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > AI Agent设计模式一:Chain

AI Agent设计模式一:Chain

2025/4/23 9:28:23 来源:https://blog.csdn.net/qq_33247435/article/details/147003503  浏览:    关键词:AI Agent设计模式一:Chain

概念 :线性任务流设计

  • ✅ 优点:逻辑清晰易调试,适合线性处理流程
  • ❌ 缺点:缺乏动态分支能力

在这里插入图片描述

from typing import TypedDictfrom langgraph.graph import StateGraph, END# 定义后续用到的一些变量
class CustomState(TypedDict):planet1: str # 星球1的名称planet2: str # 星球2的名称mass1: float # 星球1的质量mass2: float # 星球2的质量total_mass: float # 总质量# 定义函数,后续作为节点
def add_numbers(state: CustomState):"""计算两数之和参数:state (State): 包含两个数字的字典返回:None"""state["total_mass"] = state["mass1"] + state["mass2"]return statedef get_planet_mass(state: CustomState):"""查询星球质量(单位:千克)参数:state (State): 包含星球名称的字典返回:None"""PLANET_MASSES = {'Mercury': 3.301e23,'Venus': 4.867e24,'Earth': 5.972e24,'Mars': 6.417e23,'Jupiter': 1.899e27,'Saturn': 5.685e26,'Uranus': 8.682e25,'Neptune': 1.024e26,'Sun': 1.989e30}state["mass1"] = PLANET_MASSES.get(state["planet1"], 0)state["mass2"] = PLANET_MASSES.get(state["planet2"], 0)return state#定义图
workflow = StateGraph(CustomState)
# 定义节点
workflow.add_node("get_planet_mass", get_planet_mass)
workflow.add_node("add_numbers", add_numbers)# 定义边
workflow.set_entry_point("get_planet_mass")
workflow.add_edge("get_planet_mass", "add_numbers")
workflow.add_edge("add_numbers", END)# 编译
graph = workflow.compile()# 测试
custom_state = CustomState(planet1="Earth",planet2="Mars",mass1=0.0,mass2=0.0,total_mass=0.0
)
result = graph.invoke(custom_state)
print(result)

执行结果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词