Agent Development Kit 빠른 시작

메모리 뱅크를 사용하도록 에이전트 개발 키트(ADK) 에이전트를 구성한 후 에이전트는 메모리 뱅크를 호출하여 장기 메모리를 관리합니다.

이 튜토리얼에서는 ADK와 함께 메모리 뱅크를 사용하여 장기 메모리를 관리하는 방법을 보여줍니다.

  1. 로컬 ADK 에이전트와 러너를 만듭니다.

  2. 에이전트와 상호작용하여 세션 간에 액세스 가능한 장기 메모리를 동적으로 생성합니다.

  3. 삭제합니다.

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: 리전입니다. 메모리 뱅크에서 지원되는 리전을 참조하세요.

ADK 에이전트 만들기

  1. 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()]
    )
    
  2. 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로 정의된 메모리 뱅크용 ADK 래퍼이며, Agent Engine SDK와는 다른 인터페이스를 사용합니다. 메모리 뱅크에 직접 API 호출을 하고 싶다면 Agent Engine SDK를 사용할 수 있습니다. VertexAiMemoryBankService 인터페이스에는 다음이 포함됩니다.

    • memory_service.add_session_to_memory: 제공된 adk.Session을 소스 콘텐츠로 사용하여 메모리 뱅크에 GenerateMemories 요청을 트리거합니다. 이 메서드 호출은 ADK 러너에 의해 조정되지 않습니다. ADK에서 메모리 생성을 자동화하려면 자체 콜백 함수를 정의해야 합니다.

    • memory_service.search_memory: 현재 user_idapp_name에 대한 관련 메모리를 가져오기 위해 메모리 뱅크에 RetrieveMemories 요청을 트리거합니다. 이 메서드 호출은 에이전트에 메모리 도구를 제공하면 ADK 러너에 의해 조정됩니다.

  3. 에이전트, 도구, 콜백의 실행을 조정하는 ADK 런타임을 만듭니다. ADK 러너 설정은 사용하는 배포 환경에 따라 달라집니다.

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)은 로컬 환경과 Agent Engine 런타임 모두에서 ADK 에이전트를 배포하는 데 사용할 수 있습니다. Agent Engine 런타임에 배포되는 경우, Agent Engine ADK 템플릿VertexAiMemoryBankService를 기본 메모리 서비스로 사용하며, Agent Engine 런타임과 동일한 Agent Engine 인스턴스를 메모리 뱅크에 사용합니다. 이 경우 메모리 서비스를 명시적으로 제공할 필요가 없습니다.

Agent Engine 런타임 설정 및 메모리 뱅크 동작을 맞춤설정하는 방법을 포함하여 자세한 내용은 Agent Engine 구성을 참조하세요.

다음 코드를 사용하여 ADK 에이전트를 Agent Engine 런타임에 배포합니다.

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: 리전입니다. 메모리 뱅크에서 지원되는 리전을 참조하세요.
  • AGENT_ENGINE_ID: 메모리 뱅크에 사용할 Agent Engine ID입니다. 예를 들어 projects/my-project/locations/us-central1/reasoningEngines/456에서 456입니다.
  • STAGING_BUCKET: Agent Engine 런타임을 스테이징하는 데 사용할 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: 리전입니다. 메모리 뱅크에서 지원되는 리전을 참조하세요.
  • AGENT_ENGINE_ID: 메모리 뱅크에 사용할 Agent Engine ID입니다. 예를 들어 projects/my-project/locations/us-central1/reasoningEngines/456에서 456입니다.

에이전트와 상호작용

에이전트를 정의하고 메모리 뱅크를 설정한 후에는 에이전트와 상호작용할 수 있습니다.

  1. 첫 번째 세션을 만듭니다. 사용자와의 첫 번째 세션 동안에는 사용 가능한 메모리가 없기 때문에, 에이전트는 사용자의 선호도(예: 선호하는 강도)와 같은 정보를 알지 못합니다.

    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"} 형식으로 저장됩니다.
  2. 현재 세션의 메모리를 생성합니다. 메모리 뱅크가 대화에서 메모리를 추출하면 {"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)
    
  3. 두 번째 세션을 만듭니다. 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를 사용하려면 AdkAppgoogle-cloud-aiplatform 버전 1.110.0 이상으로 생성되어야 합니다. 그렇지 않으면 메모리 뱅크를 직접 호출하여 메모리를 가져올 수 있습니다.

    await agent_engine.async_search_memory(
        user_id="USER_ID",
        query="Fix the temperature!",
    )
    

삭제

이 프로젝트에 사용된 모든 리소스를 삭제하려면 빠른 시작에 사용한 Google Cloud 프로젝트를 삭제하면 됩니다.

또는 다음과 같이 이 튜토리얼에서 만든 개별 리소스를 삭제하면 됩니다.

  1. 다음 코드 샘플을 사용하여 Vertex AI Agent Engine 인스턴스를 삭제합니다. 그러면 해당 Vertex AI Agent Engine에 속한 세션 또는 메모리도 삭제됩니다.

    agent_engine.delete(force=True)
    
  2. 로컬에서 만든 파일을 삭제합니다.

다음 단계