Vertex AI Agent Engine 세션에 액세스하려면 먼저 Vertex AI Agent Engine 인스턴스를 만들어야 합니다. 세션을 사용하기 위해 코드를 배포할 필요가 없습니다. 코드를 배포하지 않고 Vertex AI Agent Engine 인스턴스를 만드는 데는 몇 초밖에 걸리지 않습니다.
importvertexaifromvertexaiimportagent_engines# Create an agent engine instanceagent_engine=agent_engines.create()
ADK 에이전트 개발
ADK 에이전트를 만들려면 에이전트 개발 키트의 안내를 따르거나 다음 코드를 사용하여 고정 인사말로 사용자를 맞이하는 에이전트를 만듭니다.
fromgoogleimportadkdefgreetings(query:str):"""Tool to greet user."""if'hello'inquery.lower():return{"greeting":"Hello, world"}else:return{"greeting":"Goodbye, world"}# Define an ADK agentroot_agent=adk.Agent(model="gemini-2.0-flash",name='my_agent',instruction="You are an Agent that greet users, always use greetings tool to respond.",tools=[greetings])
ADK 실행기 설정
ADK 런타임은 에이전트, 도구, 콜백의 실행을 조정하고 세션 읽기 및 쓰기 호출을 조정합니다. Vertex AI Agent Engine 세션과 연결되는 VertexAiSessionService로 실행기를 초기화합니다.
fromgoogle.adk.sessionsimportVertexAiSessionServiceapp_name="AGENT_ENGINE_ID"user_id="USER_ID"# Create the ADK runner with VertexAiSessionServicesession_service=VertexAiSessionService("PROJECT_ID","LOCATION")runner=adk.Runner(agent=root_agent,app_name=app_name,session_service=session_service)# Helper method to send query to the runnerdefcall_agent(query,session_id,user_id):content=types.Content(role='user',parts=[types.Part(text=query)])events=runner.run(user_id=user_id,session_id=session_id,new_message=content)foreventinevents:ifevent.is_final_response():final_response=event.content.parts[0].textprint("Agent Response: ",final_response)
다음을 바꿉니다.
PROJECT_ID: 프로젝트 ID입니다.
LOCATION: 리전 Vertex AI Agent Engine 세션에는 us-central1만 지원됩니다.
AGENT_ENGINE_ID: Vertex AI Agent Engine 인스턴스의 리소스 ID입니다.
배포된 에이전트의 경우 리소스 ID가 GOOGLE_CLOUD_AGENT_ENGINE_ID 환경 변수로 표시됩니다.
로컬 에이전트의 경우 agent_engine.name.split("/")[-1]을 사용하여 리소스 ID를 검색할 수 있습니다.
USER_ID: 비어 있지 않은 사용자 고유 식별자로, 최대 길이는 128자(영문 기준)입니다.
에이전트와 상호작용
에이전트를 정의하고 Vertex AI Agent Engine 세션을 설정한 후 에이전트와 상호작용하여 세션 기록과 상태가 유지되는지 확인할 수 있습니다.
ADK UI
ADK 사용자 인터페이스로 에이전트를 테스트하고 session_db_url 명령줄 옵션을 사용하여 Vertex AI Agent Engine 세션에 연결합니다.
agent_engine_id="AGENT_ENGINE_ID"adk web --session_db_url=agentengine://${agent_engine_id}# Sample output+-----------------------------------------------------------------------------+| ADK Web Server started || || For local testing, access at http://localhost:8000. |+-----------------------------------------------------------------------------+INFO: Application startup complete.INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
세션이 생성되고 실행기에게 전달되면 ADK는 세션을 사용하여 현재 상호작용의 이벤트를 저장합니다. 해당 세션의 ID를 제공하여 이전 세션을 재개할 수도 있습니다.
기존 세션 나열
지정된 사용자 ID와 연결된 모든 기존 세션을 표시합니다.
# List sessionsawaitsession_service.list_sessions(app_name=app_name,user_id=user_id)# ListSessionsResponse(session_ids=['1122334455', '9988776655'])
세션 상태 관리
상태는 에이전트가 대화하는 데 필요한 정보를 보유합니다. 세션을 만들 때 초기 상태를 사전으로 제공할 수 있습니다.
# Create a session with statesession=awaitsession_service.create_session(app_name=app_name,user_id=user_id,state={'key':'value'})print(session.state['key'])# value
실행기 외부에서 세션 상태를 업데이트하려면 state_delta를 사용하여 새 이벤트를 세션에 추가합니다.
fromgoogle.adk.eventsimportEvent,EventActionsimporttime# Define state changesstate_changes={'key':'new_value'}# Create event with actionsactions_with_update=EventActions(state_delta=state_changes)system_event=Event(invocation_id="invocation_id",author="system",# Or 'agent', 'tool' etc.actions=actions_with_update,timestamp=time.time())# Append the eventawaitsession_service.append_event(session,system_event)# Check updated stateupdated_session=awaitsession_service.get_session(app_name=app_name,user_id=user_id,session_id=session.id)# State is updated to new valueprint(updated_session.state['key'])# new_value
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-09(UTC)"],[],[],null,["# Manage sessions with Agent Development Kit\n\n| **Preview**\n|\n|\n| This feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nThis page describes how you can connect an Agent Development Kit (ADK) agent with Vertex AI Agent Engine Sessions and use managed sessions in the local and production environment.\n| **Note:** If you've already followed the instructions in [Develop an Agent Development Kit agent](/vertex-ai/generative-ai/docs/agent-engine/develop/adk), you don't need to follow this guide, since the `AdkApp` template is already connected to Vertex AI Agent Engine Sessions through `session_service`.\n\nBefore you begin\n----------------\n\nMake sure your environment is set up by following\nthe [Get the required roles](/vertex-ai/generative-ai/docs/agent-engine/set-up#get_the_required_roles) and [Authentication](/vertex-ai/generative-ai/docs/agent-engine/set-up#authentication) steps in [Set up your environment](/vertex-ai/generative-ai/docs/agent-engine/set-up).\n\nCreate a Vertex AI Agent Engine instance\n----------------------------------------\n\nTo access Vertex AI Agent Engine Sessions, you first need to create an Vertex AI Agent Engine instance. You don't need to deploy any code to start using Sessions. Without code deployment, creating an Vertex AI Agent Engine instance only takes a few seconds. \n\n import https://cloud.google.com/python/docs/reference/vertexai/latest/\n from vertexai import agent_engines\n\n # Create an agent engine instance\n agent_engine = agent_engines.create()\n\nDevelop your ADK agent\n----------------------\n\n| **Note:** Make sure you have installed ADK version **1.0.0** or later. This version is included in `google-cloud-aiplatform[adk,agent_engine]`.\n\nTo create your ADK agent, follow the instructions in [Agent Development Kit](https://google.github.io/adk-docs/), or use the following code to create an agent that greets a user with fixed greetings: \n\n from google import adk\n\n def greetings(query: str):\n \"\"\"Tool to greet user.\"\"\"\n if 'hello' in query.lower():\n return {\"greeting\": \"Hello, world\"}\n else:\n return {\"greeting\": \"Goodbye, world\"}\n\n # Define an ADK agent\n root_agent = adk.Agent(\n model=\"gemini-2.0-flash\",\n name='my_agent',\n instruction=\"You are an Agent that greet users, always use greetings tool to respond.\",\n tools=[greetings]\n )\n\nSet up the ADK runner\n---------------------\n\nThe [ADK Runtime](https://google.github.io/adk-docs/runtime/) orchestrates the execution of your agents, tools, and callbacks, and orchestrates calls to read and write sessions. Initialize the Runner with [`VertexAiSessionService`](https://google.github.io/adk-docs/sessions/session/#sessionservice-implementations), which connects with Vertex AI Agent Engine Sessions. \n\n from google.adk.sessions import VertexAiSessionService\n\n app_name=\"\u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e\"\n user_id=\"\u003cvar translate=\"no\"\u003eUSER_ID\u003c/var\u003e\"\n\n # Create the ADK runner with VertexAiSessionService\n session_service = VertexAiSessionService(\n \"\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e\", \"\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e\")\n runner = adk.Runner(\n agent=root_agent,\n app_name=app_name,\n session_service=session_service)\n\n # Helper method to send query to the runner\n def call_agent(query, session_id, user_id):\n content = types.Content(role='user', parts=[types.Part(text=query)])\n events = runner.run(\n user_id=user_id, session_id=session_id, new_message=content)\n\n for event in events:\n if event.is_final_response():\n final_response = event.content.parts[0].text\n print(\"Agent Response: \", final_response)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e: Your project ID.\n\n- \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: Your region.\n\n- \u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e: The resource ID of a Vertex AI Agent Engine instance.\n\n - For deployed agents, the resource ID is listed as the `GOOGLE_CLOUD_AGENT_ENGINE_ID` environment variable\n\n - For local agents, you can retrieve the resource ID using `agent_engine.name.split(\"/\")[-1]`.\n\n- \u003cvar translate=\"no\"\u003eUSER_ID\u003c/var\u003e: A non-empty unique identifier for the user, with a maximum length of 128 characters.\n\nInteract with your agent\n------------------------\n\nAfter defining your agent and setting up Vertex AI Agent Engine Sessions, you can interact with your agent to check that the session history and states persist. \n\n### ADK UI\n\nTest your agent with the ADK user interface and connect to Vertex AI Agent Engine Session using the `session_db_url` command line option: \n\n agent_engine_id=\"\u003cvar translate=\"no\"\u003eAGENT_ENGINE_ID\u003c/var\u003e\"\n\n adk web --session_db_url=agentengine://${agent_engine_id}\n\n # Sample output\n +-----------------------------------------------------------------------------+\n | ADK Web Server started |\n | |\n | For local testing, access at http://localhost:8000. |\n +-----------------------------------------------------------------------------+\n\n INFO: Application startup complete.\n INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)\n\n### Python\n\nUse ADK Python code to manage sessions and states.\n\n### Create a session and query the agent\n\nUse the following code to create a session and send a query to your agent: \n\n # Create a session\n session = await session_service.create_session(\n app_name=app_name,\n user_id=user_id)\n\n call_agent(\"Hello!\", session.id, user_id)\n # Agent response: \"Hello, world\"\n\n call_agent(\"Thanks!\", session.id, user_id)\n # Agent response: \"Goodbye, world\"\n\nAfter the session is created and passed to the runner, ADK uses the session to store events from the current interaction. You can also resume a previous session by providing the ID for that session.\n\n### List existing sessions\n\nList all existing sessions associated with a given user ID. \n\n # List sessions\n await session_service.list_sessions(app_name=app_name,user_id=user_id)\n\n # ListSessionsResponse(session_ids=['1122334455', '9988776655'])\n\n### Manage session states\n\nStates hold information that the agent needs for a conversation. You can provide an initial state as a dictionary when you create a session: \n\n # Create a session with state\n session = await session_service.create_session(\n app_name=app_name,\n user_id=user_id,\n state={'key': 'value'})\n\n print(session.state['key'])\n # value\n\nTo update the session state outside the runner, append a new event to the session using `state_delta`: \n\n from google.adk.events import Event, EventActions\n import time\n\n # Define state changes\n state_changes = {'key': 'new_value'}\n\n # Create event with actions\n actions_with_update = EventActions(state_delta=state_changes)\n system_event = Event(\n invocation_id=\"invocation_id\",\n author=\"system\", # Or 'agent', 'tool' etc.\n actions=actions_with_update,\n timestamp=time.time()\n )\n\n # Append the event\n await session_service.append_event(session, system_event)\n\n # Check updated state\n updated_session = await session_service.get_session(\n app_name=app_name,\n user_id=user_id,\n session_id=session.id)\n # State is updated to new value\n print(updated_session.state['key'])\n # new_value\n\n### Delete a session\n\nDelete a specific session associated with a user ID: \n\n await session_service.delete_session(app_name=app_name, user_id=user_id, session_id=session.id)\n\nDeploy your agent to Vertex AI Agent Engine\n-------------------------------------------\n\nAfter you test your agent locally, you can deploy the agent to production by updating the Vertex AI Agent Engine instance with parameters: \n\n agent_engines.update(resource_name=agent_engine.name, agent_engine=\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eAGENT\u003c/span\u003e\u003c/var\u003e, requirements=REQUIREMENTS)\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eAGENT\u003c/var\u003e: The application that implements the `query / stream_query` method (for example, `AdkApp` for an ADK agent). For more information, see [Deployment considerations](/vertex-ai/generative-ai/docs/agent-engine/deploy#deployment-considerations).\n\nClean up\n--------\n\nTo clean up all resources used in this project, you can delete the Vertex AI Agent Engine instance along with its child resources: \n\n agent_engine.delete(force=True)\n\nWhat's next\n-----------\n\n- [Manage sessions using API calls](/vertex-ai/generative-ai/docs/agent-engine/sessions/manage-sessions-api)."]]