在开始之前,请确保你满足以下条件:
JDK 环境
Ollama 安装
brew install ollama
brew services start ollama
# 安装 Ollama(macOS 示例)
brew install ollama
# 启动 Ollama 服务
brew services start ollama
# 下载通义千问本地模型
ollama pull qwen3:1.7b
# 查看本地模型列表
ollama list
# 查看模型详情
ollama show qwen3:1.7b
brew services list # 查看服务状态
brew services start ollama # 启动服务
brew services restart ollama # 重启服务
brew services stop ollama # 停止服务
ollama ps # 查看运行中的模型实例
ollama rm qwen3:1.7b # 删除模型
ollama run qwen3:1.7b # 运行模型
/bye 或 Ctrl+C # 停止运行模型
application.properties(本地 Ollama 示例)
# 本地 Ollama 配置
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=qwen3:1.7b
spring.ai.ollama.chat.options.temperature=0.7
Maven 依赖
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
<version>1.0.1</version></dependency>
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final ChatClient chatClient;
public ChatController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
// GET 请求测试
@GetMapping
public String chatGet(@RequestParam(required = false, defaultValue = "你好") String message) {
return processChat(message);
}
// POST 请求
@PostMapping
public String chatPost(@RequestBody Map<String, String> request) {
String message = request.getOrDefault("message", "你好");
return processChat(message);
}
private String processChat(String userMessage) {
String prompt = "你是一个AI助手,请根据用户的问题返回结果";
return chatClient.prompt(prompt)
.user(userMessage)
.call()
.content();
}
}
http://localhost:8080/api/chat?message=你是谁?
POST http://localhost:8080/api/chat
Body:
{
"message": "介绍一下你自己"
}