
本文从零开始讲解Java AI Agent的Function Calling工具调用框架涵盖工具定义、参数校验、错误重试、超时控制、结果格式化等生产级细节。通过注解式工具自动注册和执行器集成帮助程序员轻松实现大模型与工具的交互。文章提供完整Java代码可直接应用并写入简历。同时还介绍了如何搭建测试环境以及推荐的学习资源适合想要学习大模型应用开发的程序员参考。之前我们从零实现了Java AI Agent的核心框架并梳理了最常用的工具库但很多同学反馈Agent框架跑起来了但工具调用这块问题一大堆——参数传错、工具超时、调用失败不知道怎么重试、返回结果大模型看不懂。这很正常。90%的人写Function Calling只写了把参数传给工具执行这一步剩下的参数校验、错误重试、超时控制、结果格式化全是空白。Demo能跑一上生产全是bug。今天把Function Calling的生产级实现讲透从工具定义到异常处理每个环节都给完整Java代码做完直接写进简历。一、先搞懂Function Calling到底是什么很多人以为Function Calling是大模型直接执行代码完全不是。Function Calling的本质是一个协议你把工具的名称、描述、参数定义JSON Schema告诉大模型大模型根据用户问题自主判断是否需要调用工具、调用哪个、传什么参数大模型返回的不是执行结果而是一个调用指令工具名参数JSON真正执行工具的是你的后端代码执行完把结果回传给大模型大模型根据工具结果生成自然语言回答用户用户北京今天天气怎么样 ↓大模型思考需要调用天气查询工具 ↓大模型返回{”tool”:”get_weather”,”args”:{”city”:”北京”}} ↓你的后端执行调用天气API拿到结果{”temp”:”25℃”,”weather”:”晴”} ↓结果回传大模型 ↓大模型回答北京今天晴气温25℃适合出行。关键点大模型不执行任何代码它只做决策——决定调什么工具、传什么参数。执行是你后端的事所以生产级的容错全在你这边。二、生产级工具定义不只是名称和描述很多人定义工具只写个名称和描述结果大模型经常传错参数、调错工具。生产级的工具定义需要3层信息。第 1 层工具元信息给大模型看的package com.aiproject.agent.function; import java.lang.annotation.*; / * 工具定义注解 * 生产级工具定义需要名称、描述、参数Schema、超时时间、是否需要重试 */Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)public interface FunctionTool { String name(); // 工具名称大模型调用用 String description(); // 工具描述大模型根据描述决定是否调用写清楚 String parameters(); // JSON Schema格式的参数定义 long timeoutMs() default 30000; // 工具执行超时时间默认30秒 int maxRetry() default 2; // 失败最大重试次数默认2次 boolean critical() default false; // 是否关键工具关键工具失败直接终止非关键降级}第 2 层参数 Schema大模型传参的依据参数定义必须用JSON Schema写清楚大模型才知道传什么类型、哪些是必填。// 示例天气查询工具的参数SchemaString PARAMS_SCHEMA ”””{ ”type”: ”object”, ”properties”: { ”city”: { ”type”: ”string”, ”description”: ”城市名称必须是中文城市名如北京、上海、广州” }, ”date”: { ”type”: ”string”, ”description”: ”查询日期格式YYYY-MM-DD默认今天”, ”default”: ”today” } }, ”required”: [”city”]}”””;坑参数description写得越清楚大模型传错的概率越低。比如city不要只写城市要写城市名称必须是中文城市名如北京、上海。第 3 层工具执行器真正干活的package com.aiproject.agent.function;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.aiproject.agent.core.LLMClient;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Component;importjavax.annotation.Resource;importjava.lang.reflect.Method;importjava.util.Map;importjava.util.concurrent.*;/ * 工具执行器 * 生产级实现参数校验 超时控制 失败重试 异常降级 */Slf4jComponentpublic class FunctionExecutor{Resource private FunctionRegistry registry;/ 工具执行线程池和业务线程池隔离 */ private final ThreadPoolExecutor executornew ThreadPoolExecutor(10,50,60, TimeUnit.SECONDS, new LinkedBlockingQueue(200), r -{Thread tnew Thread(r, ”function-executor”);t.setDaemon(true);returnt;}, new ThreadPoolExecutor.CallerRunsPolicy());/ * 执行工具调用生产级完整流程 */ public ToolResult execute(String toolName, String argumentsJson){//1. 查找工具 FunctionRegistry.FunctionMethodfunctionregistry.get(toolName);if(functionnull){returnToolResult.fail(”工具不存在: ” toolName);}//2. 参数校验 ValidationResult validationvalidateParams(function, argumentsJson);if(!validation.isValid()){// 参数校验失败返回明确的错误信息大模型会根据错误修正参数重试returnToolResult.fail(”参数校验失败: ” validation.getErrorMsg() ”请修正参数后重新调用。正确的参数格式: ” function.getParameters());}//3. 带超时重试执行 int maxRetryfunction.getAnnotation().maxRetry();for(int attempt1;attemptmaxRetry 1;attempt){try{returnexecuteWithTimeout(function, argumentsJson, function.getAnnotation().timeoutMs());}catch(TimeoutException e){log.warn(”工具[{}]执行超时第{}次尝试”, toolName, attempt);if(attemptmaxRetry){continue;// 重试}returnhandleFailure(function, ”工具执行超时” function.getAnnotation().timeoutMs() ”ms”);}catch(Exception e){log.warn(”工具[{}]执行异常第{}次尝试:{}”, toolName, attempt, e.getMessage());if(attemptmaxRetryisRetryable(e)){continue;// 可重试异常才重试}returnhandleFailure(function, ”工具执行异常: ” e.getMessage());}}returnToolResult.fail(”工具执行失败”);}/ * 带超时控制的执行 */ private ToolResult executeWithTimeout(FunctionRegistry.FunctionMethod function, String argumentsJson, long timeoutMs)throws Exception{Future futureexecutor.submit(()-{ try { Method methodfunction.getMethod();Object resultmethod.invoke(function.getInstance(),argumentsJson);//结果格式化确保返回字符串且不超过长度限制 String formattedformatResult(result);return ToolResult.success(formatted);} catch(Exception e){ throw e;} });return future.get(timeoutMs,TimeUnit.MILLISECONDS);}/*参数校验*/private ValidationResult validateParams(FunctionRegistry.FunctionMethod function,String argumentsJson){ try { JSONObject argsJSON.parseObject(argumentsJson);//解析JSON Schema校验必填字段和类型 JSONObject schemaJSON.parseObject(function.getParameters());JSONObject propertiesschema.getJSONObject(”properties”);// 必填字段校验if(schema.containsKey(”required”)){for(String required:schema.getJSONArray(”required”).toJavaList(String.class)){if(!args.containsKey(required)||args.getString(required).isEmpty()){returnValidationResult.fail(”缺少必填参数: ” required);}}}// 类型校验简化版实际使用时做完整类型转换for(Map.Entry entry:properties.entrySet()){String propNameentry.getKey();if(args.containsKey(propName)){// 可以在这里做类型校验和值范围校验}}returnValidationResult.ok();}catch(Exception e){returnValidationResult.fail(”参数JSON格式错误: ” e.getMessage());}}/ * 结果格式化限制长度避免工具结果太长撑爆Token */ private String formatResult(Object result){if(resultnull)return”执行成功无返回数据”;String strresult.toString();// 工具结果超过2000字符截断避免Token爆炸if(str.length()2000){returnstr.substring(0,2000) ”/n...结果过长已截断”;}returnstr;}/ * 判断是否可重试异常 */ private boolean isRetryable(Exception e){// 网络超时、连接拒绝等可重试参数错误、业务异常不可重试 String msge.getMessage()null ? ””:e.getMessage();returnmsg.contains(”timeout”)||msg.contains(”connect”)||msg.contains(”Connection refused”)||e instanceof java.net.SocketException;}/ * 失败处理关键工具失败终止非关键工具降级 */ private ToolResult handleFailure(FunctionRegistry.FunctionMethod function, String errorMsg){if(function.getAnnotation().critical()){// 关键工具失败返回明确错误Agent终止returnToolResult.fail(”关键工具[” function.getName() ”]执行失败: ” errorMsg ”无法继续完成任务请告知用户。”);}else{// 非关键工具失败降级返回Agent可以继续用其他方式回答returnToolResult.fail(”工具[” function.getName() ”]执行失败: ” errorMsg ”可以尝试用其他方式回答用户问题或告知用户该功能暂时不可用。”);}}//内部类public static class ToolResult{private boolean success;private String data;public static ToolResult success(String data){ToolResult rnew ToolResult();r.successtrue;r.datadata;returnr;}public static ToolResult fail(String error){ToolResult rnew ToolResult();r.successfalse;r.dataerror;returnr;}public booleanisSuccess(){returnsuccess;}public StringgetData(){returndata;}}private static class ValidationResult{private boolean valid;private String errorMsg;public static ValidationResultok(){ValidationResult rnew ValidationResult();r.validtrue;returnr;}public static ValidationResult fail(String msg){ValidationResult rnew ValidationResult();r.validfalse;r.errorMsgmsg;returnr;}public booleanisValid(){returnvalid;}public StringgetErrorMsg(){returnerrorMsg;}}}这个执行器包含了5个生产级细节参数校验大模型传错参数时返回明确的错误信息正确格式大模型会自动修正重试超时控制每个工具独立超时用Future.get()实现避免工具卡死拖垮Agent失败重试可重试异常超时、网络错误自动重试参数错误不重试结果截断工具结果超过2000字符自动截断防止Token爆炸关键/非关键降级关键工具失败终止任务非关键工具失败降级Agent继续用其他方式回答三、工具注册中心支持注解自动注册package com.aiproject.agent.function; import lombok.extern.slf4j.Slf4j;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;import org.springframework.stereotype.Component; import java.lang.reflect.Method;import java.util.Map;import java.util.concurrent.ConcurrentHashMap; / * 工具注册中心 * 扫描所有FunctionTool注解的方法自动注册 */Slf4jComponentpublic class FunctionRegistry implements BeanPostProcessor { private final Map functions new ConcurrentHashMap(); Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { for (Method method : bean.getClass().getMethods()) { FunctionTool annotation method.getAnnotation(FunctionTool.class); if (annotation ! null) { register(annotation.name(), annotation.description(), annotation.parameters(), annotation, bean, method); log.info(”注册Agent工具: {} - {}”, annotation.name(), annotation.description()); } } return bean; } private void register(String name, String description, String parameters, FunctionTool annotation, Object instance, Method method) { if (functions.containsKey(name)) { log.warn(”工具名重复: {}将被覆盖”, name); } functions.put(name, new FunctionMethod(name, description, parameters, annotation, instance, method)); } public FunctionMethod get(String name) { return functions.get(name); } public Map getAll() { return functions; } / * 获取所有工具定义转为大模型需要的格式 */ public java.util.List getToolDefinitions() { java.util.List list new java.util.ArrayList(); for (FunctionMethod fm : functions.values()) { com.alibaba.fastjson.JSONObject tool new com.alibaba.fastjson.JSONObject(); tool.put(”type”, ”function”); com.alibaba.fastjson.JSONObject function new com.alibaba.fastjson.JSONObject(); function.put(”name”, fm.name); function.put(”description”, fm.description); function.put(”parameters”, com.alibaba.fastjson.JSON.parseObject(fm.parameters)); tool.put(”function”, function); list.add(tool); } return list; } public static class FunctionMethod { String name; String description; String parameters; FunctionTool annotation; Object instance; Method method; public FunctionMethod(String name, String description, String parameters, FunctionTool annotation, Object instance, Method method) { this.name name; this.description description; this.parameters parameters; this.annotation annotation; this.instance instance; this.method method; } public String getName() { return name; } public String getParameters() { return parameters; } public FunctionTool getAnnotation() { return annotation; } public Method getMethod() { return method; } public Object getInstance() { return instance; } }}四、一个生产级工具示例知识库检索工具光有框架不够看一个真实的生产级工具怎么写package com.aiproject.agent.tools; import com.aiproject.agent.function.FunctionTool;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Component; import javax.annotation.Resource;import java.util.List; / * 知识库检索工具 * 生产级实现参数校验、结果格式化、异常处理 */Slf4jComponentpublic class KnowledgeBaseTool { Resource private VectorSearchService vectorSearchService; // 你的向量检索服务 / * 知识库检索 */ FunctionTool( name ”search_knowledge_base”, description ”从企业知识库中检索相关文档片段用于回答用户的业务问题。” ”当用户询问公司制度、产品文档、技术规范等内部知识时使用此工具。”, parameters ””” { ”type”: ”object”, ”properties”: { ”query”: { ”type”: ”string”, ”description”: ”检索查询语句应该是具体的问题或关键词而不是泛泛的描述” }, ”top_k”: { ”type”: ”integer”, ”description”: ”返回最相关的文档数量默认3最多10”, ”default”: 3 } }, ”required”: [”query”] } ”””, timeoutMs 10000, // 检索10秒超时 maxRetry 1, // 检索失败重试1次 critical false // 非关键工具失败可降级 ) public String search(String argumentsJson) { try { JSONObject args JSON.parseObject(argumentsJson); String query args.getString(”query”); Integer topK args.getInteger(”top_k”); if (topK null || topK 1 || topK 10) topK 3; // 调用向量检索服务 List results vectorSearchService.search(query, topK); if (results null || results.isEmpty()) { return ”知识库中未找到与[” query ”]相关的内容请尝试换个关键词检索或告知用户知识库中暂无相关信息。”; } // 结果格式化编号内容方便大模型理解 StringBuilder sb new StringBuilder(); sb.append(”从知识库中检索到”).append(results.size()).append(”条相关内容/n”); for (int i 0; i results.size(); i) { sb.append(”【文档”).append(i 1).append(”】”).append(results.get(i)).append(”/n”); } return sb.toString(); } catch (Exception e) { log.error(”知识库检索异常”, e); throw new RuntimeException(”知识库检索异常: ” e.getMessage()); } }}五、Agent执行器集成Function Calling把工具执行器集成到Agent执行器中替换上一篇的简化版package com.aiproject.agent.core;importcom.aiproject.agent.function.FunctionExecutor;importcom.aiproject.agent.function.FunctionRegistry;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Component;importjavax.annotation.Resource;importjava.util.ArrayList;importjava.util.List;/ * Agent执行器生产级版 * 集成Function Calling完整流程工具调用→执行→结果回传→继续推理 */Slf4jComponentpublic class AgentExecutor{Resource private LLMClient llmClient;Resource private FunctionRegistry functionRegistry;Resource private FunctionExecutor functionExecutor;private static final int MAX_ITERATIONS10;public String execute(String userInput, String systemPrompt)throws Exception{List messagesnew ArrayList();messages.add(new LLMClient.ChatMessage(”system”, systemPrompt));messages.add(new LLMClient.ChatMessage(”user”, userInput));for(int iteration0;iterationMAX_ITERATIONS;iteration){//1. 大模型推理带工具定义 String responseJsonllmClient.chatWithTools(messages, functionRegistry.getToolDefinitions());JSONObject responseJSON.parseObject(responseJson);JSONObject messageresponse.getJSONArray(”choices”).getJSONObject(0).getJSONObject(”message”);//2. 判断是否有工具调用 JSONArray toolCallsmessage.getJSONArray(”tool_calls”);if(toolCallsnull||toolCalls.isEmpty()){String finalAnswermessage.getString(”content”);messages.add(new LLMClient.ChatMessage(”assistant”, finalAnswer));log.info(”Agent完成任务共{}轮推理”, iteration 1);returnfinalAnswer;}//3. 有工具调用加入assistant消息 messages.add(new LLMClient.ChatMessage(”assistant”, message.getString(”content”)));//4. 逐个执行工具调用for(int i0;itoolCalls.size();i){JSONObject toolCalltoolCalls.getJSONObject(i);String toolCallIdtoolCall.getString(”id”);JSONObjectfunctiontoolCall.getJSONObject(”function”);String toolNamefunction.getString(”name”);String argumentsfunction.getString(”arguments”);log.info(”Agent调用工具[{}]参数:{}”, toolName, arguments);// 使用生产级工具执行器 FunctionExecutor.ToolResult resultfunctionExecutor.execute(toolName, arguments);// 工具结果回传大模型 LLMClient.ChatMessage toolMsgnew LLMClient.ChatMessage(”tool”, result.getData());toolMsg.setTool_call_id(toolCallId);toolMsg.setName(toolName);messages.add(toolMsg);}//5. 回到循环大模型根据工具结果继续推理}return”抱歉任务复杂度超出处理能力已达到最大推理轮次请简化问题后重试。”;}}六、可写进简历的项目描述基于JavaSpringBoot设计并实现AI Agent的Function Calling工具调用框架支持注解式工具自动注册实现生产级工具执行器包含参数校验JSON Schema、超时控制独立线程池Future、失败重试可重试异常判断、结果截断防Token爆炸、关键/非关键工具降级5大机制集成大模型Function Calling协议支持多工具并行调用与结果回传单轮任务平均3次工具调用内完成已接入知识库检索、天气查询、代码执行等多个工具框架可扩展。如何学习大模型 AI 由于新岗位的生产效率要优于被取代岗位的生产效率所以实际上整个社会的生产效率是提升的。但是具体到个人只能说是“最先掌握AI的人将会比较晚掌握AI的人有竞争优势”。这句话放在计算机、互联网、移动互联网的开局时期都是一样的道理。我在一线科技企业深耕十二载见证过太多因技术卡位而跃迁的案例。那些率先拥抱 AI 的同事早已在效率与薪资上形成代际优势我意识到有很多经验和知识值得分享给大家也可以通过我们的能力和经验解答大家在大模型的学习中的很多困惑。我们整理出这套AI 大模型突围资料包✅ 从零到一的 AI 学习路径图✅ 大模型调优实战手册附医疗/金融等大厂真实案例✅ 百度/阿里专家闭门录播课✅ 大模型当下最新行业报告✅ 真实大厂面试真题✅ 2026 最新岗位需求图谱所有资料 ⚡️ 朋友们如果有需要《AI大模型入门进阶学习资源包》下方扫码获取~① 全套AI大模型应用开发视频教程包含提示工程、RAG、LangChain、Agent、模型微调与部署、DeepSeek等技术点② 大模型系统化学习路线作为学习AI大模型技术的新手方向至关重要。 正确的学习路线可以为你节省时间少走弯路方向不对努力白费。这里我给大家准备了一份最科学最系统的学习成长路线图和学习规划带你从零基础入门到精通③ 大模型学习书籍文档学习AI大模型离不开书籍文档我精选了一系列大模型技术的书籍和学习文档电子版它们由领域内的顶尖专家撰写内容全面、深入、详尽为你学习大模型提供坚实的理论基础。④ AI大模型最新行业报告2025最新行业报告针对不同行业的现状、趋势、问题、机会等进行系统地调研和评估以了解哪些行业更适合引入大模型的技术和应用以及在哪些方面可以发挥大模型的优势。⑤ 大模型项目实战配套源码学以致用在项目实战中检验和巩固你所学到的知识同时为你找工作就业和职业发展打下坚实的基础。⑥ 大模型大厂面试真题面试不仅是技术的较量更需要充分的准备。在你已经掌握了大模型技术之后就需要开始准备面试我精心整理了一份大模型面试题库涵盖当前面试中可能遇到的各种技术问题让你在面试中游刃有余。以上资料如何领取为什么大家都在学大模型最近科技巨头英特尔宣布裁员2万人传统岗位不断缩减但AI相关技术岗疯狂扩招有3-5年经验大厂薪资就能给到50K*20薪不出1年“有AI项目经验”将成为投递简历的门槛。风口之下与其像“温水煮青蛙”一样坐等被行业淘汰不如先人一步掌握AI大模型原理应用技术项目实操经验“顺风”翻盘这些资料真的有用吗这份资料由我和鲁为民博士(北京清华大学学士和美国加州理工学院博士)共同整理现任上海殷泊信息科技CEO其创立的MoPaaS云平台获Forrester全球’强劲表现者’认证服务航天科工、国家电网等1000企业以第一作者在IEEE Transactions发表论文50篇获NASA JPL火星探测系统强化学习专利等35项中美专利。本套AI大模型课程由清华大学-加州理工双料博士、吴文俊人工智能奖得主鲁为民教授领衔研发。资料内容涵盖了从入门到进阶的各类视频教程和实战项目无论你是小白还是有些技术基础的技术人员这份资料都绝对能帮助你提升薪资待遇转行大模型岗位。以上全套大模型资料如何领取