用 Function Call 让 AI 主动调用函数(超入门级示例)|保姆级大模型应用开发实战
Function Call 是什么?
简单来说: 让模型 主动调用 你定义好的函数
🎯 超简单演示:让模型告诉你当前时间
我们模拟一个 get_current_time()
函数。只要用户问“现在几点了?”,模型就会主动调用它。
💡一键复制代码(超简版)
import os
import requests
from datetime import datetime
from dotenv import load_dotenvload_dotenv()
API_KEY = os.getenv("MY_API_KEY")
BASE_URL = os.getenv("MY_API_BASE_URL")headers = {"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}"
}def get_current_time():return datetime.now().strftime("%Y-%m-%d %H:%M:%S")payload = {"model": "gpt-4o","messages": [{"role": "user", "content": "请告诉我现在的时间"}],"functions": [ ## 1. 告诉模型有个函数可以用{"name": "get_current_time","description": "获取当前时间","parameters": {"type": "object","properties": {}}}],"function_call": "auto"
}try:resp = requests.post(BASE_URL, headers=headers, json=payload) ## 2. 模型分析你的提问,自动决定是否要调用这个函数resp.raise_for_status()result = resp.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)
输出结果预期
模型会告诉你:
"function_call": {"name": "get_current_time","arguments": "{}"
}
你就执行 get_current_time()
函数,返回类似:
2025-07-24 16:12:55
✅ 总结
Function Call 是大模型连接现实世界的桥梁。
它不仅能“理解”,还能“行动”!
📚 下一步建议
- 替换成你自己的函数,如查天气、查数据库- 学会传入参数
- 把多个函数注册进去,模型会自动选择要调用哪一个!