Android开发转AI Agent:第12天——Function Calling,让LLM从“说话“变成“做事“
·
作者:一位Android开发工程师 | 2026年7月1日
系列:Agent 核心能力——让 LLM 调用你的函数
前言
之前所有调用都是"你问 LLM 答"——LLM 只能说,不能做。
Function Calling 改变了这一点:你告诉 LLM 有哪些工具可以用,LLM 决定要不要用、用哪个、传什么参数。你的代码执行工具,把结果还给 LLM。
这是 Agent 区别于普通 Chatbot 的核心能力。
完整流程(两次 API 调用)
第1次请求:用户问"北京天气?" → LLM 返回"我要调 get_weather(city=北京)"
↓
你的代码执行 get_weather("北京") → 返回"晴天25°C"
↓
第2次请求:把结果告诉 LLM → LLM 生成自然语言"北京今天晴天,25°C"
核心代码
定义工具(JSON Schema)
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"],
},
},
}]
骨架永远不变,变的是 name、description、properties。
第一次请求
response = client.chat.completions.create(
model="turing/gpt-4o-mini",
messages=[{"role": "user", "content": "北京天气怎么样"}],
tools=tools, # ← 多了这个参数
)
msg = response.choices[0].message
如果 LLM 想调工具,msg.tool_calls 会有值;否则 msg.content 直接有回答。
执行工具 + 第二次请求
if msg.tool_calls:
tool_call = msg.tool_calls[0]
args = json.loads(tool_call.function.arguments) # {"city": "北京"}
result = get_weather(args["city"]) # "晴天25°C"
response2 = client.chat.completions.create(
model="turing/gpt-4o-mini",
messages=[
{"role": "user", "content": "北京天气怎么样"},
msg, # LLM 的工具调用请求
{"role": "tool", "tool_call_id": tool_call.id, "content": result},
],
)
print(response2.choices[0].message.content)
为什么第二次请求要带上完整 messages
因为 LLM 没有记忆(第4天学的)。每次 API 调用都是全新的,你必须把完整上下文打包发过去:
user消息:原始问题(不然 LLM 不知道在为谁回答)assistant消息(tool_calls):LLM 的工具调用请求(不然 LLM 不知道这是工具返回的结果)tool消息:工具执行结果
今天的一句话总结
Function Calling 的本质是一次"请求→执行→再请求"的两次调用过程。LLM 决定调什么工具,你的代码执行工具,结果还给 LLM 生成回答。这是 Agent 循环的雏形。
下一篇预告
第13天:多工具编排——给 LLM 三个工具,看它能不能自动选对。
本系列记录一位Android开发者转行AI Agent的完整学习过程,欢迎关注交流。
更多推荐

所有评论(0)