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

相关推荐
龙的爹23331 天前
论文翻译 | LLaMA-Adapter :具有零初始化注意的语言模型的有效微调
人工智能·gpt·语言模型·自然语言处理·nlp·prompt·llama
罗曼蒂克在消亡1 天前
github项目——gpt-pilot自动创建应用
gpt·github·github项目
wgggfiy2 天前
chatgpt学术科研prompt模板有哪些?chatgpt的学术prompt有哪些?学术gpt,学术科研
论文阅读·人工智能·gpt·chatgpt·prompt·aigc
Ephemeroptera2 天前
通过python-api使用openai的gpt
人工智能·python·gpt
DC10202 天前
GPT 的工作原理:深入解析
java·开发语言·gpt
BIGSHU09233 天前
GPT带我学-设计模式16-原型模式
gpt·设计模式·原型模式
玄奕子3 天前
GPT对话知识库——bootloader是什么?ymodel协议是什么?
stm32·gpt·嵌入式·传输协议·嵌入式驱动
BIGSHU09234 天前
GPT带我学-设计模式18-访问者模式
gpt·设计模式·访问者模式
hunteritself4 天前
ChatGPT实时语音将于本周向免费用户推出:OpenAI DevDay 2024详细解读
人工智能·gpt·算法·chatgpt·openai·语音识别
刘承卓5 天前
【Text2SQL】当前在BIRD基准测试集上取得SOTA的论文
gpt·自然语言处理·prompt·aigc·llama