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本书。

相关推荐
OpenCSG3 天前
GPT‑6.2 Astra 和 GPT‑6.2 Sol 来了,OpenCSG 里怎么用 Codex?
人工智能·gpt·opencsg
谙弆悕博士4 天前
生物启发式集群(Swarm)工程实现:五条规则、一群蚂蚁和四十个粒子
人工智能·gpt·游戏引擎·cocos2d·蚁群算法·多智能体·boids
AI 编程助手GPT6 天前
GPT 写 SQL:避免订单金额被重复统计
jvm·人工智能·sql·gpt
最强小杰7 天前
GPT-6.2-astra API 完全指南:20 人成本、失败重试与故障切换(2026)
gpt·ai
Vex2une9 天前
Rufus 制作 Windows 启动盘完整指南:分区方案怎么选、Win11 硬件检测怎么绕
gpt·uefi·使用教程·rufus·mbr·制作启动盘·绕过tpm
the3clipse12 天前
系统盘怎么无损从 MBR 转 GPT 并开启 UEFI 启动?mbr2gpt 完整教程
gpt·mbr·uefi启动·无损转换分区表·bcdboot·引导修复
一缕82年的清风12 天前
百万 Token 砍到 0.5 美元!微软新模型半价、DeepSeek 连夜撤回搜索费,11 月底开发者怎么搭最省钱?
gpt·claude·deepseek
翰墨之道12 天前
AI日报:豆包工作ARR超20亿,GPT-6.2跑分与实测割裂
人工智能·gpt·数据挖掘
Maynor99612 天前
Trymodel 使用介绍:一个平台同时用 Claude、GPT、Gemini 和 Grok
人工智能·gpt·ai·程序员·教程·claude·语音
bryant_meng13 天前
ChatGPT Desktop Model Evolution (2025): From GPT-4.1 to GPT-5.1
gpt·chatgpt·gpt4·gpt4o·gpt5