· 接待 点赞 + 温雅 ?,执续学习【RMIAD-114】変身 ひなの,执续干货输出。
公众号内著作一览图片【RMIAD-114】変身 ひなの
书接上文(【AI Agent】【LangGraph】0. 快速上手:协同LangChain,LangGraph帮你用图结构即兴构建多智能体),前边咱们了解了 LangGraph 的观念和基本构造要津,今天咱们来看下 LangGraph 构造中的进阶用法:给边加个要求 - 要求分支(Conditional edges)。
LangGraph 构造的是个图的数据结构,有节点(node) 和边(edge),那它的边也不错是带要求的。如何给边加入要求呢?不错通过 add_conditional_edges 函数添加带要求的边。
1. 完好代码及起初妄言未几说,先上完好代码,和起初戒指。先跑起来望望遵守再说。
from langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage, BaseMessagefrom langgraph.graph import END, MessageGraphimport jsonfrom langchain_core.messages import ToolMessagefrom langchain_core.tools import toolfrom langchain_core.utils.function_calling import convert_to_openai_toolfrom typing import List@tooldef multiply(first_number: int, second_number: int): """Multiplies two numbers together.""" return first_number * second_numbermodel = ChatOpenAI(temperature=0)model_with_tools = model.bind(tools=[convert_to_openai_tool(multiply)])graph = MessageGraph()def invoke_model(state: List[BaseMessage]): return model_with_tools.invoke(state)graph.add_node("oracle", invoke_model)def invoke_tool(state: List[BaseMessage]): tool_calls = state[-1].additional_kwargs.get("tool_calls", []) multiply_call = None for tool_call in tool_calls: if tool_call.get("function").get("name") == "multiply": multiply_call = tool_call if multiply_call is None: raise Exception("No adder input found.") res = multiply.invoke( json.loads(multiply_call.get("function").get("arguments")) ) return ToolMessage( tool_call_id=multiply_call.get("id"), content=res )graph.add_node("multiply", invoke_tool)graph.add_edge("multiply", END)graph.set_entry_point("oracle")def router(state: List[BaseMessage]): tool_calls = state[-1].additional_kwargs.get("tool_calls", []) if len(tool_calls): return "multiply" else: return "end"graph.add_conditional_edges("oracle", router, { "multiply": "multiply", "end": END,})runnable = graph.compile()response = runnable.invoke(HumanMessage("What is 123 * 456?"))print(response)
起初戒指如下:
图片
2. 代码详解底下对上头的代码进行谛视解说。
2.1 add_conditional_edges领先【RMIAD-114】変身 ひなの,咱们知说念了不错通过 add_conditional_edges 来对边进行要求添加。这部分代码如下:
graph.add_conditional_edges("oracle", router, { "multiply": "multiply", "end": END,})
add_conditional_edges罗致三个参数:
· 第一个为这条边的第一个node的称号
· 第二个为这条边的要求
jiuse· 第三个为要求复返戒指的映射(把柄要求戒指映射到相应的node)
如上头的代码,情理等于往 “oracle” node上添加边,这个node有两条边,一条是往“multiply” node上走,一条是往“END”上走。若何决定往哪个所在去:要求是 router(背面解说),要是 router 复返的是“multiply”,则往“multiply”所在走,要是 router 复返的是 “end”,则走“END”。
来看下这个函数的源码:
def add_conditional_edges( self, start_key: str, condition: Callable[..., str], conditional_edge_mapping: Optional[Dict[str, str]] = None,) -> None: if self.compiled: logger.warning( "Adding an edge to a graph that has already been compiled. This will " "not be reflected in the compiled graph." ) if start_key not in self.nodes: raise ValueError(f"Need to add_node `{start_key}` first") if iscoroutinefunction(condition): raise ValueError("Condition cannot be a coroutine function") if conditional_edge_mapping and set( conditional_edge_mapping.values() ).difference([END]).difference(self.nodes): raise ValueError( f"Missing nodes which are in conditional edge mapping. Mapping " f"contains possible destinations: " f"{list(conditional_edge_mapping.values())}. Possible nodes are " f"{list(self.nodes.keys())}." ) self.branches[start_key].append(Branch(condition, conditional_edge_mapping))
要点是这一句:self.branches[start_key].append(Branch(condition, conditional_edge_mapping)),给现时node添加分支Branch。
2.2 要求 router要求代码如下:判断执行戒指中是否有 tool_calls 参数,要是有,则复返"multiply",莫得,则复返“end”。
def router(state: List[BaseMessage]): tool_calls = state[-1].additional_kwargs.get("tool_calls", []) if len(tool_calls): return "multiply" else: return "end"2.3 各node的界说
(1)肇端node:oracle
@tooldef multiply(first_number: int, second_number: int): """Multiplies two numbers together.""" return first_number * second_numbermodel = ChatOpenAI(temperature=0)model_with_tools = model.bind(tools=[convert_to_openai_tool(multiply)])graph = MessageGraph()def invoke_model(state: List[BaseMessage]): return model_with_tools.invoke(state)graph.add_node("oracle", invoke_model)
这个node是一个带有Tools 的 ChatOpenAI。在LangChain中使用Tools的注佛教程请看这篇著作:【AI大模子期骗成就】【LangChain系列】5. LangChain初学:智能体Agents模块的实战详解。轻便解说等于:这个node的执行戒指,将复返是否应该使用绑定的Tools。
(2)multiply
def invoke_tool(state: List[BaseMessage]): tool_calls = state[-1].additional_kwargs.get("tool_calls", []) multiply_call = None for tool_call in tool_calls: if tool_call.get("function").get("name") == "multiply": multiply_call = tool_call if multiply_call is None: raise Exception("No adder input found.") res = multiply.invoke( json.loads(multiply_call.get("function").get("arguments")) ) return ToolMessage( tool_call_id=multiply_call.get("id"), content=res )graph.add_node("multiply", invoke_tool)
这个node的作用等于执行Tools。
2.4 总体历程图片
要是合计本文对你有匡助,勤奋点个赞和温雅呗 ~~~
· 公共好,我是 同学小张,平日共享AI学问和实战案例
· 接待 点赞 + 温雅 ?,执续学习,执续干货输出。
公众号内著作一览图片
本站仅提供存储处事,统统本体均由用户发布,如发现存害或侵权本体,请点击举报。