메모리 뱅크를 사용하도록 Agent Development Kit (ADK) 에이전트를 구성하면 에이전트가 메모리 뱅크에 대한 호출을 조정하여 장기 기억을 관리합니다.
이 튜토리얼에서는 ADK로 메모리 뱅크를 사용하여 장기 기억을 관리하는 방법을 보여줍니다.
에이전트와 상호작용하여 세션 전반에서 액세스할 수 있는 장기 기억을 동적으로 생성합니다.
ADK 오케스트레이션 없이 메모리 뱅크를 직접 호출하려면 Agent Engine SDK로 빠른 시작을 참고하세요. Agent Engine SDK를 사용하면 메모리 뱅크가 기억을 생성하는 방식을 이해하거나 메모리 뱅크의 콘텐츠를 검사하는 데 도움이 됩니다.
시작하기 전에
이 튜토리얼에 설명된 단계를 완료하려면 먼저 메모리 뱅크 설정의 단계를 따라야 합니다.
환경 변수 설정하기
ADK를 사용하려면 환경 변수를 설정하세요.
import os
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "TRUE"
os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_CLOUD_LOCATION"] = "LOCATION"
다음을 바꿉니다.
- PROJECT_ID: 프로젝트 ID
- LOCATION: 리전 Memory Bank의 지원되는 리전을 참고하세요.
ADK 에이전트 만들기
ADK 에이전트를 개발할 때 에이전트가 메모리를 검색하는 시점과 메모리가 프롬프트에 포함되는 방식을 제어하는
Memory
도구를 포함하세요. 이 예시 에이전트는PreloadMemoryTool
를 사용합니다. 이 함수는 매 턴 시작 시 항상 메모리를 가져오고 시스템 명령어에 메모리를 포함합니다.from google import adk agent = adk.Agent( model="gemini-2.0-flash", name='stateful_agent', instruction="""You are a Vehicle Voice Agent, designed to assist users with information and in-vehicle actions. 1. **Direct Action:** If a user requests a specific vehicle function (e.g., "turn on the AC"), execute it immediately using the corresponding tool. You don't have the outcome of the actual tool execution, so provide a hypothetical tool execution outcome. 2. **Information Retrieval:** Respond concisely to general information requests with your own knowledge (e.g., restaurant recommendation). 3. **Clarity:** When necessary, try to seek clarification to better understand the user's needs and preference before taking an action. 4. **Brevity:** Limit responses to under 30 words. """, tools=[adk.tools.preload_memory_tool.PreloadMemoryTool()] )
ADK 러너가 메모리를 가져오는 데 사용하는
VertexAiMemoryBankService
메모리 서비스를 만듭니다. 자체 ADK 런타임을 정의하는 대신 에이전트 엔진 ADK 템플릿을 사용하는 경우 선택사항입니다.from google.adk.memory import VertexAiMemoryBankService agent_engine_id = agent_engine.api_resource.name.split("/")[-1] memory_service = VertexAiMemoryBankService( project="PROJECT_ID", location="LOCATION", agent_engine_id=agent_engine_id )
VertexAiMemoryBankService
는 ADK의BaseMemoryService
에 의해 정의되고 Agent Engine SDK와 다른 인터페이스를 사용하는 메모리 뱅크에 대한 ADK 래퍼입니다. Agent Engine SDK를 사용하여 메모리 뱅크에 직접 API 호출을 할 수 있습니다.VertexAiMemoryBankService
인터페이스에는 다음이 포함됩니다.memory_service.add_session_to_memory
: 제공된adk.Session
를 소스 콘텐츠로 사용하여 메모리 뱅크에GenerateMemories
요청을 트리거합니다. 이 메서드 호출은 ADK 러너에 의해 오케스트레이션되지 않습니다. ADK로 메모리 생성을 자동화하려면 자체 콜백 함수를 정의해야 합니다.memory_service.search_memory
는 현재user_id
및app_name
과 관련된 기억을 가져오기 위해 메모리 뱅크에RetrieveMemories
요청을 트리거합니다. 이 메서드에 대한 호출은 에이전트에 메모리 도구를 제공할 때 ADK 러너에 의해 오케스트레이션됩니다.
에이전트, 도구, 콜백의 실행을 조정하는 ADK 런타임을 만듭니다. ADK Runner 설정은 사용 중인 배포 환경에 따라 다릅니다.
adk.Runner
adk.Runner
는 일반적으로 Colab과 같은 로컬 환경에서 사용됩니다. Agent Engine 런타임과 같은 대부분의 배포 옵션은 ADK용 자체 런타임을 제공합니다.
from google.adk.sessions import VertexAiSessionService
from google.genai import types
# You can use any ADK session service.
session_service = VertexAiSessionService(
project="PROJECT_ID",
location="LOCATION",
agent_engine_id=agent_engine_id
)
app_name="APP_NAME"
runner = adk.Runner(
agent=agent,
app_name=app_name,
session_service=session_service,
memory_service=memory_service
)
def call_agent(query, session, user_id):
content = types.Content(role='user', parts=[types.Part(text=query)])
events = runner.run(user_id=user_id, session_id=session, new_message=content)
for event in events:
if event.is_final_response():
final_response = event.content.parts[0].text
print("Agent Response: ", final_response)
다음을 바꿉니다.
- APP_NAME: ADK 앱의 이름입니다.
Agent Engine ADK 템플릿
Agent Engine ADK 템플릿 (AdkApp
)은 로컬에서 사용할 수도 있고 ADK 에이전트를 Agent Engine 런타임에 배포하는 데 사용할 수도 있습니다. Agent Engine 런타임에 배포된 경우 Agent Engine ADK 템플릿은 VertexAiMemoryBankService
를 기본 메모리 서비스로 사용하여 메모리 뱅크에 Agent Engine 런타임과 동일한 Agent Engine 인스턴스를 사용합니다. 이 경우 메모리 서비스를 명시적으로 제공할 필요가 없습니다.
메모리 뱅크의 동작을 맞춤설정하는 방법을 비롯해 Agent Engine 런타임을 설정하는 방법에 관한 자세한 내용은 Agent Engine 구성을 참고하세요.
다음 코드를 사용하여 ADK 에이전트를 에이전트 엔진 런타임에 배포합니다.
import vertexai
from vertexai.preview.reasoning_engines import AdkApp
client = vertexai.Client(
project="PROJECT_ID",
location="LOCATION"
)
adk_app = AdkApp(agent=agent)
# Create a new Agent Engine with your agent deployed to Agent Engine Runtime.
# The Agent Engine instance will also include an empty Memory Bank.
agent_engine = client.agent_engines.create(
agent_engine=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-aiplatform[agent_engines,adk]"]
}
)
# Alternatively, update an existing Agent Engine to deploy your agent to Agent Engine Runtime.
# Your agent will have access to the Agent Engine instance's existing memories.
agent_engine = client.agent_engines.update(
name=agent_engine.api_resource.name,
agent_engine=adk_app,
config={
"staging_bucket": "STAGING_BUCKET",
"requirements": ["google-cloud-aiplatform[agent_engines,adk]"]
}
)
async def call_agent(query, session_id, user_id):
async for event in agent_engine.async_stream_query(
user_id=user_id,
session_id=session_id,
message=query,
):
print(event)
다음을 바꿉니다.
- PROJECT_ID: 프로젝트 ID
- LOCATION: 리전 Memory Bank의 지원되는 리전을 참고하세요.
- AGENT_ENGINE_ID: 메모리 뱅크에 사용할 Agent Engine ID입니다. 예를 들어
projects/my-project/locations/us-central1/reasoningEngines/456
의456
입니다. - STAGING_BUCKET: 에이전트 엔진 런타임을 스테이징하는 데 사용할 Cloud Storage 버킷입니다.
로컬에서 실행할 때 ADK 템플릿은 InMemoryMemoryService
을 기본 메모리 서비스로 사용합니다. 하지만 기본 메모리 서비스를 재정의하여 VertexAiMemoryBankService
를 사용할 수 있습니다.
def memory_bank_service_builder():
return VertexAiMemoryBankService(
project="PROJECT_ID",
location="LOCATION",
agent_engine_id="AGENT_ENGINE_ID"
)
adk_app = AdkApp(
agent=adk_agent,
# Override the default memory service.
memory_service_builder=memory_bank_service_builder
)
async def call_agent(query, session_id, user_id):
# adk_app is a local agent. If you want to deploy it to Agent Engine Runtime,
# use `client.agent_engines.create(...)` or `client.agent_engines.update(...)`
# and call the returned Agent Engine instance instead.
async for event in adk_app.async_stream_query(
user_id=user_id,
session_id=session_id,
message=query,
):
print(event)
다음을 바꿉니다.
- PROJECT_ID: 프로젝트 ID
- LOCATION: 리전 Memory Bank의 지원되는 리전을 참고하세요.
- AGENT_ENGINE_ID: 메모리 뱅크에 사용할 Agent Engine ID입니다. 예를 들어
projects/my-project/locations/us-central1/reasoningEngines/456
의456
입니다.
에이전트와 상호작용
에이전트를 정의하고 메모리 뱅크를 설정한 후 에이전트와 상호작용할 수 있습니다.
첫 번째 세션을 만듭니다. 사용자와의 첫 번째 세션에서는 사용할 수 있는 메모리가 없으므로 에이전트는 선호하는 온도와 같은 사용자 환경설정을 알지 못합니다.
adk.Runner
adk.Runner
를 사용하면 ADK 메모리 및 세션 서비스를 직접 호출할 수 있습니다.session = await session_service.create_session( app_name="APP_NAME", user_id="USER_ID" ) call_agent( "Can you update the temperature to my preferred temperature?", session.id, "USER_ID" ) # Agent response: "What is your preferred temperature?" call_agent("I like it at 71 degrees", session.id, "USER_ID") # Agent Response: Setting the temperature to 71 degrees Fahrenheit. # Temperature successfully changed.
다음을 바꿉니다.
- APP_NAME: 러너의 앱 이름입니다.
- USER_ID: 사용자의 식별자. 이 세션에서 생성된 기억은 이 불투명 식별자를 사용하여 키가 지정됩니다. 생성된 기억의 범위는
{"user_id": "USER_ID"}
로 저장됩니다.
Agent Engine ADK 템플릿
Agent Engine ADK 템플릿을 사용하는 경우 Agent Engine 런타임을 호출하여 메모리 및 세션과 상호작용할 수 있습니다.
session = await agent_engine.async_create_session(user_id="USER_ID") await call_agent( "Can you update the temperature to my preferred temperature?", session.get("id"), "USER_ID" ) # Agent response: "What is your preferred temperature?" await call_agent("I like it at 71 degrees", session.get("id"), "USER_ID") # Agent Response: Setting the temperature to 71 degrees Fahrenheit. # Temperature successfully changed.
다음을 바꿉니다.
- USER_ID: 사용자의 식별자. 이 세션에서 생성된 기억은 이 불투명 식별자를 사용하여 키가 지정됩니다. 생성된 기억의 범위는
{"user_id": "USER_ID"}
로 저장됩니다.
현재 세션의 추억을 생성합니다. 메모리 뱅크가 대화에서 기억을 추출하면
{"user_id": USER_ID, "app_name": APP_NAME}
범위에 저장됩니다.adk.Runner
session = await session_service.get_session( app_name=app_name, user_id="USER_ID", session_id=session.id ) memory_service.add_session_to_memory(session)
Agent Engine ADK 템플릿
await agent_engine.async_add_session_to_memory(session=session)
두 번째 세션을 만듭니다.
PreloadMemoryTool
를 사용한 경우 상담사는 각 차례가 시작될 때 메모리를 검색하여 사용자가 이전에 상담사에게 전달한 환경설정에 액세스합니다.adk.Runner
session = await session_service.create_session( app_name=app_name, user_id="USER_ID" ) call_agent("Fix the temperature!", session.id, "USER_ID") # Agent Response: Setting temperature to 71 degrees. Is that correct?
memory_service.search_memory
를 사용하여 기억을 직접 검색할 수도 있습니다.await memory_service.search_memory( app_name="APP_NAME", user_id="USER_ID", query="Fix the temperature!", )
Agent Engine ADK 템플릿
session = await agent_engine.async_create_session(user_id="USER_ID") await call_agent("Fix the temperature!", session.get("id"), "USER_ID") # Agent Response: Setting temperature to 71 degrees. Is that correct?
agent_engine.async_search_memory
를 사용하여 메모리를 직접 가져올 수도 있습니다. 참고:async_search_memory
를 사용하려면AdkApp
가google-cloud-aiplatform
버전 1.110.0 이상으로 생성되어야 합니다. 그렇지 않으면 메모리 뱅크를 직접 호출하여 기억을 검색할 수 있습니다.await agent_engine.async_search_memory( user_id="USER_ID", query="Fix the temperature!", )
삭제
이 프로젝트에 사용된 모든 리소스를 삭제하려면 빠른 시작에 사용한 Google Cloud 프로젝트를 삭제하면 됩니다.
또는 다음과 같이 이 튜토리얼에서 만든 개별 리소스를 삭제하면 됩니다.
다음 코드 샘플을 사용하여 Vertex AI Agent Engine 인스턴스를 삭제합니다. 그러면 해당 Vertex AI Agent Engine에 속한 세션 또는 기억도 삭제됩니다.
agent_engine.delete(force=True)
로컬에서 만든 파일을 삭제합니다.