惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
月光博客
月光博客
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
The GitHub Blog
The GitHub Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
宝玉的分享
宝玉的分享
A
About on SuperTechFans
Vercel News
Vercel News
P
Proofpoint News Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
Jina AI
Jina AI
Y
Y Combinator Blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI

少数派

派早报:Google 发布 Fitbit Air 等 - 少数派 「新人报到」確認需求,再開始 - 少数派 从 SOLO 独立开发者社区,我看到了越来越多开发者开始做自己的产品 - 少数派 我怎么管理那些"不常做,但总会忘"的生活事项 - 少数派 人形机器人量产元年,数据才是具身智能的“生死线” - 少数派 BuhoLaunchpad 高度还原 Mac 启动台:开发历程与思考 - 少数派 五年陪伴依然不舍,DIY 换壳后让罗技 MX Master 3 继续服役 - 少数派 新玩意 240|少数派的编辑们最近买了啥? - 少数派 一日一技|为什么你应该关闭 iOS 的键盘声音 - 少数派 我做了个插件和 Skills,一键提取任何网站的设计规范 Design.md - 少数派 住在三四线城市的你,该开始录播客了 - 少数派 甘南秘境,大白高国 - 少数派 AI的审美:谁让把我变成川内倫子 - 少数派 返工怎能不烦恼,打工人片单总有一部是你的「嘴替」 - 少数派 为了让「上厕所」更健康,我做了一个小工具 - 少数派 AI + Skill,能够让生成的文章去除 AI 味吗? - 少数派 新玩意|韶音OpenDots ONE 耳夹式耳机 - 少数派 《美满》| 在每一个春天的晚上相爱(362) - 少数派 新玩意|优篮子 PS01 MagSnap 磁吸支架 - 少数派 自我整合手记 | 我开始早睡了:用稳定规则,为自由托底 - 少数派 用龙虾(OpenClaw)两个多月,我最深的12个体会 - 少数派 听歌时间到,12 张你可能错过的 2025 华语乐坛好专辑 - 少数派 承诺能追吗 - 少数派 macOS 26启动台没了? 我做了个不一样的App启动器 - Keboard - 少数派 《四海为家的人》| INTJ对话INTJ(361) - 少数派 你发过的那些黑历史,是时候一次清干净了 - 少数派 新玩意:安安静静玩,越玩越专注:计客密码机 - 少数派 iPad 用户首次体验 Android 平板:vivo Pad6 Pro - 少数派 数据逻辑强 - 少数派 极北行+ | 一路向北,探访日本至北之地 | 001 - 少数派
openai的function calling初体验 - 少数派
2023-07-24 · via 少数派

🤖: GPT函数调用的作用是允许ChatGPT生成参数,并以结构化的数据类型与自定义函数进行交互,生成稳定的JSON输出。它能够从自然语言中提取相应的函数参数,为对话提供了更灵活的方式。尽管在某些方面可能不如预期,但它仍然是一个有用的工具。

实际 VS 预期

在我的预期里,我希望 gpt function calling 能完美实现链式调用且不产生额外的 tokens 消耗。如果能按我的预期工作,我将使用它作为 API 的调度中心,使得通过自然语言随意调用相关函数成为可能,并且可以按任意组合进行加工处理,就像函数式编程一样。
然而实际情况是,gpt function calling实际上是提取自然语言中函数的相应参数。因此,要完成一次回复,它可能需要执行两次或更多次,这取决于所采取的步骤数量。从某种程度上说,它类似于 AutoGPT,但相比之下更加稳定。它能自动选择最佳匹配的自定义函数来获取参数,但 GPT3.5 并不能始终如预期地匹配相似函数,并且在链式调用时无法确保每次都正确输出 JSON 结构化数据,从而导致链式调用中断。
或许 GPT4 的表现会更好,但由于尚未获得 GPT4 的 API,无法进行测试。

它允许 ChatGPT 生成参数,并以结构化的数据类型与自定义函数进行交互,生成稳定的 JSON 输出。
最重要的是,它能够从自然语言中提取相应的函数参数,方便我们进行函数调用,而无需将具体执行函数传递给 GPT。这为我们的对话提供了更灵活的方式。

gpt3.5 的 function calling

首先,我们可自行编写或使用 langchain 来实践一下简单的函数调用。

单函数调用

定义函数描述以获取参数

function_descriptions = [
    {
        "name": "get_student_score",
        "description": "Get the student score by given his or her name",
        "parameters": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "The student's name",
                }
            },
            "required": ["name"],
        }
    }
]

定义执行函数以返回结果

def get_student_score(name):
    """Get the student score by given his or her name"""

    score = {
        "name": name,
        "score": SCORES[name]
    }
    return json.dumps(score)

开始调用 chat

user_query = "What's the performance of Lucy in the scool this year?"
response = openai.ChatCompletion.create(
    model=OPENAI_MODEL,
    messages=[{"role": "user", "content": user_query}],
    functions=function_descriptions,
    function_call="auto"
)
ai_response_message = response["choices"][0]["message"]
print(ai_response_message)
name = eval(ai_response_message['function_call']['arguments']).get("name")
print(name)

执行以上 gpt 调用后,我们将获得提示词中的名字,其结果如下

{
  "role": "assistant",
  "content": null,
  "function_call": {
    "name": "get_student_score",
    "arguments": "{\n\"name\": \"Lucy\"\n}"
  }
}
Lucy

拿着对应参数 name='Lucy',去执行相应函数 get_student_score 获得 json 结果,再次调用 chat 函数完成自然语言的回复

second_response = openai.ChatCompletion.create(
        model=OPENAI_MODEL,
        messages=[
            {"role": "user", "content": user_query},
            ai_response_message,
            {
                "role": "function",
                "name": "get_student_score",
                "content": function_response,
            },
        ],
    )
    print(second_response['choices'][0]['message']['content'])

假设 Lucy 的分数为 60,则它将返回

Lucy has achieved a score of 60 this year.

从上述过程我们可以看出,要完成一次正确且稳定的回复,我们需要对同个提示词做 2 次操作,一次是获取结构化的 json 函数所需参数,并自行完成函数调用,一次是携带函数执行结果,完成最终回复。

接下来我们看看多函数调用,中途发生过中断。

多函数调用

此处使用 langchain 完成该过程。

定义函数描述以获取参数

function_descriptions = [
        {
            "name": "remove_word_from_string",
            "description": "Remove a word from a string by given its index",
            "parameters": {
                "type": "object",
                "properties": {
                    "string": {
                        "type": "string",
                        "description": "The original string to be processed",
                    },
                    "index": {
                        "type": "integer",
                        "description": "The index of the word to be removed"
                    },
                },
                "required": [
                    "string",
                    "index"
                ],
            },
        },
        {
            "name": "send_message_by_email",
            "description": "Send an email with the text message to a recipient",
            "parameters": {
                "type": "object",
                "properties": {
                    "recipient": {
                        "type": "string",
                        "description": "The email address of the recipient",
                    },
                    "message": {
                        "type": "string",
                        "description": "The message of the email content",
                    }
                },
                "required": [
                    "recipient",
                    "message"
                ],
            },
        }
    ]

以上两个函数,一个用来获取字符串和要移除单词的位置,一个用来获取接收者和消息

定义执行函数以返回结果

def remove_word_from_string(string, index):
    words = string.split()

    if 0 <= index < len(words):
        del words[index]

        return ' '.join(words)
    else:
        return string


def send_message_by_email(recipient, message):
    print(f'Sending {message} to {recipient}\n\n')
    return f'Just sent email to {recipient}'

开始调用 chat

question = """
    I have a string as follows:

    black yellow red blue green

    Please do the following 2 operations on it:
    1. Remove the third word in the string
    2. Send the updated string to Alex via email alex@xyz.com
    """
first_response = llm.predict_messages(
        [HumanMessage(content=question)], functions=function_descriptions)
    print(first_response.additional_kwargs, end='\n\n')

## 省略拿着对应参数调用函数的步骤,returned_value为其执行后返回的json数据

second_response = llm.predict_messages(
        [
            HumanMessage(content=question),
            AIMessage(content=str(first_response.additional_kwargs)),
            ChatMessage(
                role='function',
                additional_kwargs={'name': function_name},
                content=returned_value
            )
        ],
        functions=function_descriptions
    )
## 省略拿着对应参数调用函数的步骤,returned_value为其执行后返回的json数据
third_response = llm.predict_messages(
        [
            HumanMessage(content=question),
            AIMessage(content=str(first_response.additional_kwargs)),
            AIMessage(content=str(second_response.additional_kwargs)),
            ChatMessage(
                role='function',
                additional_kwargs={'name': function_name},
                content=returned_value
            )
        ], functions=function_descriptions
    )

最终结果如下

Sending black yellow blue green to alex@xyz.com

I have removed the third word from the string and sent the updated string to Alex via email.