赞
踩
Spring AI来了,Java生态接入LLM大模型变得更加简单!
今天官宣Spring AI已经上架到Spring Initializr 上,它提供了一种更简洁的方式和AI交互,减轻Java业务中接入LLM模型应用的学习成本,目前在 https://start.spring.io/ 上可以使用并构建。
Spring AI 是一个人工智能工程的应用框架。其目标是将 Spring 生态系统设计原则(例如可移植性和模块化设计)应用于 AI 领域,并推广使用 POJO 作为 AI 领域应用程序的构建块。
跨 AI 提供商的便携式 API 支持聊天、文本到图像和嵌入模型。支持同步和流 API 选项。还支持配置参数访问特定Model。
支持的聊天模型
支持的文生图模型
支持的向量模型
官方文档:https://spring.io/projects/spring-ai#overview
使用IDEA快速新建项目,选择要使用的AI模型依赖
这里我以ollama模型为例
Ollama帮助我们在本地的电脑上无需GPU(显卡)资源,也能一键构建大模型,并且提供控制台、RestfulAPI方式快速测试和接入Ollama上的大模型。
Ollama支持哪些模型?
Ollama官网:https://ollama.com/library
Tips:
**Tips:**Spring AI的相关依赖并没有开放在Meven中央仓库,因此需要配置Spring的仓库
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-ollama-spring-boot-starter</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>${spring-ai.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
在本地电脑控制台运行ollama run gemma:2b
(这里使用gemma模型)
第一次运行会先下载模型文件(大概3G,会比较耗时)
下载完模型资源后会自动启动模型,如上,可以在控制台测试和模型交互。
修改此项目的application.yml
配置文件,增加如下:
spring:
ai:
ollama:
## 默认地址无需配置
base-url: http://localhost:11434
chat:
model: gemma:2b
@SpringBootTest
class SpringAiApplicationTests {
@Autowired
private OllamaChatClient chatClient;
@Test
void contextLoads() {
String message = """
鲁迅和周树人是什么关系?
""";
System.out.println(chatClient.call(message));
}
}
@Test void streamChat() throws ExecutionException, InterruptedException { // 构建一个异步函数,实现手动关闭测试函数 CompletableFuture<Void> future = new CompletableFuture<>(); String message = """ 年终总结 """; PromptTemplate promptTemplate = new PromptTemplate(""" 你是一个Java开发工程师,你擅长于写公司年底的工作总结报告, 根据:{message} 场景写100字的总结报告 """); Prompt prompt = promptTemplate.create(Map.of("message", message)); chatClient.stream(prompt).subscribe( chatResponse -> { System.out.println("response: " + chatResponse.getResult().getOutput().getContent()); }, throwable -> { System.err.println("err: " + throwable.getMessage()); }, () -> { System.out.println("complete~!"); // 关闭函数 future.complete(null); } ); future.get(); }
示例代码: https://github.com/TyCoding/spring-ai
更多的应用示例关注后续文章哦!
微信群
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。