Spring AI 访问 DeepSeek 有多种方式,我来为你详细介绍具体的配置和使用方法:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-deepseek-spring-boot-starter</artifactId>
<version>0.8.1</version>
</dependency>
spring:
ai:
deepseek:
base-url: https://api.deepseek.com
api-key: ${DEEPSEEK_API_KEY}
chat:
options:
model: deepseek-chat
temperature: 0.7
max-tokens: 2048
@RestController
public class DeepSeekController {
private final ChatClient chatClient;
public DeepSeekController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/chat")
public String chat(@RequestParam String message) {
return chatClient.call(message);
}
}
spring:
ai:
openai:
base-url: https://api.deepseek.com/v1
api-key: ${DEEPSEEK_API_KEY}
chat:
options:
model: deepseek-chat
temperature: 0.7
@Service
public class DeepSeekService {
@Autowired
private OpenAiChatClient chatClient;
public String generateResponse(String prompt) {
return chatClient.call(prompt);
}
public List<String> generateMultipleResponses(String prompt, int count) {
Prompt chatPrompt = new Prompt(new UserMessage(prompt));
ChatResponse response = chatClient.call(chatPrompt);
return response.getResults().stream()
.map(Generation::getOutput)
.map(AssistantMessage::getContent)
.collect(Collectors.toList());
}
}
spring:
ai:
deepseek:
base-url: https://api.deepseek.com
api-key: ${DEEPSEEK_API_KEY}
chat:
options:
model: deepseek-chat
temperature: 0.7
max-tokens: 4096
top-p: 0.9
frequency-penalty: 0.0
presence-penalty: 0.0
retry:
max-attempts: 3
backoff:
initial-interval: 2s
multiplier: 2
max-interval: 10s
@Configuration
public class DeepSeekConfig {
@Bean
public DeepSeekChatOptions deepSeekChatOptions() {
return DeepSeekChatOptions.builder()
.withModel("deepseek-chat")
.withTemperature(0.7)
.withMaxTokens(2048)
.withTopP(0.9)
.withStream(false)
.build();
}
@Bean
public ChatClient chatClient(DeepSeekChatClient deepSeekChatClient) {
return deepSeekChatClient;
}
}
@RestController
public class StreamChatController {
@Autowired
private StreamingChatClient streamingChatClient;
@GetMapping("/chat/stream")
public Flux<String> streamChat(@RequestParam String message) {
return streamingChatClient.stream(message)
.content();
}
@GetMapping(value = "/chat/stream-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamChatSSE(@RequestParam String message) {
return streamingChatClient.stream(message)
.content()
.map(content -> ServerSentEvent.builder(content).build());
}
}
@Service
public class ConversationService {
private final List<Message> conversationHistory = new ArrayList<>();
@Autowired
private ChatClient chatClient;
public String chatWithHistory(String userMessage) {
// 添加用户消息到历史记录
conversationHistory.add(new UserMessage(userMessage));
// 构建包含历史记录的提示
Prompt prompt = new Prompt(conversationHistory);
// 调用 AI
ChatResponse response = chatClient.call(prompt);
String assistantResponse = response.getResult().getOutput().getContent();
// 添加助手响应到历史记录
conversationHistory.add(new AssistantMessage(assistantResponse));
// 限制历史记录长度
if (conversationHistory.size() > 20) {
conversationHistory.remove(0);
conversationHistory.remove(0);
}
return assistantResponse;
}
public void clearHistory() {
conversationHistory.clear();
}
}
@ControllerAdvice
public class DeepSeekExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<ErrorResponse> handleDeepSeekException(RuntimeException ex) {
ErrorResponse error = new ErrorResponse("DEEPSEEK_ERROR", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<ErrorResponse> handleHttpException(HttpClientErrorException ex) {
ErrorResponse error = new ErrorResponse("API_ERROR", ex.getStatusCode().toString());
return ResponseEntity.status(ex.getStatusCode()).body(error);
}
}
// 错误响应类
public record ErrorResponse(String code, String message) {}
@SpringBootTest
class DeepSeekServiceTest {
@Autowired
private DeepSeekService deepSeekService;
@Test
void testChat() {
String response = deepSeekService.generateResponse("你好,请介绍一下你自己");
assertNotNull(response);
assertFalse(response.isEmpty());
}
@TestConfiguration
static class TestConfig {
@Bean
@Primary
public DeepSeekChatClient deepSeekChatClient() {
// 可以在这里配置 Mock 客户端用于测试
return mock(DeepSeekChatClient.class);
}
}
}
@Configuration
public class SecurityConfig {
@Value("${deepseek.api.key}")
private String apiKey;
@Bean
public DeepSeekApi deepSeekApi() {
return new DeepSeekApi(apiKey);
}
}
spring:
ai:
deepseek:
connect-timeout: 10s
read-timeout: 30s
task:
execution:
pool:
core-size: 10
max-size: 50
queue-capacity: 1000
通过以上配置,你就可以在 Spring Boot 应用中轻松集成 DeepSeek 的 AI 能力了。记得根据实际需求调整参数和错误处理逻辑。