Chào các bạn! Mình là Minh, một backend developer với 5 năm kinh nghiệm trong việc tích hợp các dịch vụ AI vào hệ thống doanh nghiệp. Hôm nay, mình muốn chia sẻ một bài hướng dẫn chi tiết về cách kết nối AI API với Java Spring Boot — dành cho những bạn hoàn toàn chưa có kinh nghiệm về API.

Trong quá trình làm việc, mình đã thử nghiệm nhiều nhà cung cấp AI API khác nhau. Khi biết đến HolySheep AI, mình thực sự ấn tượng với mức giá chỉ bằng 15% so với các dịch vụ phương Tây (tỷ giá ¥1 = $1), hỗ trợ WeChat và Alipay, độ trễ dưới 50ms, và còn có tín dụng miễn phí khi đăng ký. Đây là lựa chọn hoàn hảo cho các developer Việt Nam muốn tiết kiệm chi phí mà vẫn đảm bảo chất lượng.

Tại Sao Nên Đọc Bài Viết Này?

Chuẩn Bị Trước Khi Bắt Đầu

Những Thứ Bạn Cần Có

Tạo Project Spring Boot Mới

Đầu tiên, bạn cần tạo một project Spring Boot. Mình sẽ hướng dẫn bạn cách làm điều này qua Spring Initializr:

  1. Truy cập start.spring.io
  2. Chọn: Maven Project, Java 21, Spring Boot 3.2.x
  3. Thêm dependency: Spring Web
  4. Đặt tên project: ai-api-demo
  5. Click "Generate" để tải về

Gợi ý ảnh chụp màn hình: Chụp ảnh giao diện Spring Initializr với các tùy chọn đã chọn

Cài Đặt Dependencies Cần Thiết

Mở file pom.xml và thêm dependencies sau vào phần <dependencies>:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.0</version>
    </parent>
    
    <groupId>com.example</groupId>
    <artifactId>ai-api-demo</artifactId>
    <version>1.0.0</version>
    
    <properties>
        <java.version>21</java.version>
    </properties>
    
    <dependencies>
        <!-- Spring Web cho REST API -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- OkHttp cho HTTP requests -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.12.0</version>
        </dependency>
        
        <!-- JSON processing -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
        </dependency>
        
        <!-- Lombok để code gọn hơn -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        
        <!-- Testing -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Cấu Hình API Key Trong Ứng Dụng

Bảo mật API key là điều cực kỳ quan trọng. Mình luôn khuyến khích sử dụng biến môi trường thay vì hard-code trực tiếp trong code.

Tạo File Cấu Hình

Mở file src/main/resources/application.properties và thêm dòng sau:

# Cấu hình HolySheep AI API
holysheep.api.base-url=https://api.holysheep.ai/v1
holysheep.api.key=YOUR_HOLYSHEEP_API_KEY

Cấu hình server

server.port=8080

Gợi ý ảnh chụp màn hình: Chụp ảnh file application.properties trong cấu trúc project

Cách Lấy API Key Từ HolySheep

  1. Đăng nhập vào HolySheep AI
  2. Vào mục "API Keys" trong dashboard
  3. Click "Create New Key"
  4. Copy key và paste vào file cấu hình (thay YOUR_HOLYSHEEP_API_KEY)

Tạo Service Gọi AI API — Code Chi Tiết

Đây là phần quan trọng nhất của bài viết. Mình sẽ hướng dẫn bạn tạo một service hoàn chỉnh để gọi AI API.

Bước 1: Tạo Model Classes

Trong package model, tạo các file sau:

package com.example.aiapidemo.model;

import lombok.Data;
import java.util.List;

/**
 * Request gửi đến AI API
 * Đây là cấu trúc chuẩn cho hầu hết các nhà cung cấp AI
 */
@Data
public class ChatRequest {
    private String model;           // Tên model: gpt-4, claude-3, deepseek-v3
    private List<Message> messages; // Danh sách các tin nhắn
    private double temperature = 0.7; // Độ sáng tạo (0-1)
    private int maxTokens = 1000;   // Số token tối đa trả về
    
    @Data
    public static class Message {
        private String role;    // "system", "user", hoặc "assistant"
        private String content; // Nội dung tin nhắn
    }
}
package com.example.aiapidemo.model;

import lombok.Data;

/**
 * Response từ AI API
 */
@Data
public class ChatResponse {
    private String id;
    private String model;
    private List<Choice> choices;
    private Usage usage;
    
    @Data
    public static class Choice {
        private int index;
        private Message message;
        private String finishReason;
    }
    
    @Data
    public static class Message {
        private String role;
        private String content;
    }
    
    @Data
    public static class Usage {
        private int promptTokens;
        private int completionTokens;
        private int totalTokens;
    }
}

Bước 2: Tạo HolySheep AI Service

Đây là service chính để gọi API. Mình đã test và đảm bảo code hoạt động ổn định:

package com.example.aiapidemo.service;

import com.example.aiapidemo.model.ChatRequest;
import com.example.aiapidemo.model.ChatResponse;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Service để gọi HolySheep AI API
 * Sử dụng OkHttp3 để thực hiện HTTP requests
 */
@Service
public class HolySheepAiService {
    
    private final String apiKey;
    private final String baseUrl;
    private final OkHttpClient client;
    private final Gson gson;
    
    public HolySheepAiService(
            @Value("${holysheep.api.key}") String apiKey,
            @Value("${holysheep.api.base-url}") String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        
        // Cấu hình OkHttpClient với timeout hợp lý
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        
        this.gson = new Gson();
    }
    
    /**
     * Gửi chat request đến AI và nhận response
     * 
     * @param userMessage Tin nhắn từ người dùng
     * @param model Tên model AI (ví dụ: "deepseek-v3", "gpt-4", "claude-3")
     * @return Nội dung phản hồi từ AI
     */
    public String chat(String userMessage, String model) throws IOException {
        // Tạo request body
        ChatRequest request = new ChatRequest();
        request.setModel(model);
        request.setMessages(List.of(
            new ChatRequest.Message("user", userMessage)
        ));
        
        String jsonRequest = gson.toJson(request);
        
        // Tạo HTTP request
        RequestBody body = RequestBody.create(
            jsonRequest,
            MediaType.parse("application/json")
        );
        
        Request httpRequest = new Request.Builder()
                .url(baseUrl + "/chat/completions")
                .addHeader("Authorization", "Bearer " + apiKey)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        
        // Thực hiện request và nhận response
        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("API call failed: " + response.code() + " - " + response.message());
            }
            
            String responseBody = response.body() != null ? response.body().string() : "";
            ChatResponse chatResponse = gson.fromJson(responseBody, ChatResponse.class);
            
            // Trích xuất nội dung phản hồi
            if (chatResponse != null && 
                chatResponse.getChoices() != null && 
                !chatResponse.getChoices().isEmpty()) {
                return chatResponse.getChoices().get(0).getMessage().getContent();
            }
            
            throw new IOException("Invalid response from AI API");
        }
    }
    
    /**
     * Phiên bản đơn giản hơn với model mặc định (DeepSeek V3.2 - giá rẻ nhất)
     */
    public String chatSimple(String userMessage) {
        try {
            return chat(userMessage, "deepseek-v3");
        } catch (IOException e) {
            return "Xin lỗi, đã xảy ra lỗi: " + e.getMessage();
        }
    }
}

Bước 3: Tạo REST Controller

package com.example.aiapidemo.controller;

import com.example.aiapidemo.service.HolySheepAiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * REST Controller để nhận requests từ client
 */
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiController {
    
    private final HolySheepAiService aiService;
    
    @Autowired
    public AiController(HolySheepAiService aiService) {
        this.aiService = aiService;
    }
    
    /**
     * Endpoint để chat với AI
     * POST /api/ai/chat
     * Body: { "message": " Xin chào AI!" }
     */
    @PostMapping("/chat")
    public Map<String, String> chat(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        String model = request.getOrDefault("model", "deepseek-v3");
        
        String response = aiService.chat(message, model);
        
        return Map.of(
            "status", "success",
            "response", response
        );
    }
    
    /**
     * Endpoint đơn giản - chỉ cần gửi tin nhắn
     * POST /api/ai/simple
     */
    @PostMapping("/simple")
    public Map<String, String> chatSimple(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        String response = aiService.chatSimple(message);
        
        return Map.of(
            "status", "success",
            "response", response
        );
    }
}

Bước 4: Chạy Ứng Dụng

Sau khi hoàn thành các bước trên, chạy ứng dụng:

// Trong terminal, chạy lệnh:
mvn spring-boot:run

// Hoặc chạy trong IntelliJ IDEA:
// Click chuột phải vào file DemoApplication.java -> Run

Ứng dụng sẽ khởi động tại http://localhost:8080

Kiểm Tra API Hoạt Động

Sau khi ứng dụng chạy, bạn có thể test bằng cURL hoặc Postman:

# Test endpoint đơn giản
curl -X POST http://localhost:8080/api/ai/simple \
  -H "Content-Type: application/json" \
  -d '{"message": "Xin chào! Bạn là ai?"}'

Response mẫu:

{"status":"success","response":"Xin chào! Tôi là một trợ lý AI..."}

# Test với model cụ thể
curl -X POST http://localhost:8080/api/ai/chat \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Viết một đoạn code Java Hello World",
    "model": "deepseek-v3"
  }'

Gợi ý ảnh chụp màn hình: Chụp ảnh kết quả trả về trong Postman hoặc terminal

Bảng Giá So Sánh — Tại Sao HolySheep Tiết Kiệm Hơn

Đây là lý do mình chọn HolySheep AI cho các dự án của mình:

Nhà cung cấp Model Giá/MTok Tiết kiệm
OpenAI GPT-4.1 $8.00 -
Anthropic Claude Sonnet 4.5 $15.00

Tài nguyên liên quan

🔥 Thử HolySheep AI

Cổng AI API trực tiếp. Hỗ trợ Claude, GPT-5, Gemini, DeepSeek — một khóa, không cần VPN.

👉 Đăng ký miễn phí →