Spring AI + ollama 本地搭建聊天 AI

不知道怎么搭建 ollama 的可以查看上一篇Spring AI 初学

项目可以查看gitee

前期准备

添加依赖

创建 SpringBoot 项目,添加主要相关依赖(spring-boot-starter-web、spring-ai-ollama-spring-boot-starter)

Spring AI supports Spring Boot 3.2.x and 3.3.x

Spring Boot 3.2.11 requires at least Java 17 and is compatible with versions up to and including Java 23

<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>
<version>1.0.0-M3</version>
</dependency>

配置文件

application.properties、yml配置文件中添加,也可以在项目中指定模型等参数,具体参数可以参考 OllamaChatProperties

# properties,模型 qwen2.5:14b 根据自己下载的模型而定
spring.ai.ollama.chat.options.model=qwen2.5:14b #yml
spring:
ai:
ollama:
chat:
model: qwen2.5:14b

聊天实现

主要使用 org.springframework.ai.chat.memory.ChatMemory 接口保存对话信息。

一、采用 Java 缓存对话信息

支持功能:聊天对话、切换对话、删除对话

controller
import com.yb.chatai.domain.ChatParam;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import java.util.UUID; /*
*@title Controller
*@description 使用内存进行对话
*@author yb
*@version 1.0
*@create 2024/11/12 14:39
*/
@Controller
public class ChatController { //注入模型,配置文件中的模型,或者可以在方法中指定模型
@Resource
private OllamaChatModel model; //聊天 client
private ChatClient chatClient; // 模拟数据库存储会话和消息
private final ChatMemory chatMemory = new InMemoryChatMemory(); //首页
@GetMapping("/index")
public String index(){
return "index";
} //开始聊天,生成唯一 sessionId
@GetMapping("/start")
public String start(Model model){
//新建聊天模型
// OllamaOptions options = OllamaOptions.builder();
// options.setModel("qwen2.5:14b");
// OllamaChatModel chatModel = new OllamaChatModel(new OllamaApi(), options);
//创建随机会话 ID
String sessionId = UUID.randomUUID().toString();
model.addAttribute("sessionId", sessionId);
//创建聊天client
chatClient = ChatClient.builder(this.model).defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory, sessionId, 10)).build();
return "chatPage";
} //聊天
@PostMapping("/chat")
@ResponseBody
public String chat(@RequestBody ChatParam param){
//直接返回
return chatClient.prompt(param.getUserMsg()).call().content();
} //删除聊天
@DeleteMapping("/clear/{id}")
@ResponseBody
public void clear(@PathVariable("id") String sessionId){
chatMemory.clear(sessionId);
} }
效果图

二、采用数据库保存对话信息

支持功能:聊天对话、切换对话、删除对话、撤回消息

实体类
import lombok.Data;

import java.util.Date;

@Data
public class ChatEntity { private String id; /** 会话id */
private String sessionId; /** 会话内容 */
private String content; /** AI、人 */
private String type; /** 创建时间 */
private Date time; /** 是否删除,Y-是 */
private String beDeleted; /** AI会话时,获取人对话ID */
private String userChatId; }
configuration
import com.yb.chatai.domain.ChatEntity;
import com.yb.chatai.service.IChatService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.context.annotation.Configuration; import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors; /*
*@title DBMemory
*@description 实现 ChatMemory,注入 spring,方便采用 service 方法
*@author yb
*@version 1.0
*@create 2024/11/12 16:15
*/
@Configuration
public class DBMemory implements ChatMemory { @Resource
private IChatService chatService; @Override
public void add(String conversationId, List<Message> messages) {
for (Message message : messages) {
chatService.saveMessage(conversationId, message.getContent(), message.getMessageType().getValue());
}
} @Override
public List<Message> get(String conversationId, int lastN) {
List<ChatEntity> list = chatService.getLastN(conversationId, lastN);
if(list != null && !list.isEmpty()) {
return list.stream().map(l -> {
Message message = null;
if (MessageType.ASSISTANT.getValue().equals(l.getType())) {
message = new AssistantMessage(l.getContent());
} else if (MessageType.USER.getValue().equals(l.getType())) {
message = new UserMessage(l.getContent());
}
return message;
}).collect(Collectors.<Message>toList());
}else {
return new ArrayList<>();
}
} @Override
public void clear(String conversationId) {
chatService.clear(conversationId);
}
}
services实现类
import com.yb.chatai.domain.ChatEntity;
import com.yb.chatai.service.IChatService;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.stereotype.Service; import java.util.*; /*
*@title ChatServiceImpl
*@description 保存用户会话 service 实现类
*@author yb
*@version 1.0
*@create 2024/11/12 15:50
*/
@Service
public class ChatServiceImpl implements IChatService { Map<String, List<ChatEntity>> map = new HashMap<>(); @Override
public void saveMessage(String sessionId, String content, String type) {
ChatEntity entity = new ChatEntity();
entity.setId(UUID.randomUUID().toString());
entity.setContent(content);
entity.setSessionId(sessionId);
entity.setType(type);
entity.setTime(new Date());
//改成常量
entity.setBeDeleted("N");
if(MessageType.ASSISTANT.getValue().equals(type)){
entity.setUserChatId(getLastN(sessionId, 1).get(0).getId());
}
//todo 保存数据库
//模拟保存到数据库
List<ChatEntity> list = map.getOrDefault(sessionId, new ArrayList<>());
list.add(entity);
map.put(sessionId, list);
} @Override
public List<ChatEntity> getLastN(String sessionId, Integer lastN) {
//todo 从数据库获取
//模拟从数据库获取
List<ChatEntity> list = map.get(sessionId);
return list != null ? list.stream().skip(Math.max(0, list.size() - lastN)).toList() : List.of();
} @Override
public void clear(String sessionId) {
//todo 数据库更新 beDeleted 字段
map.put(sessionId, new ArrayList<>());
} @Override
public void deleteById(String id) {
//todo 数据库直接将该 id 数据 beDeleted 改成 Y
for (Map.Entry<String, List<ChatEntity>> next : map.entrySet()) {
List<ChatEntity> list = next.getValue();
list.removeIf(chat -> id.equals(chat.getId()) || id.equals(chat.getUserChatId()));
}
}
}
controller
import com.yb.chatai.configuration.DBMemory;
import com.yb.chatai.domain.ChatEntity;
import com.yb.chatai.domain.ChatParam;
import com.yb.chatai.service.IChatService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*; import java.util.List;
import java.util.UUID; /*
*@title ChatController2
*@description 使用数据库(缓存)进行对话
*@author yb
*@version 1.0
*@create 2024/11/12 16:12
*/
@Controller
public class ChatController2 { //注入模型,配置文件中的模型,或者可以在方法中指定模型
@Resource
private OllamaChatModel model; //聊天 client
private ChatClient chatClient; //操作聊天信息service
@Resource
private IChatService chatService; //会话存储方式
@Resource
private DBMemory dbMemory; //开始聊天,生成唯一 sessionId
@GetMapping("/start2")
public String start(Model model){
//新建聊天模型
// OllamaOptions options = OllamaOptions.builder();
// options.setModel("qwen2.5:14b");
// OllamaChatModel chatModel = new OllamaChatModel(new OllamaApi(), options);
//创建随机会话 ID
String sessionId = UUID.randomUUID().toString();
model.addAttribute("sessionId", sessionId);
//创建聊天 client
chatClient = ChatClient.builder(this.model).defaultAdvisors(new MessageChatMemoryAdvisor(dbMemory, sessionId, 10)).build();
return "chatPage2";
} //切换会话,需要传入 sessionId
@GetMapping("/exchange2/{id}")
public String exchange(@PathVariable("id")String sessionId){
//切换聊天 client
chatClient = ChatClient.builder(this.model).defaultAdvisors(new MessageChatMemoryAdvisor(dbMemory, sessionId, 10)).build();
return "chatPage2";
} //聊天
@PostMapping("/chat2")
@ResponseBody
public List<ChatEntity> chat(@RequestBody ChatParam param){
//todo 判断 AI 是否返回会话,从而判断用户是否可以输入
chatClient.prompt(param.getUserMsg()).call().content();
//获取返回最新两条,一条用户问题(用户获取用户发送ID),一条 AI 返回结果
return chatService.getLastN(param.getSessionId(), 2);
} //撤回消息
@DeleteMapping("/revoke2/{id}")
@ResponseBody
public void revoke(@PathVariable("id") String id){
chatService.deleteById(id);
} //清空消息
@DeleteMapping("/del2/{id}")
@ResponseBody
public void clear(@PathVariable("id") String sessionId){
dbMemory.clear(sessionId);
} }
效果图

总结

主要实现 org.springframework.ai.chat.memory.ChatMemory 方法,实际项目过程需要实现该接口重写方法。

Spring AI + ollama 本地搭建聊天 AI的更多相关文章

  1. 实战!轻松搭建图像分类 AI 服务

    人工智能技术(以下称 AI)是人类优秀的发现和创造之一,它代表着至少几十年的未来.在传统的编程中,工程师将自己的想法和业务变成代码,计算机会根据代码设定的逻辑运行.与之不同的是,AI 使计算机有了「属 ...

  2. 云上快速搭建Serverless AI实验室

    Serverless Kubernetes和ACK虚拟节点都已基于ECI提供GPU容器实例功能,让用户在云上低成本快速搭建serverless AI实验室,用户无需维护服务器和GPU基础运行环境,极大 ...

  3. Spring MVC + jpa框架搭建,及全面分析

    一,hibernate与jpa的关系 首先明确一点jpa是什么?以前我就搞不清楚jpa和hibernate的关系. 1,JPA(Java Persistence API)是Sun官方提出的Java持久 ...

  4. 【译文】用Spring Cloud和Docker搭建微服务平台

    by Kenny Bastani Sunday, July 12, 2015 转自:http://www.kennybastani.com/2015/07/spring-cloud-docker-mi ...

  5. 手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

  6. spring cloud+dotnet core搭建微服务架构:配置中心(四)

    前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...

  7. Spring Cloud 入门教程 - 搭建配置中心服务

    简介 Spring Cloud 提供了一个部署微服务的平台,包括了微服务中常见的组件:配置中心服务, API网关,断路器,服务注册与发现,分布式追溯,OAuth2,消费者驱动合约等.我们不必先知道每个 ...

  8. spring cloud+.net core搭建微服务架构:服务注册(一)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

  9. spring cloud+.net core搭建微服务架构:配置中心(四)

    前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...

  10. Spring Cloud 5分钟搭建教程(附上一个分布式日志系统项目作为参考) - 推荐

    http://blog.csdn.net/lc0817/article/details/53266212/ https://github.com/leoChaoGlut/log-sys 上面是我基于S ...

随机推荐

  1. Linux下错误解决方案

    错误 "E: Unable to correct problems, you have held broken packages."这种问题包破坏问题,可能是由于镜像源与系统版本不 ...

  2. java_Web

    开始进入学习java web部分 一.Socket技术 字节流传输 使用bytes[] 封装字节进行传输数据 文件传输 浏览器访问 使用http协议进行访问 二.MySQL数据库 环境 Phpstyd ...

  3. 阿里云图床(PicGo+阿里云OSS)搭建

    阿里云图床搭建方法: 1.登录阿里云,搜索对象存储oss,新用户免费使用3个月20G,到期后,一年也就9元左右,还是很划算的. 2.在左侧列表里,点击Bucket列表,创建Bucket 3.Bucke ...

  4. LaTeX 编译 acmart 文档报错:An attempt to redefine \baselinestretch detected. Please do not do this for ACM submissions!

    在编译一篇从 arXiv 下载的文档时遇到如下错误: Class acmart Error: An attempt to redefine \baselinestretch detected. Ple ...

  5. 好多kafka难题啊,看看其中的化解之道

    文末有面经共享群 前面已经分享过几篇面试了,这是一篇关于更加面向项目和技术的面经详解,第一次遇见问那么多kafka的问题,看看这个粉丝是怎么回答的. 先来看看 职位描述: 岗位职责: 负责基于 Go ...

  6. uni-app 小程序用户信息之头像昵称填写

    小程序获取用户头像昵称,微信又叒做妖,废除之前的接口,改成了头像昵称填写 通知:微信小程序端基础库2.27.1及以上版本,wx.getUserProfile 接口被收回,详见<小程序用户头像昵称 ...

  7. 如何调用openai的TTS模型

    这是24年1月份写的了,调用代码大概率有变动,仅供参考. 1 什么是OpenAI的TTS模型 OpenAI的TTS模型是一种文本到语音(Text-to-Speech)模型,它可以将给定的文本转换为自然 ...

  8. c++实现几种常见排序算法

    一.快速排序 int getPivot(vector<int>& arr, int left, int right){ int tmp = arr[left]; while(lef ...

  9. Round #2022/12/10

    问题 D:城市大脑 题目描述 杜老师正在编写杭州城市大脑智能引擎.杭州的道路可以被抽象成为一幅无向图.每条路的初始速度都是 \(1\ m/s\).杜老师可以使用 \(1\) 块钱让任意一条路的速度提升 ...

  10. CSS – Aspect Ratio

    参考: Youtube – Chrome 88 adds aspect-ratio and 2 awesome new devtool features! MDN – aspect-ratio W3S ...