Spring AI调用Ollama

一、📥 下载并安装 Ollama

官网:https://ollama.com/

1.🌐 下载 Ollama

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

在这里插入图片描述

2. 🛠️ 安装 Ollama

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

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

在这里插入图片描述

  • 需要重启 Ollama生效

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    # 聊天模型 - 用于对话生成

4 .🔧 启动 Ollama 服务测试

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

ollama run deepseek-r1:1.5b

在这里插入图片描述

或者启动默认安装路径下的 ollama app.exe

在这里插入图片描述

二、🧪 Spring AI 代码测试

1. 📦 创建 Spring Boot 工程

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-starter-model-ollama</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. 📄 创建配置文件

application.properties

server.port=8003
spring.application.name=SpringAiOllama

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
spring.ai.ollama.init.max-retries=1
spring.ai.ollama.init.pull-model-strategy=always
spring.ai.ollama.timeout=60s

3. 🚀 创建启动类

@SpringBootApplication
public class SpringAiOllamaApplication {

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

}

4. 🎯 创建 Controller

@RestController
public class ChatModelOllamaController {
    @Autowired
    private OllamaChatModel ollamaChatModel;
    @GetMapping("/ai/Ollama")
    public String generate(@RequestParam(value = "message", defaultValue = "郑浩")
                           String message) {
        String response = this.ollamaChatModel.call(message);
        System.out.println("response : "+response);
        return response;
    }

}

5. 🧪 测试

在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐