
최근 많은 애플리케이션이 단순한 질문·답변을 넘어, 외부 도구와 연동하고 대화 맥락을 이해하는 지능형 AI 에이전트를 필요로 하고 있습니다.
이 글에서는 Google에서 제공하는 Agent Development Kit(ADK) 를 활용해, Java 및 Spring Boot 환경에서 AI 에이전트를 직접 구축하는 과정을 정리합니다.
단순 개념 소개에 그치지 않고,
- Google ADK란 무엇인지
- Spring Boot 프로젝트에서 어떻게 설정하는지
- 대화 컨텍스트를 유지하는 에이전트는 어떻게 만드는지
- 함수 호출(Function Calling)을 통해 외부 로직을 어떻게 연결하는지
를 하나의 흐름으로 이해할 수 있도록 설명합니다.
Google Agent Development Kit(ADK)란?
LLM 기반 애플리케이션의 한계와 필요성
대규모 언어 모델(LLM)은 자연어 이해와 생성에는 강력하지만,
실제 서비스 환경에서는 다음과 같은 요구가 발생합니다.
- 여러 단계의 작업을 조율해야 함
- 대화 이력을 기억해야 함
- 데이터베이스나 외부 API를 호출해야 함
이 역할을 수행하는 것이 바로 AI 에이전트입니다.
Google ADK의 역할
Google Agent Development Kit(ADK) 는
Java 생태계에서 이러한 AI 에이전트를 만들 수 있도록 지원하는 오픈소스 프레임워크입니다.
핵심 특징은 다음과 같습니다.
- LLM을 감싸는 에이전트 구조 제공
- 세션 기반 대화 컨텍스트 관리
- Java 메서드를 도구(Function)로 등록 가능
- Spring Boot와 자연스러운 통합
프로젝트 설정: AI 에이전트 개발 준비
1) 필수 의존성 추가
Spring Boot 프로젝트에서 Google ADK를 사용하기 위해
pom.xml에 다음 의존성을 추가합니다.
<dependency>
<groupId>com.google.adk</groupId>
<artifactId>google-adk</artifactId>
<version>0.5.0</version>
</dependency>
참고 사항
- Java 17 이상 필요
- Gemini API Key를 GOOGLE_API_KEY 환경 변수로 전달해야 함
2) 에이전트 성격을 정의하는 System Prompt
AI 에이전트가 일관된 말투와 역할을 유지하려면 시스템 프롬프트가 필요합니다.
src/main/resources/prompts/agent-system-prompt.txt 파일을 생성하고 다음과 같이 정의합니다.
You are Baelgent, an AI agent representing Baeldung.
You speak like a wise Java developer and answer everything concisely using terminologies from the Java and Spring ecosystem.
If someone asks about non-Java topics, gently remind them that the world and everything in it is a Spring Boot application.
이 프롬프트는 에이전트에게 다음을 명확히 지시합니다.
- 역할: Baeldung을 대표하는 AI 에이전트
- 말투: 현명한 Java 개발자
- 관점: 모든 세상을 Spring Boot 관점에서 해석
3) 에이전트 설정 정보 구성
에이전트의 기본 정보를 application.yaml로 관리합니다.
com:
baeldung:
agent:
name: baelgent
description: Baeldung's AI agent
ai-model: gemini-2.5-flash
system-prompt: classpath:prompts/agent-system-prompt.txt
이를 매핑하기 위한 설정 클래스는 다음과 같습니다.
@ConfigurationProperties(prefix = "com.baeldung.agent")
record AgentProperties(
String name,
String description,
String aiModel,
Resource systemPrompt
) {}
AI 에이전트 구현하기
1) BaseAgent Bean 생성
Google ADK에서 BaseAgent는 LLM을 감싸는 핵심 객체입니다.
@Bean
BaseAgent baseAgent(AgentProperties agentProperties) {
return LlmAgent
.builder()
.name(agentProperties.name())
.description(agentProperties.description())
.model(agentProperties.aiModel())
.instruction(
agentProperties.systemPrompt()
.getContentAsString(Charset.defaultCharset())
)
.build();
}
이 설정을 통해 에이전트는 다음을 갖게 됩니다.
- 이름과 설명
- 사용할 LLM 모델
- 고정된 성격과 응답 방식
2) 사용자 요청과 응답 구조
대화형 에이전트를 위해 요청과 응답을 명확히 분리합니다.
record UserRequest(@Nullable UUID userId,
@Nullable UUID sessionId,
String question) {}
record UserResponse(UUID userId,
UUID sessionId,
String answer) {}
- userId, sessionId는 대화 컨텍스트 유지를 위해 사용
- 값이 없으면 새로 생성
3) 대화 컨텍스트를 유지하는 서비스 로직
@Service
class AgentService {
private final InMemoryRunner runner;
private final ConcurrentMap<String, Session> inMemorySessionCache
= new ConcurrentHashMap<>();
AgentService(BaseAgent baseAgent) {
this.runner = new InMemoryRunner(baseAgent);
}
UserResponse interact(UserRequest request) {
UUID userId = request.userId() != null
? request.userId()
: UUID.randomUUID();
UUID sessionId = request.sessionId() != null
? request.sessionId()
: UUID.randomUUID();
String cacheKey = userId + ":" + sessionId;
Session session = inMemorySessionCache.computeIfAbsent(
cacheKey,
key -> runner.sessionService()
.createSession(
runner.appName(),
userId.toString(),
null,
sessionId.toString()
)
.blockingGet()
);
Content userMessage =
Content.fromParts(Part.fromText(request.question()));
StringBuilder answerBuilder = new StringBuilder();
runner.runAsync(userId.toString(), session.id(), userMessage)
.blockingForEach(event -> {
String content = event.stringifyContent();
if (content != null && !content.isBlank()) {
answerBuilder.append(content);
}
});
return new UserResponse(
userId,
sessionId,
answerBuilder.toString()
);
}
}
이 구현의 핵심은 다음과 같습니다.
- 사용자 + 세션 기준으로 대화 이력 관리
- 동일한 sessionId로 요청 시 이전 대화 맥락 유지
- LLM의 스트리밍 응답을 누적 처리
Function Calling: 외부 로직을 호출하는 에이전트
1) Java 메서드를 도구로 정의
Google ADK는 LLM이 필요하다고 판단하면 Java 메서드를 호출할 수 있도록 지원합니다.
public class AuthorFetcher {
@Schema(description = "Get author details using an article title")
public static Author fetch(String articleTitle) {
return new Author(
"John Doe",
"john.doe@baeldung.com"
);
}
record Author(String name, String emailId) {}
}
- 실제 예제에서는 하드코딩
- 실제 서비스에서는 DB 또는 외부 API 연동 가능
- @Schema 설명은 LLM이 함수 호출 여부를 판단하는 기준이 됨
2) 에이전트에 도구 등록
@Bean
BaseAgent baseAgent(AgentProperties agentProperties) {
return LlmAgent
.builder()
// 기존 설정 생략
.tools(
FunctionTool.create(AuthorFetcher.class, "fetch")
)
.build();
}
이제 에이전트는
“글 작성자가 누구인가?”와 같은 질문에 대해
자동으로 fetch() 메서드를 호출할 수 있습니다.
REST API로 에이전트와 대화하기
1) API 엔드포인트
@PostMapping("/api/v1/agent/interact")
UserResponse interact(@RequestBody UserRequest request) {
return agentService.interact(request);
}
2) 대화 예시
초기 질문:
http POST localhost:8080/api/v1/agent/interact \
question='Which programming language is better than Java?'
응답 특징:
- userId / sessionId 자동 생성
- 시스템 프롬프트에 정의된 Java 중심 답변 유지
후속 질문 시 동일 sessionId 사용하면
이전 대화 내용을 자연스럽게 이어서 응답합니다.
3) 함수 호출 확인 예시
http POST localhost:8080/api/v1/agent/interact \
question="Who wrote the article 'Testing CORS in Spring Boot' and how can I contact him?"
결과적으로 에이전트는
등록된 AuthorFetcher.fetch()를 호출하고
작성자 정보가 포함된 답변을 생성합니다.
글에서는 Google ADK를 활용해 다음을 구현했습니다.
- Java 기반 LLM 에이전트 구축
- 시스템 프롬프트를 통한 에이전트 성격 정의
- 세션 기반 대화 컨텍스트 유지
- Function Calling으로 외부 로직 확장
- REST API를 통한 실제 사용 예시
기대되는 점
- Spring Boot 환경에서 AI 에이전트를 표준 구조로 구현 가능
- 단순 챗봇을 넘어 업무 로직을 수행하는 에이전트로 확장 가능
- Java 개발자에게 친숙한 방식으로 LLM 활용 가능
Google ADK는
**“LLM을 어떻게 애플리케이션 안으로 자연스럽게 가져올 것인가”**에 대한
현실적인 해답을 제공하는 도구라고 볼 수 있습니다.

'JAVA' 카테고리의 다른 글
| Java에서 로컬 LLM을 실행하는 방법: Jlama로 시작하기 (0) | 2026.01.12 |
|---|---|
| 엔터프라이즈 AI 전략, 왜 Python이 아니라 Java부터 시작해야 할까? (0) | 2025.12.23 |
| MyBatis Dynamic SQL 완전 정리: 타입 안전하게 SQL을 생성하는 방법 (0) | 2025.12.16 |
| Java Thread Pool 완벽 가이드: Executor부터 ForkJoinPool, Guava까지 한 번에 정리 (0) | 2025.12.06 |
| Java 25의 Compact Object Headers(객체 헤더 압축) 완전 정복 - JEP 519 기반 메모리 절감 및 성능 향상 분석 (0) | 2025.12.02 |