开启左侧

六、、使用LangGraph自定义State

[复制链接]
米落枫 发表于 昨天 22:39 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
作者:CSDN博客
        State中除了消息列表(messages: Annotated[list, add_messages]),也可以加入其它字段,如下,加入name和birthday字段:
  1. class State(TypedDict):
  2.     messages: Annotated[list, add_messages]
  3.     name: str
  4.     birthday: str
复制代码
使用human_assistance 工具更新state
  1. from langchain_core.messages import ToolMessage
  2. from langchain_core.tools import InjectedToolCallId, tool
  3. from langgraph.types import Command, interrupt
  4. @tool
  5. def human_assistance(
  6.     name: str, birthday: str, tool_call_id: Annotated[str, InjectedToolCallId]
  7. ) -> str:
  8.     """Request assistance from a human."""
  9.     human_response = interrupt(
  10.         {
  11.             "question": "Is this correct?",
  12.             "name": name,
  13.             "birthday": birthday,
  14.         },
  15.     )
  16.     # If the information is correct, update the state as-is.
  17.     if human_response.get("correct", "").lower().startswith("y"):
  18.         verified_name = name
  19.         verified_birthday = birthday
  20.         response = "Correct"
  21.     # Otherwise, receive information from the human reviewer.
  22.     else:
  23.         verified_name = human_response.get("name", name)
  24.         verified_birthday = human_response.get("birthday", birthday)
  25.         response = f"Made a correction: {human_response}"
  26.     # This time we explicitly update the state with a ToolMessage inside
  27.     # the tool.
  28.     state_update = {
  29.         "name": verified_name,
  30.         "birthday": verified_birthday,
  31.         "messages": [ToolMessage(response, tool_call_id=tool_call_id)],
  32.     }
  33.     # We return a Command object in the tool to update our state.
  34.     return Command(update=state_update)
复制代码
完整代码:
  1. import os
  2. from typing import Annotated
  3. from typing_extensions import
复制代码
原文地址:https://blog.csdn.net/Mrhiuser/article/details/151395406
回复

使用道具 举报

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

本版积分规则

发布主题
阅读排行更多+

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