找回密码
 立即注册
首页 业界区 业界 大模型function calling多轮对话开发示例

大模型function calling多轮对话开发示例

饨篦 5 天前
OpenAI接口支持的function calling使得大模型能够方便的集成外部能力和数据,是实现agent(智能体)的重要基础,能让LLM和各种功能集成,从而解决复杂的问题。 对于兼容openai接口的大模型如阿里的通义千问,也是可以使用类似的方法进行调用。
模型实际上从不自行执行函数,仅生成需要调用的函数名称和调用的参数,应用自行判断执行,对于langchain等框架则把这一层封装到框架中。并且传入的函数描述,和输出的函数调用描述都是计算在token上。
如果确实想使用openai相关模型,可以通过点击我的推荐链接 https://referer.shadowai.xyz/r/1017200  ,进入CloseAI平台,该平台提供商用级OpenAI代理服务。
或者也可以使用兼容openai接口的模型,如阿里百炼 https://bailian.console.aliyun.com/。
开发流程通常如下:
  1. 步骤1:定义一个你希望模型调用的函数
  2. 步骤2:向模型描述你的函数,以便它知道如何调用它
  3. 步骤3:将您的函数定义作为可用的“工具”传递给模型,同时附上消息内容
  4. 步骤4:接收并处理模型响应
  5. 步骤5:将函数调用结果返回给模型
  6. 步骤6:流程如果尚未结束可以继续循环上述步骤.
复制代码
以下我们用一个使用大模型openai的function calling并且是多轮对话的例子进行讲解。
场景如下,在用户需要查询本机内存使用情况的时候如果可用内存超过80%时,保存至文件mem_high.txt;不超过80%时,保存到mem_ok.txt。
因此我们提供了能够一个查询本机可用内存和一个保存文本到本地文件工具函数,那么我们应该怎么让大模型进行调用呢?

  • 安装所需库:psuti、openai。psutil = process and system utilities,支持linux,mac和windows操作系统,实现系统信息获取和监控
  1. pip install psutil openai
复制代码

  • 准备大模型的apikey,兼容openai接口协议即可。
  • 以下是详细的代码及解释
  1. from openai import OpenAI
  2. from openai.types.chat.chat_completion_message_function_tool_call import ChatCompletionMessageFunctionToolCall
  3. import psutil
  4. import json
  5. client = OpenAI(
  6.     api_key="xxxxx",
  7.     base_url="xxxx"
  8. )
  9. def get_memory_info():
  10.     mem = psutil.virtual_memory()
  11.     mem_info = {"total": mem.total, "available": mem.available, "used": mem.used, "free": mem.free}
  12.     return json.dumps(mem_info)
  13. def write_file(file_name, text):
  14.     with open(file_name, "w", encoding="utf-8") as f:
  15.         f.write(text)
  16. def do_function_tool_call(function_tool_call: ChatCompletionMessageFunctionToolCall):
  17.     """
  18.     基于大模型返回的函数调用说明,进行函数调用,并且构造tool的message返回
  19.     """
  20.     function_call = function_tool_call.function
  21.     name = function_call.name
  22.     args = function_call.arguments
  23.     if name == "get_memory_info":
  24.         func_result = get_memory_info()
  25.     elif name == "write_file":
  26.         args_dict = json.loads(args)
  27.         func_result = write_file(args_dict["file_name"], args_dict["text"])
  28.     else:
  29.         raise Exception("unkown function:" + name)
  30.     if func_result is None:
  31.         func_result = ""
  32.     ## 需要把response的关联的function_tool_call设置tool_call_id
  33.     tool_message = {"role": "tool", "tool_call_id": function_tool_call.id, "content": func_result}
  34.     return tool_message
  35. ## 以下对传递给llm的工具集描述,注意在早期版本是使用functions参数进行调用格式上会有所差异,openai认为tools可以支持更加广泛的工具支持因此推荐使用tools传参
  36. tools = [
  37.     {
  38.         "type": "function",
  39.         "function": {
  40.             "name": "get_memory_info",
  41.             "description": "获取系统内存,会将系统的内存情况用json格式返回",
  42.             "parameters": {
  43.                 "type": "object",
  44.                 "properties": {},
  45.                 "required": []
  46.             }
  47.         }
  48.     },
  49.     {
  50.         "type": "function",
  51.         "function": {
  52.             "name": "write_file",
  53.             "description": "将文本数据写入文件",
  54.             "parameters": {
  55.                 "type": "object",
  56.                 "properties": {
  57.                     "file_name": {
  58.                         "type": "string",
  59.                         "description": "文件名"
  60.                     },
  61.                     "text": {
  62.                         "type": "string",
  63.                         "description": "写入的文本数据"
  64.                     }
  65.                 },
  66.                 "required": ["file_name", "text"]
  67.             }
  68.         }
  69.     }]
  70. user_input = "需要帮我计算电脑的内存使用率和具体的使用情况,如果内存使用率超过80%,则将内存相关信息写到mem_high.txt文件,不超过80%将内存相关信息写到mem_ok.txt文件中"
  71. messages = [{"role": "user", "content": user_input}]
  72. response = client.chat.completions.create(
  73.     model="gpt-5-mini",
  74.     messages=messages,
  75.     tools=tools
  76. )
  77. resp_msg = response.choices[0].message
  78. # 实现多轮对话,首先会执行查询内存函数调用
  79. messages.append(resp_msg)
  80. # 对于实际开发来说需要严格tool_calls是否为空再决定是否调用
  81. function_tool_call = resp_msg.tool_calls[0]
  82. # 大模型只返回需要调用的函数名称和参数,需要应用自行调用。
  83. tool_message = do_function_tool_call(function_tool_call)
  84. # 将函数(工具)执行结果封装成tool类型返回.
  85. messages.append(tool_message)
  86. response = client.chat.completions.create(
  87.     model="gpt-5-mini",
  88.     messages=messages,
  89.     tools=tools
  90. )
  91. # 实现多轮对话,执行写入函数的调用
  92. resp_msg = response.choices[0].message
  93. messages.append(resp_msg)
  94. function_tool_call = resp_msg.tool_calls[0]
  95. tool_message = do_function_tool_call(function_tool_call)
  96. messages.append(tool_message)
  97. response = client.chat.completions.create(
  98.     model="gpt-5-mini",
  99.     messages=messages,
  100.     tools=tools
  101. )
  102. print(response.choices[0].message.content)
复制代码
最终的输出:
1.jpeg

为了了解下实际出入参格式,贴一下实际的json辅助理解
这是首轮输入输出:
req:
  1. {
  2.     "messages": [
  3.         {
  4.             "role": "user",
  5.             "content": "需要帮我计算我电脑的内存使用率和具体的使用情况,如果内存使用率超过80%,写到mem_high.txt文件,否则写到mem_ok.txt"
  6.         }
  7.     ],
  8.     "model": "gpt-5-mini",
  9.     "tools": [
  10.         {
  11.             "type": "function",
  12.             "function": {
  13.                 "name": "get_memory_info",
  14.                 "description": "获取系统内存,会将系统的内存情况用json格式返回",
  15.                 "parameters": {
  16.                     "type": "object",
  17.                     "properties": {},
  18.                     "required": []
  19.                 }
  20.             }
  21.         },
  22.         {
  23.             "type": "function",
  24.             "function": {
  25.                 "name": "write_file",
  26.                 "description": "将文本数据写入文件",
  27.                 "parameters": {
  28.                     "type": "object",
  29.                     "properties": {
  30.                         "file_name": {
  31.                             "type": "string",
  32.                             "description": "文件名"
  33.                         },
  34.                         "text": {
  35.                             "type": "string",
  36.                             "description": "写入的文本数据"
  37.                         }
  38.                     },
  39.                     "required": [
  40.                         "file_name",
  41.                         "text"
  42.                     ]
  43.                 }
  44.             }
  45.         }
  46.     ]
  47. }
复制代码
resp:
  1. {
  2.         "choices": [
  3.                 {
  4.                         "finish_reason": "tool_calls",
  5.                         "index": 0,
  6.                         "logprobs": null,
  7.                         "message": {
  8.                                 "annotations": [],
  9.                                 "content": null,
  10.                                 "refusal": null,
  11.                                 "role": "assistant",
  12.                                 "tool_calls": [
  13.                                         {
  14.                                                 "function": {
  15.                                                         "arguments": "{}",
  16.                                                         "name": "get_memory_info"
  17.                                                 },
  18.                                                 "id": "call_1k3y8eKABbbNKpUT7SBm7L3l",
  19.                                                 "type": "function"
  20.                                         }
  21.                                 ]
  22.                         }
  23.                 }
  24.         ],
  25.         "created": 1758770660,
  26.         "id": "chatcmpl-CJWseIPtV6FGKTi7XsAdwkbeskgXO",
  27.         "model": "gpt-5-mini-2025-08-07",
  28.         "object": "chat.completion",
  29.         "system_fingerprint": null,
  30.         "usage": {
  31.                 "completion_tokens": 213,
  32.                 "completion_tokens_details": {
  33.                         "accepted_prediction_tokens": 0,
  34.                         "audio_tokens": 0,
  35.                         "reasoning_tokens": 192,
  36.                         "rejected_prediction_tokens": 0
  37.                 },
  38.                 "prompt_tokens": 201,
  39.                 "prompt_tokens_details": {
  40.                         "audio_tokens": 0,
  41.                         "cached_tokens": 0
  42.                 },
  43.                 "total_tokens": 414
  44.         }
  45. }
复制代码
这个是最后一轮输入输出:
req:
  1. {
  2.     "messages": [
  3.         {
  4.             "role": "user",
  5.             "content": "需要帮我计算电脑的内存使用率和具体的使用情况,如果内存使用率超过80%,则将内存相关信息写到mem_high.txt文件,不超过80%将内存相关信息写到mem_ok.txt文件中"
  6.         },
  7.         {
  8.             "role": "assistant",
  9.             "annotations": [],
  10.             "tool_calls": [
  11.                 {
  12.                     "id": "call_vxeBJnnY6W4iFKdbuGlzCgix",
  13.                     "function": {
  14.                         "arguments": "{}",
  15.                         "name": "get_memory_info"
  16.                     },
  17.                     "type": "function"
  18.                 }
  19.             ]
  20.         },
  21.         {
  22.             "role": "tool",
  23.             "tool_call_id": "call_vxeBJnnY6W4iFKdbuGlzCgix",
  24.             "content": "{"total": 34219794432, "available": 12072124416, "used": 22147670016, "free": 12072124416}"
  25.         },
  26.         {
  27.             "role": "assistant",
  28.             "annotations": [],
  29.             "tool_calls": [
  30.                 {
  31.                     "id": "call_c6Bw3DaspJCBVefCYk74aXkr",
  32.                     "function": {
  33.                         "arguments": "{"file_name":"mem_ok.txt","text":"内存使用情况:\\n\\n总内存: 34219794432 字节 (约 31.87 GiB)\\n已用: 22147670016 字节 (约 20.63 GiB)\\n可用: 12072124416 字节 (约 11.24 GiB)\\n空闲: 12072124416 字节 (约 11.24 GiB)\\n内存使用率: 64.75%\\n\\n结论: 内存使用率低于 80%,已将上述内存信息保存到文件 mem_ok.txt。"}",
  34.                         "name": "write_file"
  35.                     },
  36.                     "type": "function"
  37.                 }
  38.             ]
  39.         },
  40.         {
  41.             "role": "tool",
  42.             "tool_call_id": "call_c6Bw3DaspJCBVefCYk74aXkr",
  43.             "content": ""
  44.         }
  45.     ],
  46.     "model": "gpt-5-mini",
  47.     "tools": [
  48.         {
  49.             "type": "function",
  50.             "function": {
  51.                 "name": "get_memory_info",
  52.                 "description": "获取系统内存,会将系统的内存情况用json格式返回",
  53.                 "parameters": {
  54.                     "type": "object",
  55.                     "properties": {},
  56.                     "required": []
  57.                 }
  58.             }
  59.         },
  60.         {
  61.             "type": "function",
  62.             "function": {
  63.                 "name": "write_file",
  64.                 "description": "将文本数据写入文件",
  65.                 "parameters": {
  66.                     "type": "object",
  67.                     "properties": {
  68.                         "file_name": {
  69.                             "type": "string",
  70.                             "description": "文件名"
  71.                         },
  72.                         "text": {
  73.                             "type": "string",
  74.                             "description": "写入的文本数据"
  75.                         }
  76.                     },
  77.                     "required": [
  78.                         "file_name",
  79.                         "text"
  80.                     ]
  81.                 }
  82.             }
  83.         }
  84.     ]
  85. }
复制代码
resp:
  1. {
  2.         "choices": [
  3.                 {
  4.                         "finish_reason": "stop",
  5.                         "index": 0,
  6.                         "logprobs": null,
  7.                         "message": {
  8.                                 "annotations": [],
  9.                                 "content": "已计算并保存内存信息,结果如下:\n\n- 总内存:34,219,794,432 字节(约 31.87 GiB)\n- 已用内存:22,147,670,016 字节(约 20.63 GiB)\n- 可用/空闲:12,072,124,416 字节(约 11.24 GiB)\n- 内存使用率:64.75%(计算方法:已用 / 总内存 × 100)\n\n判断与操作:\n- 由于使用率 64.75% 小于阈值 80%,已把内存信息写入文件 mem_ok.txt(文件名:mem_ok.txt,位于当前工作目录)。\n\n如果你希望,我可以:\n- 展示 mem_ok.txt 的完整内容;\n- 或者把内存使用率限制、告警阈值改为其他值并重新检查; \n- 或给出减少内存占用的建议。要做哪项请告诉我。",
  10.                                 "refusal": null,
  11.                                 "role": "assistant"
  12.                         }
  13.                 }
  14.         ],
  15.         "created": 1758770581,
  16.         "id": "chatcmpl-CJWrNpvVIS2HVUZDLdSHJPwfrbRwH",
  17.         "model": "gpt-5-mini-2025-08-07",
  18.         "object": "chat.completion",
  19.         "system_fingerprint": null,
  20.         "usage": {
  21.                 "completion_tokens": 608,
  22.                 "completion_tokens_details": {
  23.                         "accepted_prediction_tokens": 0,
  24.                         "audio_tokens": 0,
  25.                         "reasoning_tokens": 384,
  26.                         "rejected_prediction_tokens": 0
  27.                 },
  28.                 "prompt_tokens": 438,
  29.                 "prompt_tokens_details": {
  30.                         "audio_tokens": 0,
  31.                         "cached_tokens": 0
  32.                 },
  33.                 "total_tokens": 1046
  34.         }
  35. }
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

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