【保姆级 - 大模型应用开发】Function Call 让 AI 调用函数 | 代码实战

在这里插入图片描述

Function Call 是什么?

简单来说: 让模型 主动调用 你定义好的函数


效果演示:让模型告诉你当前时间

我们模拟一个 get_current_time() 函数。只要用户问“现在几点了?”,模型就会主动调用它


📦 准备工作: 注册&申请获取 API Key

你可以使用如 OpenAI、阿里云百炼 等服务商,注册后获取一串 API 密钥 sk-xxx


💡 完整代码:无参函数

import os
import requests  ## HTTP 客户端库,需要提前安装:pip install requests


API_KEY = None  ## 注册后获取的密钥
BASE_URL = None ## 路由地址

# 构建请求头
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_KEY}"  	## 使用 Bearer Token 认证授权
}

def get_current_time():
	from datetime import datetime
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 构建请求体(对话格式)
data = {
    "model": "gpt-4o-mini",					## 要调用的模型名称 (不同模型收费不同,看具体厂商)
    "messages": [  							## 对话式 API 的核心输入,支持多轮对话
        {"role": "system", "content": "你是一个有帮助的助手"},
        {"role": "user", "content": "请告诉我现在的时间!"}
    ],
    "functions": [  ## 1. 告诉模型有个函数可以用
        {
            "name": "get_current_time",
            "description": "获取当前时间",
            "parameters": {
                "type": "object",
                "properties": {}
            }
        }
    ],
    "function_call": "auto"    
}


try:  ## 2. 尝试请求大模型
    response = requests.post(BASE_URL, headers=headers, json=data, timeout=10)  ## 发起 HTTP 请求
    response.raise_for_status()  												## 会对非 2xx 响应抛出异常
    result = response.json()
    
    choice = result["choices"][0]
    if "function_call" in choice["message"]:  ## 3. 如果决定要调用,它会返回一个函数调用请求 "function_call" 
        print("模型想调用函数:", choice["message"]["function_call"])
        print("返回当前时间:", get_current_time())  ## 4. 你捕获这个请求,真的去执行,然后把结果返回给用户
    else:
        print("模型直接回答:", choice["message"]["content"])
except Exception as e:
    print("请求失败:", e)

输出结果预期

模型想调用函数: {'name': 'get_current_time', 'arguments': '{}'}
返回当前时间: 2025-07-26 22:06:42

💡 完整代码:带参函数

✨ 新增亮点:给函数 增加参数在原来“无参”调用的基础上,我们为 get_current_time 函数新增 timezone 参数,让模型能根据时区返回当地时间。

  • 我们模拟一个 get_current_time(timezone) 函数。只要用户说“请告诉我美国纽约现在几点了?”,模型就会主动调用它并填入参数。
import os
import requests  # pip install requests
import json

API_KEY = None   ## 注册后获取的密钥
BASE_URL = None  ## 路由地址

# 构建请求头
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_KEY}"
}

# 模拟真实功能:根据时区返回当前时间
def get_current_time(timezone="UTC"):
    from datetime import datetime
    import pytz  # pip install pytz
    tz = pytz.timezone(timezone)
    return datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")

# 构建对话请求体,带入函数定义和参数说明
data = {
    "model": "gpt-4o-mini",
    "messages": [
        {"role": "system", "content": "你是一个有帮助的助手"},
        {"role": "user", "content": "请告诉我美国纽约现在几点了?"}
    ],
    "functions": [
        {
            "name": "get_current_time",
            "description": "根据时区获取当前时间",
            "parameters": {
                "type": "object",
                "properties": {
                    "timezone": {
                        "type": "string",
                        "description": "时区,例如 America/New_York、Asia/Shanghai、UTC 等"
                    }
                },
                "required": ["timezone"]
            }
        }
    ],
    "function_call": "auto"
}

try:
    resp = requests.post(BASE_URL, headers=headers, json=data, timeout=10)
    resp.raise_for_status()
    result = resp.json()
    
    choice = result["choices"][0]["message"]
    if choice.get("function_call"):
        # 模型决定调用函数,且自动生成了参数
        func = choice["function_call"]
        print("模型想调用函数:", func["name"])
        
        # 解析模型生成的参数
        args = json.loads(func.get("arguments", "{}"))
        tz = args.get("timezone", "UTC")
        
        # 真正执行函数
        current_time = get_current_time(timezone=tz)
        print("返回当前时间:", current_time)
    else:
        print("模型直接回答:", choice.get("content"))
except Exception as e:
    print("请求失败:", e)

输出结果预期

模型想调用函数: {'name': 'get_current_time', 'arguments': '{"timezone":"America/New_York"}'}
返回当前时间: 2025-07-26 11:08:28

✅ 总结

Function Call 是大模型连接现实世界的桥梁,让大模型不仅能“理解”,还能“行动”!还能“带参行动”!


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值