프레임워크/Spring

[Spring Boot] Spring AI와 GCP Vertex API 연동하기

munsik22 2026. 6. 9. 15:37

사전 작업

  • GCP 콘솔에서 Vertex API 기능 활성화하기
gcloud services enable aiplatform.googleapis.com
  • Agent Platform API 활성화 (주의: Vertex AI 기능이 Agent Platform API로 통합되었다. 아마 최근에 바뀐듯?)

  • IAM 설정: 'Agent Platform' 사용자 추가

  • API 및 서비스 - 사용자 인증 정보 만들기 - 서비스 계정 생성
    • 'Agent Platform 익스프레스 사용자(베타)' 권한 추가
    • JSON 키 발급
  • 다운로드받은 JSON 키를 base64 인코딩 문자열로 변환
import base64

# JSON 파일 경로 지정
json_file_path = 'my_key.json'

# JSON 파일을 바이너리 모드로 읽기
with open(json_file_path, 'rb') as f:
    json_bytes = f.read()

# base64 인코딩
encoded_bytes = base64.b64encode(json_bytes)

# 바이트를 문자열로 변환
encoded_str = encoded_bytes.decode('utf-8')

print(encoded_str)

Spring 프로젝트 생성하기

  • build.gradle
repositories {
    mavenCentral()
    maven { url 'https://repo.spring.io/milestone' }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation 'org.springframework.ai:spring-ai-starter-model-vertex-ai-gemini'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.ai:spring-ai-bom:1.1.7"
    }
}
  • .env 파일 생성
GCP_PROJECT_ID=your-project-id
GCP_CREDENTIALS_BASE64=ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCi...
  • application.yml 생성
spring:
  ai:
    vertex:
      ai:
        gemini:
          project-id: ${GCP_PROJECT_ID}
          location: asia-northeast3
          chat:
            options:
              model: "gemini-2.5-flash"
              temperature: 0.7
              max-output-tokens: 8192
              top-k: 40
              top-p: 0.8

 

사용 가능한 location과 model의 조합은 아래 링크를 보면 된다. (참고로 asia-northeast3에서는 gemini-2.5-flash만 사용 가능하다.)

 

배포 및 엔드포인트  |  Gemini Enterprise Agent Platform  |  Google Cloud Documentation

지원되는 위치와 제한사항을 비롯해 Agent Platform에서 Google 및 파트너 생성형 AI 모델에 사용할 수 있는 리전 및 전역 엔드포인트에 대해 알아봅니다.

docs.cloud.google.com

  • VertexAiConfig 생성
@Configuration
public class VertexAiConfig {

    @Value("${GCP_CREDENTIALS_BASE64}")
    private String base64Credentials;

    @Value("${spring.ai.vertex.ai.gemini.project-id}")
    private String projectId;

    @Value("${spring.ai.vertex.ai.gemini.location}")
    private String location;

    @Bean
    @Primary
    public VertexAI vertexAi() throws IOException {
        byte[] decodedKey = Base64.getDecoder().decode(base64Credentials.trim());
        
        GoogleCredentials credentials = GoogleCredentials.fromStream(new ByteArrayInputStream(decodedKey))
                .createScoped(Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));

        return new VertexAI.Builder()
                .setProjectId(projectId)
                .setLocation(location)
                .setCredentials(credentials)
                .build();
    }
}
  • AiController 생성
@RestController
public class AiController {

    private final ChatClient chatClient;

    public AiController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping(value = "/chat", produces = "text/plain;charset=UTF-8")
    public String chat(@RequestParam("message") String message) {

        ChatResponse response = chatClient.prompt()
                .user(message)
                .call()
                .chatResponse();

        return response.getResult().getOutput().getText();
    }
}
  • Postman 테스트