开启左侧

LangGraph(四)——加入人机交互控制

[复制链接]
AI小编 发表于 昨天 22:37 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
作者:CSDN博客
目录

    1. 引言2. 添加Human Assistance工具3. 编译状态图4. 提示聊天机器人5. 恢复执行参考

1. 引言

  智能体可能不可靠,甚至需要人工输入才能完成任务。同样,对于某些操作,你可能需要在运行前获得人工批准,以保证一切按预期运行。
  LangGraph的持久层支持人机交互工作流,允许根据用户反馈暂停和恢复执行。此功能的主要接口是interrupt函数。在节点内部调用Interrupt将暂停执行。可以通过传入command来interrupt执行,并接收新的人工输入。interrupt在人机工程学上类似于Python的内置input(),但也有一些注意事项。
2. 添加Human Assistance工具

  初始化聊天模型:
  1. from langchain.chat_models import init_chat_model
  2. llm = init_chat_model("deepseek:deepseek-chat")
复制代码
  使用附加工具将human assistance附加到状态图中:
  1. from typing import Annotated
  2. from langchain_tavily import TavilySearch
  3. from langchain_core.tools import tool
  4. from typing_extensions import TypedDict
  5. from langgraph.checkpoint.memory import MemorySaver
  6. from langgraph.graph import StateGraph, START, END
  7. from langgraph.graph.message import add_messages
  8. from langgraph.prebuilt import ToolNode, tools_condition
  9. from langgraph.types import Command, interrupt
  10. classState(TypedDict):
  11.     messages: Annotated[list, add_messages]
  12. graph_builder = StateGraph(State)@tooldefhuman_assistance(query:str)->str:"""Request assistance from a human."""
  13.     human_response = interrupt({"query": query})return human_response["data"]
  14. tool = TavilySearch(max_results=2)
  15. tools =[tool, human_assistance]
  16. llm_with_tools = llm.bind_tools(tools)defchatbot(state: State):
  17.     message = llm_with_tools.invoke(state["messages"])# Because we will be interrupting during tool execution,# we disable parallel tool calling to avoid repeating any# tool invocations when we resume.assertlen(message.tool_calls)<=1return{"messages":[message]}
  18. graph_builder.add_node("chatbot", chatbot)
  19. tool_node = ToolNode(tools=tools)
  20. graph_builder.add_node("tools", tool_node)
  21. graph_builder.add_conditional_edges("chatbot",
  22.     tools_condition,)
  23. graph_builder.add_edge("tools","chatbot")
  24. graph_builder.add_edge(START,"chatbot")
复制代码
3. 编译状态图

  使用检查点编译状态图:
  1. memory = MemorySaver()
  2. graph = graph_builder.compile(checkpointer=memory)
复制代码
4. 提示聊天机器人

  向聊天机器人提出一个问题,该问题将使用human assistance工具:
  1. user_input ="I need some expert guidance for building an AI agent. Could you request assistance for me?"
  2. config ={"configurable":{"thread_id":"1"}}
  3. events = graph.stream({"messages":[{"role":"user","content": user_input}]},
  4.     config,
  5.     stream_mode="values",)for event in events:if"messages"in event:
  6.         event["messages"][-1].pretty_print()
复制代码
  运行结果为:

LangGraph(四)——加入人机交互控制-1.jpg

  聊天机器人生成了一个工具调用,但随后执行被中断。如果你检查状态图,会发现它在工具节点处停止了:
  1. snapshot = graph.get_state(config)
  2. snapshot.next
复制代码
  运行结果为:
  1. ('tools',)
复制代码
5. 恢复执行

  要恢复执行需要传递一个包含工具所需数据的Command对象。此数据的格式可根据需要自定义。在本例中,使用一个带有键”data"字典:
  1. human_response =("We, the experts are here to help! We'd recommend you check out LangGraph to build your agent."" It's much more reliable and extensible than simple autonomous agents.")
  2. human_command = Command(resume={"data": human_response})
  3. events = graph.stream(human_command, config, stream_mode="values")for event in events:if"messages"in event:
  4.         event["messages"][-1].pretty_print()
复制代码
  运行结果为:
  1. ================================== Ai Message ==================================
  2. Tool Calls:
  3.   human_assistance (call_0_cee258cf-15db-49d4-8495-46761c7ddc65)
  4. Call ID: call_0_cee258cf-15db-49d4-8495-46761c7ddc65
  5.   Args:
  6.     query: I need expert guidance for building an AI agent.================================= Tool Message =================================
  7. Name: human_assistance
  8. We, the experts are here to help! We'd recommend you check out LangGraph to build your agent. It's much more reliable and extensible than simple autonomous agents.================================== Ai Message ==================================
  9. Great! It seems the experts recommend using **LangGraph**for building your AI agent,as it is more reliable and extensible compared to simple autonomous agents.
  10. If you'd like, I can provide more details about LangGraph or assist you with specific steps to get started. Let me know how you'd like to proceed!
复制代码
参考

https://langchain-ai.github.io/langgraph/tutorials/get-started/4-human-in-the-loop/

原文地址:https://blog.csdn.net/qq_51180928/article/details/148014677
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

发布主题
阅读排行更多+

Powered by Discuz! X3.4© 2001-2013 Discuz Team.( 京ICP备17022993号-3 )