下载与安装 Ollama

Ollama 是一个本地运行大型语言模型的工具,支持多种开源模型。访问 Ollama 官网 下载适用于操作系统(Windows/macOS/Linux)的安装包。安装完成后,通过命令行运行 ollama pull <模型名> 下载模型,例如 ollama pull llama3

配置 Spring AI 和 Alibaba ChatModel

在 Spring Boot 项目中引入依赖:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-alibaba-spring-boot-starter</artifactId>
    <version>0.8.1</version>
</dependency>

配置 application.yml 指定 Ollama 本地服务地址:

spring:
  ai:
    alibaba:
      base-url: http://localhost:11434
      chat:
        model: llama3

实现流式输出 ChatClient

创建 Controller 接收请求并返回流式响应:

import org.springframework.ai.chat.ChatClient;
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
public class ChatController {
    private final ChatClient chatClient;

    public ChatController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @GetMapping("/chat/stream")
    public Flux<String> streamChat(@RequestParam String message) {
        return chatClient.stream(message)
                .map(response -> response.getResult().getOutput().getContent());
    }
}

IDEA 开发与测试

  1. 启动 Ollama 服务:命令行执行 ollama serve
  2. 在 IDEA 中运行 Spring Boot 项目,使用 curl 或 Postman 测试流式接口:
curl --location 'http://localhost:8080/chat/stream?message=你好'
  1. 前端可通过 EventSource 或 WebSocket 接收分块响应。

关键代码说明

  • Flux<String>:Spring WebFlux 的响应式流类型,支持分块传输。
  • chatClient.stream():Alibaba ChatClient 提供的流式调用方法。
  • 响应内容通过 response.getResult().getOutput().getContent() 提取。

注意事项

  1. Ollama 默认端口为 11434,确保未被防火墙拦截。
  2. 流式响应需客户端支持 Server-Sent Events (SSE)。
  3. 可在 application.yml 调整超时等参数以适应长对话场景。
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐