springboot 硅基流动 deepseek
时间: 2025-02-20 10:33:04 浏览: 209
### 集成 DeepSeek 至 Spring Boot
为了在 Spring Boot 中集成 DeepSeek 并实现硅基流动的功能,主要步骤涉及设置开发环境、配置 `application.properties` 文件以及编写必要的代码来调用 DeepSeek 的 API。
#### 设置开发环境
确保使用的是支持最新特性的 IDE 如 IntelliJ IDEA,并安装 Maven 来管理依赖项。项目应基于 Spring Boot 3.4 和 Spring AI 1.0.0-SNAPSHOT 版本[^1]。
#### 修改 application.properties 文件
在项目的资源目录下找到并编辑 `application.properties` 文件,加入以下特定于 DeepSeek API 的配置:
```properties
spring.ai.openai.base-url=https://api.siliconflow.cn/
spring.ai.openai.api-key=你自己的密钥
spring.ai.openai.chat.options.model=deepseek-ai/DeepSeek-V3
logging.level.org.springframework.ai.chat.client.advisor=DEBUG
```
这里的 `base-url` 是指向硅基流动提供的 DeepSeek API 服务地址;而 `api-key` 则是在完成注册后获得的个人专属密钥。
#### 编写控制器类
接下来,在应用中定义一个新的 REST 控制器用于处理来自客户端的请求并向 DeepSeek 发起查询。下面是一个简单的例子说明如何创建这样的端点:
```java
@RestController
@RequestMapping("/ai")
public class AiController {
@Autowired
private ChatService chatService;
@GetMapping("/generate")
public ResponseEntity<String> generateResponse(@RequestParam String prompt){
try {
// 调用ChatService中的方法获取响应
String response = chatService.getResponse(prompt);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("Error processing request", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
```
上述代码片段展示了一个名为 `/ai/generate` 的 GET 请求处理器,它接收一个参数作为提示(`prompt`)并通过 `chatService` 对象发送给 DeepSeek 进行处理[^2]。
#### 创建聊天服务组件
为了让上面提到的控制层工作正常,还需要有一个实现了与 DeepSeek 交互逻辑的服务组件。这里简单给出框架示意:
```java
@Service
public class ChatServiceImpl implements ChatService {
@Value("${spring.ai.openai.base-url}")
private String baseUrl;
@Value("${spring.ai.openai.api-key}")
private String apiKey;
@Override
public String getResponse(String message) throws Exception{
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + this.apiKey);
HttpEntity<String> entity = new HttpEntity<>(message, headers);
ResponseEntity<String> result = restTemplate.exchange(
this.baseUrl,
HttpMethod.POST,
entity,
String.class
);
return result.getBody();
}
}
```
这段 Java 代码展示了如何利用 `RestTemplate` 向指定 URL 发送 POST 请求,并附带认证信息以访问受保护的 API 接口。
阅读全文
相关推荐




















