빠른 시작: 메모리 뱅크를 사용하여 ADK 에이전트에 장기 메모리 추가

Agent Platform 메모리 뱅크는 에이전트 개발 키트(ADK)로 빌드하는 에이전트에 세션 간 장기 메모리를 제공합니다. 이 빠른 시작에서는 한 세션에서 사용자가 선호하는 온도를 학습하고 다음 세션에서 이 선호도를 기억하는 에이전트를 실행합니다.

이 빠른 시작에서는 다음 단계를 안내합니다.

  • 환경을 설정합니다.
  • 메모리 뱅크 인스턴스를 만듭니다.
  • 메모리가 사용 설정된 ADK 에이전트를 로컬에서 실행합니다.
  • 에이전트가 새 세션에서 선호도를 기억하는지 확인합니다.

ADK 없이 메모리 뱅크를 직접 호출하려면 메모리 뱅크 API 빠른 시작을 참조하세요. 다른 메모리 도구, 콜백 또는 런타임을 선택하려면 ADK와 함께 메모리 뱅크 사용을 참조하세요.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. 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.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

  6. 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 the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. 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.

  8. Verify that billing is enabled for your Google Cloud project.

  9. Enable the Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. 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.

    Enable the API

  10. Python 개발 환경을 설정합니다.
  11. 로컬 셸을 사용하는 경우 사용자 계정에 대한 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login

    Cloud Shell을 사용하는 경우 이 작업을 수행할 필요는 없습니다.

    인증 오류가 반환되고 외부 ID 공급업체(IdP)를 사용하는 경우 제휴 ID로 gcloud CLI에 로그인했는지 확인합니다.

필요한 역할

메모리 뱅크 인스턴스를 만들고 메모리를 생성 및 검색하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 다음 IAM 역할을 부여해 달라고 요청하세요.

  • 메모리 뱅크 인스턴스 만들기 또는 업데이트: Agent Platform 사용자(`roles/aiplatform.user`)
  • 메모리 읽기, 쓰기 또는 생성: 메모리 뱅크 사용자(`roles/aiplatform.memoryUser`)

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

환경 설정

  1. 터미널에서 ADK 및 Agent Platform SDK를 설치합니다.

    pip install --upgrade "google-adk[gcp]" "google-cloud-agentplatform>=2.0.1"
  2. 이 빠른 시작의 스크립트가 읽는 환경 변수를 설정합니다.

    export GOOGLE_GENAI_USE_ENTERPRISE=TRUE
    export GOOGLE_CLOUD_PROJECT=PROJECT_ID
    export GOOGLE_CLOUD_LOCATION=global

    PROJECT_ID를 Google Cloud 프로젝트 ID로 바꿉니다.

    이 빠른 시작에서는 전역 엔드포인트를 사용합니다. 리전 또는 멀티 리전 위치를 대신 사용하려면 global을 지원되는 위치 중 하나로 바꿉니다. 고객 관리 암호화 키(CMEK)가 필요한 경우 전역 엔드포인트에서 CMEK를 사용할 수 없으므로 리전 또는 멀티 리전 위치를 사용하세요.

    스크립트가 이러한 변수를 읽을 수 있도록 동일한 터미널 세션 및 디렉터리에서 이 빠른 시작의 나머지 부분을 실행합니다.

메모리 뱅크 인스턴스 만들기

  1. 다음 코드를 사용하여 create_memory_bank.py 파일을 만듭니다.

    import os
    
    import agentplatform
    
    client = agentplatform.Client(
        project=os.environ["GOOGLE_CLOUD_PROJECT"],
        location=os.environ["GOOGLE_CLOUD_LOCATION"],
    )
    
    memory_bank = client.memory_banks.create(
        config={"display_name": "Memory Bank quickstart"}
    )
    
    # Print only the instance ID, for example 1234567890.
    print(memory_bank.name.split("/")[-1])
    
  2. 스크립트를 실행하고 인스턴스 ID를 MEMORY_BANK_ID 환경 변수에 저장합니다.

    export MEMORY_BANK_ID=$(python create_memory_bank.py)

    첫 번째 메모리 뱅크 인스턴스인 경우 생성하는 데 1~2분 정도 걸릴 수 있습니다.

  3. 변수에 인스턴스 ID가 포함되어 있는지 확인합니다.

    echo $MEMORY_BANK_ID

    출력은 1234567890과 같은 ID입니다. 출력이 비어 있거나 401 또는 403 오류가 반환되면 필수 역할을 확인하고 gcloud auth application-default login를 실행합니다. 새 global 인스턴스가 처음 사용할 때 일시적인 403 오류를 반환하면 30초 동안 기다린 후 스크립트를 다시 실행합니다.

메모리 지원 에이전트 실행

이 섹션의 스크립트는 동일한 사용자에 대해 두 개의 세션을 실행합니다. 첫 번째 세션에서 사용자는 선호하는 온도를 말합니다. 두 번째 세션에서 에이전트는 메모리 뱅크에서 해당 환경설정을 기억합니다.

다음 단계를 완료합니다.

  1. memory_agent라는 디렉터리를 만듭니다.

    mkdir memory_agent
  2. 다음 코드를 사용하여 memory_agent/agent.py 파일을 만듭니다. 코드는 환경 설정 및 Memory Bank 인스턴스 만들기에서 설정한 변수에서 프로젝트, 위치, 인스턴스 ID를 읽습니다. 코드를 수정할 필요가 없습니다.

    import asyncio
    import os
    
    import agentplatform
    from google import adk
    from google.adk.agents.callback_context import CallbackContext
    from google.adk.memory import VertexAiMemoryBankService
    from google.adk.sessions import InMemorySessionService
    from google.adk.tools.preload_memory_tool import PreloadMemoryTool
    from google.genai import types
    
    PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"]
    LOCATION = os.environ["GOOGLE_CLOUD_LOCATION"]
    MEMORY_BANK_ID = os.environ["MEMORY_BANK_ID"]
    # Memory Bank scopes memories to this app name and user ID.
    APP_NAME = "memory_agent"
    USER_ID = "quickstart_user"
    
    async def generate_memories_callback(
        callback_context: CallbackContext,
    ) -> None:
        # Send the latest turn to Memory Bank and wait until memory generation
        # finishes, so that the next session can retrieve the new memory.
        await callback_context.add_events_to_memory(
            events=callback_context.session.events[-5:],
            custom_metadata={"wait_for_completion": True},
        )
        return None
    
    root_agent = adk.Agent(
        model="gemini-3.5-flash",
        name="memory_agent",
        instruction=(
            "You are a vehicle voice agent that controls in-vehicle settings. "
            "Use what you know about the user's preferences. "
            "If you don't know the user's preferred temperature, ask for it. "
            "Limit responses to under 30 words."
        ),
        tools=[PreloadMemoryTool()],
        after_agent_callback=generate_memories_callback,
    )
    
    memory_service = VertexAiMemoryBankService(
        project=PROJECT_ID,
        location=LOCATION,
        agent_engine_id=MEMORY_BANK_ID,
    )
    session_service = InMemorySessionService()
    runner = adk.Runner(
        agent=root_agent,
        app_name=APP_NAME,
        session_service=session_service,
        memory_service=memory_service,
    )
    
    async def send_message(session_id: str, text: str) -> None:
        print(f"User: {text}")
        message = types.Content(role="user", parts=[types.Part(text=text)])
        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(f"Agent: {event.content.parts[0].text}")
    
    async def main() -> None:
        print("--- Session 1: share a preference ---")
        session = await session_service.create_session(
            app_name=APP_NAME, user_id=USER_ID
        )
        await send_message(session.id, "Can you fix the temperature?")
        await send_message(session.id, "I'm comfortable at 71 degrees.")
    
        print("--- Session 2: recall the preference ---")
        session = await session_service.create_session(
            app_name=APP_NAME, user_id=USER_ID
        )
        await send_message(session.id, "Fix the temperature.")
    
        print("--- Memories stored in Memory Bank ---")
        client = agentplatform.Client(project=PROJECT_ID, location=LOCATION)
        memory_bank_name = (
            f"projects/{PROJECT_ID}/locations/{LOCATION}"
            f"/reasoningEngines/{MEMORY_BANK_ID}"
        )
        results = client.memory_banks.memories.retrieve(
            name=memory_bank_name,
            scope={"app_name": APP_NAME, "user_id": USER_ID},
        )
        for retrieved_memory in results.page:
            print(f"* {retrieved_memory.memory.fact}")
    
    if __name__ == "__main__":
        asyncio.run(main())
    
  3. 스크립트를 실행합니다.

    python memory_agent/agent.py

    콜백은 각 차례가 끝난 후 메모리 생성이 완료될 때까지 기다리므로 두 번째 세션이 시작될 때 메모리를 사용할 수 있습니다.

에이전트가 기억하는지 확인

스크립트가 완료되면 두 대화와 저장된 메모리가 터미널에 출력됩니다. 이 출력을 다음 예시와 비교하여 에이전트가 새 세션에서 선호도를 기억했는지 확인합니다.

첫 번째 세션에서 에이전트는 사용자에 대한 메모리가 없으므로 온도를 요청합니다.

--- Session 1: share a preference ---
User: Can you fix the temperature?
Agent: Sure. What temperature would you like?
User: I'm comfortable at 71 degrees.
Agent: Okay, I've set the temperature to 71 degrees.

두 번째 세션에서 에이전트는 메모리 뱅크에서 기억을 검색하고 묻지 않고 온도를 71도로 설정합니다. 저장된 메모리가 출력 끝에 표시됩니다.

--- Session 2: recall the preference ---
User: Fix the temperature.
Agent: Okay, I've set the temperature to 71 degrees, as you prefer.
--- Memories stored in Memory Bank ---
* I like the temperature to be 71 degrees.

에이전트 대답과 메모리의 표현은 에이전트와 메모리 뱅크가 사용하는 모델에 따라 다릅니다.

선택사항: ADK 웹에서 에이전트와 채팅하기

ADK 웹은 개발 중에 에이전트를 테스트하기 위한 브라우저 기반 인터페이스입니다.

  1. 동일한 터미널 세션에서 memory_agent 디렉터리가 포함된 디렉터리에서 다음 명령어를 실행합니다.

    adk web --memory_service_uri=agentengine://$MEMORY_BANK_ID memory_agent
  2. 브라우저에서 http://localhost:8000?userId=quickstart_user을 엽니다.

    userId 쿼리 매개변수는 스크립트의 사용자 ID와 일치하므로 에이전트는 스크립트에서 만든 메모리를 검색할 수 있습니다.

  3. Fix the temperature. 메시지를 보내고 에이전트가 묻지 않고 온도를 71도로 설정하는지 확인합니다. 에이전트는 메모리 지원 에이전트 실행에 저장된 스크립트의 환경설정을 사용합니다.

  4. ADK 웹을 중지하려면 터미널에서 Control+C를 누릅니다.

삭제

이 페이지에서 사용한 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 Google Cloud프로젝트를 삭제하면 됩니다. 그렇지 않은 경우 개별 리소스를 삭제합니다.

  1. 다음 코드를 사용하여 clean_up.py 파일을 만듭니다.

    import os
    
    import agentplatform
    
    project = os.environ["GOOGLE_CLOUD_PROJECT"]
    location = os.environ["GOOGLE_CLOUD_LOCATION"]
    memory_bank_id = os.environ["MEMORY_BANK_ID"]
    
    client = agentplatform.Client(project=project, location=location)
    client.memory_banks.delete(
        name=f"projects/{project}/locations/{location}/reasoningEngines/{memory_bank_id}",
        force=True,
    )
    
  2. 스크립트를 실행하여 메모리 뱅크 인스턴스를 삭제합니다.

    python clean_up.py
  3. 생성된 로컬 파일을 삭제합니다.

    rm -r memory_agent create_memory_bank.py clean_up.py

다음 단계

빠른 시작

Memory Bank API를 사용하여 장기 메모리를 관리하세요.

가이드

ADK의 콜백, 도구, 런타임을 선택합니다.

가이드

메모리 뱅크에서 메모리를 생성하는 방법을 알아보세요.

가이드

메모리 뱅크를 설정하는 방법을 알아보세요.