大家好我是Java1234_小锋老师最近更新《2027版本 LangChain4j 开发Java Agent 智能体 视频教程》专辑感谢大家支持。本课程主要介绍和讲解 LangChain4j 简介阿里云百炼大模型 平台接入Ollama简介以及安装和使用HelloWorld 实现日志配置集成SpringBootAi Service 使用对话与提示词工程(Prompt)结构化输出会话记忆工具调用(Function Calling)嵌入模型 与向量数据库RAG(检索增强生成)MCP(模型上下文协议)多模态支持视频教程课件源码打包下载链接https://pan.baidu.com/s/1o-zRfndo1HHrS_uFroOiCw?pwd1234提取码0000LangChain4j 开发Java Agent智能体- 工具调用(Function Calling)大模型本身只会「说话」。但有些任务它并不擅长——比如精确算术、查实时天气、查你自己的业务数据库。这时候就需要工具调用也叫Function Calling。需要特别强调的是LLM 本身并不能真正执行函数它只是在响应中表达调用特定工具的意图包括要调用哪个工具、传入什么参数真正的执行由开发者完成然后将结果返回给 LLM 继续生成回答。例如当用户问475695037565 的平方根是多少时LLM 本身的计算并不精确。但如果为它提供了squareRoot工具它会返回一个调用请求squareRoot(475695037565)框架执行后得到结果689706.486532LLM 再基于此给出精确答案。我们来看一个具体示例调用天气预报的工具类因为大模型是不知道某个城市今天的天气信息的所以我们可以定义一个工具类模拟来返回某个城市今天的天气信息。首先第一步定义Tool工具类WeatherToolpackagecom.java1234.tool;importdev.langchain4j.agent.tool.P;importdev.langchain4j.agent.tool.Tool;importorg.springframework.stereotype.Component;ComponentpublicclassWeatherTool{Tool(根据城市名称查询当前天气返回温度、天气现象、湿度、风力等)publicStringgetWeather(P(中国城市名称如北京、上海、成都)Stringcity){System.out.println(正在查询city);// 模拟逻辑if(北京.equals(city)){return北京天气温度25℃、天气晴转多云、湿度70%、风力3级;}elseif(上海.equals(city)){return上海天气温度28℃、天气晴转小雨、湿度60%、风力4级;}elseif(成都.equals(city)){return成都天气温度23℃、天气晴转小雨、湿度65%、风力3级;}return暂不支持该城市查询天气;}}再新建一个WeatherAssistantService, AI Service里tools属性指定工具weatherTool。packagecom.java1234.service;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.spring.AiService;importdev.langchain4j.service.spring.AiServiceWiringMode;AiService(wiringModeAiServiceWiringMode.EXPLICIT,// 手动指定接入模型 手动装配chatModelopenAiChatModel,// 指定模型tools{weatherTool}// 指定工具)publicinterfaceWeatherAssistantService{SystemMessage( 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据 再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。 )Stringchat(StringuserMessage);}再新建一个MyWeatherController,注入weatherAssistantService以及新建chat方法packagecom.java1234.controller;importcom.java1234.service.*;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;RestControllerRequestMapping(/weather)publicclassMyWeatherController{AutowiredprivateWeatherAssistantServiceweatherAssistantService;RequestMapping(/chat)publicStringchat(Stringquestion){returnweatherAssistantService.chat(question);}}我们来测试下先问下 北京的天气。http://localhost:8080/weather/chat?question北京今天天气如何控制台 输出的 日志2026-06-03T21:51:56.33208:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP request: - method: POST - url: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions - headers: [Authorization: Beare...bd], [User-Agent: langchain4j-openai], [Content-Type: application/json] - body: { model : qwen3.6-plus, messages : [ { role : system, content : 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据\n再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。\n }, { role : user, content : 北京今天天气怎么样 } ], temperature : 0.7, stream : false, tools : [ { type : function, function : { name : getWeather, description : 根据城市名称查询当前天气返回温度、天气现象、湿度、风力等, parameters : { type : object, properties : { city : { type : string, description : 中国城市名称如北京、上海、成都 } }, required : [ city ] } } } ] } 2026-06-03T21:52:02.90208:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP response: - status code: 200 - headers: [x-request-id: 10db1b3a-3e0d-9a07-9a75-8a4af711ab00], [date: Wed, 03 Jun 2026 13:52:03 GMT], [x-dashscope-call-gateway: true], [server: istio-envoy], [x-envoy-upstream-service-time: 4231], [transfer-encoding: chunked], [vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding], [content-type: application/json], [req-arrive-time: 1780494719522], [req-cost-time: 4238], [resp-start-time: 1780494723760] - body: {choices:[{message:{content:,reasoning_content:Thinking Process:\n1. **Identify User Intent**: The user is asking for the current weather in Beijing (\北京今天天气怎么样\).\n2. **Identify Available Tools**: I have access to getWeather(city).\n3. **Check Parameters**: The tool requires a city parameter. The user provided \北京\.\n4. **Construct Tool Call**: Call getWeather with city\北京\.\n5. **Formulate Response**: Once I get the result (simulated or actual), I will format it concisely in Chinese as requested by the system prompt.\n\n*Self-Correction/Safety Check*: The system prompt explicitly states: \User asks for weather - MUST call getWeather - Answer in Chinese concisely - DO NOT fabricate numbers.\\n\nAction: Call getWeather(city\北京\).,role:assistant,tool_calls:[{function:{arguments:{\city\: \北京\},name:getWeather},id:call_c5c9997f6e744444b03c3208,index:0,type:function}]},finish_reason:tool_calls,index:0,logprobs:null}],object:chat.completion,usage:{prompt_tokens:342,completion_tokens:212,total_tokens:554,completion_tokens_details:{reasoning_tokens:182,text_tokens:212},prompt_tokens_details:{text_tokens:342}},created:1780494724,system_fingerprint:null,model:qwen3.6-plus,id:chatcmpl-10db1b3a-3e0d-9a07-9a75-8a4af711ab00} 正在查询北京 2026-06-03T21:52:02.92808:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP request: - method: POST - url: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions - headers: [Authorization: Beare...bd], [User-Agent: langchain4j-openai], [Content-Type: application/json] - body: { model : qwen3.6-plus, messages : [ { role : system, content : 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据\n再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。\n }, { role : user, content : 北京今天天气怎么样 }, { role : assistant, tool_calls : [ { id : call_c5c9997f6e744444b03c3208, type : function, function : { name : getWeather, arguments : {\city\: \北京\} } } ] }, { role : tool, tool_call_id : call_c5c9997f6e744444b03c3208, content : 北京天气温度25℃、天气晴转多云、湿度70%、风力3级 } ], temperature : 0.7, stream : false, tools : [ { type : function, function : { name : getWeather, description : 根据城市名称查询当前天气返回温度、天气现象、湿度、风力等, parameters : { type : object, properties : { city : { type : string, description : 中国城市名称如北京、上海、成都 } }, required : [ city ] } } } ] } 2026-06-03T21:52:05.57308:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP response: - status code: 200 - headers: [x-request-id: b485a4e2-6fba-919d-98c3-ab94c9d89749], [date: Wed, 03 Jun 2026 13:52:06 GMT], [x-dashscope-call-gateway: true], [server: istio-envoy], [x-envoy-upstream-service-time: 2604], [transfer-encoding: chunked], [vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding], [content-type: application/json], [req-arrive-time: 1780494723849], [req-cost-time: 2605], [resp-start-time: 1780494726455] - body: {choices:[{message:{content:北京今天天气晴转多云温度25℃湿度70%风力3级。,reasoning_content:用户询问北京天气已调用getWeather工具获取数据。\n返回结果为温度25℃、天气晴转多云、湿度70%、风力3级。\n根据指示需要用中文简洁回答不要编造数据。\n\n构建回答\n北京今天天气晴转多云温度25℃湿度70%风力3级。,role:assistant},finish_reason:stop,index:0,logprobs:null}],object:chat.completion,usage:{prompt_tokens:406,completion_tokens:100,total_tokens:506,completion_tokens_details:{reasoning_tokens:75,text_tokens:100},prompt_tokens_details:{text_tokens:406}},created:1780494726,system_fingerprint:null,model:qwen3.6-plus,id:chatcmpl-b485a4e2-6fba-919d-98c3-ab94c9d89749}我们可以看到第一次请求的时候工具信息都一并作为提示词发送给大模型。langchaing4j框架调用本地工具weather工具得到 北京城市的天气信息后也一并作为提示词再次去请求大模型。最终大模型第二次返回的结果才是到业务逻辑层最终返回到前端页面。下面是这个项目执行的具体原理图非常重要大家一起好好学习下。我们还可以再测试下上海天气如何http://localhost:8080/weather/chat?question上海今天天气如何
LangChain4j 开发Java Agent智能体- 工具调用(Function Calling)
发布时间:2026/6/8 0:11:57
大家好我是Java1234_小锋老师最近更新《2027版本 LangChain4j 开发Java Agent 智能体 视频教程》专辑感谢大家支持。本课程主要介绍和讲解 LangChain4j 简介阿里云百炼大模型 平台接入Ollama简介以及安装和使用HelloWorld 实现日志配置集成SpringBootAi Service 使用对话与提示词工程(Prompt)结构化输出会话记忆工具调用(Function Calling)嵌入模型 与向量数据库RAG(检索增强生成)MCP(模型上下文协议)多模态支持视频教程课件源码打包下载链接https://pan.baidu.com/s/1o-zRfndo1HHrS_uFroOiCw?pwd1234提取码0000LangChain4j 开发Java Agent智能体- 工具调用(Function Calling)大模型本身只会「说话」。但有些任务它并不擅长——比如精确算术、查实时天气、查你自己的业务数据库。这时候就需要工具调用也叫Function Calling。需要特别强调的是LLM 本身并不能真正执行函数它只是在响应中表达调用特定工具的意图包括要调用哪个工具、传入什么参数真正的执行由开发者完成然后将结果返回给 LLM 继续生成回答。例如当用户问475695037565 的平方根是多少时LLM 本身的计算并不精确。但如果为它提供了squareRoot工具它会返回一个调用请求squareRoot(475695037565)框架执行后得到结果689706.486532LLM 再基于此给出精确答案。我们来看一个具体示例调用天气预报的工具类因为大模型是不知道某个城市今天的天气信息的所以我们可以定义一个工具类模拟来返回某个城市今天的天气信息。首先第一步定义Tool工具类WeatherToolpackagecom.java1234.tool;importdev.langchain4j.agent.tool.P;importdev.langchain4j.agent.tool.Tool;importorg.springframework.stereotype.Component;ComponentpublicclassWeatherTool{Tool(根据城市名称查询当前天气返回温度、天气现象、湿度、风力等)publicStringgetWeather(P(中国城市名称如北京、上海、成都)Stringcity){System.out.println(正在查询city);// 模拟逻辑if(北京.equals(city)){return北京天气温度25℃、天气晴转多云、湿度70%、风力3级;}elseif(上海.equals(city)){return上海天气温度28℃、天气晴转小雨、湿度60%、风力4级;}elseif(成都.equals(city)){return成都天气温度23℃、天气晴转小雨、湿度65%、风力3级;}return暂不支持该城市查询天气;}}再新建一个WeatherAssistantService, AI Service里tools属性指定工具weatherTool。packagecom.java1234.service;importdev.langchain4j.service.SystemMessage;importdev.langchain4j.service.spring.AiService;importdev.langchain4j.service.spring.AiServiceWiringMode;AiService(wiringModeAiServiceWiringMode.EXPLICIT,// 手动指定接入模型 手动装配chatModelopenAiChatModel,// 指定模型tools{weatherTool}// 指定工具)publicinterfaceWeatherAssistantService{SystemMessage( 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据 再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。 )Stringchat(StringuserMessage);}再新建一个MyWeatherController,注入weatherAssistantService以及新建chat方法packagecom.java1234.controller;importcom.java1234.service.*;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;RestControllerRequestMapping(/weather)publicclassMyWeatherController{AutowiredprivateWeatherAssistantServiceweatherAssistantService;RequestMapping(/chat)publicStringchat(Stringquestion){returnweatherAssistantService.chat(question);}}我们来测试下先问下 北京的天气。http://localhost:8080/weather/chat?question北京今天天气如何控制台 输出的 日志2026-06-03T21:51:56.33208:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP request: - method: POST - url: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions - headers: [Authorization: Beare...bd], [User-Agent: langchain4j-openai], [Content-Type: application/json] - body: { model : qwen3.6-plus, messages : [ { role : system, content : 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据\n再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。\n }, { role : user, content : 北京今天天气怎么样 } ], temperature : 0.7, stream : false, tools : [ { type : function, function : { name : getWeather, description : 根据城市名称查询当前天气返回温度、天气现象、湿度、风力等, parameters : { type : object, properties : { city : { type : string, description : 中国城市名称如北京、上海、成都 } }, required : [ city ] } } } ] } 2026-06-03T21:52:02.90208:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP response: - status code: 200 - headers: [x-request-id: 10db1b3a-3e0d-9a07-9a75-8a4af711ab00], [date: Wed, 03 Jun 2026 13:52:03 GMT], [x-dashscope-call-gateway: true], [server: istio-envoy], [x-envoy-upstream-service-time: 4231], [transfer-encoding: chunked], [vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding], [content-type: application/json], [req-arrive-time: 1780494719522], [req-cost-time: 4238], [resp-start-time: 1780494723760] - body: {choices:[{message:{content:,reasoning_content:Thinking Process:\n1. **Identify User Intent**: The user is asking for the current weather in Beijing (\北京今天天气怎么样\).\n2. **Identify Available Tools**: I have access to getWeather(city).\n3. **Check Parameters**: The tool requires a city parameter. The user provided \北京\.\n4. **Construct Tool Call**: Call getWeather with city\北京\.\n5. **Formulate Response**: Once I get the result (simulated or actual), I will format it concisely in Chinese as requested by the system prompt.\n\n*Self-Correction/Safety Check*: The system prompt explicitly states: \User asks for weather - MUST call getWeather - Answer in Chinese concisely - DO NOT fabricate numbers.\\n\nAction: Call getWeather(city\北京\).,role:assistant,tool_calls:[{function:{arguments:{\city\: \北京\},name:getWeather},id:call_c5c9997f6e744444b03c3208,index:0,type:function}]},finish_reason:tool_calls,index:0,logprobs:null}],object:chat.completion,usage:{prompt_tokens:342,completion_tokens:212,total_tokens:554,completion_tokens_details:{reasoning_tokens:182,text_tokens:212},prompt_tokens_details:{text_tokens:342}},created:1780494724,system_fingerprint:null,model:qwen3.6-plus,id:chatcmpl-10db1b3a-3e0d-9a07-9a75-8a4af711ab00} 正在查询北京 2026-06-03T21:52:02.92808:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP request: - method: POST - url: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions - headers: [Authorization: Beare...bd], [User-Agent: langchain4j-openai], [Content-Type: application/json] - body: { model : qwen3.6-plus, messages : [ { role : system, content : 你是天气助手。用户询问某地天气时必须调用 getWeather 工具获取数据\n再基于工具返回结果用中文简洁回答不要编造未在工具结果中出现的数值。\n }, { role : user, content : 北京今天天气怎么样 }, { role : assistant, tool_calls : [ { id : call_c5c9997f6e744444b03c3208, type : function, function : { name : getWeather, arguments : {\city\: \北京\} } } ] }, { role : tool, tool_call_id : call_c5c9997f6e744444b03c3208, content : 北京天气温度25℃、天气晴转多云、湿度70%、风力3级 } ], temperature : 0.7, stream : false, tools : [ { type : function, function : { name : getWeather, description : 根据城市名称查询当前天气返回温度、天气现象、湿度、风力等, parameters : { type : object, properties : { city : { type : string, description : 中国城市名称如北京、上海、成都 } }, required : [ city ] } } } ] } 2026-06-03T21:52:05.57308:00 INFO 49784 --- [nio-8080-exec-4] d.l.http.client.log.LoggingHttpClient : HTTP response: - status code: 200 - headers: [x-request-id: b485a4e2-6fba-919d-98c3-ab94c9d89749], [date: Wed, 03 Jun 2026 13:52:06 GMT], [x-dashscope-call-gateway: true], [server: istio-envoy], [x-envoy-upstream-service-time: 2604], [transfer-encoding: chunked], [vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers, Accept-Encoding], [content-type: application/json], [req-arrive-time: 1780494723849], [req-cost-time: 2605], [resp-start-time: 1780494726455] - body: {choices:[{message:{content:北京今天天气晴转多云温度25℃湿度70%风力3级。,reasoning_content:用户询问北京天气已调用getWeather工具获取数据。\n返回结果为温度25℃、天气晴转多云、湿度70%、风力3级。\n根据指示需要用中文简洁回答不要编造数据。\n\n构建回答\n北京今天天气晴转多云温度25℃湿度70%风力3级。,role:assistant},finish_reason:stop,index:0,logprobs:null}],object:chat.completion,usage:{prompt_tokens:406,completion_tokens:100,total_tokens:506,completion_tokens_details:{reasoning_tokens:75,text_tokens:100},prompt_tokens_details:{text_tokens:406}},created:1780494726,system_fingerprint:null,model:qwen3.6-plus,id:chatcmpl-b485a4e2-6fba-919d-98c3-ab94c9d89749}我们可以看到第一次请求的时候工具信息都一并作为提示词发送给大模型。langchaing4j框架调用本地工具weather工具得到 北京城市的天气信息后也一并作为提示词再次去请求大模型。最终大模型第二次返回的结果才是到业务逻辑层最终返回到前端页面。下面是这个项目执行的具体原理图非常重要大家一起好好学习下。我们还可以再测试下上海天气如何http://localhost:8080/weather/chat?question上海今天天气如何