Agent Platform Memory Bank를 사용하면 Agent Platform SDK를 사용하여 세션 및 메모리 뱅크에 직접 API 호출을 할 수 있습니다. 에이전트 프레임워크가 호출을 대신 조정하지 않기를 원하거나 에이전트 개발 키트 (ADK) 이외의 다른 에이전트 프레임워크와 세션 및 메모리 뱅크를 통합하려는 경우 Agent Platform SDK를 사용하세요.
이 문서에서는 API 호출을 사용하여 메모리를 만들고, 업로드하고, 검색하고, 삭제하는 방법을 보여줍니다.
ADK를 사용하는 빠른 시작은 ADK를 사용한 메모리 뱅크 빠른 시작 을 참조하세요.
시작하기 전에
이 튜토리얼에 설명된 단계를 완료하려면 먼저 메모리 뱅크 설정의 단계를 수행해야 합니다.
Agent Platform 세션으로 메모리 생성
Agent Platform 세션 및 메모리 뱅크를 설정한 후 세션을 만들고 이벤트를 추가할 수 있습니다. 메모리는 사용자가 에이전트와 나눈 대화에서 사실(fact)로 생성되며, 이후 사용자 상호작용에서 활용할 수 있습니다. 자세한 내용은 메모리 생성 및 메모리 가져오기를 참조하세요.
불투명 사용자 ID로 세션을 만듭니다. 이 세션에서 생성된 메모리는 메모리를 생성할 때 범위를 명시적으로 제공하지 않는 한 범위
{"user_id": "USER_ID"}를 사용하여 자동으로 키가 지정됩니다.import vertexai client = vertexai.Client( project="PROJECT_ID", location="LOCATION" ) # This assumes that you already have an Agent Platform instance. If you don't, # you can create one using `agent_engine = client.agent_engines.create()`. session = client.agent_engines.sessions.create( # The name can be fetched using `agent_engine.api_resource.name`. name="AGENT_ENGINE_NAME", user_id="USER_ID" )다음을 바꿉니다.
PROJECT_ID: 프로젝트 ID입니다.
LOCATION: 리전 메모리 뱅크에서 지원되는 리전을 참조하세요.
AGENT_ENGINE_NAME: 사용자가 만든 Agent Platform 인스턴스 또는 기존 Agent Platform 인스턴스 이름입니다. 이름은 다음 형식이어야 합니다.
projects/{your project}/locations/{your location}/reasoningEngine/{your reasoning engine}.USER_ID: 사용자의 식별자입니다. 이 세션에서 생성된 메모리는 메모리를 생성할 때 범위를 명시적으로 제공하지 않는 한 범위
{"user_id": "USER_ID"}를 사용하여 자동으로 키가 지정됩니다.
세션에 이벤트를 반복적으로 업로드합니다. 이벤트에는 사용자, 에이전트, 도구 간의 모든 상호작용이 포함될 수 있습니다. 순서가 지정된 이벤트 목록은 세션의 대화 기록을 나타냅니다. 이 대화 기록은 특정 사용자의 메모리를 생성하기 위한 소스 자료로 사용됩니다.
import datetime client.agent_engines.sessions.events.append( name=session.response.name, author="user", # Required by Sessions. invocation_id="1", # Required by Sessions. timestamp=datetime.datetime.now(tz=datetime.timezone.utc), # Required by Sessions. config={ "content": { "role": "user", "parts": [{"text": "hello"}] } } )대화 기록에서 메모리를 생성하려면 세션의 메모리 생성 요청을 트리거합니다.
client.agent_engines.memories.generate( name=agent_engine.api_resource.name, vertex_session_source={ # `session` should have the format "projects/.../locations/.../reasoningEngines/.../sessions/...". "session": session.response.name }, # Optional when using Sessions. Defaults to {"user_id": session.user_id}. scope=SCOPE )
다음을 바꿉니다.
- (선택사항) SCOPE: 생성된 메모리의 범위를 나타내는 사전으로, 키-값 쌍은 최대 5개까지 허용되며
*문자는 허용되지 않습니다. 예를 들면{"session_id": "MY_SESSION"}입니다. 동일한 범위의 메모리만 통합 대상으로 간주됩니다. 제공되지 않으면{"user_id": session.user_id}가 사용됩니다.
기억 업로드
원시 대화로부터 메모리를 생성하는 대신, 사전 추출된 사실을 활용해서 메모리를 직접 업로드하거나 에이전트가 GenerateMemories를 사용해 추가하도록 할 수 있습니다.
즉, 메모리 뱅크가 콘텐츠에서 정보를 추출하는 대신 사용자가 보존해야 할 사실을 직접 제공하는 방식입니다.
생성된 메모리와 일관성을 유지하려면 지정된 범위에 구성한 것과 동일한 관점에서 사전 추출된 사실을 작성해 보세요. 기본적으로 메모리는 1인칭 관점에서 생성됩니다 (예: I
am a software engineer).
client.agent_engines.memories.generate(
name=agent_engine.api_resource.name,
direct_memories_source={"direct_memories": [{"fact": "FACT"}]},
scope=SCOPE
)
다음을 바꿉니다.
FACT: 기존 메모리와 통합해야 하는 사전 추출된 사실(fact)입니다. 최대 5개의 사전 추출된 사실(fact)을 목록으로 제공할 수 있습니다.
{"direct_memories": [{"fact": "fact 1"}, {"fact": "fact 2"}]}SCOPE: 생성된 메모리의 범위를 나타내는 사전입니다. 예를 들면
{"session_id": "MY_SESSION"}입니다. 동일한 범위의 메모리만 통합 대상으로 간주됩니다.
또는 CreateMemory를 사용하여 메모리 뱅크의 추출이나 통합을 거치지 않고 메모리를 업로드할 수도 있습니다.
memory = client.agent_engines.memories.create(
name=agent_engine.api_resource.name,
fact="This is a fact.",
scope={"user_id": "123"}
)
"""
Returns an AgentEngineMemoryOperation containing the created Memory like:
AgentEngineMemoryOperation(
done=True,
metadata={
"@type': 'type.googleapis.com/google.cloud.aiplatform.v1beta1.CreateMemoryOperationMetadata",
"genericMetadata": {
"createTime": '2025-06-26T01:15:29.027360Z',
"updateTime": '2025-06-26T01:15:29.027360Z'
}
},
name="projects/.../locations/us-central1/reasoningEngines/.../memories/.../operations/...",
response=Memory(
create_time=datetime.datetime(2025, 6, 26, 1, 15, 29, 27360, tzinfo=TzInfo(UTC)),
fact="This is a fact.",
name="projects/.../locations/us-central1/reasoningEngines/.../memories/...",
scope={
"user_id": "123"
},
update_time=datetime.datetime(2025, 6, 26, 1, 15, 29, 27360, tzinfo=TzInfo(UTC))
)
)
"""
기억 검색 및 사용
사용자에 대한 메모리를 검색하여 시스템 지침에 포함시킴으로써 LLM이 맞춤설정된 컨텍스트에 액세스하도록 할 수 있습니다.
범위 기반 메서드를 사용해 메모리를 검색하는 방법에 대한 자세한 내용은 메모리 가져오기를 참조하세요.
# Retrieve all memories for User ID 123.
retrieved_memories = list(
client.agent_engines.memories.retrieve(
name=agent_engine.api_resource.name,
scope={"user_id": "123"}
)
)
jinja를 사용하여 구조화된 메모리를 프롬프트로 변환할 수 있습니다.
from jinja2 import Template
template = Template("""
<MEMORIES>
Here is some information about the user:
{% for retrieved_memory in data %}* {{ retrieved_memory.memory.fact }}
{% endfor %}</MEMORIES>
""")
prompt = template.render(data=retrieved_memories)
"""
Output:
<MEMORIES>
Here is some information about the user:
* This is a fact
</MEMORIES>
"""
메모리 삭제
삭제할 메모리를 선택하는 방법에 따라 메모리 뱅크 인스턴스에서 메모리를 삭제하는 방법은 여러 가지가 있습니다.
리소스 이름으로 삭제
삭제하려는 메모리 리소스를 정확히 알고 있다면 해당 리소스 이름을 사용하여 특정 메모리를 삭제할 수 있습니다.
client.agent_engines.memories.delete(
name=MEMORY_NAME,
config={
# Set to false (default) if you want to delete the memory asynchronously.
"wait_for_completion": True
}
)
다음을 바꿉니다.
- MEMORY_NAME: 삭제할 메모리의 이름입니다. 이름은
다음 형식이어야 합니다.
projects/{your project}/locations/{your location}/reasoningEngine/{your reasoning engine}/memories/{your memory}. 메모리 이름은 메모리를 가져오는 과정에서 확인할 수 있습니다.
기준으로 삭제
기준 기반 삭제를 사용하여 메모리를 하나 이상 삭제할 수 있습니다. 제공된 필터와 일치하는 메모리만 삭제됩니다.
`filter` (시스템 필드에 적용됨) 또는 filter_groups (메타데이터 필드에 적용됨) 중 하나 이상을 지정해야 합니다.filter
operation = client.agent_engines.memories.purge(
name=agent_engine.api_resource.name,
# Specify at least one of `filter` or `filter_groups`.
filter="FILTER_STRING",
filter_groups=FILTER_GROUPS,
# Set to false (default) if you want to stage but not execute the purge operation.
force=True,
config={
# Set to false (default) if you want to purge memories asynchronously.
"wait_for_completion": True
}
)
다음을 바꿉니다.
- FILTER_STRING: 시스템 필드에 대해 필터링하는 데
EBNF 구문을 사용하는 문자열입니다. 시스템 필드에는
create_time,update_time,fact, andtopics가 포함됩니다. 시스템 필드에 대해 필터링하는 방법에 대한 자세한 내용은 메모리 가져오기 페이지의 메타데이터 필드로 필터링 섹션을 참조하세요. - FILTER_GROUPS: 메모리 메타데이터에 대해 필터링하기 위한 사전 또는 객체 목록입니다. 메타데이터 필드에 대해 필터링하는 방법에 대한 자세한 내용은 메모리 가져오기 페이지의 시스템 필드로 필터링 섹션을 참조하세요.
이 작업은 삭제된 메모리 수 (force=True인 경우) 또는 작업이 실행될 경우 삭제될 메모리 수 (force=False인 경우)를 반환합니다.
print(operation.response.purge_count)
예를 들어 user_id '123'의 범위에 속하는 모든 메모리를 삭제할 수 있습니다.
operation = client.agent_engines.memories.purge(
name=agent_engine.api_resource.name,
filter="scope.user_id=\"123\""
force=True
)
의미론적 의미로 삭제
메모리 생성 중에
메모리 뱅크는 새로 추출된 정보의 콘텐츠와
기존 메모리를 기반으로 메모리를 만들지, 업데이트할지, 삭제할지 결정합니다. 새 정보가 메모리와 상충되거나 추출된 콘텐츠가 메모리 뱅크에 주제를 잊으라고 지시하는 경우 (EXPLICIT_INSTRUCTIONS 메모리
주제) 메모리가 삭제될 수 있습니다.
예를 들어 다음 요청은 지정된 scope에 있는 경우 식단 선호도에 관한 정보가 포함된 기존 메모리를 삭제합니다.
from google import genai
client.agent_engines.memories.generate(
name=agent_engine.api_resource.name,
direct_contents_source={
"events": [{
"content": genai.types.Content(
role="user",
parts=[
genai.types.Part.from_text(text="Forget my dietary preferences.")
]
)
}]
},
scope={...}
)
정리
이 프로젝트에 사용된 모든 리소스를 정리하려면 빠른 시작에 사용한 프로젝트 Google Cloud 를 삭제하면 됩니다.
또는 다음과 같이 이 튜토리얼에서 만든 개별 리소스를 삭제하면 됩니다.
다음 코드 샘플을 사용하여 Agent Platform 인스턴스를 삭제합니다. 그러면 Agent Platform 인스턴스와 연결된 모든 세션 또는 메모리도 삭제됩니다.
agent_engine.delete(force=True)로컬에서 만든 파일을 삭제합니다.