轻松入门SpringAI-SpringAI调用Ollama

第五章 Spring AI调用Ollama

5.1 下载并安装 Ollama

官网:https://ollama.com/

5.1.1 下载Ollama

Ollama 是一个用于本地化部署和管理大型语言模型(LLM)的工具。它支持多种开源模型(如 LLaMA、Alpaca 等),并提供了简单的 API 接口,方便开发者调用。Ollama可以让你在自己的电脑上运行各种强大的 AI 模型,就像运行普通软件一样简单。

在这里插入图片描述

5.1.2 安装Ollama

  • 模型默认安装在C盘,可以修改安装路径

  • 点击环境变量,选择下面新建一个系统环境变量 OLLAMA_MODELS ,然后指定想要安装模型的路径 ,比如 “D:\Deepseek”

在这里插入图片描述

  • 需要重启 Ollama生效

5.1.3 拉取 DeepSeek 模型

硬件配置建议

  • GPU选择(根据模型大小灵活调整):
    入门配置:NVIDIA显卡(≥8GB显存) → 适合7B/8B模型。
    高性能配置:NVIDIA显卡(≥16GB显存) → 支持14B大模型。
    无独立显卡用户:可使用CPU模式运行(速度约为GPU的20%)。

  • 内存要求:≥16GB(推荐32GB,处理长文本时不易卡顿)

  • 存储空间:≥50GB可用空间(建议SSD硬盘,加快模型加载速度)

  • 操作系统
    Windows 10/11(21H2及以上版本)。
    macOS Ventura 13.4+。
    Ubuntu 22.04 LTS/24.04 LTS

选择适合自己的版本 https://ollama.com/library/deepseek-r1

在这里插入图片描述

以windows为例,根据不同版本,执行不同的命令拉取模型

比如,下载1.5b,执行下面命令

ollama pull deepseek-r1:1.5b

5.1.4 启动Ollama服务测试

启动 Ollama 服务,默认会监听 http://localhost:11434

ollama run deepseek-r1:1.5b

在这里插入图片描述

5.2 Spring AI代码测试

5.2.1 创建SpringBoot工程

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>org.example</groupId>
    <artifactId>springai-deepseek</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <spring-ai.version>1.0.0-M5</spring-ai.version>
    </properties>

    <dependencies>
        <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-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!--下载spring-ai相关包需要用到的仓库地址-->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>

</project>

5.2.2 创建配置文件

application.properties

server.port=8899
spring.application.name=spring-ai-deepseek-demo

spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=deepseek-r1:1.5b
spring.ai.ollama.chat.options.temperature=0.7

5.2.3 创建启动类

@SpringBootApplication
public class SpringAiDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringAiDemoApplication.class, args);
    }

}

5.2.4 创建Controller

@RestController
public class ChatDeepSeekController {

    @Autowired
    private OllamaChatModel ollamaChatModel;

    @GetMapping("/ai/test")
    public String generate(@RequestParam(value = "message", defaultValue = "hello")
                           String message) {
        String response = this.ollamaChatModel.call(message);
        System.out.println("response : "+response);
        return response;
    }
}

5.2.5 测试

### 实现动态打字效果 为了在 Spring AI 的 Ollama 中实现动态打字效果,可以采用异步处理的方式逐步显示生成的文本。这不仅提升了用户体验,还模拟了人类输入的效果。 通过使用 `OllamaChatModel` 和 WebSockets 或 Server-Sent Events (SSE),能够实现实时更新前端界面的功能[^1]。具体来说,在接收到部分响应时立即发送给客户端而不是等待整个回复完成后再一次性展示全部内容。 #### 配置说明 首先确保已经在应用程序中集成了 OpenAI API,并获得了有效的 API 密钥[^2]。接着按照如下方式设置: - **引入依赖库**:如果尚未添加必要的 Maven/Gradle 依赖项,则需先加入这些包来支持 WebSocket/SSE 功能。 对于 Maven 用户而言,应在 pom.xml 文件内增加相应条目;而 Gradle 则是在 build.gradle 文件里操作。 ```xml <!-- 对于Maven--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- 如果选择 SSE --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> ``` ```groovy // 对于Gradle implementation 'org.springframework.boot:spring-boot-starter-websocket' // 如果选择 SSE implementation 'org.springframework.boot:spring-boot-starter-webflux' ``` - **创建控制器类** 定义一个新的 REST 控制器用于接收来自用户的请求并启动聊天会话。此过程中应初始化 `OllamaChatModel` 实例以便调用其方法来进行消息传递与处理。 ```java @RestController @RequestMapping("/chat") public class ChatController { private final OllamaChatModel ollama; public ChatController(OllamaChatModel ollama) { this.ollama = ollama; } @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> streamResponse(@RequestParam String message) throws Exception { return Flux.create(sink -> { try { // 调用 Ollama 模型获取流式响应 ollama.sendMessage(message, responsePart -> sink.next(responsePart)); } catch (Exception e) { sink.error(e); } }); } } ``` 上述代码片段展示了如何利用 Project Reactor 提供的支持函数构建一个返回类型为 `Flux<String>` 的端点。每当有新的数据可用时就会触发一次事件通知订阅者(即浏览器),从而实现了所谓的“服务器推送”。 最后一步就是在 HTML 页面上编写 JavaScript 来监听这些事件并将它们逐字符地呈现在界面上形成动态打字效果。 ```html <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { const eventSource = new EventSource('/chat/stream?message=Hello%20World'); let outputElement = document.getElementById('output'); eventSource.onmessage = function(event) { // 将每一段文字追加到页面上的指定位置 outputElement.innerHTML += event.data; // 可选:添加短暂延迟以增强视觉体验 setTimeout(() => {}, Math.random() * 50); }; }); </script> <div id="output"></div> ``` 以上就是关于如何在基于 Spring AI 构建的应用程序中集成 Ollama 并实现动态打字效果的大致流程介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员码小跳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值