DeepSeek 集成
大约 6 分钟
第四章:集成DeepSeek
4.1 DeepSeek模型特性
DeepSeek是智谱AI开发的大语言模型,以其强大的中文处理能力和专业知识而闻名。
4.1.1 DeepSeek模型特点
- 卓越的中文理解:专门优化中文语言处理
- 专业知识丰富:涵盖多个专业领域
- 推理能力强:复杂的逻辑推理能力
- API响应快:高效的API服务
4.1.2 可用的DeepSeek模型
DeepSeek提供了多个模型版本:
- deepseek-chat:标准对话模型
- deepseek-code:代码生成和编程助手
- deepseek-math:数学问题解决
- deepseek-research:研究级模型
4.2 配置DeepSeek客户端
4.2.1 添加依赖
在pom.xml中添加DeepSeek依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-deepseek-spring-boot-starter</artifactId>
</dependency>4.2.2 配置API密钥
在application.properties中配置DeepSeek API密钥:
# DeepSeek配置
spring.ai.deepseek.api-key=your-deepseek-api-key
spring.ai.deepseek.chat.options.model=deepseek-chat
spring.ai.deepseek.chat.options.temperature=0.7
spring.ai.deepseek.chat.options.max-tokens=10004.2.3 编程配置
@Configuration
public class DeepSeekConfig {
@Bean
public ChatClient deepSeekChatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("You are a helpful assistant with deep knowledge")
.defaultOptions(DeepSeekChatOptions.builder()
.withModel("deepseek-plus")
.withTemperature(0.8f)
.withMaxTokens(1500)
.build())
.build();
}
}4.3 对话应用开发
4.3.1 基础对话
@RestController
public class DeepSeekController {
private final ChatClient deepSeekChatClient;
public DeepSeekController(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
@GetMapping("/deepseek/chat")
public String chat(@RequestParam String message) {
return deepSeekChatClient.prompt()
.user(message)
.call()
.content();
}
}4.3.2 专业领域对话
@GetMapping("/deepseek/expert")
public String expertChat(
@RequestParam String domain,
@RequestParam String question) {
return deepSeekChatClient.prompt()
.system("You are an expert in " + domain)
.user(question)
.call()
.content();
}4.3.3 代码生成
DeepSeek特别适合代码生成任务:
@GetMapping("/deepseek/code")
public String generateCode(
@RequestParam String language,
@RequestParam String requirement) {
return deepSeekChatClient.prompt()
.system("You are a professional " + language + " developer")
.user("Write code for: " + requirement)
.call()
.content();
}4.4 多轮对话管理
4.4.1 上下文管理
@RestController
public class ConversationController {
private final ChatClient deepSeekChatClient;
public ConversationController(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
@PostMapping("/deepseek/conversation")
public ConversationResponse conversation(@RequestBody ConversationRequest request) {
ChatPrompt chatPrompt = new ChatPrompt();
// 添加系统提示
chatPrompt.add(new SystemMessage(request.getSystemPrompt()));
// 添加历史消息
for (Message message : request.getHistory()) {
chatPrompt.add(message);
}
// 添加当前消息
chatPrompt.add(new UserMessage(request.getCurrentMessage()));
ChatResponse response = deepSeekChatClient.prompt(chatPrompt).call();
return new ConversationResponse(
response.getContent(),
response.getResults().get(0).getGenerationMetadata()
);
}
}4.4.2 对话状态管理
@Service
public class ConversationService {
private final ChatClient deepSeekChatClient;
private final Map<String, Conversation> conversations = new ConcurrentHashMap<>();
public ConversationService(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
public String sendMessage(String conversationId, String message) {
Conversation conversation = conversations.computeIfAbsent(
conversationId,
id -> new Conversation()
);
conversation.addMessage(new UserMessage(message));
ChatPrompt chatPrompt = new ChatPrompt();
chatPrompt.add(new SystemMessage(conversation.getSystemPrompt()));
for (Message msg : conversation.getMessages()) {
chatPrompt.add(msg);
}
ChatResponse response = deepSeekChatClient.prompt(chatPrompt).call();
String content = response.getContent();
conversation.addMessage(new AssistantMessage(content));
return content;
}
public void clearConversation(String conversationId) {
conversations.remove(conversationId);
}
}4.4.3 对话持久化
@Repository
public class ConversationRepository {
private final Map<String, Conversation> conversations = new ConcurrentHashMap<>();
public Conversation save(Conversation conversation) {
conversations.put(conversation.getId(), conversation);
return conversation;
}
public Optional<Conversation> findById(String id) {
return Optional.ofNullable(conversations.get(id));
}
public void deleteById(String id) {
conversations.remove(id);
}
}4.5 高级功能
4.5.1 函数调用
DeepSeek支持强大的函数调用功能:
@RestController
public class DeepSeekFunctionController {
private final ChatClient deepSeekChatClient;
public DeepSeekFunctionController(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
@GetMapping("/deepseek/function")
public String functionCall(@RequestParam String question) {
FunctionCallback weatherFunction = new FunctionCallback(
"getWeather",
"Get current weather for a location",
new Schema(SchemaType.OBJECT)
.addProperty("location", SchemaProperty.of(SchemaType.STRING, "City name"))
.addRequired("location"),
this::getWeather
);
FunctionCallback calculatorFunction = new FunctionCallback(
"calculate",
"Perform mathematical calculations",
new Schema(SchemaType.OBJECT)
.addProperty("expression", SchemaProperty.of(SchemaType.STRING, "Mathematical expression"))
.addRequired("expression"),
this::calculate
);
return deepSeekChatClient.prompt()
.user(question)
.functions(weatherFunction, calculatorFunction)
.call()
.content();
}
private String getWeather(Map<String, Object> arguments) {
String location = (String) arguments.get("location");
return "The current weather in " + location + " is 25°C and sunny";
}
private String calculate(Map<String, Object> arguments) {
String expression = (String) arguments.get("expression");
// 实际计算逻辑
return "Result: " + evaluateExpression(expression);
}
}4.5.2 图像分析
DeepSeek视觉模型支持图像分析:
@RestController
public class DeepSeekImageController {
private final ImageClient imageClient;
public DeepSeekImageController(ImageClient imageClient) {
this.imageClient = imageClient;
}
@PostMapping("/deepseek/analyze-image")
public String analyzeImage(@RequestParam MultipartFile image, @RequestParam String question) {
ImagePrompt imagePrompt = new ImagePrompt(image, question);
ImageResponse response = imageClient.generate(imagePrompt);
return response.getResult().getOutput().getContent();
}
}4.6 实际应用示例
4.6.1 智能问答系统
@Service
public class QaSystemService {
private final ChatClient deepSeekChatClient;
public QaSystemService(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
public QaResponse answerQuestion(String question) {
return deepSeekChatClient.prompt()
.system("You are a knowledge base assistant")
.user(question)
.call()
.entity(QaResponse.class);
}
}
public class QaResponse {
private String answer;
private String source;
private double confidence;
// getters and setters
}4.6.2 内容审核系统
@RestController
public class ContentModerationController {
private final ChatClient deepSeekChatClient;
public ContentModerationController(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
@PostMapping("/deepseek/moderate")
public ModerationResult moderateContent(@RequestBody Content content) {
String prompt = "Analyze the following content for inappropriate material: " + content.getText();
return deepSeekChatClient.prompt()
.user(prompt)
.call()
.entity(ModerationResult.class);
}
}
public class ModerationResult {
private boolean containsProfanity;
private boolean containsHateSpeech;
private boolean containsViolence;
private String explanation;
// getters and setters
}4.7 性能优化
4.7.1 批量处理
@RestController
public class BatchProcessingController {
private final ChatClient deepSeekChatClient;
public BatchProcessingController(ChatClient deepSeekChatClient) {
this.deepSeekChatClient = deepSeekChatClient;
}
@PostMapping("/deepseek/batch")
public List<String> batchProcess(@RequestBody List<String> messages) {
return messages.stream()
.map(message -> deepSeekChatClient.prompt()
.user(message)
.call()
.content())
.collect(Collectors.toList());
}
}4.7.2 连接池管理
@Configuration
public class DeepSeekPoolingConfig {
@Bean
public ChatClient pooledChatClient(ChatClient chatClient) {
return new ChatClient() {
private final ExecutorService executor = Executors.newFixedThreadPool(10);
@Override
public ChatResponse call(Prompt prompt) {
try {
return executor.submit(() -> chatClient.call(prompt)).get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Failed to call DeepSeek", e);
}
}
// 实现其他方法...
};
}
}4.8 错误处理
4.8.1 异常处理
@RestControllerAdvice
public class DeepSeekExceptionHandler {
@ExceptionHandler(DeepSeekApiException.class)
public ResponseEntity<ErrorResponse> handleDeepSeekError(DeepSeekApiException ex) {
ErrorResponse error = new ErrorResponse(
"DEEPSEEK_API_ERROR",
"DeepSeek API调用失败: " + ex.getMessage()
);
return new ResponseEntity<>(error, HttpStatus.SERVICE_UNAVAILABLE);
}
}4.8.2 降级策略
@Configuration
public class DeepSeekFallbackConfig {
@Bean
public ChatClient fallbackChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
try {
return chatClient.call(prompt);
} catch (Exception ex) {
// 降级到本地模型或默认响应
return new ChatResponse(
List.of(new Generation("对不起,我暂时无法回答您的问题。", null)),
Map.of()
);
}
}
// 实现其他方法...
};
}
}4.9 监控与日志
4.9.1 指标监控
@RestController
public class DeepSeekMetricsController {
private final MeterRegistry meterRegistry;
public DeepSeekMetricsController(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@GetMapping("/deepseek/metrics")
public Map<String, Object> getMetrics() {
return Map.of(
"totalCalls", meterRegistry.counter("deepseek.total.calls").count(),
"averageDuration", meterRegistry.timer("deepseek.duration").mean(),
"errorRate", meterRegistry.counter("deepseek.errors").count() /
(meterRegistry.counter("deepseek.total.calls").count() + 1.0)
);
}
}4.9.2 请求日志
@Configuration
public class DeepSeekLogging {
@Bean
public ChatClient loggingChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
long startTime = System.currentTimeMillis();
try {
ChatResponse response = chatClient.call(prompt);
long duration = System.currentTimeMillis() - startTime;
log.info("DeepSeek调用 - 耗时: {}ms, Prompt: {}", duration, prompt);
return response;
} catch (Exception ex) {
log.error("DeepSeek调用失败", ex);
throw ex;
}
}
// 实现其他方法...
};
}
}4.10 小结
本章详细介绍了DeepSeek模型的集成和使用:
- 模型特点:了解DeepSeek的核心优势,特别是中文处理能力
- 客户端配置:掌握DeepSeek客户端的配置方法
- 对话应用:学习基本的对话交互和专业领域应用
- 多轮对话:掌握上下文管理和对话状态管理
- 高级功能:了解函数调用、图像分析等高级特性
- 实际应用:学习智能问答、内容审核等实际应用场景
- 性能优化:掌握批量处理、连接池等优化技术
- 错误处理:了解异常处理和降级策略
- 监控日志:掌握指标监控和请求日志
在下一章中,我们将学习如何集成OpenAI模型。 点击这里👇🏻获取:100万QPS短链系统、复杂的商城微服务系统、智能翻译助手AI Agent、SaaS点餐系统、刷题吧小程序、商城系统、秒杀系统、AI项目、代码生成神器、苏三demo项目、智能天气播报AI Agent、智能代码审查AI Agent等 10 个项目的:项目源代码、开发教程和技术答疑
