当前位置: 首页 > news >正文

AI Tool Calling 实战——让 LLM 控制 Java 工具

在这里插入图片描述

目录

  • 一、前言
  • 二、什么是 Tool Calling?
  • 三、項目示例
    • 1. 创建工具 Bean
    • 2. 启动配置
    • 3. 注入并使用 ToolCallingChatClient
    • 4. 发起调用
  • 四、背后机制解析
    • 1. 自动生成 Function Schema
    • 2. 调用流程
  • 五、进阶集成:
    • 多轮示例
  • 六、总结
  • 七、参考


一、前言

LLM(大语言模型)不只是聊天工具,而是可以调用后端服务、控制系统行为的智能体核心。

Spring AI 借助 Tool Specification 机制与函数调用能力,让 Java Bean 中的函数变成 LLM 可调的“工具”。

本篇将带你掌握:

  • 如何声明 Java 方法为可调用 Tool
  • 如何注册工具并被 LLM 自动发现
  • 如何结合上下文与多轮调用,构建智能任务执行系统

二、什么是 Tool Calling?

Tool Calling 是指:

LLM 在对话过程中,自动选择调用某些外部工具(函数、API、数据库查询等),辅助完成任务。

在 Spring AI 中,只需使用 Spring Boot 3.4+ 与 spring-ai-openai-spring-boot-starter,就能快速构建支持 Tool Calling 的服务。

三、項目示例

这里我们实战构建 IT 助手 Agent

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>spring-ai-tool-calling-demo</artifactId><version>1.0.0</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.3</version></parent><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai</artifactId><version>1.0.0-SNAPSHOT</version></dependency></dependencies>
</project>

1. 创建工具 Bean

package com.example.toolai;import org.springframework.ai.function.annotation.AiFunction;
import org.springframework.ai.function.annotation.AiParam;
import org.springframework.stereotype.Component;@Component
public class ToolFunctions {@AiFunctionpublic Integer add(@AiParam("a") Integer a, @AiParam("b") Integer b) {return a + b;}@AiFunctionpublic String weather(@AiParam("city") String city) {return city + ": 30°C 晴天";}
}

2. 启动配置

application.yml 中加入配置:

spring:ai:openai:api-key: sk-xxxchat:options:model: gpt-4o

3. 注入并使用 ToolCallingChatClient

@Autowired
ToolFunctions tools;@Autowired
OpenAiChatClient baseClient;FunctionCallingChatClient chatClient = new FunctionCallingChatClient(baseClient, List.of(tools));

4. 发起调用


package com.example.toolai;import org.springframework.ai.chat.client.*;
import org.springframework.ai.chat.memory.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.List;@SpringBootApplication
public class ToolCallingApp {public static void main(String[] args) {SpringApplication.run(ToolCallingApp.class, args);}@Beanpublic CommandLineRunner run(OpenAiChatClient baseClient, ToolFunctions tool, ServerOps ops) {return args -> {ChatMemory memory = new InMemoryChatMemory("session-001");FunctionCallingChatClient chatClient = new FunctionCallingChatClient(baseClient, List.of(tool, ops), memory);String userInput = "请问北京的天气是多少度?";ChatResponse response = chatClient.call(userInput);System.out.println("🧠 Response: " + response.getResult().getOutput().getContent());userInput = "那我明天适合跑步吗?";response = chatClient.call(userInput);System.out.println("🧠 Response: " + response.getResult().getOutput().getContent());userInput = "重启一下 CRM 服务";response = chatClient.call(userInput);System.out.println("🧠 Response: " + response.getResult().getOutput().getContent());};}
}

LLM 会自动根据描述调用 weather(city="北京")


四、背后机制解析

1. 自动生成 Function Schema

每个 @AiFunction 都会自动转换为 JSON 格式的 OpenAI 工具定义:

{"type": "function","function": {"name": "add","parameters": {"type": "object","properties": {"a": {"type": "integer"},"b": {"type": "integer"}},"required": ["a", "b"]}}
}

2. 调用流程

在这里插入图片描述


五、进阶集成:

可以结合 Memory 实现上下文追踪

Spring AI 提供 ChatMemory 接口,可保存历史上下文,如下例所示。

ChatMemory memory = new InMemoryChatMemory("session-001");
FunctionCallingChatClient chatClient = new FunctionCallingChatClient(baseClient, List.of(tools), memory);

多轮示例

用户:北京天气如何?

用户:那我明天适合跑步吗?(使用上轮结果)


六、总结

通过 Tool Calling,Spring AI 让你只用一个注解,就能将本地方法暴露为 LLM 的智能工具。

企业可以基于此快速构建数据接口封装、流程驱动服务、自动化运维系统等。

七、参考

《Java驱动AI革命:Spring AI八篇进阶指南——从架构基础到企业级智能系统实战》
在这里插入图片描述

http://www.dtcms.com/a/268632.html

相关文章:

  • java-Milvus 连接池(多key)与自定义端点监听设计
  • C++开源项目—2048.cpp
  • 部署MongoDB
  • 接口漏洞怎么抓?Fiddler 中文版 + Postman + Wireshark 实战指南
  • 记录一个关于Maven配置TSF的报错问题
  • 基于 Three.js 开发三维引擎-02动态圆柱墙体实现
  • Python中50个常用的内置函数(2/2)
  • 剑指offer第2版:动态规划+记忆化搜索
  • 回溯题解——子集【LeetCode】输入的视角(选或不选)
  • YOLOv11模型轻量化挑战:边缘计算设备部署优化方案
  • FastAPI依赖注入:构建高可维护API的核心理念与实战
  • Modbus_TCP 客户端低版本指令(归档)
  • Hadoop 分布式存储与计算框架详解
  • Web后端开发-请求响应
  • NLP:文本特征处理和回译数据增强法
  • Mac-右键用 VS Code 打开文件夹
  • 【Echarts】“折线+柱状”实现双图表-家庭用电量可视化【文章附完整代码】
  • 泛微虚拟视图-数据虚拟化集成
  • 从库函数到API接口,深挖不同语言背后的“封装”与“调用”思想
  • pytest通过pytest_runtest_makereport添加失败截图到Allure报告中
  • 常见问题与最佳实践——AI教你学Docker
  • 1-Kafka介绍及常见应用场景
  • 学习基于springboot秒杀系统-环境配置(接口封装,mybatis,mysql,redis(Linux))
  • 2025年全国青少年信息素养大赛图形化(Scratch)编程小学低年级组初赛样题答案+解析
  • 登山第二十六梯:单目3D检测一切——一只眼看世界
  • 【C++开源库使用】使用libcurl开源库发送url请求(http请求)去下载用户头像文件(附完整源码)
  • 【R语言】 在读取 CSV 或 Excel 文件时的标准输出
  • 自定义简单线性回归模型
  • 【AI大模型】神经网络反向传播:核心原理与完整实现
  • 电脑电压过高的影响与风险分析