【GPT入门】第20课 langchain的function calling 开端体验

[复制链接]
发表于 2025-10-14 23:21:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
1. langchain的function calling 非常简便


  • 在方法名分析方法用途和参数作用
  • 增长@tool 标签
  • langchain方法自动把@tool转为方法界说,后续方法调用都很简便
    下面代码用支持单函数与多函数调用,自己体验一下
query = “3 加 4的和 的 5 倍是多少?” 这个会调用两次函数
query = " 4的 5 倍是多少?"
2. 代码

  1. from langchain_core.messages import HumanMessage
  2. from langchain_core.tools import tool
  3. from langchain_openai import ChatOpenAI
  4. @tool
  5. def add(a: int, b: int) -> int:
  6.     """Add two integers together.
  7.     Args:
  8.         a: The first integer.
  9.         b: The second integer.
  10.     """
  11.     return a + b
  12. @tool
  13. def multiply(a: int, b: int) -> int:
  14.     """Multiply two integers together.
  15.     Args:
  16.         a: The first integer.
  17.         b: The second integer.
  18.     """
  19.     return a * b
  20. import json
  21. # model_name = 'gpt-4o-mini'
  22. # model_name = 'gpt-4'
  23. # llm = ChatOpenAI(model_name=model_name)
  24. llm = ChatOpenAI()
  25. llm_with_tools = llm.bind_tools([add, multiply])
  26. query = "3 加 4的和 的 5 倍是多少?"
  27. # query = " 4的 5 倍是多少?"
  28. messages = [HumanMessage(content=query)]
  29. output = llm_with_tools.invoke(messages)
  30. print(output)
  31. print("------------tool_calls:")
  32. print(json.dumps(output.tool_calls, indent=4))
  33. messages.append(output)
  34. avaliable_tools = {"add":add, "multiply": multiply}
  35. for tool_call in output.tool_calls:
  36.     selected_tools = avaliable_tools[tool_call["name"].lower()] # tool_call就是一个字典
  37.     tool_msg = selected_tools.invoke(tool_call)
  38.     messages.append(tool_msg)
  39.     print("tool_msg:, type:", type(tool_msg))  # <class 'langchain_core.messages.tool.ToolMessage'>
  40.     print(tool_msg)
  41.     # content='20' name='multiply' tool_call_id='call_e5EY7klNZlBD8W68y7X0BcYD'
  42. new_output = llm_with_tools.invoke(messages)
  43. for message in messages:
  44.     print("message.dump:")
  45.     print(json.dumps(message.model_dump(), indent=4, ensure_ascii=False))
  46. print(new_output.content)
复制代码
3. 实验效果:

  1. C:\ProgramData\anaconda3\envs\gptLearning\python.exe E:\workspace\gptLearning\gptLearning\ls10\functionCalling\ls01_tools.py
  2. content='' additional_kwargs={'tool_calls': [{'id': 'call_0HGpTdeo2zm9G6zZPbewVi8g', 'function': {'arguments': '{"a": 3, "b": 4}', 'name': 'add'}, 'type': 'function'}, {'id': 'call_m6Uc0OfQ9ea0uTyFNbwEWIBq', 'function': {'arguments': '{"a": 7, "b": 5}', 'name': 'multiply'}, 'type': 'function'}], 'refusal': None} response_metadata={'token_usage': {'completion_tokens': 49, 'prompt_tokens': 121, 'total_tokens': 170, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': 'fp_0165350fbb', 'finish_reason': 'tool_calls', 'logprobs': None} id='run-e83caecd-ca6f-4851-b35e-b5ea8f2804a2-0' tool_calls=[{'name': 'add', 'args': {'a': 3, 'b': 4}, 'id': 'call_0HGpTdeo2zm9G6zZPbewVi8g', 'type': 'tool_call'}, {'name': 'multiply', 'args': {'a': 7, 'b': 5}, 'id': 'call_m6Uc0OfQ9ea0uTyFNbwEWIBq', 'type': 'tool_call'}] usage_metadata={'input_tokens': 121, 'output_tokens': 49, 'total_tokens': 170, 'input_token_details': {}, 'output_token_details': {}}
  3. ------------tool_calls:
  4. [
  5.     {
  6.         "name": "add",
  7.         "args": {
  8.             "a": 3,
  9.             "b": 4
  10.         },
  11.         "id": "call_0HGpTdeo2zm9G6zZPbewVi8g",
  12.         "type": "tool_call"
  13.     },
  14.     {
  15.         "name": "multiply",
  16.         "args": {
  17.             "a": 7,
  18.             "b": 5
  19.         },
  20.         "id": "call_m6Uc0OfQ9ea0uTyFNbwEWIBq",
  21.         "type": "tool_call"
  22.     }
  23. ]
  24. tool_msg:, type: <class 'langchain_core.messages.tool.ToolMessage'>
  25. content='7' name='add' tool_call_id='call_0HGpTdeo2zm9G6zZPbewVi8g'
  26. tool_msg:, type: <class 'langchain_core.messages.tool.ToolMessage'>
  27. content='35' name='multiply' tool_call_id='call_m6Uc0OfQ9ea0uTyFNbwEWIBq'
  28. message.dump:
  29. {
  30.     "content": "3 加 4的和 的 5 倍是多少?",
  31.     "additional_kwargs": {},
  32.     "response_metadata": {},
  33.     "type": "human",
  34.     "name": null,
  35.     "id": null,
  36.     "example": false
  37. }
  38. message.dump:
  39. {
  40.     "content": "",
  41.     "additional_kwargs": {
  42.         "tool_calls": [
  43.             {
  44.                 "id": "call_0HGpTdeo2zm9G6zZPbewVi8g",
  45.                 "function": {
  46.                     "arguments": "{"a": 3, "b": 4}",
  47.                     "name": "add"
  48.                 },
  49.                 "type": "function"
  50.             },
  51.             {
  52.                 "id": "call_m6Uc0OfQ9ea0uTyFNbwEWIBq",
  53.                 "function": {
  54.                     "arguments": "{"a": 7, "b": 5}",
  55.                     "name": "multiply"
  56.                 },
  57.                 "type": "function"
  58.             }
  59.         ],
  60.         "refusal": null
  61.     },
  62.     "response_metadata": {
  63.         "token_usage": {
  64.             "completion_tokens": 49,
  65.             "prompt_tokens": 121,
  66.             "total_tokens": 170,
  67.             "completion_tokens_details": null,
  68.             "prompt_tokens_details": null
  69.         },
  70.         "model_name": "gpt-3.5-turbo-0125",
  71.         "system_fingerprint": "fp_0165350fbb",
  72.         "finish_reason": "tool_calls",
  73.         "logprobs": null
  74.     },
  75.     "type": "ai",
  76.     "name": null,
  77.     "id": "run-e83caecd-ca6f-4851-b35e-b5ea8f2804a2-0",
  78.     "example": false,
  79.     "tool_calls": [
  80.         {
  81.             "name": "add",
  82.             "args": {
  83.                 "a": 3,
  84.                 "b": 4
  85.             },
  86.             "id": "call_0HGpTdeo2zm9G6zZPbewVi8g",
  87.             "type": "tool_call"
  88.         },
  89.         {
  90.             "name": "multiply",
  91.             "args": {
  92.                 "a": 7,
  93.                 "b": 5
  94.             },
  95.             "id": "call_m6Uc0OfQ9ea0uTyFNbwEWIBq",
  96.             "type": "tool_call"
  97.         }
  98.     ],
  99.     "invalid_tool_calls": [],
  100.     "usage_metadata": {
  101.         "input_tokens": 121,
  102.         "output_tokens": 49,
  103.         "total_tokens": 170,
  104.         "input_token_details": {},
  105.         "output_token_details": {}
  106.     }
  107. }
  108. message.dump:
  109. {
  110.     "content": "7",
  111.     "additional_kwargs": {},
  112.     "response_metadata": {},
  113.     "type": "tool",
  114.     "name": "add",
  115.     "id": null,
  116.     "tool_call_id": "call_0HGpTdeo2zm9G6zZPbewVi8g",
  117.     "artifact": null,
  118.     "status": "success"
  119. }
  120. message.dump:
  121. {
  122.     "content": "35",
  123.     "additional_kwargs": {},
  124.     "response_metadata": {},
  125.     "type": "tool",
  126.     "name": "multiply",
  127.     "id": null,
  128.     "tool_call_id": "call_m6Uc0OfQ9ea0uTyFNbwEWIBq",
  129.     "artifact": null,
  130.     "status": "success"
  131. }
  132. 3 加 4 的和是 7,7 的 5 倍是 35。
  133. Process finished with exit code 0
  134. ``
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表