Xz's blog Xz's blog
首页
时间序列
多模态
合成生物学
其他方向
生活
工具相关
PyTorch
导航站

Xu Zhen

首页
时间序列
多模态
合成生物学
其他方向
生活
工具相关
PyTorch
导航站
  • 深度学习基础

  • Agent

    • FunctionCalling
      • Function Calling
        • 一句话理解 Function Calling:
        • Function Calling 的组成
        • 适用场景
        • 总结图示
        • 注意事项
      • 代码示例
        • 不使用 FunctionCalling 的例子
        • 加入 FunctionCalling
      • 参考
  • 时序预测

  • 图学习

  • 其他

  • 其他方向
  • Agent
xuzhen
2025-08-04
目录

FunctionCalling

可以配合下面的例子来理解 FunctionCalling 的作用。

# Function Calling

Function Calling(函数调用)功能,是一个强大的能力,允许语言模型“调用你定义的函数”来获取更准确、更结构化的输出 —— 尤其适用于你想让模型和你的后端逻辑交互的场景。

# 一句话理解 Function Calling:

你可以给模型定义一组函数的“接口”,当模型理解到用户的问题需要某个函数时,它会“生成”一组结构化的参数并“调用”这个函数(你可以选择是否自动调用),最终将结果返回给用户。

# Function Calling 的组成

使用时通常包括以下几部分:

组件 说明
tools 包含一个或多个函数的描述(类似于 OpenAPI 中的 schema)
type 必须为 "function",表示这个是函数类型的工具
function 函数的元信息,包含 name、description、parameters
tool_choice 指定是否让模型自动选择函数并调用(例如 "auto")
tool_calls 模型判断需要调用哪个函数时,会在返回中生成该字段

# 适用场景

Function Calling 特别适合以下场景:

  • 🔧 调用已有后端逻辑(如数据库查询、运算、API调用等)
  • 📅 日历/任务助手
  • 🔢 数学或金融计算器
  • 📚 RAG(检索增强生成)系统中的文档搜索
  • 🧩 多轮对话系统的 agent 架构(如 ReAct、Toolformer)

# 总结图示

+------------+      问题       +-----------------+
|   用户      |  ----------->  |     模型         |
+------------+                +-----------------+
                                  |
                                  |   根据工具描述识别调用函数
                                  v
                            "tool_calls": [{
                                name: "get_weather",
                                arguments: { location: "北京" }
                            }]
                                  |
                                  |  (开发者解析参数 & 执行实际函数)
                                  v
                      你返回函数执行结果给模型继续回答
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 注意事项

  • function.arguments 是 JSON 字符串,要用 json.loads() 解析。
  • tool_choice="auto" 是可选的,也可以自己根据返回的 tool_calls 决定是否调用。
  • 函数名必须是符合 OpenAI 要求的:不能有空格、不能是空字符串、必须是非空英文标识符。

# 代码示例

下面让 gpt-3.5-turbo-0125(这里使用的是一步API (opens new window)来调用大模型) 回答 9.11 - 9.9 = ? 这个问题,我们

一步API (opens new window) 有 1 美元的免费额度,还是挺好用的。

# 不使用 FunctionCalling 的例子

就直接将 9.11 - 9.9 = ? 给 gpt-3.5-turbo-0125。

我们可以看到模型的输出 -0.21,这明显是不对的。下面我们使用 FunctionCalling 的方式来解决这个问题。

import openai

# 这里填写您在https://yibuapi.com上创建的apikey
api_key = "sk-xxxxxx"
# 这里填写https://yibuapi.com/v1
base_url = "https://yibuapi.com/v1"
# 这是问题
questions = f"""
9.11 - 9.9 = ?
"""

def get_openai_response(question, api_key, base_url):
    try:
        client = openai.OpenAI(api_key=api_key, base_url=base_url)
        response = client.chat.completions.create(
            model="gpt-3.5-turbo-0125",
            messages=[{"role": "user", "content": question}]
        )
        return response
    except Exception as e:
        return f"请求失败: {str(e)}"

if __name__ == "__main__":
    response = get_openai_response(questions, api_key, base_url)
    print(f"回答: {response.choices[0].message.content}\n")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

最终输出:

回答: 9.11 - 9.9 = -0.21
1

直接问 GPT 4o 它不会出错,稍微加点东西就不行了,GPT 4o 也会出错。。。

# 加入 FunctionCalling

好的,这里是一个完整的 Function Calling 示例,包含以下内容:

  1. 定义一个“减法函数”的调用接口
  2. 让 GPT 理解用户的问题并自动调用该函数
  3. 自动解析返回的函数调用信息,执行运算
  4. 将运算结果再发给 GPT,让它生成最终回答
import openai
import json

# 这里填写您在https://yibuapi.com上创建的apikey
api_key = "sk-xxxxx"
# 这里填写https://yibuapi.com/v1
base_url = "https://yibuapi.com/v1"

# 1. 定义一个“减法函数”的调用接口 定义函数 schema
subtract_tool_description = {
    "type": "function",
    "function": {
        "name": "subtraction",
        "description": "执行减法运算",
        "parameters": {
            "type": "object",
            "properties": {
                "number1": {
                    "type": "number",
                    "description": "第一个数字"
                },
                "number2": {
                    "type": "number",
                    "description": "第二个数字"
                }
            },
            "required": ["number1", "number2"]
        }
    }
}
# 实际执行减法的函数
def subtraction(number1, number2):
    return str(number1 - number2)  # OpenAI 接口要求 content 为字符串

if __name__ == "__main__":
    # 我们询问的问题
    question = f"""
9.11 - 9.9 = ?
"""
    # 2. 让 GPT 理解用户的问题并自动调用该函数,这里就是增加了 tools 参数
    client = openai.OpenAI(api_key=api_key, base_url=base_url)
    response = client.chat.completions.create(
        model="gpt-3.5-turbo-0125",
        tools=[subtract_tool_description],
        messages=[{"role": "user", "content": question}]
    )
    
    message = response.choices[0].message
    '''
    ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_igk0lq82Xp61tElDZM80bDmL', function=Function(arguments='{"number1":9.11,"number2":9.9}', name='subtraction'), type='function')])
    '''
    
    # 3. 自动解析返回的函数调用信息,执行运算
    if message.tool_calls:
        tool_call = message.tool_calls[0]
        '''tool_call
        ChatCompletionMessageToolCall(id='call_igk0lq82Xp61tElDZM80bDmL', function=Function(a...9}', name='subtraction'), type='function')
        '''
        func_name = tool_call.function.name
        '''func_name
        subtraction
        '''
        arguments = json.loads(tool_call.function.arguments)
        '''arguments
        {'number1': 9.11, 'number2': 9.9}
        '''

        # 执行对应的函数
        if func_name == "subtraction":
            result = subtraction(**arguments)

            # 4. 将运算结果再发给 GPT,让它生成最终回答,将函数执行结果作为 tool 的响应发回模型
            follow_up = client.chat.completions.create(
                model="gpt-3.5-turbo-0125",
                messages=[
                    {"role": "user", "content": question},
                    message,  # 包含tool_calls字段的assistant回复
                    {
                        "role": "tool",
                        "tool_call_id": tool_call.id,
                        "name": func_name,
                        "content": result
                    }
                ]
            )

            print("最终回答:", follow_up.choices[0].message.content)
        else:
            print("未识别的函数调用")
    else:
        print("没有触发函数调用。模型直接回答:", message.content)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

输出:

最终回答: 9.11 - 9.9 = -0.79.
1

# 参考

https://www.bilibili.com/video/BV1XFhPzoEBx

#Agent
上次更新: 2025/08/14, 10:32:31

← 训练集、验证集和测试集 Transformer 时序预测模型汇总→

最近更新
01
Linux 通过Windows代理上网
09-18
02
vscode远程使用copilot和codex(内网环境)
09-18
03
跨机器克隆环境
09-18
更多文章>
Theme by Vdoing | Copyright © 2025-2025 Xu Zhen | 鲁ICP备2025169719号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式