本地已经使用了 Ollama 部署了 deepseek 7B, 怎么在springboot 系统中使用
时间: 2025-06-24 11:38:25 浏览: 3
### 集成本地 Ollama 的 DeepSeek 7B 模型到 Spring Boot
要在 Spring Boot 系统中集成并使用本地部署的 Ollama 和 DeepSeek 7B 模型,可以通过以下方式完成:
#### 1. **配置 Ollama**
首先需要确保已经在本地成功安装和运行了 Ollama 并拉取了所需的 DeepSeek 模型。以下是基本操作命令:
```bash
wsl --install -d Ubuntu-22.04
curl -fsSL https://ollama.ai/install.sh | sh
ollama pull deepseek-r1:7b
```
这些命令会帮助你在 WSL2 上安装 Ubuntu,并通过 Ollama 下载 DeepSeek 7B 模型。
#### 2. **Spring Boot 应用程序配置**
在 Spring Boot 中,可以通过 `application.properties` 或 `application.yml` 文件来定义与 Ollama 的连接参数。以下是基于 `application.properties` 的配置示例[^3]:
```properties
spring.application.name=demo
spring.ai.ollama.chat.options.model=deepseek-r1:7b
spring.ai.ollama.base-url=http://127.0.0.1:11434
spring.ai.ollama.chat.enabled=true
server.port=9091
```
如果更倾向于 YAML 格式的配置,则可以参考以下内容[^2]:
```yaml
spring:
ai:
ollama:
base-url: http://localhost:11434
chat:
model: deepseek-r1:7b
```
以上配置指定了 Ollama 运行的服务地址以及使用的具体模型版本。
#### 3. **编写控制器代码**
为了使应用程序能够响应请求并与 DeepSeek 对话,可以在 Spring Boot 中创建一个 REST 控制器。下面是一个简单的例子:
```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ai")
public class AiController {
@Value("${spring.ai.ollama.base-url}")
private String baseUrl;
@Value("${spring.ai.ollama.chat.options.model}")
private String modelName;
@PostMapping("/chat")
public ResponseEntity<String> chat(@RequestBody Map<String, String> request) {
try {
// 构造 HTTP 请求发送给 Ollama API
HttpClient client = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(new URI(baseUrl + "/api/generate"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"{\"model\": \"" + modelName + "\", \"prompt\": \"" + request.get("message") + "\"}"
))
.build();
HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return ResponseEntity.ok(httpResponse.body());
} catch (Exception e) {
return ResponseEntity.status(500).body(e.getMessage());
}
}
}
```
此代码片段展示了如何通过 Java 的 `HttpClient` 向 Ollama 发送 POST 请求,并接收其返回的结果作为 JSON 响应。
#### 4. **测试接口**
启动 Spring Boot 项目后,可以通过 Postman 或者直接访问 URL 来测试该功能。假设服务器端口设置为默认值(即未更改),则可通过以下方式进行交互:
```plaintext
POST http://localhost:9091/ai/chat
Content-Type: application/json
{
"message": "你好"
}
```
这将触发向 DeepSeek 提问的过程,并获得相应的回复。
---
###
阅读全文
相关推荐


















