使用spring ai实现简单会话
前序文章
本地部署ollama及deepseek(linux版)
如何通过http访问ollama接口
1、首先要引入对应的jar包
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-ollama-spring-boot-starter</artifactId><version>1.0.0-M6</version></dependency>
2、配置文件
spring:application:name: knowledge_aiai:ollama:base-url: http://192.168.1.116:11434chat:model: deepseek-r1:1.5b
3、 java类实现,目前是一个简单的DEMO,可以直接调用
package com.hxzy.knowledge_ai.controller;import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class OllamaController {private final ChatClient ollamaChatClient;private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";public OllamaController(ChatClient.Builder chatClientBuilder) {this.ollamaChatClient = chatClientBuilder.defaultSystem(DEFAULT_PROMPT)// 实现 Chat Memory 的 Advisor// 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。.defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))// 实现 Logger 的 Advisor.defaultAdvisors(new SimpleLoggerAdvisor())// 设置 ChatClient 中 ChatModel 的 Options 参数
// .defaultOptions(
// OllamaOptions.builder().model("deepseek-r1:1.5b").build()
//
// ).build();}@GetMapping("/simple/chat")public String simpleChat(String question) {return this.ollamaChatClient.prompt(question).call().content();}
}
4、调用接口