这是我的代码:
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"}))
在上面的代码中,我想在“function1”处结束函数并得到这个结果:
{'messages': [HumanMessage(content='告诉我关于你的事', id='70a7cb55-4cb2-4d0b-9623-79cb06bcabf3'), HumanMessage(content='Hi', id='d95bd56d-93b6-44b1- ae05-3449472d8463')]}
但我得到以下结果:
{'messages': [HumanMessage(content='告诉我关于你的事', id='70a7cb55-4cb2-4d0b-9623-79cb06bcabf3'), HumanMessage(content='Hi', id='d95bd56d-93b6-44b1- ae05-3449472d8463'), HumanMessage(content='你好', id='7ea9ab2a-635f-46eb-8f17-d9a6af79688e')]}
边告诉 lang 图在哪里照顾节点。 如果它是“条件边”,它将在不同的条件下转到不同的下一个节点。 如果它只是一条普通边,那么它是从该节点到下一个节点的直线。
在您的代码中,您将添加来自同一“代理”节点的条件边和普通边。
workflow.add_edge('agent','tool')
...
workflow.add_conditional_edges("agent", my_condition,{ "end": END})
你需要决定,在调用“代理”函数之后,你接下来想要发生哪件事?