이 페이지에서는 에이전트 개발 키트 템플릿 (Vertex AI SDK for Python의 AdkApp
클래스)을 사용하여 에이전트를 개발하는 방법을 보여줍니다. 이 에이전트는 지정된 날짜에 두 통화 간 환율을 반환합니다.
다음 단계를 따르세요.
- 모델 정의 및 구성
- (선택사항) 도구 정의 및 사용
- (선택사항) 세션 관리
- (선택사항) 추억 관리하기
시작하기 전에
환경 설정 단계에 따라 환경이 설정되었는지 확인합니다.
모델 정의 및 구성
모델 버전을 정의합니다.
model = "gemini-2.0-flash"
(선택사항) 모델의 안전 설정을 구성합니다. Gemini에서 안전 설정에 사용할 수 있는 옵션에 대한 자세한 내용은 안전 속성 구성을 참조하세요. 다음은 안전 설정을 구성하는 방법의 예시입니다.
from google.genai import types
safety_settings = [
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.OFF,
),
]
(선택사항) 콘텐츠 생성 파라미터를 지정합니다.
from google.genai import types
generate_content_config = types.GenerateContentConfig(
safety_settings=safety_settings,
temperature=0.28,
max_output_tokens=1000,
top_p=0.95,
)
모델 구성을 사용하여 AdkApp
를 만듭니다.
from google.adk.agents import Agent
from vertexai.agent_engines import AdkApp
agent = Agent(
model=model, # Required.
name='currency_exchange_agent', # Required.
generate_content_config=generate_content_config, # Optional.
)
app = AdkApp(agent=agent)
터미널 또는 Colab 노트북과 같은 대화형 환경에서 실행하는 경우 중간 테스트 단계로 쿼리를 실행할 수 있습니다.
async for event in app.async_stream_query(
user_id="USER_ID", # Required
message="What is the exchange rate from US dollars to Swedish currency?",
):
print(event)
- USER_ID: 128자(영문 기준)로 제한된 사용자 ID를 선택합니다.
예를 들면
user-123
입니다.
응답은 다음 예시와 유사한 Python 사전입니다.
{'actions': {'artifact_delta': {},
'requested_auth_configs': {},
'state_delta': {}},
'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'To provide you with the most accurate '
'exchange rate, I need to know the specific '
'currencies you\'re asking about. "Swedish '
'currency" could refer to:\n'
'\n'
'* **Swedish Krona (SEK):** This is the '
'official currency of Sweden.\n'
'\n'
"Please confirm if you're interested in the "
'exchange rate between USD and SEK. Once you '
'confirm, I can fetch the latest exchange rate '
'for you.\n'}],
'role': 'model'},
'id': 'LYg7wg8G',
'invocation_id': 'e-113ca547-0f19-4d50-9dde-f76cbc001dce',
'timestamp': 1744166956.925927}
(선택사항) 도구 정의 및 사용
모델을 정의한 후 추론을 위해 모델에 사용되는 도구를 정의합니다.
함수를 정의할 때는 함수 파라미터, 함수 기능 및 함수 반환값을 완전히 명확하게 기술하는 설명을 포함하는 것이 중요합니다. 이 정보는 모델이 사용할 함수를 결정하기 위해 사용됩니다. 또한 함수를 로컬로 테스트하여 작동하는지 확인해야 합니다.
다음 코드를 사용하여 환율을 반환하는 함수를 정의합니다.
def get_exchange_rate(
currency_from: str = "USD",
currency_to: str = "EUR",
currency_date: str = "latest",
):
"""Retrieves the exchange rate between two currencies on a specified date.
Uses the Frankfurter API (https://api.frankfurter.app/) to obtain
exchange rate data.
Args:
currency_from: The base currency (3-letter currency code).
Defaults to "USD" (US Dollar).
currency_to: The target currency (3-letter currency code).
Defaults to "EUR" (Euro).
currency_date: The date for which to retrieve the exchange rate.
Defaults to "latest" for the most recent exchange rate data.
Can be specified in YYYY-MM-DD format for historical rates.
Returns:
dict: A dictionary containing the exchange rate information.
Example: {"amount": 1.0, "base": "USD", "date": "2023-11-24",
"rates": {"EUR": 0.95534}}
"""
import requests
response = requests.get(
f"https://api.frankfurter.app/{currency_date}",
params={"from": currency_from, "to": currency_to},
)
return response.json()
에이전트에 사용하기 전에 함수를 테스트하기 위해 다음을 실행합니다.
get_exchange_rate(currency_from="USD", currency_to="SEK")
응답은 다음과 비슷하게 표시됩니다.
{'amount': 1.0, 'base': 'USD', 'date': '2025-04-03', 'rates': {'SEK': 9.6607}}
AdkApp
내에서 도구를 사용하려면 tools=
인수 아래의 도구 목록에 추가합니다.
from google.adk.agents import Agent
agent = Agent(
model=model, # Required.
name='currency_exchange_agent', # Required.
tools=[get_exchange_rate], # Optional.
)
테스트 쿼리를 수행하여 로컬에서 에이전트를 테스트할 수 있습니다. 다음 명령어를 실행하여 미국 달러와 스웨덴 크로나를 사용해 로컬에서 에이전트를 테스트합니다.
from vertexai.agent_engines import AdkApp
app = AdkApp(agent=agent)
async for event in app.async_stream_query(
user_id="USER_ID",
message="What is the exchange rate from US dollars to SEK on 2025-04-03?",
):
print(event)
여기서 USER_ID는 정의한 사용자 ID입니다. 예를 들면 user-123
입니다.
응답은 다음과 유사한 딕셔너리 시퀀스입니다.
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
'currency_from': 'USD',
'currency_to': 'SEK'},
'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
'name': 'get_exchange_rate'}}],
'role': 'model'},
'id': 'zFyIaaif',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_response': {'id': 'adk-e39f3ba2-fa8c-4169-a63a-8e4c62b89818',
'name': 'get_exchange_rate',
'response': {'amount': 1.0,
'base': 'USD',
'date': '2025-04-03',
'rates': {'SEK': 9.6607}}}}],
'role': 'user'},
'id': 'u2YR4Uom',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
'2025-04-03 is 9.6607.'}],
'role': 'model'},
'id': 'q3jWA3wl',
# ...
}
(선택사항) 세션 관리
AdkApp
은 로컬에서 실행할 때는 메모리 내 세션을 사용하고 Vertex AI Agent Engine에 에이전트를 배포한 후에는 클라우드 기반 관리 세션을 사용합니다. 이 섹션에서는 관리 세션과 함께 작동하도록 ADK 에이전트를 구성하는 방법을 설명합니다.
(선택사항) 세션 데이터베이스 맞춤설정
기본 관리 세션 서비스를 자체 데이터베이스로 재정의하려면 다음과 같이 session_service_builder
함수를 정의하면 됩니다.
def session_service_builder():
from google.adk.sessions import InMemorySessionService
return InMemorySessionService()
데이터베이스를 AdkApp
에 session_service_builder=
로 전달합니다.
from vertexai.agent_engines import AdkApp
app = AdkApp(
agent=agent, # Required.
session_service_builder=session_service_builder, # Optional.
)
세션과 함께 에이전트 사용
AdkApp
을 로컬에서 실행할 때 다음 안내에서는 메모리 내 세션을 사용합니다.
에이전트의 세션을 만듭니다.
session = await app.async_create_session(user_id="USER_ID")
print(session)
세션은 ADK 세션 객체의 사전 표현으로 생성됩니다.
에이전트와 연결된 세션을 나열합니다.
await app.async_list_sessions(user_id="USER_ID")
특정 세션을 가져옵니다.
session = await app.async_get_session(user_id="USER_ID", session_id="SESSION_ID")
각 항목의 의미는 다음과 같습니다.
USER_ID는 사용자가 정의한 사용자 ID입니다. 예를 들면
user-123
입니다.SESSION_ID는 가져오려는 특정 세션의 ID입니다.
세션을 사용하여 AdkApp
를 쿼리합니다.
async for event in app.async_stream_query(
user_id="USER_ID",
session_id=SESSION_ID, # Optional. you can pass in the session_id when querying the agent
message="What is the exchange rate from US dollars to Swedish currency on 2025-04-03?",
):
print(event)
에이전트는 다음과 같은 정보 요청으로 응답할 수 있습니다.
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'I need to know the Swedish currency code to '
'provide you with the exchange rate.'}],
'role': 'model'},
'id': 'wIgZAtQ4',
#...
}
다음과 같이 지정하여 session
에 해당하는 세션 내에서 USER_ID
를 대신하여 응답 (예: "SEK"
)을 보낼 수 있습니다.
async for event in app.async_stream_query(
user_id="USER_ID",
session_id=session.id, # Optional. you can pass in the session_id when querying the agent
message="SEK",
):
print(event)
다음과 같은 사전 시퀀스와 같이 대화가 계속됩니다.
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_call': {'args': {'currency_date': '2025-04-03',
'currency_from': 'USD',
'currency_to': 'SEK'},
'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate'}}],
'role': 'model'},
'id': 'bOPHtzji',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'function_response': {'id': 'adk-2b9230a6-4b92-4a1b-9a65-b708ff6c68b6',
'name': 'get_exchange_rate',
'response': {'amount': 1.0,
'base': 'USD',
'date': '2025-04-03',
'rates': {'SEK': 9.6607}}}}],
'role': 'user'},
'id': '9AoDFmiL',
# ...
}
{'author': 'currency_exchange_agent',
'content': {'parts': [{'text': 'The exchange rate from USD to SEK on '
'2025-04-03 is 1 USD to 9.6607 SEK.'}],
'role': 'model'},
'id': 'hmle7trT',
# ...
}
(선택사항) 추억 관리
기본적으로 AdkApp
은 로컬에서 실행할 때는 에이전트 메모리의 메모리 내 구현을 사용하고 Vertex AI Agent Engine에 에이전트를 배포한 후에는 Vertex AI Agent Engine 메모리 뱅크를 사용합니다.
ADK 에이전트를 개발할 때는 에이전트가 언제 메모리를 가져오고 프롬프트에 메모리를 어떻게 포함할지를 제어하는 PreloadMemoryTool
를 포함할 수 있습니다. 다음 예시 에이전트는 각 턴의 시작 시 항상 메모리를 가져오고 시스템 지침에 메모리를 포함합니다.
from google import adk
from vertexai.agent_engines import AdkApp
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()],
)
app = AdkApp(agent=agent)
(선택사항) 메모리 서비스 맞춤설정
기본 메모리 서비스를 재정의하려면 BaseMemoryService
를 반환하는 memory_service_builder
함수를 다음과 같이 정의하면 됩니다.
def memory_service_builder():
from google.adk.memory import InMemoryMemoryService
return InMemoryMemoryService()
데이터베이스를 AdkApp
에 memory_service_builder=
로 전달합니다.
from vertexai.agent_engines import AdkApp
app = AdkApp(
agent=agent, # Required.
memory_service_builder=memory_service_builder, # Optional.
)
메모리가 있는 에이전트 사용
메모리를 사용하여 ADK 에이전트를 테스트합니다.
세션을 만들고 에이전트와 상호작용합니다.
initial_session = await app.async_create_session(user_id="USER_ID") async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="Can you update the temperature to my preferred temperature?", ): print(event)
첫 번째 세션 동안에는 사용 가능한 메모리가 없고 에이전트가 사용자 선호도를 알지 못하므로 에이전트는 '선호하는 강도는 무엇인가요?'와 같은 대답으로 응답할 수 있습니다. 다음 명령어로 응답할 수 있습니다.
async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="I like it at 71 degrees", ): print(event)
에이전트는 '온도를 22도로 설정합니다. 온도가 변경되었습니다.' 에이전트의 대답은 사용한 모델에 따라 다를 수 있습니다.
세션에서 메모리를 생성합니다. 향후 세션에서 사용할 수 있도록 세션의 정보를 저장하려면
async_add_session_to_memory
메서드를 사용합니다.await app.async_add_session_to_memory(session=initial_session)
새 세션을 만들고 에이전트에게 다음과 같이 프롬프트를 표시하여 에이전트가 세션의 메모리를 유지했는지 (
PreloadMemoryTool
사용) 테스트합니다.new_session = await app.async_create_session(user_id="USER_ID") async for event in app.async_stream_query( user_id="USER_ID", session_id=initial_session.id, message="Fix the temperature!", ): print(event)
에이전트는 '온도를 22도로 설정합니다. 맞나요?' 에이전트의 응답은 사용한 모델 및 메모리 서비스 제공업체에 따라 다를 수 있습니다.
async_search_memory
메서드를 사용하여 에이전트의 메모리를 표시합니다.response = await app.async_search_memory( user_id="USER_ID", query="Fix the temperature!", ) print(response)