在AI浪潮席卷全球的当下,基本上前沿的事物都会打上 AI 的标签。我们的 Java 也不例外。当时一则消息 Spring 支持 AI,那会公众号到处都是 Spring AI 推文。
最近自己搭建了个开源llama3,正好就可以使用 Java Spring AI 来实现它的调用。
第一步:安装Ollama
我使用的是Ollama,Ollama 是一个开源框架,专门设计用于在本地运行大型语言模型。它将模型权重、配置和数据捆绑到一个包中,优化了设置和配置细节,包括 GPU 使用情况,从而简化了在本地运行大型模型的过程。
step1:下载Ollama
直接可以官网下载
step2:安装Ollama
双击安装OllamaSetup.exe,安装完成后在电脑状态栏会多一个羊驼的图标
step3:安装模型
选择相应的模型
github.com/ollama/ollama
选择你需要的模型,然后在windows上打开一个cmd,执行,比如:
ollama run llama3.2
接下就是会下载相应的模型,这里比较大,要花不少时间
step4:使用对话
现在就可以打开windows命令窗口,看看是否成功
看到上面的就代表 AI 已经搭建完成。
以下就是官方 Rest API 调用方式,也就是我们使用 Java 调用 AI 的调用方式。
第二步:Java 调用
下面就是基于官方 chat-models-ollama 实现 Java 调用 AI 的实现
1. 项目结构
2. 依赖配置
在pom.xml中添加必要的依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AI -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-ai</artifactId>
</dependency>
<!-- Thymeleaf for HTML templates -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- OpenAI API Client -->
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>client</artifactId>
<version>0.8.0</version>
</dependency>
<!-- Ollama Client (假设你有一个Ollama的Java客户端) -->
<dependency>
<groupId>com.example</groupId>
<artifactId>ollama-client</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
3. 配置文件
在application.properties中配置Ollama模型的URL:
spring:
ai:
ollama:
chat:
options:
model: llama3.2
thymeleaf:
cache: false
mode: HTML
encoding: UTF-8
4. 业务实现层
主页 IndexController
package com.thomasvitale.ai.spring;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
public class IndexController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "index"; // 返回模板名称,不带后缀
}
}
实现聊天业务:
package com.thomasvitale.ai.spring;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.ChatOptionsBuilder;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
class ChatController {
// 声明一个ChatClient类型的成员变量,用于与聊天机器人进行交互
private final ChatClient chatClient;
// 构造函数,接收一个ChatClient.Builder对象,并使用它来构建ChatClient实例
ChatController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
// 使用@GetMapping注解定义一个处理GET请求的方法,路径为"/chat"
// 该方法接收一个名为"question"的请求参数,默认值为"What did Gandalf say to the Balrog?"
@GetMapping("/chat")
String chat(@RequestParam(defaultValue = "What did Gandalf say to the Balrog?") String question) {
// 使用chatClient的prompt方法创建一个聊天提示,并设置用户的问题
// 调用call方法发送请求并获取响应,最后返回响应的内容
return chatClient.prompt()
.user(question)
.call()
.content();
}
}
Spring AI 最核心的调用类就是ChatClient。
5. 启动类
创建Spring Boot应用的启动类:
package com.thomasvitale.ai.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChatModelsOllamaApplication {
public static void main(String[] args) {
SpringApplication.run(ChatModelsOllamaApplication.class, args);
}
}
6. 前端页面
在src/main/resources/templates目录下创建index.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Chatbot</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.chat-container {
max-width: 600px;
margin: auto;
}
.chat-box {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
height: 200px;
overflow-y: scroll;
}
.message {
margin-bottom: 10px;
}
.user-message {
text-align: right;
}
.bot-message {
text-align: left;
}
</style>
</head>
<body>
<div class="chat-container">
<h1>Chatbot</h1>
<div class="chat-box" id="chatBox">
<div class="message bot-message" th:text="${response}"></div>
</div>
<form id="chatForm">
<input type="text" id="messageInput" name="message" placeholder="Type your message here..." required>
<button type="submit">Send</button>
</form>
</div>
<script>
document.getElementById('chatForm').addEventListener('submit', function(event) {
event.preventDefault(); // 阻止表单默认提交行为
const message = document.getElementById('messageInput').value;
const chatBox = document.getElementById('chatBox');
// 创建用户消息
const userMessage = document.createElement('div');
userMessage.className = 'message user-message';
userMessage.textContent = message;
chatBox.appendChild(userMessage);
// 发送AJAX请求
fetch(`/chat?question=${encodeURIComponent(message)}`, {
method: 'GET'
})
.then(response => response.text())
.then(data => {
// 创建机器人消息
const botMessage = document.createElement('div');
botMessage.className = 'message bot-message';
botMessage.textContent = data;
chatBox.appendChild(botMessage);
// 滚动到底部
chatBox.scrollTop = chatBox.scrollHeight;
})
.catch(error => {
console.error('Error:', error);
});
// 清空输入框
document.getElementById('messageInput').value = '';
});
</script>
</body>
</html>
7. 运行应用
运行ChatModelsOllamaApplication类,启动Spring Boot应用。访问http://localhost:8080/chat?question=xxx,你将看到一个简单的聊天网页,可以与聊天机器人进行交互。
把 xxx 换成你要问的问题,如 what you name?
可以看到已经调用了本地的 llama3.2 模型回答了。
再来访问一下简单的页面访问http://localhost:8080/
总结
这个简易的聊天机器人使用了Spring Boot、Spring AI、RESTful API,并包含一个简单的聊天网页。后续还需要进一步扩展和优化这个聊天机器人,如集成Ollama模型、支持多轮对话、页面 UI 等。