专业的编程技术博客社区

网站首页 > 博客文章 正文

如何在 Java 项目中集成 DeepSeek

baijin 2025-06-23 14:47:09 博客文章 2 ℃ 0 评论

一、使用官方 SDK 基础集成

1. 添加依赖(Maven)

<dependency>
    <groupId>com.deepseek</groupId>
    <artifactId>deepseek-sdk</artifactId>
    <version>最新版本号</version>
</dependency>

需替换为 SDK 最新版本号

2. 初始化客户端

import com.deepseek.client.DeepSeekClient;
import com.deepseek.client.DeepSeekClientBuilder;

public class DeepSeekExample {
    public static void main(String[] args) {
        DeepSeekClient client = DeepSeekClientBuilder.newBuilder()
                .withApiKey("your_api_key")  // 替换真实 API 密钥
                .build();
        
        // 示例:执行搜索
        SearchResponse response = client.search(
            new SearchRequest.Builder("Java 多线程").build()
        );
        System.out.println(response.getResults());
    }
}

支持异常捕获 DeepSeekException 处理网络或 API 错误1


二、Spring Boot 深度集成

1. 配置文件(application.yml)

@Service
public class DeepSeekService {
    @Value("${deepseek.api.key}")
    private String apiKey;

    public String chatCompletion(String prompt) {
        // 使用 SDK 或 HTTP 客户端实现
        return sendChatRequest(prompt);
    }

    private String sendChatRequest(String prompt) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://api.deepseek.com/chat/completions");
        post.setHeader("Authorization", "Bearer " + apiKey);
        
        String jsonBody = String.format("{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}]}", prompt);
        post.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
        
        try (CloseableHttpResponse response = client.execute(post)) {
            return EntityUtils.toString(response.getEntity());
        }
    }
}

支持流式响应处理,需结合 ResponseEntity<Flux<String>>4 7


三、使用第三方库 DeepSeek4J(推荐)

1. 添加 Starter 依赖

<dependency>
    <groupId>io.github.pig-mesh.ai</groupId>
    <artifactId>deepseek-spring-boot-starter</artifactId>
    <version>1.1.0</version>
</dependency>

2. 流式交互接口

@RestController
@RequestMapping("/ai")
public class ChatController {
    @Autowired
    private DeepSeekClient deepSeekClient;

    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatCompletionResponse> streamChat(String question) {
        return deepSeekClient.chatFluxCompletion(question);
    }
}

该库完整保留思维链输出,支持响应式编程9


四、原生 HTTP 请求实现

public static String askDeepSeek(String question) throws IOException {
    URL url = new URL("https://api.deepseek.com/chat/completions");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer your_api_key");
    conn.setRequestProperty("Content-Type", "application/json");

    String jsonInput = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\""+question+"\"}]}";
    try (OutputStream os = conn.getOutputStream()) {
        os.write(jsonInput.getBytes(StandardCharsets.UTF_8));
    }
    
    try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        return br.lines().collect(Collectors.joining());
    }
}

五、扩展功能示例(数据上传分析)

// 上传 CSV 数据集
File dataFile = new File("data.csv");
DatasetService datasetService = client.getDatasetService();
Dataset dataset = datasetService.uploadCsv(dataFile, "销售数据");

// 执行 SQL 式查询
String query = "SELECT product, SUM(amount) FROM " + dataset.getId() + " GROUP BY product";
List<DataRecord> results = datasetService.executeQuery(query);

支持复杂数据分析操作,需企业版 API 权限5


注意事项

  1. API 密钥管理:推荐使用环境变量或 Vault 加密存储,避免硬编码4 5
  2. 错误处理:需捕获 IOException 和 DeepSeekException 处理超时/限流1 7
  3. 性能优化:对高频调用建议使用连接池(如 Apache HttpClient Pooling)

以上方案可根据项目复杂度选择,小型项目推荐直接使用 HTTP 实现,企业级建议采用官方 SDK 或 DeepSeek4J 方案。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表