Claude Function Calling(Anthropic 称之为 Tool Use)是目前 LLM 集成中最强大的能力之一。它让 Claude 能够主动调用外部工具、查询实时数据、读写文件,而不仅仅是生成文本。本文通过构建一个数据分析助手的完整案例,讲解 Function Calling 的使用方法。
什么是 Function Calling
传统 LLM 输出是纯文本,你告诉它「帮我查天气」,它只能回答「我无法查天气」。Function Calling 改变了这个模式:
1LLM 收到用户请求2 ↓3LLM 识别需要调用外部工具4 ↓5输出结构化的工具调用请求 { tool: "get_weather", args: { city: "北京" } }6你的代码执行这个工具,获取结果7 ↓8结果返回给 LLM9 ↓10LLM 整合工具结果,给出最终回答Anthropic 的 Tool Use
Claude 的 Function Calling 叫做「Tool Use」,在 API 中叫 tools 参数。支持的工具类型:
- User-defined tools:你自己定义的任何工具
- Built-in tools:
web_search(Anthropic 内置搜索)、computer(2025 年新增的计算机操作工具)
Anthropic 2025 年初推出的 computer 工具让 Claude 可以像人一样操作计算机——移动鼠标、输入文字、截屏。这是 Function Calling 的进化版。
完整案例:构建数据分析助手
需求
用户用自然语言查询销售数据,助手自动:
- 连接 PostgreSQL 查询
- 执行 Python 计算
- 生成自然语言回答
Step 1:定义 Tools
1import Anthropic from '@anthropic-ai/sdk'2 3const client = new Anthropic()4 5const tools = [6 {7 name: "run_sql",8 description: "执行 SQL 查询并返回结果",9 input_schema: {10 type: "object",11 properties: {12 query: {13 type: "string",14 description: "要执行的 SELECT 查询语句"15 }16 },17 required: ["query"]18 }19 },20 {21 name: "run_python",22 description: "执行 Python 代码进行数据分析",23 input_schema: {24 type: "object",25 properties: {26 code: {27 type: "string",28 description: "要执行的 Python 代码(仅支持数据处理,不能执行系统命令)"29 }30 },31 required: ["code"]32 }33 }34]Step 2:构造对话
1async function askQuestion(question: string) {2 const response = await client.messages.create({3 model: 'claude-sonnet-4-20250514',4 max_tokens: 1024,5 tools,6 messages: [7 {8 role: 'user',9 content: question10 }11 ]12 })13 14 // 处理工具调用15 if (response.stop_reason === 'tool_use') {16 const toolResult = await handleToolCalls(response.content)17 // 把工具结果继续发送给 LLM18 return askFollowUp(question, toolResult)19 }20 21 return response.content[0].text22}Step 3:处理工具调用
1async function handleToolCalls(content: any[]) {2 const results = []3 4 for (const block of content) {5 if (block.type === 'tool_use') {6 const { name, input } = block.input7 8 if (name === 'run_sql') {9 const result = await db.query(input.query)10 results.push({11 tool_use_id: block.id,12 content: JSON.stringify(result.rows)13 })14 }15 16 if (name === 'run_python') {17 const result = await executePython(input.code)18 results.push({19 tool_use_id: block.id,20 content: result21 })22 }23 }24 }25 26 return results27}Step 4:完整的多轮对话
1async function askFollowUp(originalQuestion: string, toolResults: any[]) {2 const response = await client.messages.create({3 model: 'claude-sonnet-4-20250514',4 max_tokens: 2048,5 tools,6 messages: [7 { role: 'user', content: originalQuestion },8 // 这里是关键:把第一轮的结果注入回去9 ...await buildToolResultMessages(toolResults)10 ]11 })12 13 return response.content[0].text14}Tool Use 的设计原则
原则 1:Description 决定调用时机
Claude 什么时候决定调用工具?靠 description 字段。好的 description:
1{2 "name": "run_sql",3 "description": "执行 SELECT 查询从 PostgreSQL 数据库获取数据。仅支持查询语句,禁止执行 INSERT/UPDATE/DELETE。"4}技巧:在 description 里明确说「仅支持查询」可以防止注入。
原则 2:input_schema 要具体
1{2 "name": "get_weather",3 "input_schema": {4 "type": "object",5 "properties": {6 "city": {7 "type": "string",8 "description": "城市名,需要是中文全称,如'北京'而不是'BJ'"9 },10 "date": {11 "type": "string",12 "description": "日期,格式 YYYY-MM-DD。如查询今天,传当天日期"13 }14 },15 "required": ["city"]16 }17}越具体的 schema,Claude 调用时错误越少。
原则 3:结果要结构化
工具返回的结果最好也是结构化的(JSON),Claude 能更好地理解。
好:{"temperature": 22, "humidity": 65, "condition": "晴"}
差:温度22度,湿度65%,天气晴
常见陷阱
陷阱 1:工具循环调用
Claude 可能会在一次回复中调用多个工具,或者第一轮没拿到足够信息时继续调用。
解决方案:在 prompt 中限制调用次数,例如:
1// 在 system prompt 中加:2"你最多可以调用 3 次工具。如果无法完成,回答'我无法完成这个查询'"陷阱 2:SQL 注入
用户可能输入恶意 SQL:
1用户输入:我想知道所有订单 SELECT * FROM orders; DROP TABLE orders;解决方案:
- description 里明确写「仅支持 SELECT」
- 后端在执行前验证语句以 SELECT 开头
- 使用参数化查询
1function safeExecute(sql: string) {2 const trimmed = sql.trim().toUpperCase()3 if (!trimmed.startsWith('SELECT')) {4 throw new Error('仅支持 SELECT 查询')5 }6 return db.query(sql)7}陷阱 3:工具超时
Claude 可能调用一个很慢的工具(复杂 SQL、大数据计算),导致用户体验差。
解决方案:给工具加超时控制:
1async function withTimeout(fn: () => Promise<any>, ms: number) {2 return Promise.race([3 fn(),4 new Promise((_, reject) =>5 setTimeout(() => reject(new Error('Tool timeout')), ms)6 )7 ])8}Anthropic computer 工具(2025 新功能)
computer 工具让 Claude 可以像人一样操作电脑:
1const computerTool = {2 name: "computer",3 description: "Control the user's computer. Use this tool when you need to interact with desktop applications, browsers, or the file system.",4 input_schema: {5 type: "object",6 properties: {7 action: {8 type: "string",9 enum: ["screenshot", "mouse_move", "keypress", "type"]10 },11 coordinate: { type: "array" },12 text: { type: "string" }13 }14 }15}这个工具让「AI 替你操作电脑」成为现实,适合 RPA 场景。
总结
Function Calling 是 AI 应用的转折点——从「AI 生成文本」到「AI 执行动作」。
核心要点:
- 工具描述决定调用时机 — 写清楚每个工具的能力边界
- Schema 要具体 — 减少 Claude 对参数含义的误解
- 结果要结构化 — JSON 比纯文本更容易被 LLM 理解
- 安全不能只靠 prompt — description + 后端验证双保险
- 限制调用次数 — 防止工具循环和超时
