【Tool calls原理】调用AI回调函数

发布时间:2026/8/16 15:01:12
【Tool calls原理】调用AI回调函数 from datetime import datetime, timedelta import json import random from openai import OpenAI # 连接lmstdio服务器并选择模型 client OpenAI(base_urlhttps://dashscope.aliyuncs.com/compatible-mode/v1, api_key***) # 连接lmstdio服务器 model qwen-plus # 选择模型 # 设计需要调用的函数 def get_delivery_date(order_id: str) - datetime: # 生成一个随机的交付日期从今天开始到14天内的任意一天 today datetime.now() random_days random.randint(1, 14) delivery_date today timedelta(daysrandom_days) return delivery_date tools [ { type: function, function: { name: get_delivery_date, description: 根据订单号获取预计的交付日期当顾客询问订单的预计交付日期时调用此函数比如当用户问我的订单什么时候能送达时调用此函数, parameters: { type: object, properties: { order_id: { type: string, description: 顾客的订单号ID, }, }, required: [order_id], additionalProperties: False, }, }, } ] messages [ { role: system, content: 您是一位乐于助人的客户支持助理。使用提供的工具协助用户。, }, { role: user, content: 给我1017号订单的交货日期和时间, }, ] # LM Studio response client.chat.completions.create( modelmodel, messagesmessages, toolstools, ) # 获取顾客输入的参数 # 请注意下方代码假设我们已经确定模型生成了一个函数调用。 tool_call response.choices[0].message.tool_calls[0] arguments json.loads(tool_call.function.arguments) order_id arguments.get(order_id) # 使用提取的order_id调用get_delivery_date函数 delivery_date get_delivery_date(order_id) assistant_tool_call_request_message { role: assistant, tool_calls: [ { id: response.choices[0].message.tool_calls[0].id, type: response.choices[0].message.tool_calls[0].type, function: response.choices[0].message.tool_calls[0].function, } ], } # 创建一条包含函数调用结果的消息 function_call_result_message { role: tool, content: json.dumps( { order_id: order_id, delivery_date: delivery_date.strftime(%Y-%m-%d %H:%M:%S), } ), tool_call_id: response.choices[0].message.tool_calls[0].id, } # 准备聊天完成回调装载内容包括历史消息、助手工具调用请求消息和函数调用结果消息 completion_messages_payload [ messages[0], messages[1], assistant_tool_call_request_message, function_call_result_message, ] # 调用OpenAI API的聊天完成端点将工具调用结果发送回模型 response client.chat.completions.create( modelmodel, messagescompletion_messages_payload, ) print(response.choices[0].message.content, flushTrue)默认情况下模型将确定何时以及使用多少工具。您可以使用tool_choice参数强制特定行为。Auto默认调用零个、一个或多个函数。tool_choice: autoRequired调用一个或多个函数。tool_choice: requiredForced Function精确调用一个特定函数。tool_choice: {type: function, function: {name: get_weather}}Skill 教会 AI 做事的说明书MCP 统一插各种外部系统的数据线标准CLI 在本机直接动手干活的工具MCP 只是通信协议本身不带治理。治理边界 在 MCP Client / MCP Server 外层增加管控层绝对不能把治理逻辑裸写在大模型侧。很多人踩坑直接依赖 LLM 自己判断能不能调用工具边界极易恶化、越权、泄露。关键原则治理不放在 Agent放在 MCP 网关层。 Agent 只负责业务决策能不能执行、能传什么参数由网关一票否决。