이 페이지에서는 Agent Development Kit 템플릿(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.preview.reasoning_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 노트북과 같은 대화형 환경에서 실행하는 경우 중간 테스트 단계로 쿼리를 실행할 수 있습니다.
for event in app.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입니다.
응답은 다음 예시와 유사한 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.preview.reasoning_engines import AdkApp
app = AdkApp(agent=agent)
for event in app.stream_query(
user_id="USER_ID",
message="What is the exchange rate from US dollars to SEK on 2025-04-03?",
):
print(event)
응답은 다음과 유사한 사전 시퀀스입니다.
{'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.preview.reasoning_engines import AdkApp
app = AdkApp(
agent=agent, # Required.
session_service_builder=session_service_builder, # Optional.
)
세션과 함께 에이전트 사용
에이전트를 로컬에서 실행할 때 다음 안내는 메모리 내 세션을 사용합니다.
에이전트의 세션을 만듭니다.
session = app.create_session(user_id="USER_ID")
에이전트와 연결된 세션을 나열합니다.
app.list_sessions(user_id="USER_ID")
특정 세션을 가져옵니다.
session = app.get_session(user_id="USER_ID", session_id="SESSION_ID")
여기서 SESSION_ID는 검색하려는 특정 세션의 ID입니다.
세션을 사용하여 에이전트를 쿼리합니다.
for event in app.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_id
를 지정하여 세션 내에서 응답(예: "SEK"
)을 보낼 수 있습니다.
for event in app.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',
# ...
}