이 튜토리얼에서는 Vertex AI Agent Engine 세션 및 메모리 뱅크에 직접 REST API를 호출하여 세션과 장기 기억을 만들고 사용하는 방법을 보여줍니다. 에이전트 프레임워크가 호출을 조정하지 않도록 하거나 세션 및 메모리 뱅크를 Agent Development Kit(ADK) 이외의 에이전트 프레임워크와 통합하려면 REST API를 사용하세요.
ADK를 사용하는 빠른 시작은 Agent Development Kit를 사용한 빠른 시작을 참고하세요.
이 튜토리얼에서는 다음 단계를 사용합니다.
- Vertex AI Agent Engine 세션 및 메모리 뱅크에 액세스하려면 Vertex AI Agent Engine 인스턴스를 만듭니다.
- 다음 옵션을 사용하여 기억을 만듭니다.
- Vertex AI Agent Engine 메모리 뱅크를 사용하여 기억 생성: Vertex AI Agent Engine 메모리 뱅크가 기억를 생성할 소스로 세션과 이벤트를 Vertex AI Agent Engine 세션에 씁니다.
- 기억 직접 업로드: 저장되는 정보를 완전히 제어하려면 직접 기억을 작성하거나 에이전트에게 기억을 작성하도록 요청하세요.
- 기억 검색
- 삭제
시작하기 전에
이 튜토리얼에 설명된 단계를 완료하려면 먼저 프로젝트와 환경을 설정해야 합니다.
프로젝트 설정
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
- 프로젝트를 선택한 경우 프로젝트에 대한 Vertex AI 사용자(
roles/aiplatform.user
) IAM 역할이 있는지 확인합니다. -
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
- PROJECT_ID: 프로젝트 ID
- LOCATION: 리전 Vertex AI Agent Engine 메모리 뱅크에는
us-central1
만 지원됩니다. 불투명한 사용자 ID로 세션을 만듭니다. 이 세션에서 생성된 기억은 기억을 생성할 때 범위를 명시적으로 제공하지 않는 한 범위
{"user_id": "USER_ID"}
를 사용하여 자동으로 키가 지정됩니다.from google.cloud import aiplatform_v1beta1 sessions_client = aiplatform_v1beta1.SessionServiceClient( client_options={ "api_endpoint": "https://LOCATION-aiplatform.googleapis.com" }, transport="rest" ) session_lro = sessions_client.create_session( parent=AGENT_ENGINE_NAME, session={"user_id": "USER_ID"} ) session_name = "/".join(session_lro.operation.name.split("/")[0:-2])
다음을 바꿉니다.
LOCATION: 리전 Vertex AI Agent Engine 메모리 뱅크에는
us-central1
만 지원됩니다.AGENT_ENGINE_NAME: 내가 만든 Vertex AI Agent Engine 인스턴스 또는 기존 Vertex AI Agent Engine 인스턴스의 이름. 이름 형식은 다음과 같아야 합니다:
projects/{your project}/locations/{your location}/reasoningEngine/{your reasoning engine}
.USER_ID: 사용자의 식별자. 이 세션에서 생성된 기억은 기억을 생성할 때 범위를 명시적으로 제공하지 않는 한 범위
{"user_id": "USER_ID"}
를 사용하여 자동으로 키가 지정됩니다.
세션에 이벤트를 반복적으로 업로드합니다. 이벤트에는 사용자, 에이전트, 도구 간의 모든 상호작용이 포함될 수 있습니다. 순서가 지정된 이벤트 목록은 세션의 대화 기록을 나타냅니다. 이 대화 기록은 특정 사용자의 기억을 생성하기 위한 소스 자료로 사용됩니다.
event = aiplatform_v1beta1.SessionEvent( author="user", # Required by Sessions. invocation_id="1", # Required by Sessions. timestamp=datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'), # Required by Sessions. content = aiplatform_v1beta1.Content( role="user", parts=[aiplatform_v1beta1.Part(text="Hello")] ) ) sessions_client.append_event(name=session_name, event=event)
대화 기록에서 기억을 생성하려면 세션의 기억 생성 요청을 트리거합니다.
client.agent_engines.generate_memories( name=agent_engine.api_resource.name, vertex_session_source={ "session": session_name }, # Optional when using Agent Engine Sessions. Defaults to {"user_id": session.user_id}. scope=SCOPE )
- (선택사항) SCOPE: 생성된 기억의 범위를 나타내는 사전으로, 키-값 쌍은 최대 5개까지 허용되며
*
문자는 허용되지 않습니다. 예를 들면{"session_id": "MY_SESSION"}
입니다. 동일한 범위의 기억만 통합 대상으로 간주됩니다. 입력하지 않으면{"user_id": session.user_id}
가 사용됩니다. 다음 코드 샘플을 사용하여 Vertex AI Agent Engine 인스턴스를 삭제합니다. 그러면 Vertex AI Agent Engine 인스턴스와 연결된 모든 세션 또는 기억도 삭제됩니다.
agent_engine.delete(force=True)
로컬에서 만든 파일을 삭제합니다.
Vertex AI에 인증
로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.
자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경의 ADC 설정을 참조하세요.
라이브러리 가져오기
Vertex AI SDK를 설치합니다.
pip install google-cloud-aiplatform>=1.100.0
Vertex AI Agent Engine 인스턴스 만들기
Vertex AI Agent Engine 세션 및 Vertex AI Agent Engine 메모리 뱅크에 액세스하려면 먼저 Vertex AI Agent Engine 인스턴스를 만들어야 합니다. 세션 및 메모리 뱅크를 사용하기 위해 에이전트를 배포할 필요는 없습니다. 에이전트 배포가 없으므로 Vertex AI Agent Engine 인스턴스를 만드는 데는 몇 초면 됩니다.
import vertexai
client = vertexai.Client(
project="PROJECT_ID",
location="LOCATION",
)
agent_engine = client.agent_engines.create()
다음을 바꿉니다.
Vertex AI Agent Engine 세션에서 기억 생성
Vertex AI Agent Engine 세션 및 메모리 뱅크를 설정한 후 세션을 만들고 이벤트를 추가할 수 있습니다. 기억은 향후 사용자 상호작용에 사용할 수 있도록 사용자와 에이전트의 대화에서 사실로 생성됩니다. 자세한 내용은 기억 생성 및 검색을 참고하세요.
다음을 바꿉니다.
기억 업로드
원시 대화를 사용하여 기억을 생성하는 대신 CreateMemory
를 사용하여 기억을 직접 업로드할 수 있습니다. Memory Bank에서 콘텐츠에서 정보를 추출하는 대신 사용자에 관해 저장해야 하는 사실을 직접 제공합니다. 사용자에 관한 사실을 1인칭으로 작성하는 것이 좋습니다(예: I am a software engineer
).
memory = client.agent_engines.create_memory(
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.retrieve_memories(
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>
"""
삭제
이 프로젝트에 사용된 모든 리소스를 삭제하려면 빠른 시작에 사용한 Google Cloud 프로젝트를 삭제하면 됩니다.
또는 다음과 같이 이 튜토리얼에서 만든 개별 리소스를 삭제하면 됩니다.