에이전트 개발 키트(ADK)는 ADK BaseMemoryService 인터페이스의 구현인 VertexAiMemoryBankService를 통해 에이전트를 Agent Platform 메모리 뱅크에 연결합니다. 이 문서에서는 메모리 콜백 및 검색 도구를 선택하는 방법과 각 ADK 런타임에서 메모리 서비스를 연결하는 방법을 설명합니다.
전체 예시를 먼저 실행하려면 ADK를 사용한 메모리 뱅크 빠른 시작을 참고하세요.
시작하기 전에
- Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
로컬 셸을 사용하는 경우 사용자 계정에 대한 로컬 인증 사용자 인증 정보를 만듭니다.
gcloud auth application-default login
Cloud Shell을 사용하는 경우 이 작업을 수행할 필요는 없습니다.
인증 오류가 반환되고 외부 ID 공급업체(IdP)를 사용하는 경우 제휴 ID로 gcloud CLI에 로그인했는지 확인합니다.
- ADK 및 Agent Platform SDK를 설치합니다.
pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"
- Google Cloud 콘솔 또는 Agent Platform SDK를 사용하여 메모리 뱅크 인스턴스를 만듭니다. 메모리 뱅크 페이지에서 에이전트에 연결 > ADK와 함께 사용을 클릭하여 미리 채워진 설정 코드를 확인합니다. Agent Runtime에서 인스턴스를 만드는 경우 이 단계를 건너뜁니다.
필요한 역할
메모리 뱅크 인스턴스를 만들고 메모리를 생성 및 검색하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 다음 IAM 역할을 부여해 달라고 요청하세요.
- 메모리 뱅크 인스턴스 만들기 또는 업데이트: Agent Platform 사용자(`roles/aiplatform.user`)
- 메모리 읽기, 쓰기 또는 생성: 메모리 뱅크 사용자(`roles/aiplatform.memoryUser`)
역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.
커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.
ADK 구성요소가 메모리 뱅크와 작동하는 방식
ADK 에이전트는 다음 구성요소를 사용하여 메모리를 읽고 씁니다.
| 구성요소 | 역할 | 필수 |
|---|---|---|
| 메모리 뱅크 인스턴스 | 메모리를 저장하고 통합합니다. | 예 |
VertexAiMemoryBankService |
에이전트를 ADK 메모리 서비스로 메모리 뱅크에 연결합니다. | 예 |
| 세션 서비스 | 대화 기록을 저장합니다. 모든 ADK 세션 서비스를 사용할 수 있습니다. | 예 |
| 메모리 검색 도구 | 에이전트의 메모리를 검색합니다. 도구로 메모리 검색을 참고하세요. | 추억 읽기 |
| 메모리 생성 콜백 | 에이전트가 응답한 후 대화 이벤트를 메모리 뱅크로 전송합니다. 콜백으로 메모리 생성을 참고하세요. | 추억 작성 |
ADK Runner 또는 AdkApp |
에이전트, 서비스, 도구, 콜백을 조정합니다. | 예 |
다음 다이어그램은 에이전트가 PreloadMemoryTool 및 메모리 콜백을 사용할 때 각 차례에서 이러한 구성요소가 상호작용하는 방식을 보여줍니다.
메모리 뱅크는 각 메모리의 범위를 에이전트를 실행하는 사용자 ID 및 앱 이름으로 지정합니다({"user_id": USER_ID, "app_name": APP_NAME}). 사용자 ID와 앱 이름이 동일한 요청만 해당 기억을 검색합니다.
콜백으로 메모리 생성하기
메모리 생성 콜백은 대화 이벤트를 메모리 뱅크로 전송합니다. 메모리 뱅크는 이러한 이벤트에서 메모리를 추출하고 기존 메모리와 통합합니다. 이벤트를 처리하는 빈도에 따라 방법을 선택합니다.
| 메서드 | 전송된 이벤트 | 사용 시기 |
|---|---|---|
callback_context.add_events_to_memory |
선택한 이벤트의 하위 집합 | Recommended. 각 차례가 끝난 후와 같이 이벤트를 점진적으로 처리합니다. |
callback_context.add_session_to_memory |
세션의 모든 이벤트 | 동일한 이벤트가 두 번 이상 처리되지 않도록 세션이 끝날 때 한 번 호출합니다. |
다음 예시에서는 각 에이전트 응답 후에 최근 이벤트를 전송합니다.
from google.adk.agents.callback_context import CallbackContext
async def generate_memories_callback(
callback_context: CallbackContext,
) -> None:
await callback_context.add_events_to_memory(
events=callback_context.session.events[-5:]
)
return None
대신 전체 세션을 전송하려면 세션이 끝날 때 콜백에서 await callback_context.add_session_to_memory()를 호출합니다.
기본적으로 VertexAiMemoryBankService는 이벤트 수집을 사용하여 이벤트를 전송합니다. 테스트 또는 데모에서 메모리 생성이 완료될 때까지 기다리려면 custom_metadata={"wait_for_completion": True}를 add_events_to_memory에 전달합니다.
도구로 기억 검색
메모리 검색 도구는 에이전트가 메모리를 검색하는 시점과 메모리가 프롬프트에 입력되는 방식을 제어합니다. 다음 도구 중 하나를 선택합니다.
| 도구 | 추억이 검색되는 경우 | 사용 시기 |
|---|---|---|
PreloadMemoryTool |
매 턴 시작 시 기억은 현재 사용자 차례 전에 모델 요청 컨텍스트에 삽입됩니다. | 모든 차례에서 사용자에 대한 기본 컨텍스트를 설정합니다. |
LoadMemoryTool |
모델이 질문에 답변하는 데 기억이 필요하다고 판단하는 경우 | 메모리가 관련성이 있는 경우를 모델이 결정하도록 합니다. |
커스텀 FunctionTool |
모델이 도구 설명을 참고하여 도구를 호출할 때 | 에이전트에게 기억을 검색할 시점에 관한 요청 사항을 제공합니다. |
다음 예시에서는 PreloadMemoryTool 및 이전 섹션의 콜백을 사용하는 에이전트를 만듭니다.
from google import adk
from google.adk.tools.preload_memory_tool import PreloadMemoryTool
agent = adk.Agent(
model="gemini-3.5-flash",
name="stateful_agent",
instruction="You are a vehicle voice agent. Limit responses to 30 words.",
tools=[PreloadMemoryTool()],
after_agent_callback=generate_memories_callback,
)
모델이 메모리를 검색할 시점을 결정하도록 하려면 google.adk.tools.load_memory_tool에서 LoadMemoryTool를 가져오고 tools에 LoadMemoryTool()를 전달합니다.
커스텀 검색 도구를 작성하려면 함수 도구에서 tool_context.search_memory를 호출합니다.
from typing import Any
from google import adk
from google.adk.tools import FunctionTool, ToolContext
async def search_memories(query: str, tool_context: ToolContext) -> Any:
"""Query this tool when you need information about user preferences."""
return await tool_context.search_memory(query)
agent = adk.Agent(
model="gemini-3.5-flash",
name="stateful_agent",
instruction=(
"You are a vehicle voice agent. Before you change a setting, call "
"search_memories to look up the user's preferences. Limit responses "
"to 30 words."
),
tools=[FunctionTool(func=search_memories)],
after_agent_callback=generate_memories_callback,
)
런타임에 메모리 서비스 연결
VertexAiMemoryBankService를 연결하는 방법은 에이전트가 실행되는 위치에 따라 다릅니다. 런타임을 선택합니다.
로컬 러너
adk.Runner로 에이전트를 실행할 때 메모리 서비스를 만들고 실행기에 전달합니다.
import asyncio
import os
from google import adk
from google.adk.memory import VertexAiMemoryBankService
from google.adk.sessions import InMemorySessionService
from google.genai import types
os.environ["GOOGLE_GENAI_USE_ENTERPRISE"] = "TRUE"
os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_CLOUD_LOCATION"] = "LOCATION"
memory_service = VertexAiMemoryBankService(
project="PROJECT_ID",
location="LOCATION",
agent_engine_id="MEMORY_BANK_ID",
)
# You can use any ADK session service. This example keeps sessions in memory.
# To persist conversation history, use VertexAiSessionService with a
# Sessions instance instead.
session_service = InMemorySessionService()
runner = adk.Runner(
agent=agent,
app_name="APP_NAME",
session_service=session_service,
memory_service=memory_service,
)
async def main() -> None:
session = await session_service.create_session(
app_name="APP_NAME",
user_id="USER_ID",
)
message = types.Content(
role="user", parts=[types.Part(text="Can you fix the temperature?")]
)
async for event in runner.run_async(
user_id="USER_ID",
session_id=session.id,
new_message=message,
):
if event.is_final_response() and event.content:
print(event.content.parts[0].text)
asyncio.run(main())
다음을 바꿉니다.
- PROJECT_ID: Google Cloud 프로젝트 ID(예:
my-project) - LOCATION: 위치(예:
global) 메모리 뱅크의 지원되는 위치 및 전역 및 멀티 리전 엔드포인트를 참조하세요. - MEMORY_BANK_ID: 메모리 뱅크 인스턴스 ID입니다(예:
projects/my-project/locations/us-central1/reasoningEngines/456의456). - APP_NAME: ADK 앱 이름입니다(예:
my_agent). 메모리 뱅크는 메모리 범위에 앱 이름을 포함하므로 메모리가 앱 간에 격리됩니다. - USER_ID: 사용자의 식별자입니다(예:
user-123). 이 세션에서 생성된 메모리는 이 식별자로 범위가 지정됩니다.
Gemini Enterprise Agent Platform의 Agent Runtime
ADK 템플릿(AdkApp)을 사용하여 Agent Runtime에 ADK 에이전트를 배포하면 템플릿은 기본적으로 VertexAiMemoryBankService를 사용합니다. 한 단계로 메모리 뱅크 인스턴스를 만들고 에이전트를 배포할 수 있습니다.
import asyncio
import agentplatform
from agentplatform.frameworks import AdkApp
client = agentplatform.Client(
project="PROJECT_ID",
location="LOCATION",
)
adk_app = AdkApp(agent=agent)
# Create a resource with your agent deployed to Agent Runtime. The
# resource also includes an empty Memory Bank instance.
runtime_instance = client.runtimes.create(
agent=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-agentplatform[runtimes,adk]"],
},
)
async def main() -> None:
session = await runtime_instance.async_create_session(
user_id="USER_ID"
)
async for event in runtime_instance.async_stream_query(
user_id="USER_ID",
session_id=session.get("id"),
message="Can you fix the temperature?",
):
print(event)
asyncio.run(main())
에이전트를 기존 리소스에 배포하고 리소스의 기존 메모리를 유지하려면 대신 client.runtimes.update를 호출합니다.
runtime_instance = client.runtimes.update(
name="RUNTIME_NAME",
agent=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-agentplatform[runtimes,adk]"],
},
)
로컬에서 AdkApp를 실행하면 기본적으로 InMemoryMemoryService가 사용됩니다.
메모리 뱅크를 로컬에서 사용하려면 메모리 서비스를 재정의합니다.
from google.adk.memory import VertexAiMemoryBankService
def memory_bank_service_builder() -> VertexAiMemoryBankService:
return VertexAiMemoryBankService(
project="PROJECT_ID",
location="LOCATION",
agent_engine_id="MEMORY_BANK_ID",
)
adk_app = AdkApp(
agent=agent,
memory_service_builder=memory_bank_service_builder,
)
다음을 바꿉니다.
- PROJECT_ID: Google Cloud 프로젝트 ID(예:
my-project) - LOCATION: Agent Runtime 리전 또는 멀티 리전(예:
us-central1) 독립형VertexAiMemoryBankService인스턴스만global를 지원하고client.runtimes.create는 지원하지 않습니다. 지원되는 위치를 참조하세요. - STAGING_BUCKET: Agent Runtime을 스테이징하기 위한 Cloud Storage 버킷 URI입니다(예:
gs://my-staging-bucket). - USER_ID: 사용자의 식별자입니다(예:
user-123). - RUNTIME_NAME: 기존 Agent Runtime의 리소스 이름입니다(
projects/.../locations/.../reasoningEngines/...형식). - MEMORY_BANK_ID: 메모리 뱅크 인스턴스 ID입니다(예:
projects/my-project/locations/us-central1/reasoningEngines/456의456).
Cloud Run
에이전트를 Cloud Run에 배포하려면 ADK 문서를 따르고 메모리 뱅크 인스턴스를 메모리 서비스로 전달합니다.
adk deploy cloud_run \
...
--memory_service_uri=agentengine://MEMORY_BANK_ID
MEMORY_BANK_ID를 메모리 뱅크 인스턴스 ID(예: 456)로 바꿉니다. 배포된 에이전트를 테스트하려면 ADK Cloud Run 배포 문서를 참조하세요.
Google Kubernetes Engine(GKE)
에이전트를 GKE에 배포하려면 ADK 문서를 따르고 메모리 뱅크 인스턴스를 메모리 서비스로 전달합니다.
adk deploy gke \
...
--memory_service_uri=agentengine://MEMORY_BANK_ID
MEMORY_BANK_ID를 메모리 뱅크 인스턴스 ID(예: 456)로 바꿉니다. 배포된 에이전트를 테스트하려면 ADK GKE 배포 문서의 에이전트 테스트 섹션을 참조하세요.
ADK Web
ADK 웹은 개발 중에 에이전트를 테스트하고 검사하기 위한 로컬 브라우저 인터페이스입니다.
ADK Web은 환경 변수에서 프로젝트와 위치를 읽습니다. 에이전트 폴더가 포함된 디렉터리의 터미널에서 다음 명령어를 실행합니다.
export GOOGLE_GENAI_USE_ENTERPRISE=TRUE
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
export GOOGLE_CLOUD_LOCATION=LOCATION
adk web --memory_service_uri=agentengine://MEMORY_BANK_ID다음을 바꿉니다.
- PROJECT_ID: Google Cloud 프로젝트 ID(예:
my-project) - LOCATION: 위치(예:
global) 메모리 뱅크의 지원되는 위치 및 전역 및 멀티 리전 엔드포인트를 참조하세요. - MEMORY_BANK_ID: 메모리 뱅크 인스턴스 ID입니다(예:
456).
그런 다음 브라우저에서 http://localhost:8000을 엽니다. 기본적으로 ADK 웹은 사용자 ID를 user로 설정합니다. 다른 사용자 ID를 사용하려면 userId 쿼리 매개변수(예: http://localhost:8000?userId=USER_ID)를 추가합니다.
리전 런타임과 함께 멀티 리전 메모리 뱅크 사용
기본적으로 기본 제공 메모리 뱅크와 함께 런타임을 사용하면 에이전트와 메모리 뱅크가 동일한 리전에 배포됩니다. 리전 배포 전반에서 하나의 중앙 메모리 뱅크를 유지하려면 멀티 리전 메모리 뱅크(예: us)를 리전 런타임(예: us-central1)과 페어링하면 됩니다.
멀티 리전 메모리 뱅크를 사용하려면 기본 ADK 메모리 서비스 빌더를 재정의하여 멀티 리전 위치와 인스턴스 ID를 가리키도록 합니다.
import agentplatform
from agentplatform.frameworks import AdkApp
from google.adk.memory import VertexAiMemoryBankService
# Create the Memory Bank instance in a multi-region location.
client_mb = agentplatform.Client(
project="PROJECT_ID",
location="us",
)
memory_bank = client_mb.memory_banks.create()
memory_bank_id = memory_bank.name.split("/")[-1]
# Point the memory service to the multi-regional instance.
def memory_bank_service_builder() -> VertexAiMemoryBankService:
return VertexAiMemoryBankService(
project="PROJECT_ID",
location="us",
agent_engine_id=memory_bank_id,
)
adk_app = AdkApp(
agent=agent,
memory_service_builder=memory_bank_service_builder,
)
# Deploy the runtime to a specific region.
client_runtime = agentplatform.Client(
project="PROJECT_ID",
location="us-central1",
)
runtime_instance = client_runtime.runtimes.create(
agent=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-agentplatform[runtimes,adk]"],
},
)
다음을 바꿉니다.
- PROJECT_ID: Google Cloud 프로젝트 ID(예:
my-project) - STAGING_BUCKET: Agent Runtime을 스테이징하기 위한 Cloud Storage 버킷 URI입니다(예:
gs://my-staging-bucket).
이러한 리소스를 삭제하려면 런타임과 멀티 리전 인스턴스를 삭제합니다.
대화 직후에 인스턴스를 삭제하면 메모리 생성이 완료되는 동안 FAILED_PRECONDITION 오류와 함께 요청이 실패할 수 있습니다. 이 경우 잠시 기다렸다가 삭제를 다시 실행합니다.
client_runtime.runtimes.delete(
name=runtime_instance.api_resource.name,
force=True,
)
client_mb.memory_banks.delete(name=memory_bank.name, force=True)