最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用Spring AI集成本地Ollama實(shí)現(xiàn)AI快速對(duì)話的完整示例

 更新時(shí)間:2026年06月01日 08:40:47   作者:霸道流氓氣質(zhì)  
在實(shí)際開(kāi)發(fā)中,我們經(jīng)常需要在本地運(yùn)行大模型進(jìn)行測(cè)試和開(kāi)發(fā),雖然阿里云百煉等云平臺(tái)提供了便捷的API服務(wù),但在一些場(chǎng)景中,本地Ollama是更好的選擇,因此本文給大家詳細(xì)介紹了SpringBoot使用Spring AI集成本地Ollama實(shí)現(xiàn)AI快速對(duì)話的完整示例,需要的朋友可以參考下

場(chǎng)景

在實(shí)際開(kāi)發(fā)中,我們經(jīng)常需要在本地運(yùn)行大模型進(jìn)行測(cè)試和開(kāi)發(fā)。雖然阿里云百煉等云平臺(tái)提供了便捷的API服務(wù),但在以下場(chǎng)景中,本地Ollama是更好的選擇:

  1. 開(kāi)發(fā)測(cè)試:快速驗(yàn)證AI功能,無(wú)需等待網(wǎng)絡(luò)請(qǐng)求
  2. 數(shù)據(jù)隱私:敏感數(shù)據(jù)不想上傳到云端
  3. 成本控制:完全免費(fèi),無(wú)API調(diào)用費(fèi)用
  4. 離線環(huán)境:無(wú)外網(wǎng)或網(wǎng)絡(luò)不穩(wěn)定時(shí)使用
  5. 定制化需求:需要運(yùn)行特定開(kāi)源模型

Ollama是一個(gè)開(kāi)源的大模型運(yùn)行工具,支持多種主流模型,并提供OpenAI兼容的API接口,可以無(wú)縫集成到Spring AI框架中。

實(shí)現(xiàn)

安裝和配置Ollama

步驟1:下載并安裝Ollama

訪問(wèn)Ollama官網(wǎng)下載安裝包:

https://ollama.com/

Windows用戶下載Windows版本,安裝后Ollama默認(rèn)運(yùn)行在 http://localhost:11434

步驟2:?jiǎn)?dòng)Ollama服務(wù)

安裝完成后,Ollama會(huì)自動(dòng)啟動(dòng)??梢酝ㄟ^(guò)以下命令檢查狀態(tài):

# Windows PowerShell
ollama list
# 查看運(yùn)行的模型
ollama ps

步驟3:拉取本地模型

# 拉取qwen2.5模型(推薦,與阿里云百煉兼容性好)
ollama pull qwen2.5
# 或者拉取其他模型
ollama pull llama3.2
ollama pull phi3
ollama pull mistral

模型選擇建議:

  • qwen2.5: 中文支持好,適合練手
  • llama3.2: 性能優(yōu)秀,生態(tài)豐富
  • phi3: 體積小,適合低配置機(jī)器
  • mistral: 平衡性能和效果

步驟4:驗(yàn)證模型是否正常工作

# 測(cè)試模型對(duì)話
ollama run qwen2.5 "你好,請(qǐng)介紹一下你自己"
# 測(cè)試完成后退出
/bye

環(huán)境準(zhǔn)備:JDK 17配置

為什么必須使用JDK 17?

Spring AI框架和Spring Boot 3.x都要求最低JDK 17版本。如果您的系統(tǒng)環(huán)境變量配置的是JDK 8,需要為項(xiàng)目單獨(dú)指定JDK 17。

為項(xiàng)目單獨(dú)配置JDK 17(不影響全局JDK 8)

步驟1:下載JDK 17解壓版

直接解壓到指定目錄,例如:D:\SoftWare\jdk\jdk17

注意:

  • ? 不要添加到系統(tǒng)PATH
  • ? 不要修改系統(tǒng)環(huán)境變量
  • ? 全局JDK 8完全不動(dòng)

步驟2:在項(xiàng)目中指定JDK 17

創(chuàng)建項(xiàng)目啟動(dòng)腳本,在腳本中指定JDK路徑:

@echo off
REM 設(shè)置JDK 17路徑
set JAVA_HOME=D:\SoftWare\jdk\jdk17
set PATH=%JAVA_HOME%\bin;%PATH%
REM 驗(yàn)證Java版本
java -version
REM 執(zhí)行Maven命令
mvn clean install
mvn spring-boot:run

新建SpringBoot項(xiàng)目

修改pom.xml

添加Spring AI OpenAI Starter依賴(Ollama兼容OpenAI API):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-ai-ollama-demo</artifactId>
<version>1.0</version>
<properties>
    <java.version>17</java.version>
    <spring-ai.version>1.0.0-M5</spring-ai.version>
</properties>
<dependencies>
    <!-- Spring Boot Web Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring AI OpenAI Starter (兼容Ollama) -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        <version>1.0.0-M5</version>
    </dependency>
    <!-- Spring Boot Test Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>

注意:

  • 使用 spring-ai-openai-spring-boot-starter 而不是 spring-ai-alibaba-starter
  • Ollama提供OpenAI兼容的API接口

配置application.yml

server:
  port: 885
  servlet:
    context-path: /
  tomcat:
    uri-encoding: UTF-8
    max-threads: 800
    min-spare-threads: 30
logging:
  level:
    com.example: info
    org.springframework: info
spring:
  ai:
    openai:
      api-key: ollama  # Ollama不需要API key,但必須填寫(xiě)
      base-url: http://localhost:11434  # Ollama服務(wù)地址
      chat:
        options:
          model: qwen2.5  # 使用本地模型名稱
          temperature: 0.7
          max-tokens: 2048

關(guān)鍵配置說(shuō)明:

  • api-key: ollama - Ollama不需要真實(shí)的API key,但字段不能為空
  • base-url: http://localhost:11434 - 指向本地Ollama服務(wù)
  • model: qwen2.5 - 必須與 ollama pull 下載的模型名稱一致

創(chuàng)建對(duì)話Controller

新建一個(gè)對(duì)話Controller,實(shí)現(xiàn)AI對(duì)話接口:

package com.badao.ai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class ChatController {

    private final ChatClient chatClient;

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

    /**
     * GET方式簡(jiǎn)單對(duì)話
     * 訪問(wèn):http://localhost:885/ai/generate?message=你好
     */
    @GetMapping("/ai/generate")
    public String generate(@RequestParam(value = "message", defaultValue = "你好") String message) {
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }

    /**
     * POST方式JSON對(duì)話
     * 請(qǐng)求體:{"message": "你好"}
     */
    @PostMapping("/ai/chat")
    public Map<String, String> chat(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        String response = chatClient.prompt()
                .user(message)
                .call()
                .content();
        
        return Map.of(
                "message", message,
                "response", response,
                "model", "ollama-qwen2.5"
        );
    }

    /**
     * 健康檢查接口
     */
    @GetMapping("/ai/health")
    public Map<String, String> health() {
        return Map.of(
                "status", "running",
                "model", "ollama-qwen2.5",
                "type", "local"
        );
    }
}

創(chuàng)建啟動(dòng)類

package com.badao.ai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringAiDemoApplication {

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

}

項(xiàng)目完整結(jié)構(gòu)

spring-ai-ollama-demo/
├── src/
│   ├── main/
│   │   ├── java/com/badao/ai/
│   │   │   ├── SpringAiDemoApplication.java
│   │   │   └── controller/
│   │   │       └── ChatController.java
│   │   └── resources/
│   │       └── application.yml
│   └── test/
│       └── java/com/badao/ai/
│           └── SpringAiZhipuHelloApplicationTests.java
├── pom.xml
└── 一鍵啟動(dòng).bat

創(chuàng)建交互式啟動(dòng)腳本

為方便項(xiàng)目管理,創(chuàng)建一鍵啟動(dòng)腳本 一鍵啟動(dòng).bat

@echo off
chcp 65001 >nul
echo ========================================
echo   Spring AI Ollama Manager
echo ========================================
echo.
REM 配置路徑(修改這里)
set MVN=D:\SoftWare\Maven\apache-maven-3.6.3\bin\mvn.cmd
set JAVA_HOME=D:\SoftWare\jdk\jdk17
set PATH=%JAVA_HOME%\bin;%PATH%
set PROJECT_DIR=%~dp0
cd /d %PROJECT_DIR%
echo Maven: %MVN%
echo JDK:   %JAVA_HOME%
echo.
if not exist "%JAVA_HOME%\bin\java.exe" (
    echo [ERROR] JDK 17 not found
    pause
    exit /b 1
)
java -version
echo.
if not exist "%MVN%" (
    echo [ERROR] Maven not found
    pause
    exit /b 1
)
:MENU
echo ========================================
echo 1. Build Project
echo 2. Start Project
echo 3. Package Project
echo 4. Exit
echo ========================================
set /p choice=Choice (1-4): 
if "%choice%"=="1" goto BUILD
if "%choice%"=="2" goto START
if "%choice%"=="3" goto PACKAGE
if "%choice%"=="4" goto END
echo Invalid choice!
goto MENU
:BUILD
call "%MVN%" clean install -DskipTests
if %errorlevel% neq 0 (echo Build FAILED! & pause & goto MENU)
echo Build SUCCESS!
pause
goto MENU
:START
echo Starting on http://localhost:885
call "%MVN%" spring-boot:run
goto MENU
:PACKAGE
call "%MVN%" clean package -DskipTests
if %errorlevel% neq 0 (echo Package FAILED! & pause & goto MENU)
echo Package SUCCESS!
dir /b target\*.jar 2>nul
pause
goto MENU
:END
echo Goodbye!
exit /b 0

運(yùn)行測(cè)試

方式1:使用啟動(dòng)腳本

# 雙擊運(yùn)行
一鍵啟動(dòng).bat
# 選擇選項(xiàng)2啟動(dòng)項(xiàng)目

方式2:使用Maven命令

# 設(shè)置環(huán)境
$env:JAVA_HOME = "D:\SoftWare\jdk\jdk17"
$env:PATH = "D:\SoftWare\jdk\jdk17\bin;" + $env:PATH
# 進(jìn)入項(xiàng)目目錄
cd d:\WorkSpace\Gitee\java-demo\AI\spring-ai-ollama-demo
# 編譯項(xiàng)目
mvn clean install -DskipTests
# 啟動(dòng)項(xiàng)目
mvn spring-boot:run

測(cè)試接口

1. 瀏覽器訪問(wèn):

http://localhost:885/ai/generate?message=你好,請(qǐng)介紹下你自己

2. 使用curl測(cè)試:

# GET請(qǐng)求
curl "http://localhost:885/ai/generate?message=請(qǐng)介紹一下人工智能"
# POST請(qǐng)求
curl -X POST http://localhost:885/ai/chat \
  -H "Content-Type: application/json" \
  -d "{\"message\": \"請(qǐng)解釋機(jī)器學(xué)習(xí)\"}"

3. 健康檢查:

curl http://localhost:885/ai/health

預(yù)期響應(yīng):

{
  "status": "running",
  "model": "ollama-qwen2.5",
  "type": "local"
}

多模型切換示例

如果想嘗試不同的模型,只需修改 application.yml 中的 model 配置:

spring:
  ai:
    openai:
      chat:
        options:
          model: llama3.2  # 切換到Llama模型
          # model: phi3    # 或者切換到Phi模型
          # model: mistral # 或者使用Mistral模型

注意: 切換模型前,需要先使用 ollama pull 下載對(duì)應(yīng)模型。

高級(jí)配置

如果需要更精細(xì)的控制,可以添加更多配置選項(xiàng):

spring:
  ai:
    openai:
      api-key: ollama
      base-url: http://localhost:11434
      chat:
        options:
          model: qwen2.5
          temperature: 0.7          # 創(chuàng)造性 (0-1),越高越有創(chuàng)意
          max-tokens: 2048          # 最大生成token數(shù)
          top-p: 0.9                # 核采樣參數(shù)
          frequency-penalty: 0.0    # 頻率懲罰,降低重復(fù)內(nèi)容
          presence-penalty: 0.0     # 存在懲罰,鼓勵(lì)新話題

對(duì)比:阿里云百煉 vs 本地Ollama

特性阿里云百煉本地Ollama
成本有免費(fèi)額度,超出后收費(fèi)完全免費(fèi)
網(wǎng)絡(luò)需要外網(wǎng)本地運(yùn)行,無(wú)需外網(wǎng)
速度受網(wǎng)絡(luò)影響取決于本地硬件
隱私數(shù)據(jù)傳到云端數(shù)據(jù)完全本地
配置需要API Key無(wú)需Key(填ollama即可)
模型qwen-max等云端模型qwen2.5、llama等本地模型
適用場(chǎng)景生產(chǎn)環(huán)境開(kāi)發(fā)測(cè)試、離線使用

常見(jiàn)問(wèn)題

Q1: Ollama啟動(dòng)失???

# Windows下檢查Ollama是否運(yùn)行
tasklist | findstr ollama
# 手動(dòng)啟動(dòng)Ollama
ollama serve
# 檢查服務(wù)狀態(tài)
curl http://localhost:11434/api/tags

Q2: 模型下載慢?

# 可以使用國(guó)內(nèi)鏡像或代理
# 或者選擇較小的模型(如phi3)
ollama pull phi3

Q3: 內(nèi)存不足?

  • Ollama默認(rèn)使用GPU,如果沒(méi)有GPU會(huì)使用CPU
  • 小內(nèi)存機(jī)器建議使用較小模型(如phi3、qwen2.5:1.5b)
  • 查看模型大?。?code>ollama list

Q4: 編譯失敗 - 測(cè)試依賴缺失?

確保pom.xml包含測(cè)試依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Q5: 端口885被占用?

修改 application.yml 中的端口號(hào):

server:
  port: 8080  # 改為其他端口

Q6: 模型響應(yīng)慢?

  • 首次加載模型需要時(shí)間(從磁盤(pán)加載到內(nèi)存)
  • 后續(xù)請(qǐng)求會(huì)快很多
  • 可以調(diào)整 max-tokens 控制響應(yīng)長(zhǎng)度

進(jìn)階使用:流式響應(yīng)

如果需要實(shí)現(xiàn)流式響應(yīng)(Server-Sent Events),可以修改Controller:

@GetMapping("/ai/stream")
public SseEmitter stream(@RequestParam String message) {
    SseEmitter emitter = new SseEmitter();
    
    chatClient.prompt()
        .user(message)
        .stream()
        .content()
        .subscribe(
            content -> {
                try {
                    emitter.send(content);
                } catch (IOException e) {
                    emitter.completeWithError(e);
                }
            },
            error -> emitter.completeWithError(error),
            () -> emitter.complete()
        );
    
    return emitter;
}

總結(jié)

通過(guò)本示例,我們成功實(shí)現(xiàn)了在SpringBoot項(xiàng)目中集成本地Ollama大模型。主要步驟包括:

  1. 安裝Ollama:下載并拉取所需模型
  2. 配置JDK 17:確保滿足Spring AI的版本要求
  3. 創(chuàng)建SpringBoot項(xiàng)目:添加Spring AI OpenAI Starter依賴
  4. 配置Ollama連接:設(shè)置base-url為本地Ollama服務(wù)
  5. 實(shí)現(xiàn)對(duì)話接口:使用ChatClient進(jìn)行AI對(duì)話
  6. 測(cè)試驗(yàn)證:通過(guò)API接口測(cè)試功能

核心優(yōu)勢(shì):

  • ? 完全免費(fèi),無(wú)API費(fèi)用
  • ? 數(shù)據(jù)完全本地,隱私安全
  • ? 無(wú)需外網(wǎng),離線可用
  • ? 支持多種開(kāi)源模型
  • ? 與Spring AI無(wú)縫集成

適用場(chǎng)景:

  • 本地開(kāi)發(fā)和測(cè)試
  • AI功能原型驗(yàn)證
  • 敏感數(shù)據(jù)處理
  • 離線環(huán)境使用
  • 學(xué)習(xí)大模型技術(shù)

以上就是SpringBoot使用Spring AI集成本地Ollama實(shí)現(xiàn)AI快速對(duì)話的完整示例的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot Ollama實(shí)現(xiàn)AI快速對(duì)話的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

普洱| 阿尔山市| 甘德县| 铜鼓县| 浦北县| 梅州市| 平度市| 安化县| 长兴县| 临泉县| 满城县| 中宁县| 长宁县| 武汉市| 张家口市| 永靖县| 定陶县| 门头沟区| 凤冈县| 射阳县| 洛浦县| 石城县| 石家庄市| 大新县| 顺平县| 万宁市| 定州市| 黄梅县| 乌拉特中旗| 措美县| 龙江县| 荆门市| 林芝县| 安新县| 马鞍山市| 和静县| 稷山县| 闽清县| 长葛市| 渝中区| 博湖县|