一、什么是function calling
Function Calling = 让大模型不仅“说话”,还会“用工具”。当你把“工具列表(schema)”传给模型后,它有两种输出选择:
- 直接回答(自然语言)
- 发起函数调用请求(一个带 name 和 arguments 的
JSON),你再用自己的代码执行这个函数,把结果回传给模型,由模型把结果转成人话给用户。
你可以把它理解成:
“模型像个助理,会在需要时说:‘我去查一下(调用某函数),查完再回来回答。’”
二、安装环境
conda create -n llm python=3.10
pip install openai
export OPENAI_API_KEY="your-api-key"
三、demo
from openai import OpenAI
import json
from datetime import date
client = OpenAI()
# 定义函数 (工具) schema
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询城市天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"date": {"type": "string", "description": "日期 YYYY-MM-DD"}
},
"required": ["city", "date"]
}
}
}
]
# 本地实现的函数(模拟调用真实 API)
def get_weather(city, date):
return {"city": city, "date": date, "weather": "Sunny", "temperature": "28°C"}
# 用户输入
user_msg = {"role": "user", "content": "查一下北京明天的天气"}
# 第一步:让模型决定是否调用函数
resp = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[user_msg],
tools=tools,
tool_choice="auto"
)
msg = resp.choices[0].message
print("🟡 模型输出:", msg)
# 如果模型调用了函数
if msg.tool_calls:
tool_call = msg.tool_calls[0]
args = json.loads(tool_call.function.arguments)
# 调用本地函数
result = get_weather(**args)
# 第二步:把结果交给模型生成自然语言回答
final = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
user_msg,
msg, # 模型的函数调用请求
{
"role": "tool",
"tool_call_id": tool_call.id,
"name": tool_call.function.name,
"content": json.dumps(result, ensure_ascii=False)
}
]
)
print("✅ 最终回答:", final.choices[0].message.content)
四、常见问题


经测试,服务器无法直连 OpenAI API。
是因为访问openai需要代理。
因为是公用服务器,故决定使用SSH反向端口转发,将服务器的流量通过本机127.0.0.1:7980进行转发。
ssh -R 7890:127.0.0.1:7890 user@服务器ip
export HHTPS_PROXY="http://127.0.0.1:7980"
export HHTP_PROXY="http://127.0.0.1:7980"


被折叠的 条评论
为什么被折叠?



