빠른 시작¶
이 빠른 시작 가이드는 Agent Development Kit (ADK)를 설치하고, 여러 도구를 갖춘 기본 에이전트를 설정한 후, 터미널이나 대화형 브라우저 기반 개발 UI에서 로컬로 실행하는 과정을 안내합니다.
이 빠른 시작은 로컬 IDE(VS Code, PyCharm, IntelliJ IDEA 등)에 Python 3.9+ 또는 Java 17+가 설치되어 있고 터미널을 사용할 수 있다고 가정합니다. 이 방법은 애플리케이션을 전적으로 사용자 컴퓨터에서 실행하며, 내부 개발에 권장됩니다.
1. 환경 설정 및 ADK 설치¶
2. 에이전트 프로젝트 생성¶
프로젝트 구조¶
다음과 같은 프로젝트 구조를 만들어야 합니다:
multi_tool_agent
폴더를 만드세요:
Windows 사용자를 위한 참고 사항
Windows에서 ADK를 사용하여 다음 몇 단계를 진행할 때, 다음 명령어들(mkdir
, echo
)이 일반적으로 null 바이트나 잘못된 인코딩으로 파일을 생성하기 때문에 파일 탐색기나 IDE를 사용하여 Python 파일을 만드는 것을 권장합니다.
__init__.py
¶
이제 폴더에 __init__.py
파일을 만드세요:
이제 __init__.py
파일은 다음과 같아야 합니다:
agent.py
¶
같은 폴더에 agent.py
파일을 만드세요:
다음 코드를 복사하여 agent.py
에 붙여넣으세요:
import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent
def get_weather(city: str) -> dict:
"""Retrieves the current weather report for a specified city.
Args:
city (str): The name of the city for which to retrieve the weather report.
Returns:
dict: status and result or error msg.
"""
if city.lower() == "new york":
return {
"status": "success",
"report": (
"The weather in New York is sunny with a temperature of 25 degrees"
" Celsius (77 degrees Fahrenheit)."
),
}
else:
return {
"status": "error",
"error_message": f"Weather information for '{city}' is not available.",
}
def get_current_time(city: str) -> dict:
"""Returns the current time in a specified city.
Args:
city (str): The name of the city for which to retrieve the current time.
Returns:
dict: status and result or error msg.
"""
if city.lower() == "new york":
tz_identifier = "America/New_York"
else:
return {
"status": "error",
"error_message": (
f"Sorry, I don't have timezone information for {city}."
),
}
tz = ZoneInfo(tz_identifier)
now = datetime.datetime.now(tz)
report = (
f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
)
return {"status": "success", "report": report}
root_agent = Agent(
name="weather_time_agent",
model="gemini-2.0-flash",
description=(
"Agent to answer questions about the time and weather in a city."
),
instruction=(
"You are a helpful agent who can answer user questions about the time and weather in a city."
),
tools=[get_weather, get_current_time],
)
.env
¶
같은 폴더에 .env
파일을 만드세요:
이 파일에 대한 자세한 내용은 다음 섹션인 모델 설정에서 설명합니다.
Java 프로젝트는 일반적으로 다음과 같은 프로젝트 구조를 가집니다:
project_folder/
├── pom.xml (or build.gradle)
├── src/
├── └── main/
│ └── java/
│ └── agents/
│ └── multitool/
└── test/
MultiToolAgent.java
생성¶
src/main/java/agents/multitool/
디렉토리의 agents.multitool
패키지에 MultiToolAgent.java
소스 파일을 만드세요.
다음 코드를 복사하여 MultiToolAgent.java
에 붙여넣으세요:
package agents.multitool;
import com.google.adk.agents.BaseAgent;
import com.google.adk.agents.LlmAgent;
import com.google.adk.events.Event;
import com.google.adk.runner.InMemoryRunner;
import com.google.adk.sessions.Session;
import com.google.adk.tools.Annotations.Schema;
import com.google.adk.tools.FunctionTool;
import com.google.genai.types.Content;
import com.google.genai.types.Part;
import io.reactivex.rxjava3.core.Flowable;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Scanner;
public class MultiToolAgent {
private static String USER_ID = "student";
private static String NAME = "multi_tool_agent";
// The run your agent with Dev UI, the ROOT_AGENT should be a global public static variable.
public static BaseAgent ROOT_AGENT = initAgent();
public static BaseAgent initAgent() {
return LlmAgent.builder()
.name(NAME)
.model("gemini-2.0-flash")
.description("Agent to answer questions about the time and weather in a city.")
.instruction(
"You are a helpful agent who can answer user questions about the time and weather"
+ " in a city.")
.tools(
FunctionTool.create(MultiToolAgent.class, "getCurrentTime"),
FunctionTool.create(MultiToolAgent.class, "getWeather"))
.build();
}
public static Map<String, String> getCurrentTime(
@Schema(description = "The name of the city for which to retrieve the current time")
String city) {
String normalizedCity =
Normalizer.normalize(city, Normalizer.Form.NFD)
.trim()
.toLowerCase()
.replaceAll("(\\p{IsM}+|\\p{IsP}+)", "")
.replaceAll("\\s+", "_");
return ZoneId.getAvailableZoneIds().stream()
.filter(zid -> zid.toLowerCase().endsWith("/" + normalizedCity))
.findFirst()
.map(
zid ->
Map.of(
"status",
"success",
"report",
"The current time in "
+ city
+ " is "
+ ZonedDateTime.now(ZoneId.of(zid))
.format(DateTimeFormatter.ofPattern("HH:mm"))
+ "."))
.orElse(
Map.of(
"status",
"error",
"report",
"Sorry, I don't have timezone information for " + city + "."));
}
public static Map<String, String> getWeather(
@Schema(description = "The name of the city for which to retrieve the weather report")
String city) {
if (city.toLowerCase().equals("new york")) {
return Map.of(
"status",
"success",
"report",
"The weather in New York is sunny with a temperature of 25 degrees Celsius (77 degrees"
+ " Fahrenheit).");
} else {
return Map.of(
"status", "error", "report", "Weather information for " + city + " is not available.");
}
}
public static void main(String[] args) throws Exception {
InMemoryRunner runner = new InMemoryRunner(ROOT_AGENT);
Session session =
runner
.sessionService()
.createSession(NAME, USER_ID)
.blockingGet();
try (Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8)) {
while (true) {
System.out.print("\nYou > ");
String userInput = scanner.nextLine();
if ("quit".equalsIgnoreCase(userInput)) {
break;
}
Content userMsg = Content.fromParts(Part.fromText(userInput));
Flowable<Event> events = runner.runAsync(USER_ID, session.id(), userMsg);
System.out.print("\nAgent > ");
events.blockingForEach(event -> System.out.println(event.stringifyContent()));
}
}
}
}
3. 모델 설정¶
에이전트가 사용자 요청을 이해하고 응답을 생성하는 능력은 거대 언어 모델(LLM)에 의해 구동됩니다. 에이전트는 이 외부 LLM 서비스에 안전하게 호출해야 하며, 이를 위해 인증 자격 증명이 필요합니다. 유효한 인증 없이는 LLM 서비스가 에이전트의 요청을 거부하게 되며, 에이전트는 작동할 수 없습니다.
- Google AI Studio에서 API 키를 받으세요.
-
Python을 사용하는 경우, (
multi_tool_agent/
안에 위치한).env
파일을 열고 다음 코드를 복사하여 붙여넣으세요.Java를 사용하는 경우, 환경 변수를 정의하세요:
-
PASTE_YOUR_ACTUAL_API_KEY_HERE
를 실제API 키
로 교체하세요.
- 기존 Google Cloud 계정과 프로젝트가 필요합니다.
- Google Cloud 프로젝트 설정
- gcloud CLI 설정
- 터미널에서
gcloud auth login
을 실행하여 Google Cloud에 인증하세요. - Vertex AI API 활성화.
-
Python을 사용하는 경우, (
multi_tool_agent/
안에 위치한).env
파일을 여세요. 다음 코드를 복사하여 붙여넣고 프로젝트 ID와 위치를 업데이트하세요.multi_tool_agent/.envGOOGLE_GENAI_USE_VERTEXAI=TRUE GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID GOOGLE_CLOUD_LOCATION=LOCATION
Java를 사용하는 경우, 환경 변수를 정의하세요:
4. 에이전트 실행¶
터미널을 사용하여 에이전트 프로젝트의 부모 디렉토리로 이동하세요 (예: cd ..
사용):
에이전트와 상호 작용하는 방법은 여러 가지가 있습니다:
다음 명령어를 실행하여 개발자 UI를 시작하세요.
Windows 사용자를 위한 참고 사항
_make_subprocess_transport NotImplementedError
가 발생하면 대신 adk web --no-reload
를 사용하는 것을 고려해보세요.
1단계: 제공된 URL(보통 http://localhost:8000
또는 http://127.0.0.1:8000
)을 브라우저에서 직접 여세요.
2단계. UI의 왼쪽 상단 모서리에서, 드롭다운 메뉴에서 에이전트를 선택할 수 있습니다. "multi_tool_agent"를 선택하세요.
문제 해결
드롭다운 메뉴에서 "multi_tool_agent"가 보이지 않으면, adk web
을 에이전트 폴더의 부모 폴더(즉, multi_tool_agent의 부모 폴더)에서 실행하고 있는지 확인하세요.
3단계. 이제 텍스트 상자를 사용하여 에이전트와 채팅할 수 있습니다:
4단계. 왼쪽의 Events
탭을 사용하여, 액션을 클릭함으로써 개별 함수 호출, 응답 및 모델 응답을 검사할 수 있습니다:
Events
탭에서 Trace
버튼을 클릭하여 각 이벤트의 추적 로그를 볼 수도 있습니다. 이 로그는 각 함수 호출의 지연 시간을 보여줍니다:
5단계. 마이크를 활성화하여 에이전트와 대화할 수도 있습니다:
음성/영상 스트리밍을 위한 모델 지원
ADK에서 음성/영상 스트리밍을 사용하려면 Live API를 지원하는 Gemini 모델을 사용해야 합니다. 문서에서 Gemini Live API를 지원하는 모델 ID를 찾을 수 있습니다:
그런 다음 이전에 생성한 agent.py
파일의 root_agent
에서 model
문자열을 바꿀 수 있습니다 (섹션으로 이동). 코드는 다음과 같아야 합니다:
adk api_server
를 사용하면 단일 명령으로 로컬 FastAPI 서버를 생성할 수 있어, 에이전트를 배포하기 전에 로컬 cURL 요청을 테스트할 수 있습니다.
테스트를 위해 adk api_server
를 사용하는 방법을 배우려면, 테스트에 대한 문서를 참조하세요.
터미널을 사용하여 에이전트 프로젝트의 부모 디렉토리로 이동하세요 (예: cd ..
사용):
project_folder/ <-- 이 디렉토리로 이동
├── pom.xml (or build.gradle)
├── src/
├── └── main/
│ └── java/
│ └── agents/
│ └── multitool/
│ └── MultiToolAgent.java
└── test/
터미널에서 다음 명령어를 실행하여 개발자 UI를 시작하세요.
개발자 UI 서버의 메인 클래스 이름을 변경하지 마세요.
mvn exec:java \
-Dexec.mainClass="com.google.adk.web.AdkWebServer" \
-Dexec.args="--adk.agents.source-dir=src/main/java" \
-Dexec.classpathScope="compile"
1단계: 제공된 URL(보통 http://localhost:8080
또는 http://127.0.0.1:8080
)을 브라우저에서 직접 여세요.
2단계. UI의 왼쪽 상단 모서리에서, 드롭다운 메뉴에서 에이전트를 선택할 수 있습니다. "multi_tool_agent"를 선택하세요.
문제 해결
드롭다운 메뉴에서 "multi_tool_agent"가 보이지 않으면, Java 소스 코드가 위치한 곳(보통 src/main/java
)에서 mvn
명령어를 실행하고 있는지 확인하세요.
3단계. 이제 텍스트 상자를 사용하여 에이전트와 채팅할 수 있습니다:
4단계. 액션을 클릭하여 개별 함수 호출, 응답 및 모델 응답을 검사할 수도 있습니다:
Maven을 사용하여, 다음 명령으로 Java 클래스의 main()
메서드를 실행하세요:
Gradle을 사용하는 경우, build.gradle
또는 build.gradle.kts
빌드 파일의 plugins
섹션에 다음 Java 플러그인이 있어야 합니다:
그런 다음, 빌드 파일의 다른 곳, 최상위 레벨에서 에이전트의 main()
메서드를 실행하기 위한 새 태스크를 만드세요:
task runAgent(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
mainClass = "agents.multitool.MultiToolAgent"
}
마지막으로, 명령줄에서 다음 명령을 실행하세요:
📝 시도해볼 예제 프롬프트¶
- 뉴욕의 날씨는 어떤가요?
- 뉴욕은 지금 몇 시인가요?
- 파리의 날씨는 어떤가요?
- 파리는 지금 몇 시인가요?
🎉 축하합니다!¶
ADK를 사용하여 첫 번째 에이전트를 성공적으로 만들고 상호 작용했습니다!