AI创想

标题: LangGraph 调用工具过程详解 [打印本页]

作者: AI小编    时间: 昨天 23:18
标题: LangGraph 调用工具过程详解
作者:CSDN博客
一、Agent调用tool

定义tool函数,其中注释 “add two int number”,必须要有否则会报错;
  1. @tool
  2. def  add(a:int, b:int) -> int:
  3.     """add two int number""" # 这个必须有,而且很重要,是要输入到LLM;
  4.     return a + b
复制代码
完整代码:
  1. from langchain_openai import ChatOpenAI
  2. from langgraph.checkpoint.memory import InMemorySaver
  3. from langgraph.graph import StateGraph, START, END
  4. from langgraph.graph.message import add_messages
  5. from langgraph.prebuilt import ToolNode, tools_condition
  6. from langgraph.types import Command, interrupt
  7. llm = ChatOpenAI(
  8.     model="Qwen3-4B-Instruct-2507",  
  9.     openai_api_base="http:/localhost:8000/v1",  # vLLM 服务的地址
  10.     openai_api_key="EMPTY",  # vLLM 通常不需要 API key,但 LangChain 要求设置,可设为任意值如 "EMPTY"
  11.     temperature=0.7,
  12.     max_tokens=1024
  13. )
  14. class State(TypedDict):
  15.     messages: Annotated[list, add_messages]
  16. graph_builder = StateGraph(State)
  17. @tool
  18. def  add(a:int, b:int) -> int:
  19.     """add two int number"""
  20.     return a + b
  21. tools = [add]
  22. llm_with_tools = llm.bind_tools(tools)
  23. def chatbot(state: State):
  24.     message = llm_with_tools.invoke(state["messages"])
  25.     assert(len(message.tool_calls) <= 1)
  26.     return {"messages": [message]}
  27. graph_builder.add_node("chatbot", chatbot)
  28. tool_node = ToolNode(tools=tools)
  29. graph_builder.add_node("tools", tool_node)
  30. graph_builder.add_conditional_edges(
  31.     "chatbot",
  32.     tools_condition,
  33. )
  34. graph_builder.add_edge("tools", "chatbot")
  35. graph_builder.add_edge(START, "chatbot")
  36. graph = graph_builder.compile()
  37. def print_stream(stream):
  38.     for s in stream:
  39.         message = s["messages"][-1]
  40.         if isinstance(message, tuple):
  41.             print(message)
  42.         else:
  43.             message.pretty_print()
  44. while True:
  45.     try:
  46.         user_input = input("User: ")
  47.         if user_input.lower() in ["quit", "exit", "q"]:
  48.             print("Goodbye!")
  49.             break
  50.         print_stream(graph.stream({"messages": [{"role": "user", "content": user_input}]}, stream_mode="values"))
  51.     except:
  52.         user_input = "What do you know about LangGraph?"
  53.         print("User: " + user_input)
  54.         print_stream(graph.stream({"messages": [{"role": "user", "content": user_input}]}, stream_mode="values"))
  55.         break
复制代码
(, 下载次数: 0)


执行的过程:
1、user输入 “1+1”,调用LLM
2、LLM返回调用工具说明 “Tool Calls”,
3、调用工具生成结果 “2”;
4、将结果输入到LLM;
5、LLM 返回最终的结果 “The result of 1 + 1 is 2.”
输出如下:
  1. User: 1+1
  2. ================================ Human Message =================================
  3. 1+1
  4. ================================== Ai Message ==================================
  5. Tool Calls:
  6.   add (chatcmpl-tool-2b1940050a9548d68a299f1a2ee88ede)
  7. Call ID: chatcmpl-tool-2b1940050a9548d68a299f1a2ee88ede
  8.   Args:
  9.     a: 1
  10.     b: 1
  11. ================================= Tool Message =================================
  12. Name: add
  13. 2
  14. ================================== Ai Message ==================================
  15. The result of 1 + 1 is 2.
复制代码
二、LLM服务

从LLM服务的后台日志,查看Agent调用tool的流程;
1、第一次调用LLM

当客户端输入 “1+1”时,LLM服务端接受的输入,如下:
  1. prompt: '<|im_start|>system\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n
  2. <tools>\n{
  3.         "type": "function",
  4.         "function": {
  5.                 "name": "add",
  6.                 "description": "add two int number",
  7.                 "parameters": {
  8.                         "properties": {
  9.                                 "a": {
  10.                                         "type": "integer"
  11.                                 },
  12.                                 "b": {
  13.                                         "type": "integer"
  14.                                 }
  15.                         },
  16.                         "required": ["a", "b"],
  17.                         "type": "object"
  18.                 }
  19.         }
  20. }\n</tools>
  21. \n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n
  22. <tool_call>\n{
  23.         "name": < function -name > ,
  24.         "arguments": < args - json - object >
  25. }\n</tool_call><|im_end|>\n
  26. <|im_start|>user\n1+1<|im_end|>\n<|im_start|>assistant\n',
复制代码
上述输入包含了:
系统提示词 :“system\n# Tools\n\nYou may ...”
函数定义的说明 <tools>...</tools>
函数调用返回的格式<tool_call>...</tool_call>
用户的输入 “1+1”
2、LLM的Response:

LLM的输出见下图:
content字段是None;
tool_calls 字段说明的调用的tool函数的名称、参数等;
(, 下载次数: 0)


3、第二次调用LLM

前端根据上述大模型的结果,调用tool后生成结果“2”,再次调用LLM,输入
  1. prompt: '<|im_start|>system\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>\n
  2. {
  3.         "type": "function",
  4.         "function": {
  5.                 "name": "add",
  6.                 "description": "add two int number",
  7.                 "parameters": {
  8.                         "properties": {
  9.                                 "a": {
  10.                                         "type": "integer"
  11.                                 },
  12.                                 "b": {
  13.                                         "type": "integer"
  14.                                 }
  15.                         },
  16.                         "required": ["a", "b"],
  17.                         "type": "object"
  18.                 }
  19.         }
  20. }\n
  21. </tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n
  22. <tool_call>\n
  23. {
  24.         "name": < function -name > ,
  25.         "arguments": < args - json - object >
  26. }
  27. </tool_call><|im_end|>\n<|im_start|>user\n1+1<|im_end|>\n<|im_start|>assistant\n<tool_call>\n
  28. {
  29.         "name": "add",
  30.         "arguments": {
  31.                 "a": 1,
  32.                 "b": 1
  33.         }
  34. }\n
  35. </tool_call><|im_end|>\n<|im_start|>user\n
  36. <tool_response>\n
  37. 2
  38. \n</tool_response>
  39. <|im_end|>\n<|im_start|>assistant\n'
复制代码
上述包含了除了之前的系统提示、函数说明等,还追加了调用具体函数的名称、参数以及返回的结果;
4、LLM第二次reponse

content字段是大模型输出结果
(, 下载次数: 0)


(完)

原文地址:https://blog.csdn.net/Mrhiuser/article/details/151760868




欢迎光临 AI创想 (https://www.llms-ai.com/) Powered by Discuz! X3.4