SpringBoot集成Ollama本地模型

SpringBoot集成Ollama本地模型

目錄

  1. 項目準備
  2. 創建Ollama服務客戶端
  3. 創建控制器
  4. 配置應用屬性
  5. 創建前端界面
  6. 添加靜態資源支持
  7. 完整項目結構
  8. 啟動應用
  9. 高級功能擴展
  10. 部署注意事項
  11. 性能優化

1. 項目準備

  1. 創建一個SpringBoot項目,可以使用Spring Initializr或IDE創建
  2. 添加必要的依賴到pom.xml:
    <dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- WebClient --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency>
    </dependencies>
    

2. 創建Ollama服務客戶端

package com.example.ollama.service;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import java.util.List;
import java.util.Map;@Slf4j
@Service
public class OllamaService {private final WebClient webClient;public OllamaService(@Value("${ollama.api.url:http://localhost:11434}") String ollamaApiUrl) {this.webClient = WebClient.builder().baseUrl(ollamaApiUrl).build();}/*** 生成文本*/public Mono<String> generateText(String model, String prompt, Double temperature) {Map<String, Object> requestBody = Map.of("model", model,"prompt", prompt,"temperature", temperature != null ? temperature : 0.7);return webClient.post().uri("/api/generate").bodyValue(requestBody).retrieve().bodyToMono(Map.class).map(response -> (String) response.get("response"));}/*** 聊天對話*/public Mono<String> chat(String model, List<Map<String, String>> messages) {Map<String, Object> requestBody = Map.of("model", model,"messages", messages);return webClient.post().uri("/api/chat").bodyValue(requestBody).retrieve().bodyToMono(Map.class).map(response -> {Map<String, Object> message = (Map<String, Object>) response.get("message");return (String) message.get("content");});}/*** 流式生成文本*/public Flux<String> streamGenerateText(String model, String prompt, Double temperature) {Map<String, Object> requestBody = Map.of("model", model,"prompt", prompt,"temperature", temperature != null ? temperature : 0.7,"stream", true);return webClient.post().uri("/api/generate").bodyValue(requestBody).retrieve().bodyToFlux(Map.class).map(response -> (String) response.get("response"));}
}

3. 創建控制器

package com.example.ollama.controller;import com.example.ollama.service.OllamaService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import java.util.List;
import java.util.Map;@RestController
@RequestMapping("/api/ollama")
@RequiredArgsConstructor
public class OllamaController {private final OllamaService ollamaService;@PostMapping("/generate")public Mono<String> generateText(@RequestParam(defaultValue = "llama2") String model,@RequestParam String prompt,@RequestParam(required = false) Double temperature) {return ollamaService.generateText(model, prompt, temperature);}@PostMapping("/chat")public Mono<String> chat(@RequestParam(defaultValue = "llama2") String model,@RequestBody List<Map<String, String>> messages) {return ollamaService.chat(model, messages);}@PostMapping("/stream")public Flux<String> streamGenerateText(@RequestParam(defaultValue = "llama2") String model,@RequestParam String prompt,@RequestParam(required = false) Double temperature) {return ollamaService.streamGenerateText(model, prompt, temperature);}
}

4. 配置應用屬性

application.propertiesapplication.yml中添加配置:

# Ollama API配置
ollama.api.url=http://localhost:11434# 服務器配置
server.port=8080

5. 創建前端界面

創建一個簡單的HTML頁面用于與Ollama交互:

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Ollama聊天界面</title><style>body {font-family: Arial, sans-serif;max-width: 800px;margin: 0 auto;padding: 20px;}.chat-container {border: 1px solid #ccc;border-radius: 5px;padding: 20px;margin-bottom: 20px;height: 400px;overflow-y: auto;}.message {margin-bottom: 10px;padding: 10px;border-radius: 5px;}.user-message {background-color: #e6f7ff;margin-left: 20%;}.ai-message {background-color: #f0f0f0;margin-right: 20%;}.input-container {display: flex;}#message-input {flex-grow: 1;padding: 10px;border: 1px solid #ccc;border-radius: 5px;margin-right: 10px;}button {padding: 10px 20px;background-color: #4CAF50;color: white;border: none;border-radius: 5px;cursor: pointer;}button:hover {background-color: #45a049;}</style>
</head>
<body><h1>Ollama聊天界面</h1><div class="chat-container" id="chat-container"></div><div class="input-container"><input type="text" id="message-input" placeholder="輸入消息..."><button onclick="sendMessage()">發送</button></div><script>const chatContainer = document.getElementById('chat-container');const messageInput = document.getElementById('message-input');// 按Enter鍵發送消息messageInput.addEventListener('keypress', function(e) {if (e.key === 'Enter') {sendMessage();}});function sendMessage() {const message = messageInput.value.trim();if (!message) return;// 添加用戶消息到聊天界面addMessage(message, 'user');messageInput.value = '';// 發送消息到后端fetch('/api/ollama/chat', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify([{'role': 'user','content': message}])}).then(response => response.text()).then(response => {// 添加AI回復到聊天界面addMessage(response, 'ai');}).catch(error => {console.error('Error:', error);addMessage('發生錯誤,請稍后重試。', 'ai');});}function addMessage(message, sender) {const messageDiv = document.createElement('div');messageDiv.classList.add('message');messageDiv.classList.add(sender === 'user' ? 'user-message' : 'ai-message');messageDiv.textContent = message;chatContainer.appendChild(messageDiv);chatContainer.scrollTop = chatContainer.scrollHeight;}</script>
</body>
</html>

6. 添加靜態資源支持

在SpringBoot應用中添加靜態資源支持:

package com.example.ollama.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");}
}

7. 完整項目結構

src/
├── main/
│   ├── java/
│   │   └── com/
│   │       └── example/
│   │           └── ollama/
│   │               ├── OllamaApplication.java
│   │               ├── controller/
│   │               │   └── OllamaController.java
│   │               ├── service/
│   │               │   └── OllamaService.java
│   │               └── config/
│   │                   └── WebConfig.java
│   └── resources/
│       ├── static/
│       │   └── index.html
│       └── application.properties

8. 啟動應用

  1. 確保Ollama服務已啟動并運行在默認端口(11434)
  2. 運行SpringBoot應用
  3. 訪問http://localhost:8080查看聊天界面

9. 高級功能擴展

9.1 添加模型選擇功能

@GetMapping("/models")
public Mono<List<String>> listModels() {return webClient.get().uri("/api/tags").retrieve().bodyToMono(Map.class).map(response -> {List<Map<String, Object>> models = (List<Map<String, Object>>) response.get("models");return models.stream().map(model -> (String) model.get("name")).collect(Collectors.toList());});
}

9.2 添加流式響應支持

@GetMapping(value = "/stream-chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamChat(@RequestParam(defaultValue = "llama2") String model,@RequestParam String message) {return ollamaService.streamGenerateText(model, message, 0.7).map(response -> ServerSentEvent.<String>builder().data(response).build());
}

9.3 添加會話管理

@Service
public class ChatSessionService {private final Map<String, List<Map<String, String>>> sessions = new ConcurrentHashMap<>();public List<Map<String, String>> getOrCreateSession(String sessionId) {return sessions.computeIfAbsent(sessionId, k -> new ArrayList<>());}public void addMessage(String sessionId, String role, String content) {List<Map<String, String>> messages = getOrCreateSession(sessionId);messages.add(Map.of("role", role, "content", content));}public void clearSession(String sessionId) {sessions.remove(sessionId);}
}

10. 部署注意事項

  1. 確保服務器上已安裝并運行Ollama服務
  2. 配置適當的防火墻規則,允許SpringBoot應用訪問Ollama服務
  3. 在生產環境中使用HTTPS保護API通信
  4. 考慮添加身份驗證和授權機制
  5. 監控Ollama服務的資源使用情況,避免過載

11. 性能優化

  1. 使用連接池管理WebClient連接
  2. 實現請求緩存,避免重復請求
  3. 使用異步處理提高并發能力
  4. 考慮使用響應式編程模式處理流式響應

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/76301.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/76301.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/76301.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ResNet改進(19):基于PyTorch的ResNet改進方案詳解:Mish激活+SPP模塊+MixUp數據增強

1. 前言 ResNet作為深度學習領域里程碑式的網絡架構,在圖像分類等計算機視覺任務中表現出色。然而,隨著研究的深入和技術的發展,原始的ResNet架構仍有改進空間。本文將詳細介紹一種基于PyTorch的ResNet改進方案,該方案融合了Mish激活函數、SPP模塊和MixUp數據增強等先進技…

leetcode68.左右文本對齊

思路源自 leetcode-字符串篇 68題 文本左右對齊 難度高的模擬類型題目&#xff0c;關鍵點在于事先知道有多少單詞要放在本行并且還要知道本行是不是最后一行&#xff08;最后一行需要全部單空格右對齊&#xff0c;不是最后一行就空格均攤&#xff09;&#xff0c;非最后一行的空…

深入理解 Spring 的 MethodParameter 類

MethodParameter 是 Spring 框架中一個非常重要的類&#xff0c;它封裝了方法參數&#xff08;或返回類型&#xff09;的元數據信息。這個類在 Spring MVC、AOP、數據綁定等多個模塊中都有廣泛應用。 核心功能 MethodParameter 主要提供以下功能&#xff1a; 獲取參數類型信息…

Qt 5.14.2入門(一)寫個Hello Qt!程序

目錄 參考鏈接&#xff1a;一、新建項目二、直接運行三、修改代碼增加窗口內容1、Qt 顯示一個 QLabel 標簽控件窗口2、添加按鍵 參考鏈接&#xff1a; Qt5教程&#xff08;一&#xff09;&#xff1a;Hello World 程序 Qt 編程指南 一、新建項目 1、新建一個項目&#xff08…

Spring Boot 3.x 集成 MongoDB 的 默認配置項及默認值,以及 常用需要修改的配置項 的詳細說明

以下是 Spring Boot 3.x 集成 MongoDB 的 默認配置項及默認值&#xff0c;以及 常用需要修改的配置項 的詳細說明&#xff1a; 一、默認配置項及默認值 Spring Boot 對 MongoDB 的默認配置基于 spring.data.mongodb 前綴&#xff0c;以下是核心配置項&#xff1a; 配置項默認…

【QT】 進程

目錄 QT 多進程復習 Linux-C 多進程QProcess 進程類常用方法簡單示例信號與槽應用場景 跨平臺注意事項技巧&#xff1a;使用宏控制平臺命令 QProcess 在嵌入式系統中的使用示例&#xff1a;調用 ALSA 播放音頻示例&#xff1a;調用 arecord 錄音示例&#xff1a;QProcess Shel…

原子操作(cpp atomic)

目錄 一.原子操作 1.原子操作的概念 2.原子變量 二.原子性 1.中間狀態描述 2.單處理器單核 3.多處理器或多核的情況下 4.cache&#xff08;高速緩沖器的作用&#xff09; 5.在cpu cache基礎上,cpu如何讀寫數據&#xff1f;&#xff1f;&#xff1f; 6.為什么會有緩存…

Unet網絡的Pytorch實現和matlab實現

文章目錄 一、Unet網絡簡介1.1 輸入圖像1.2 編碼器部分&#xff08;Contracting Path&#xff09;1.3 解碼器部分&#xff08;Expanding Path&#xff09;1.4 最后一層&#xff08;輸出&#xff09;1.5 跳躍連接&#xff08;Skip Connections&#xff09; 二、Unet網絡的Pytorc…

記錄一次JVM調優過程1

如何通過jmap 診斷&#xff0c;服務運行一段時間后內存使用量飆升的問題 通過 jmap 診斷服務運行一段時間后內存使用量飆升的問題&#xff0c;需結合堆轉儲分析、對象分布統計及工具鏈配合。以下是具體操作步驟和關鍵方法&#xff1a; 一、實時監控與初步分析 獲取進程 PID 使…

接口自動化學習五:mock工具使用

Moco簡介&#xff1a; Mock是一個簡單搭建模擬服務器的框架&#xff0c;可以用來模擬http、https、socket等協議。 原理&#xff1a; Mock會根據一些配置&#xff0c;啟動一個真正的HTTP服務&#xff08;會監聽本地的某個端口&#xff09;,當發起的請求滿足某個條件時&#xf…

若依 前后端部署

后端&#xff1a;直接把代碼從gitee上拉去到本地目錄 (https://gitee.com/y_project/RuoYi-Vue ) 注意下redis連接時password改auth 后端啟動成功 前端&#xff1a;運行前首先確保安裝了node環境&#xff0c;隨后執行&#xff1a; &#xff01;&#xff01;一定要用管理員權限…

Adaptive AUTOSAR 狀態管理和轉換——ActionItemList

在AUTOSAR的狀態轉換管理(STM,State Transition Manager) 框架中,ActionItemList 是連接 狀態機狀態(State Machine State) 與 功能組狀態(Function Group States) 的核心配置元素。 以下是其關系與作用的詳細解釋: 1. 核心概念 狀態機狀態(State Machine State) 表…

一個基于ragflow的工業文檔智能解析和問答系統

工業復雜文檔解析系統 一個基于ragflow的工業文檔智能解析和問答系統,支持多種文檔格式的解析、知識庫管理和智能問答功能。 系統功能 1. 文檔管理 支持多種格式文檔上傳(PDF、Word、Excel、PPT、圖片等)文檔自動解析和分塊處理實時處理進度顯示文檔解析結果預覽批量文檔…

linux系統下如何提交git和調試

我們默認的ubuntu20.04鏡像是沒有Git提交的工具&#xff0c;我們需要配置安裝包。 安裝和更新git的命令 sudo apt update //用于更新軟件包索引sudo apt install git //用于安裝git版本控制工具 git --version //檢查git版本,確認是否安裝成功 隨便進入linux系統下的一…

輕量級爬蟲框架Feapder入門:快速搭建企業級數據管道

一、目標與前置知識 1. 目標概述 本教程的主要目標是&#xff1a; 介紹輕量級爬蟲框架 Feapder 的基本使用方式。快速搭建一個采集豆瓣電影數據的爬蟲&#xff0c;通過電影名稱查找對應的電影詳情頁并提取相關信息&#xff08;電影名稱、導演、演員、劇情簡介、評分&#xf…

spring mvc的攔截器HandlerInterceptor 接口詳解

HandlerInterceptor 接口詳解 1. 接口方法說明 方法作用執行時機返回值/注意事項preHandle請求處理前攔截在控制器方法執行前調用返回 false 中斷后續流程&#xff1b;返回 true 繼續執行postHandle控制器方法執行后攔截在控制器方法返回結果后&#xff0c;視圖渲染前調用無返…

數據可視化 —— 柱形圖應用(大全)

一、案例一&#xff1a;單柱形圖 1.導入庫 import matplotlib.pyplot as plt import pandas as pd import numpy as np 2.給窗口名稱和畫布大小 plt.figure(num單柱形圖, figsize(6, 4), facecolorw) 3.定義x、y軸的數據 # range(0-4) x np.arange(5) # 創建數組 y1 np.a…

apijson 快速上手

apijson是強大的工具&#xff0c;簡化了CRUD的操作&#xff0c;只要有數據庫表&#xff0c;就能自動生成RESTFUL接口。但初次上手也是摸索了很長時間&#xff0c;尤其是部署與使用上&#xff0c;這里嘗試以初學者角度來說下&#xff1a; 一、好處 1、對于簡單的應用&#xff…

V4L2雜談

V4L2的開發手冊 在做v4l2的開發的時候&#xff0c; 可以使用v4l2-ctl命令協助調試和軟件開發。關于linux多媒體開發可以參考鏈接&#xff1a;https://www.linuxtv.org/wiki/index.php/Main_Page關于v4l2的api接口開發可以參考&#xff1a;https://linuxtv.org/docs.php在linux…

(五)深入了解AVFoundation-播放:多音軌、字幕、倍速播放與橫豎屏切換

引言 在之前的博客中&#xff0c;我們已經實現了一個相對完整的播放器&#xff0c;具備了基本功能&#xff0c;如播放、暫停、播放進度顯示和拖拽快進等。這為我們提供了一個堅實的基礎。接下來&#xff0c;我們將進一步擴展播放器的功能&#xff0c;使其更具靈活性和實用性&a…