Hutool AI模块已经上线
<!-- 引入AI模块 -->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-ai</artifactId><version>5.8.40</version>
</dependency>
Hutool AI:Java生态的AI集成新范式
随着大模型技术的普及,Hutool在5.8.x版本中新增了hutool-ai模块,为开发者提供了简单易用的AI能力集成方案。
核心优势
多模型支持: 一套API调用多种AI服务,目前支持DeepSeek、豆包等主流大模型
开箱即用: 简单的Maven依赖引入即可使用,无需复杂配置
企业级支持: 源自Hutool生态,有稳定的社区维护和版本迭代
初始化AI客户端
/ 配置API密钥
AIConfig config = new BaseConfig();
config.setApiKey("你的API密钥");
config.setApiUrl("https://api.deepseek.com/v1");
config.setModel("deepseek-reasoner");
// 创建DeepSeek客户端
DeepSeekServiceImpl deepSeekService = new DeepSeekServiceImpl(config);
Hutool AI核心功能详解
文本生成功能
DeepSeekService是Hutool AI模块中专门对接DeepSeek大模型服务的接口,在基础AIService功能基础上扩展了DeepSeek特有的功能。
// 普通对话
String content = deepSeekService.chat("写一个疯狂星期五广告词");
System.out.println(content);// 流式对话(适合长内容实时输出)
deepSeekService.chat("写一篇关于AI的短文", new Consumer<String>() {@Overridepublic void accept(String chunk) {// 每次接收到部分响应时调用System.out.print(chunk);}
});
多模态能力(图片理解)
DoubaoService支持豆包特有的多模态功能,允许开发者进行图片理解等高级操作。
// 图片理解示例
String base64Image = "图片的Base64编码内容";
String answer = doubaoService.chatVision("图片上有些什么?", Arrays.asList(base64Image));
System.out.println(answer);
实用辅助功能
除了核心的AI能力,Hutool AI还提供了一些实用方法:
// 查询模型列表
String models = deepSeekService.models();
// 查询账户余额
String balance = deepSeekService.balance();
实战案例:传统HTTP调用 vs Hutool AI
为了更好理解Hutool AI的价值,我们对比下传统HTTP调用和Hutool AI的差异。
传统HTTP调用方式(使用Apache HttpClient)
// 繁琐的HTTP客户端配置和处理
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Authorization", "Bearer " + apiKey);
// 手动构建请求体
String json = "{\"question\": \"hello\"}";
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
HttpResponse res = client.execute(post);
String responseStr = EntityUtils.toString(res.getEntity(), "UTF-8");
使用Hutool AI后
// 一行代码完成AI对话
String answer = AIUtil.chat(config, "你的问题");
初始化 AI 客户端(以豆包为例):
// 配置API密钥
AIConfig config = new BaseConfig();
config.setApiKey("sk-");
config.setApiUrl("https://api.deepseek.com/v1");
config.setModel("deepseek-reasoner");// 创建deepseekAI客户端
DeepSeekServiceImpl baseAIService = new DeepSeekServiceImpl(config);
文本生成功能
DeepSeekService 是 Hutool AI 模块中专门对接 DeepSeek 大模型服务的接口,在基础 AIService 功能基础上扩展了 DeepSeek 特有的功能。
// 配置API密钥
AIConfig config = new BaseConfig();
config.setApiKey("sk-");
config.setApiUrl("https://api.deepseek.com/v1");
config.setModel("deepseek-reasoner");// 创建deepseekAI客户端
DeepSeekServiceImpl baseAIService = new DeepSeekServiceImpl(config);// 普通对话
String content = baseAIService.chat("写一个疯狂星期五广告词");// 流式对话
baseAIService.chat("写一个疯狂星期五广告词", s -> {System.out.println(s);
});// 查询模型列表
String models = baseAIService.models();
// 查询账户余额
String balance = baseAIService.balance();
图片理解
DoubaoService 是 Hutool AI 模块中对接豆包大模型服务的扩展接口,在基础 AIService 功能基础上提供了豆包特有的多模态和高级功能支持。
// 配置API密钥
AIConfig config = new BaseConfig();
config.setApiKey("sk-");
config.setApiUrl("https://api.deepseek.com/v1");
config.setModel("deepseek-reasoner");// 创建deepseekAI客户端
DoubaoServiceImpl baseAIService = new DoubaoServiceImpl(config);
String base64 = "xxx"; // 图片base64内容
String chatVision = baseAIService.chatVision("图片上有些什么?", Arrays.asList(base64));
视频生成
// 配置API密钥
AIConfig config = new BaseConfig();
config.setApiKey("sk-");
config.setApiUrl("https://api.deepseek.com/v1");
config.setModel("deepseek-reasoner");// 创建deepseekAI客户端
DoubaoServiceImpl baseAIService = new DoubaoServiceImpl(config);String videoTasks = baseAIService.videoTasks("生成一段动画视频,主角是神厨小福贵,一个厨艺精湛的小男孩。", "https://img2.baidu.com/xxxx");//查询视频生成任务信息
String videoTasksInfo = baseAIService.getVideoTasksInfo("任务id");
最简单的对话
// 配置DeepSeek模型var config = new AIConfigBuilder(ModelName.DEEPSEEK.getValue()).setApiKey("your-api-key").setModel("deepseek-chat") // 可选,设置具体模型.build();// 发起对话String response = AIUtil.chat(config, "用Java写一个冒泡排序"方法);System.out.println("AI回复: " + response);
多轮对话实践
var config = new AIConfigBuilder(ModelName.OPENAI.getValue()).setApiKey("your-openai-key").build();// 构建多轮对话消息List<Message> messages = new ArrayList<>();messages.add(new Message("system", "你是一个专业的Java开发助手"));messages.add(new Message("user", "如何优化Spring Boot应用的查询速度?"));messages.add(new Message("assistant", "可以通过配置优化"));messages.add(new Message("user", "说一下怎么优化,加缓存的方式"));String response = AIUtil.chat(config, messages);System.out.println("优化建议: " + response);
高级功能深度解析(流式响应处理)
var config = new AIConfigBuilder(ModelName.DEEPSEEK.getValue()).setApiKey("your-key").build();// 获取具体服务实例进行流式调用var deepSeekService = AIUtil.getDeepSeekService(config);deepSeekService.chat("解释Java虚拟机的内存模型", new Consumer<String>() {private final StringBuilder fullResponse = new StringBuilder();@Overridepublic void accept(String chunk) {System.out.print(chunk); // 实时输出fullResponse.append(chunk);if (chunk.contains("。") || chunk.contains("\n")) {System.out.flush();}}});// 等待流式响应完成try { Thread.sleep(5000); } catch (InterruptedException e) {}
视觉对话与多模态支持
var config = new AIConfigBuilder(ModelName.OPENAI.getValue()).setApiKey("your-openai-key").build();OpenaiService openaiService = AIUtil.getOpenAIService(config);// 视觉对话示例String response = openaiService.chatVision("描述这张图片中的内容",Arrays.asList("https://example.com/image.jpg"),"high" // 细节程度: high/low);System.out.println("图片描述: " + response);
智能客服系统集成(企业级配置管理)
private final AIService aiService;private final Setting config;public CustomerServiceAI() {// 从配置文件加载配置config = new Setting("ai-config.setting");this.aiService = AIUtil.getAIService(new AIConfigBuilder(config.get("model")).setApiKey(config.get("apiKey")).setApiUrl(config.get("apiUrl")).setTimeout(config.getInt("timeout", 30)).setReadTimeout(config.getInt("readTimeout", 60)).putAdditionalConfig("temperature", 0.7).putAdditionalConfig("max_tokens", 1000).build());}public String handleCustomerQuery(String query, String context) {String systemPrompt = "你是一个专业的客服助手,负责处理用户咨询。"+ "当前服务上下文: " + context+ "\n请用友好、专业的态度回应用户。";return aiService.chat(systemPrompt + "\n用户问题: " + query);}// 批量处理查询public void processBatchQueries(List<String> queries) {queries.parallelStream().forEach(query -> {try {String response = handleCustomerQuery(query, "常规咨询");System.out.println("Q: " + query + "\nA: " + response + "\n");} catch (Exception e) {System.err.println("处理查询失败: " + query + ", 错误: " + e.getMessage());}});}
配置示例(ai-config.setting)
# AI服务配置
model = deepseek
apiKey = sk-your-deepseek-key-here
apiUrl = https://api.deepseek.com/v1/chat/completions
timeout = 30
readTimeout = 60
# 高级参数
temperature = 0.7
max_tokens = 1000
top_p = 0.9
性能优化与最佳实践
public class OptimizedAIClient {private static final Map<String, AIService> servicePool = new ConcurrentHashMap<>();public static AIService getCachedService(String modelName, String apiKey) {String cacheKey = modelName + ":" + apiKey;return servicePool.computeIfAbsent(cacheKey, key -> {return AIUtil.getAIService(new AIConfigBuilder(modelName).setApiKey(apiKey).setTimeout(15) // 连接超时15秒.setReadTimeout(30) // 读取超时30秒.build());});}// 带重试机制的调用public static String callWithRetry(String prompt, int maxRetries) {for (int i = 0; i < maxRetries; i++) {try {AIService service = getCachedService(ModelName.DEEPSEEK.getValue(), "your-key");return service.chat(prompt);} catch (Exception e) {if (i == maxRetries - 1) throw e;try { Thread.sleep(1000 * (i + 1)); } catch (InterruptedException ie) {}}}throw new RuntimeException("所有重试尝试都失败了");}
}
错误处理与监控
import cn.hutool.ai.core.AIException;
import io.micrometer.core.instrument.Metrics;
import java.util.concurrent.TimeUnit;public class MonitoredAIService {private final AIService delegate;public MonitoredAIService(AIService delegate) {this.delegate = delegate;}public String chat(String prompt) {long startTime = System.nanoTime();try {String response = delegate.chat(prompt);long duration = System.nanoTime() - startTime;// 记录成功指标Metrics.timer("ai.request.duration").record(duration, TimeUnit.NANOSECONDS);Metrics.counter("ai.request.success").increment();return response;} catch (AIException e) {// 记录失败指标Metrics.counter("ai.request.failure").increment();Metrics.counter("ai.error." + e.getClass().getSimpleName()).increment();throw e;}}
}
Hutool AI模块通过统一接口设计,极大简化了多AI厂商的集成复杂度。关键优势包括:
接口统一化:一套API兼容主流AI服务
配置简单化:链式配置Builder模式,直观易用
功能全面化:支持流式响应、多模态、视觉对话等高级特性
企业级支持:连接池、监控、重试等生产环境特性