LLM:函数调用(Function Calling)

1 函数调用

虽然大模型能解决很多问题,但大模型并不能知晓一切。比如,大模型不知道最新消息(GPT-3.5 的知识截至 2021年9月,GPT-4 是 2023 年12月)。另外,大模型没有"真逻辑"。它表现出的逻辑、推理,是训练文本的统计规律,而不是真正的逻辑,所以有幻觉。所以大模型需要连接真实世界,并对接真逻辑系统。这就需要用到"函数调用"。

函数调用(Function Calling)可以**使LLM具有与外部API交互的能力。**让用户能够使用高效的外部工具、与外部API进行交互。其使用机制如下:

关于function calling,有以下几点需要注意:

  • 在最新版本的OpenAI API中,可以使用tools参数对函数进行描述。并让大模型智能地选择输出包含函数参数的JSON对象来调用一个或多个函数。
  • 最新的GPT模型(gpt-3.5-turbo-0125 and gpt-4-turbo-preview)可以自动检测何时应该调用函数(还有一个相关的参数tool_choice,一般不用自己设置),还可以输出更加符合函数签名的JSON串。
  • GPT不负责调用和执行外部函数,需要用户自己完成。

2 使用GPT进行函数调用

在使用GPT模型进行函数调用时,需要用到tools参数进行函数声明,关于该参数有以下几点需要说明:

2.1 使用函数调用完成加法计算

大模型可以做加法是因为大模型记住了简单加法的统计规律,但大模型无法保证每次都能得到正确的加法计算结果。这里我们使用函数调用来完成加法计算。具体代码如下:

python 复制代码
from openai import OpenAI
from dotenv import load_dotenv,find_dotenv
import json
from math import *

_=load_dotenv(find_dotenv())
client=OpenAI()

def get_completion(messages,model="gpt-3.5-turbo"):
    response=client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0.7,
        tools=[{
            "type":"function",
            "function":{
                "name":"sum",
                "description":"加法器,计算一组数的和",
                "parameters":{
                    "type":"object",
                    "properties":{
                        "numbers":{
                            "type":"array",
                            "items":{"type":"number"}
                        }
                    }
                }
            }
        }],
    )
    return response.choices[0].message

prompt="计算这些数据的和:345,2313,89,632."
messages=[
    {"role":"system","content":"你是一个数学家"},
    {"role":"user","content":prompt}
]
response=get_completion(messages)
print(response)
#GPT模型第一次的回复中有关于函数调用信息,包括GPT生成的函数调用的参数,所以这些信息需要返回给GPT模型。
messages.append(response)
if response.tool_calls is not None:
    tool_call=response.tool_calls[0]
    if tool_call.function.name=="sum":
        args=json.loads(tool_call.function.arguments)
        result=sum(args["numbers"])
        messages.append({
            "tool_call_id":tool_call.id,
            "role":"tool",
            "name":"sum",
            "content":str(result) 
        })
        print(get_completion(messages).content)

其结果如下:

ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_vYramfrhZX7kLZLYhqDiFVHP', function=Function(arguments='{"numbers":[345,2313,89,632]}', name='sum'), type='function')])

这些数据的和是3379.

2.2 同时启动多个函数调用

借助上述加法函数的代码,可以一次启动同一个函数的多次调用,具体代码如下:

python 复制代码
from openai import OpenAI 
import json
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
client=OpenAI()
def run_conversation(prompt,model='gpt-3.5-turbo'):
    messages=[{"role":"user","content":prompt}]
    tools=[{ 
            "type": "function",
            "function": {
                "name": "sum",
                "description": "加法器,计算一组数的和",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "numbers": {"type": "array", "items": { "type": "number"}}
                    }
                }
            }
        }
    ]
    response=client.chat.completions.create(
        model=model,
        messages=messages,
        tools=tools,
        tool_choice="auto",
    )
    response_message=response.choices[0].message
    messages.append(response_message)
    print(response_message)
    tool_calls=response_message.tool_calls
    if tool_calls:
        for tool_call in tool_calls:
            function_name=tool_call.function.name
            function_args=json.loads(tool_call.function.arguments)
            function_response=sum(function_args.get("numbers"))
            messages.append(
                {"tool_call_id":tool_call.id,
                "role":"tool",
                "name":function_name,
                "content":str(function_response)}
            )
        second_response=client.chat.completions.create(
            model=model,
            messages=messages,
        )
        return second_response.choices[0].message.content
if __name__=="__main__":
    prompt="小明第一天买了5本书2个苹果,第二天买了3本书4个橘子,第三天买了7个梨和10本书,那么小明总共买了多个水果和多少本书?"
    print(prompt)
    print("====GPT回复====")
    print(run_conversation(prompt))

其执行结果如下:

小明第一天买了5本书2个苹果,第二天买了3本书4个橘子,第三天买了7个梨和10本书,那么小明总共买了多个水果和多少本书?

ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_XB4SBFVfhMtyeo4zRu1lvpim', function=Function(arguments='{"numbers": [2, 4, 7]}', name='sum'), type='function'), ChatCompletionMessageToolCall(id='call_d0B4e1j7Fhi1OPxxH9skJRAi', function=Function(arguments='{"numbers": [5, 3, 10]}', name='sum'), type='function')])

GPT回复: 小明总共买了13个水果和18本书。

相关推荐
白狐_7983 小时前
2026 避坑指南:GPT-5.4 Codex、OpenClaw 与订阅版本全解析
gpt·自动化代理
智算菩萨13 小时前
GPT-5.4原生操控电脑揭秘:从Playwright脚本到屏幕截图识别,手把手搭建你的第一个自动化智能体
人工智能·gpt·ai·chatgpt·自动化
x-cmd19 小时前
[260307] x-cmd v0.8.6:新增 gpt-5.4 模型支持,sudo/os/hostname/cpu 等模块文档更新
java·数据库·gpt·sudo·x-cmd·googel
2501_9481142419 小时前
星链4SAPI + OpenClaw实战:给GPT-5.4与Claude 4.6装上“职业传送门”
python·gpt·架构
BUG?不,是彩蛋!21 小时前
从 Q-Learning 到 LLM:我把 AI 的“大脑”换成了 GPT,发生了什么?
人工智能·python·gpt
体育分享_大眼1 天前
AI天花板级碰撞!GPT-5.4正式接入DataEyes,数据智能进入「秒级响应」时代
大数据·人工智能·gpt
流氓架构师1 天前
正面交锋:Gemini 3.1 Pro与GPT-5.4的技术分野与选择逻辑
人工智能·gpt
2501_945837432 天前
OpenClaw 与 GPT-5 中转站的碰撞
gpt
AndrewHZ2 天前
【大模型通关指南】2. 大模型发展时间线:从GPT-1到当前主流模型的演进逻辑
人工智能·gpt·语言模型·大模型·llm·主流模型
Menahem2 天前
Windows无法安装到这个磁盘.选中的磁盘具有MBR分区表,在EFI 系统上,Windows 只能安装到 GPT 磁盘。
gpt