题意:在语言图(lang graph)中使用add_conditional_edges
函数未能正常工作
问题背景:
this is my code: 这是我的代码
import os
from dotenv import load_dotenv
load_
dotenv()
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langgraph.graph import Graph, MessagesState
from typing import Annotated, Any, Dict, Optional, List,Sequence, TypedDict
from langgraph.graph.message import add_messages
class AgentState(TypedDict):
# The `add_messages` function within the annotation defines
# *how* updates should be merged into the state.
messages: Annotated[list, add_messages]
def function1(state):
return {"messages": "Hi"}
def function2(state):
return {"messages": "Hello"}
def my_condition(state):
return "end"
workflow=StateGraph(AgentState)
workflow.add_node("agent", function1)
workflow.add_node("tool", function2)
workflow.add_edge('agent','tool')
workflow.set_entry_point("agent")
workflow.add_conditional_edges("agent", my_condition,{ "end": END})
app=workflow.compile()
print(app.invoke({"messages": "tell me about you"}))
In above code I want to END function at "function1" and get this result:
在上面的代码中,我希望在“function1”处结束函数并获得这个结果:
{'messages': [HumanMessage(content='tell me about you', id='70a7cb55-4cb2-4d0b-9623-79cb06bcabf3'), HumanMessage(content='Hi', id='d95bd56d-93b6-44b1-ae05-3449472d8463')]}
But I am getting this below result: 但是我得到了下面的结果:
{'messages': [HumanMessage(content='tell me about you', id='70a7cb55-4cb2-4d0b-9623-79cb06bcabf3'), HumanMessage(content='Hi', id='d95bd56d-93b6-44b1-ae05-3449472d8463'), HumanMessage(content='Hello', id='7ea9ab2a-635f-46eb-8f17-d9a6af79688e')]}
问题解决:
Edges tell lang graph where to look after a node. If it's "conditional edges," it will go to different next nodes in different conditions. If it's just a normal edge, it is a direct line from that node to the next node.
边(Edges)告诉语言图(lang graph)在遍历一个节点之后应该去哪里。如果是“条件边(conditional edges)”,则在不同的条件下它会前往不同的下一个节点。如果只是普通的边,那么它就是从那个节点到下一个节点的直接连线。
In your code, you are adding both conditional edges and a normal edge from the same "agent" node.
在你的代码中,你从同一个“agent”节点既添加了条件边也添加了普通边。
workflow.add_edge('agent','tool')
...
workflow.add_conditional_edges("agent", my_condition,{ "end": END})
You need to decide, after the "agent" function is called, which thing do you want to happen next? If you want to reach END, you could put the conditional edges from "tool" instead of "agent," which already has an edge, and all of the functions will be called.
你需要在调用“agent”函数之后决定接下来想要发生什么事情。如果你想要达到“END”,你可以从已经有一个边的“tool”节点而不是“agent”节点添加条件边,这样所有的函数都会被调用。