DeepSeek是国内领先的人工智能大模型平台,提供强大的自然语言处理能力。通过API接入,开发者可以快速为应用添加以下AI功能:
确保项目已包含基础依赖:
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.13version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
dependency>
dependencies>
创建配置类管理API密钥:
@Configuration
public class DeepSeekConfig {
@Value("${deepseek.api.key}")
private String apiKey;
@Value("${deepseek.api.url}")
private String apiUrl;
@Bean
public CloseableHttpClient httpClient() {
return HttpClients.createDefault();
}
// 其他配置...
}
在application.yml
中添加配置:
deepseek:
api:
key: your_api_key_here
url: https://api.deepseek.com/v1/chat/completions
创建服务层处理API调用:
@Service
@Slf4j
public class DeepSeekService {
private final String apiUrl;
private final String apiKey;
private final CloseableHttpClient httpClient;
private final ObjectMapper objectMapper;
public DeepSeekService(@Value("${deepseek.api.url}") String apiUrl,
@Value("${deepseek.api.key}") String apiKey,
CloseableHttpClient httpClient,
ObjectMapper objectMapper) {
this.apiUrl = apiUrl;
this.apiKey = apiKey;
this.httpClient = httpClient;
this.objectMapper = objectMapper;
}
public String chatCompletion(String prompt) throws IOException {
HttpPost httpPost = new HttpPost(apiUrl);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + apiKey);
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", "deepseek-chat");
requestBody.put("messages", List.of(Map.of("role", "user", "content", prompt)));
requestBody.put("temperature", 0.7);
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
httpPost.setEntity(entity);
// 执行请求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseBody = EntityUtils.toString(response.getEntity());
Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
// 解析响应
List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
if (choices != null && !choices.isEmpty()) {
Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
return (String) message.get("content");
}
return "未获取到有效响应";
}
}
}
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AIController {
private final DeepSeekService deepSeekService;
@PostMapping("/chat")
public ResponseEntity<String> chat(@RequestBody ChatRequest request) {
try {
String response = deepSeekService.chatCompletion(request.getPrompt());
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("请求DeepSeek服务失败: " + e.getMessage());
}
}
@Data
public static class ChatRequest {
private String prompt;
}
}
@Async
public CompletableFuture<String> asyncChatCompletion(String prompt) {
try {
String response = chatCompletion(prompt);
return CompletableFuture.completedFuture(response);
} catch (Exception e) {
CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
}
public void streamChatCompletion(String prompt, OutputStream outputStream) throws IOException {
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setHeader("Accept", "text/event-stream");
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", "deepseek-chat");
requestBody.put("messages", List.of(Map.of("role", "user", "content", prompt)));
requestBody.put("stream", true);
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("data: ")) {
String jsonData = line.substring(6);
if (!"[DONE]".equals(jsonData)) {
Map<String, Object> data = objectMapper.readValue(jsonData, Map.class);
// 处理流式数据
outputStream.write(processStreamData(data).getBytes());
outputStream.flush();
}
}
}
}
}
@Retryable(value = {IOException.class, RuntimeException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, multiplier = 2))
public String reliableChatCompletion(String prompt) throws IOException {
return chatCompletion(prompt);
}
@Recover
public String recoverChatCompletion(Exception e, String prompt) {
log.error("DeepSeek服务调用失败,已重试3次", e);
return "服务暂时不可用,请稍后再试";
}
@Service
public class CustomerSupportService {
private final DeepSeekService deepSeekService;
private final KnowledgeBaseService knowledgeBaseService;
public String handleCustomerQuery(String question) {
// 1. 从知识库检索相关文档
String context = knowledgeBaseService.searchRelevantDocuments(question);
// 2. 构建增强提示词
String enhancedPrompt = String.format(
"你是一个专业的客服助手。根据以下上下文回答问题:\n\n%s\n\n问题:%s\n\n回答:",
context, question);
// 3. 调用DeepSeek获取回答
return deepSeekService.chatCompletion(enhancedPrompt);
}
}
@Service
public class ContentGenerationService {
public String generateBlogPost(String topic, String keywords) {
String prompt = String.format(
"请以'%s'为主题,包含关键词'%s',撰写一篇1000字左右的技术博客文章。" +
"要求结构清晰,包含引言、正文和结论部分。", topic, keywords);
return deepSeekService.chatCompletion(prompt);
}
}
@Service
@CacheConfig(cacheNames = "aiResponses")
public class CachedDeepSeekService {
private final DeepSeekService deepSeekService;
@Cacheable(key = "#prompt.hashCode()", unless = "#result.length() > 10000")
public String cachedChatCompletion(String prompt) throws IOException {
return deepSeekService.chatCompletion(prompt);
}
}
@Configuration
public class RateLimitConfig {
@Bean
public RateLimiter deepSeekRateLimiter() {
// 每秒2个请求,突发5个
return RateLimiter.create(2.0);
}
}
@Service
public class RateLimitedDeepSeekService {
private final DeepSeekService deepSeekService;
private final RateLimiter rateLimiter;
public String rateLimitedChatCompletion(String prompt) throws IOException {
if (rateLimiter.tryAcquire(1, 5, TimeUnit.SECONDS)) {
return deepSeekService.chatCompletion(prompt);
}
throw new RuntimeException("请求过于频繁,请稍后再试");
}
}
@Aspect
@Component
@Slf4j
public class DeepSeekMonitoringAspect {
@Around("execution(* com.example.service.DeepSeekService.*(..))")
public Object monitorDeepSeekCalls(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
String methodName = joinPoint.getSignature().getName();
try {
Object result = joinPoint.proceed();
long duration = System.currentTimeMillis() - startTime;
log.info("DeepSeek调用成功 - 方法: {}, 耗时: {}ms", methodName, duration);
Metrics.counter("deepseek.calls", "method", methodName, "status", "success").increment();
Metrics.timer("deepseek.latency", "method", methodName).record(duration, TimeUnit.MILLISECONDS);
return result;
} catch (Exception e) {
Metrics.counter("deepseek.calls", "method", methodName, "status", "failure").increment();
log.error("DeepSeek调用失败 - 方法: {}", methodName, e);
throw e;
}
}
}
API密钥保护:
输入验证:
public String safeChatCompletion(String prompt) {
if (prompt == null || prompt.trim().isEmpty()) {
throw new IllegalArgumentException("提示词不能为空");
}
if (prompt.length() > 1000) {
throw new IllegalArgumentException("提示词过长");
}
// 防止注入攻击
String sanitizedPrompt = prompt.replaceAll("[<>\"']", "");
return deepSeekService.chatCompletion(sanitizedPrompt);
}
敏感数据过滤:
通过本文,你已经掌握了在SpringBoot项目中接入DeepSeek的核心方法。关键步骤包括:
进一步扩展方向:
通过合理利用DeepSeek的AI能力,可以显著提升应用的智能化水平,为用户提供更优质的服务体验。