Function Calling
目录
DeepSeek
Function Calling 是一种让大语言模型在生成回复时,根据用户意图自动调用预定义函数或 API 的能力。它使模型不再局限于文本生成,而是能结构化输出参数,精准触发外部工具、数据库或业务系统,完成实时查询、执行操作等任务。这一机制极大拓展了 AI 的应用边界,让模型从“对话者”变为“执行者”,是实现智能体、自动化工作流与业务闭环的关键桥梁。
场景示例
编写一个获取当前时间的函数调用示例,展示如何使用函数调用机制。

环境准备
pip install flask os配置好自定义大模型的环境变量:MODEL_BASE_URL、MODEL_NAME、API_KEY。
创建 Server
server.py 文件:
from flask import Flask, request, jsonify
import os
import json
import requests
import datetime
app = Flask(__name__)
# ----------------------------
# 1️⃣ 定义可被模型调用的函数
# ----------------------------
def get_current_time():
"""返回当前服务器时间"""
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("[Function] get_current_time() called ->", now)
return now
# 模型函数映射表
FUNCTION_MAP = {"get_current_time": get_current_time}
# ----------------------------
# 2️⃣ 接收用户输入
# ----------------------------
@app.route("/chat", methods=["POST"])
def chat():
user_input = request.json.get("user_input", "")
print("[Server] Received user input:", user_input)
# ----------------------------
# 3️⃣ 调用大模型生成函数调用指令
# ----------------------------
model_base_url = os.environ.get("MODEL_BASE_URL")
model_name = os.environ.get("MODEL_NAME")
api_key = os.environ.get("API_KEY")
functions = [
{
"name": "get_current_time",
"description": "获取当前服务器时间",
"parameters": {},
}
]
# 构造请求体(参考官方 Function Calling 格式)
payload = {
"model": model_name,
"messages": [{"role": "user", "content": user_input}],
"functions": functions,
"function_call": "auto", # 让模型自动决定是否调用函数
}
headers = {"Authorization": f"Bearer {api_key}"}
# 请求模型生成函数调用指令
print("[Server] Sending request to model for function call...")
response = requests.post(
f"{model_base_url}/v1/chat/completions", json=payload, headers=headers
)
model_output = response.json()
print("[Server] Model raw response:", json.dumps(model_output, indent=2))
# ----------------------------
# 4️⃣ 执行模型指定函数
# ----------------------------
# 精简示例:直接取第一个 message
message = model_output["choices"][0]["message"]
function_call = message.get("function_call")
if function_call:
func_name = function_call["name"]
func_args = json.loads(function_call.get("arguments", "{}"))
print(f"[Server] Model requests function: {func_name} with args {func_args}")
# 执行函数
result = FUNCTION_MAP[func_name]()
return jsonify({"function_result": result})
# 如果模型未请求函数调用,则返回原始内容
return jsonify({"model_response": message.get("content", "")})
# ----------------------------
# 启动 Flask
# ----------------------------
if __name__ == "__main__":
app.run(port=5000, debug=True)创建 Client
client.py 文件,发送请求:
# client.py
import requests
SERVER_URL = "http://127.0.0.1:5000/chat"
# 用户测试输入
user_input = "请告诉我现在时间"
response = requests.post(SERVER_URL, json={"user_input": user_input})
print("[Client] Response:", response.json())运行和测试
开 2 个终端,分别运行:
python server.py
python client.py参考
[1] https://developers.openai.com/api/docs/guides/function-calling