Spring AI来了,Java生态接入LLM大模型变得更加简单!

SpringAI

今天官宣Spring AI已经上架到Spring Initializr 上,它提供了一种更简洁的方式和AI交互,减轻Java业务中接入LLM模型应用的学习成本,目前在 https://start.spring.io/ 上可以使用并构建。

Spring AI 是一个人工智能工程的应用框架。其目标是将 Spring 生态系统设计原则(例如可移植性和模块化设计)应用于 AI 领域,并推广使用 POJO 作为 AI 领域应用程序的构建块。

Features

跨 AI 提供商的便携式 API 支持聊天、文本到图像和嵌入模型。支持同步和流 API 选项。还支持配置参数访问特定Model。

支持的聊天模型

OpenAIAzure Open AIAmazon Bedrock

Anthropic’s ClaudeCohere’s CommandAI21 Labs’ Jurassic-2Meta’s LLama 2Amazon’s Titan Google Vertex AIHuggingFace - HuggingFace上的大量模型,例如Llama2Ollama - 支持本地无GPU情况下运行AI模型

支持的文生图模型

OpenAI with DALL-EStabilityAI

支持的向量模型

OpenAIAzure OpenAIOllamaONNXPostgresMLBedrock CohereBedrock TitanGoogle VertexAI

官方文档:https://spring.io/projects/spring-ai#overview

快速开始

使用IDEA快速新建项目,选择要使用的AI模型依赖

这里我以ollama模型为例

Ollama

Ollama帮助我们在本地的电脑上无需GPU(显卡)资源,也能一键构建大模型,并且提供控制台、RestfulAPI方式快速测试和接入Ollama上的大模型。

Ollama支持哪些模型?

Ollama官网:https://ollama.com/library

Tips:

其中gemma就是谷歌Meta近期新发布的模型llama2模型基本不支持中文语言,gemma模型对中文支持比较友好

引入依赖

**Tips:**Spring AI的相关依赖并没有开放在Meven中央仓库,因此需要配置Spring的仓库

org.springframework.boot

spring-boot-starter-web

org.springframework.ai

spring-ai-ollama-spring-boot-starter

org.springframework.ai

spring-ai-bom

${spring-ai.version}

pom

import

启动Ollama模型

在本地电脑控制台运行ollama run gemma:2b(这里使用gemma模型)

第一次运行会先下载模型文件(大概3G,会比较耗时)

下载完模型资源后会自动启动模型,如上,可以在控制台测试和模型交互。

配置Ollama模型

修改此项目的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 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

更多的应用示例关注后续文章哦!

推荐项目

https://github.com/TyCoding/lang-sora React NextJS全栈快速构建Sora AI Video演示项目

合作和联系

个人博客:http://tycoding.cnGitHub:https://github.com/tycoding微信公众号:程序员涂陌微信交流群:公众号后台回复:微信群

精彩文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: