AIGC开发 -- 本地方法与AI的互动Function calling

简介

上一篇主要讲了如何调用OPEN AI模型的API,提前将简单信息准备好后可以完成简单的机器人互动,这一章主要介绍如何通过API回调我们自己本地的方法

用途

当触发某一个具体业务功能时,我们将用自己实现的方法精确处理逻辑时,通过此方法可以满足该场景

API介绍

官方文档说明

https://platform.openai.com/docs/guides/function-calling

在 API 调用中,您可以描述函数,并让模型智能地选择输出包含调用一个或多个函数的参数的 JSON 对象。聊天完成 API 不会调用该函数;相反,模型会生成 JSON,您可以使用它来调用代码中的函数。

最新模型(gpt-3.5-turbo-1106 和 gpt-4-turbo-preview)经过训练,可以检测何时应调用函数(取决于输入)并使用符合函数签名的 JSON 进行响应比以前的型号更接近。这种能力也带来了潜在的风险。我们强烈建议在代表用户采取影响世界的行动(发送电子邮件、在线发布内容、购买等)之前构建用户确认流程。

简单使用示例

定义对话模型,声明工具方法类

def get_completion(messages, model="gpt-3.5-turbo"):
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0.7,  # 模型输出的随机性,0 表示随机性最小
        tools=[{  # 用 JSON 描述函数。可以定义多个。由大模型决定调用谁。也可能都不调用
            "type": "function",
            "function": {
                "name": "sum",
                "description": "加法器,计算一组数的和",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "numbers": {
                            "type": "array",
                            "items": {
                                "type": "number"
                            }
                        }
                    }
                }
            }
        }],
    )
    return response.choices[0].message

对话模拟,大模型判断调用工具类

if __name__ == "__main__":
	prompt = "1+2+3"
    messages = [
        {"role": "system", "content": "你是一个数学家"},
        {"role": "user", "content": prompt}
    ]
    response = get_completion(messages)

    # 把大模型的回复加入到对话历史中
    print_json(response)
    messages.append(response)

    print("=====GPT回复=====")
    print_json(response)

    # 如果返回的是函数调用结果,则打印出来
    if (response.tool_calls is not None):
        # 是否要调用 sum
        tool_call = response.tool_calls[0]
        if (tool_call.function.name == "sum"):
            # 调用 sum
            args = json.loads(tool_call.function.arguments)
            result = sum(args["numbers"])
            print("=====函数返回=====")
            print(result)

            # 把函数调用结果加入到对话历史中
            messages.append(
                {
                    "tool_call_id": tool_call.id,  # 用于标识函数调用的 ID
                    "role": "tool",
                    "name": "sum",
                    "content": str(result)  # 数值 result 必须转成字符串
                }
            )

            # 再次调用大模型
            print("=====最终回复=====")
            print(get_completion(messages).content)

案例说明

  • 模拟一个身份:数学家
  • 给出一个问题"1+2+3…+99+100"
  • 调用API,API中定义好可以使用的本地方法
  • 获取大模型返回,判断是否需要调用本地方法
  • 如果返回的tool_calls不为空则表示大模型需要调用本地方法
  • 判断方法名称为sum,则进行本地运算
  • 运算完成后将上下文消息返回给大模型,同时带上工具消息标识
  • 大模型继续处理结果组成自然语言返回给用户

调用过程

{
    "content": null,
    "role": "assistant",
    "function_call": null,
    "tool_calls": [
        {
            "id": "call_E4GpMEOSsaOMhi6Vwc0REjaX",
            "function": {
                "arguments": "{\n  \"numbers\": [1, 2, 3]\n}",
                "name": "sum"
            },
            "type": "function"
        }
    ]
}
=====GPT回复=====
{
    "content": null,
    "role": "assistant",
    "function_call": null,
    "tool_calls": [
        {
            "id": "call_E4GpMEOSsaOMhi6Vwc0REjaX",
            "function": {
                "arguments": "{\n  \"numbers\": [1, 2, 3]\n}",
                "name": "sum"
            },
            "type": "function"
        }
    ]
}
=====函数返回=====
6
=====最终回复=====
1 + 2 + 3 = 6

你可能感兴趣的:(AIGC,AIGC,人工智能,数据库)