使用 Java SpringAI 接入 DeepSeek 教程

SpringAI 是 Spring 生态中用于集成 AI 模型的项目,它支持对接各种 AI 提供商,包括 OpenAI、Azure OpenAI、Ollama 等。Ollama 是一个本地运行的 AI 模型推理平台,可以让你轻松地在本地运行 Llama、Mistral、Gemma 等模型。

本指南将详细介绍如何在 Spring Boot 应用中集成 SpringAI 并对接 Ollama,让你的 Java 项目能够调用本地 AI 推理能力。

1. 准备工作

1.1 安装 Ollama

首先,你需要在本地安装 Ollama

  • 访问 https://ollama.com 并下载适合你系统的安装包。
  • 安装完成后,运行 ollama --version 确保安装成功。

使用 Java SpringAI 接入 DeepSeek 教程

1.2 下载模型

Ollama 需要本地模型才能进行推理,你可以运行以下命令拉取一个模型:

ollama pull mistral

这里我们使用 Mistral 模型,你也可以换成 llama3 或其他支持的模型。

2. 创建 Spring Boot 项目

确保你的项目使用 **Spring Boot 3+**,然后添加 SpringAI 依赖。

2.1 添加 Maven 依赖

pom.xml 中添加 SpringAI 相关依赖:

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <!-- SpringAI Core -->
    <dependency>
        <groupId>org.springframework.experimental.ai</groupId>
        <artifactId>spring-ai-core</artifactId>
        <version>0.8.0</version>
    </dependency>

    <!-- SpringAI Ollama Client -->
    <dependency>
        <groupId>org.springframework.experimental.ai</groupId>
        <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
        <version>0.8.0</version>
    </dependency>
</dependencies>

如果使用 Gradle,可以添加:

dependencies {
    implementation 'org.springframework.experimental.ai:spring-ai-core:0.8.0'
    implementation 'org.springframework.experimental.ai:spring-ai-ollama-spring-boot-starter:0.8.0'}

3. 配置 SpringAI 连接 Ollama

application.ymlapplication.properties 中配置 Ollama。

3.1 application.yml 配置:

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      model: mistral
  • base-url: Ollama 服务器的地址,默认是 http://localhost:11434
  • model: 指定使用的 AI 模型(如 mistralllama3 等)。

4. 编写 Spring 服务调用 Ollama

创建一个 OllamaService 来调用 SpringAI 提供的接口。

4.1 编写 OllamaService

import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.ai.chat.messages.ChatMessage;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OllamaService {

    private final OllamaChatClient chatClient;

    public OllamaService(OllamaChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String chatWithAI(String userMessage) {
        List<ChatMessage> messages = List.of(
            new ChatMessage(MessageType.SYSTEM, "你是一个智能助手"),
            new ChatMessage(MessageType.USER, userMessage)
        );

        return chatClient.call(messages).getResult().getOutput().getContent();
    }
}

4.2 创建 REST API

OllamaController 中暴露一个 HTTP 接口:

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/chat")
public class OllamaController {

    private final OllamaService ollamaService;

    public OllamaController(OllamaService ollamaService) {
        this.ollamaService = ollamaService;
    }

    @PostMapping
    public String chat(@RequestBody String message) {
        return ollamaService.chatWithAI(message);
    }
}

5. 启动并测试

5.1 启动 Spring Boot 项目

运行:

mvn spring-boot:run

或者:

./mvnw spring-boot:run

5.2 发送请求测试

PostmancURL 发送请求:

curl -X POST http://localhost:8080/api/chat -H "Content-Type: text/plain" -d "你好,介绍一下自己。"

Ollama 会返回 AI 生成的回答,比如:

"我是一个智能助手,可以回答你的问题。"

6. 进阶优化

6.1 添加流式响应(Streaming)

如果想要实现 流式输出(像 ChatGPT 那样一边生成一边返回),可以修改 OllamaService

import org.springframework.ai.chat.messages.ChatMessage;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;

@Service
public class OllamaService {

    private final OllamaChatClient chatClient;

    public OllamaService(OllamaChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public Flux<String> chatWithAIStream(String userMessage) {
        List<ChatMessage> messages = List.of(
            new ChatMessage(MessageType.SYSTEM, "你是一个智能助手"),
            new ChatMessage(MessageType.USER, userMessage)
        );

        return chatClient.stream(messages)
                .map(response -> response.getOutput().getContent());
    }
}

然后在 OllamaController 里返回 Flux<String>

import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/api/chat")
public class OllamaController {

    private final OllamaService ollamaService;

    public OllamaController(OllamaService ollamaService) {
        this.ollamaService = ollamaService;
    }

    @PostMapping("/stream")
    public Flux<String> chatStream(@RequestBody String message) {
        return ollamaService.chatWithAIStream(message);
    }
}

测试流式输出:

curl -X POST http://localhost:8080/api/chat/stream -H "Content-Type: text/plain" -d "介绍一下SpringAI。"

原文始发于微信公众号(安哥说后端)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/310378.html

(0)
葫芦侠五楼的头像葫芦侠五楼

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!