function calling 的机制原理

7

什么是 function calling

function callingopen ai 创建的能让大模型调用外部工具的一套规则,我们按照这套规则去编写代码,那么我们就能让大语言模型调用我们定义的一些外部工具。

场景:

原来的大语言模型只能指导我们但无法做出实际的行动。有了function calling 就能通过分析使用者的意图,去调用一些外部工具。Function Calling允许我们以 JSON 格式向 LLM 模型描述函数,并使用模型的固有推理能力来决定在生成响应之前是否调用该函数。模型本身不执行函数,而是生成包含函数名称执行函数所需的参数JSON

function calling工作流程

微信图片_20260502102412_1_23.png

代码使用

tool的定义

OpenAIfunction calling的核心是我们将Prompts 提示词和可用函数列表一起发送给LLM

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "获取城市实时天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "城市名称,例如北京"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

调用看下输出

messages = [
    {"role": "user", "content": "帮我查一下上海现在天气"}
]

response = client.chat.completions.create(
    model="Qwen3.6-27B",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

msg = response.choices[0].message

msg如下:

ChatCompletionMessage(
  content='Here\'sathinkingprocess: \n\n1.**AnalyzeUserInput: **\n-Usersays: "帮我查一下上海现在天气"(HelpmecheckthecurrentweatherinShanghai)\n-Keyinformation: Location=上海(Shanghai),
  Request=实时天气(current/real-timeweather)\n\n2.**IdentifyAvailableTools: **\n-Ihaveatool: `get_weather`\n-Parameters: `city`(string,required)-descriptionsays"城市名称,例如北京"(Cityname,e.g.,Beijing)\n\n3.**MapInputtoToolParameters: **\n-`city`="上海"\n\n4.**ConstructToolCall: **\n-Function: `get_weather`\n-Arguments: `{"city": "上海"}`\n\n5.**ExecuteToolCall(MentalSimulation/Preparation): **\n-Iwillcallthefunctionwiththespecifiedparameters.\n\n*(Self-Correction/Verificationduringthought)*\n-Thetoolmatchestherequestperfectly.\n-Theparameternameandtypearecorrect.\n-Noadditionalparametersneeded.\n-Proceed.\n\n6.**GenerateResponse: **(Willbedoneafterreceivingthetooloutput,
butIneedtooutputthetoolcallnow)\n-Iwilloutputthefunctioncallintherequiredformat.✅\n</think>\n\n',
  refusal=None,
  role='assistant',
  annotations=None,
  audio=None,
  function_call=None,
  tool_calls=[
    ChatCompletionMessageFunctionToolCall(id='chatcmpl-tool-a0f87e6afb4a58ba',function=Function(arguments='{"city": "上海"}',name='get_weather'),
    type='function')
  ],
  reasoning=None
)

这里模型告诉我们它需要调用的工具和调用工具所需要的参数值。

我们可以循环去获取并调用它所需要调用的工具,然后将调用结果反喂给模型。

让模型结合调用结果组织自然语言回答。

def get_weather(city: str):
    # ... 实现代码 ...
    return "25°C"

def get_stock_price(symbol: str):
    # ... 实现代码 ...
    return "150.00 USD"

available_functions = {
    "get_weather": get_weather,
    "get_stock_price": get_stock_price
}


if msg.tool_calls:

    for tool_call in msg.tool_calls:
        function_name = tool_call.function.name
        function_args = json.loads(tool_call.function.arguments)

        function_to_call = available_functions.get(function_name)

        if function_to_call:
            result = function_to_call(**function_args)
            print(f"成功调用 {function_name},结果: {result}")
        else:
            print(f"错误:模型想调用 {function_name},但我没定义这个函数")

    messages.append(msg)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": result
    })

    final_response = client.chat.completions.create(
        model="Qwen3.6-27B",
        messages=messages
    )
    print(final_response.choices[0].message.content)

else:
    print("模型没有调用函数:", msg.content)

到现在为止简单的function calling的简单调用已经完成了
具体的流程可以总结为以下的流程,可以看到function calling跟LLM模型至少有两次交互的的过程。