원래 AutoGen의 커뮤니티 주도 포크인 AG2는 AI 기반 상담사를 빌드하기 위한 오픈소스 프레임워크입니다.
이 페이지에서는 프레임워크별 AG2 템플릿 (Python용 Vertex AI SDK의 AG2Agent
클래스)을 사용하여 에이전트를 개발하는 방법을 보여줍니다. 상담사는 지정된 날짜에 두 통화 간의 환율을 반환합니다. 단계별로 알려드리겠습니다.
- 실행 파일 정의 및 구성
- 도구 정의 및 사용
- (선택사항) 조정 맞춤설정
시작하기 전에
환경 설정 단계에 따라 환경이 설정되었는지 확인합니다.
1단계: 실행 가능한 항목 정의 및 구성
사용할 모델 버전을 정의합니다.
model = "gemini-1.5-flash-001"
사용할 실행 가능 이름을 정의합니다.
runnable_name = "Get Exchange Rate Agent"
(선택사항) 모델을 구성합니다.
from google.cloud.aiplatform.aiplatform import initializer
llm_config = {
"config_list": [{
"project_id": initializer.global_config.project,
"location": initializer.global_config.location,
"model": "gemini-1.5-flash-001",
"api_type": "google",
}]
}
AG2에서 모델을 구성하는 방법에 관한 자세한 내용은 모델 구성 심층 분석을 참고하세요.
(선택사항) 모델의 안전 설정을 구성합니다. 다음은 안전 설정을 구성하는 방법의 예시입니다.
from vertexai.generative_models import HarmBlockThreshold, HarmCategory
safety_settings = {
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
}
for config_item in llm_config["config_list"]:
config_item["safety_settings"] = safety_settings
Gemini에서 안전 설정에 사용할 수 있는 옵션에 대한 자세한 내용은 안전 속성 구성을 참고하세요.
모델 구성을 사용하여 AG2Agent
를 만듭니다.
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
대화형 환경 (예: 터미널 또는 Colab 노트북)에서 실행하는 경우 중간 테스트 단계로 쿼리를 실행할 수 있습니다.
response = agent.query(input="What is the exchange rate from US dollars to Swedish currency?", max_turns=1)
print(response)
응답은 다음 예시와 유사한 Python 사전입니다.
{'chat_id': None,
'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
'role': 'user',
'name': 'Exchange Rate Agent'}],
'summary': 'I do not have access to real-time information, including currency exchange rates. To get the most up-to-date exchange rate from US dollars to Swedish Krona (SEK), I recommend using a reliable online currency converter or checking with your bank. \n',
'cost': {'usage_including_cached_inference': {'total_cost': 5.2875e-06,
'gemini-1.5-flash-001': {'cost': 5.2875e-06,
'prompt_tokens': 34,
'completion_tokens': 62,
'total_tokens': 96}},
'usage_excluding_cached_inference': {'total_cost': 5.2875e-06,
'gemini-1.5-flash-001': {'cost': 5.2875e-06,
'prompt_tokens': 34,
'completion_tokens': 62,
'total_tokens': 96}}},
'human_input': []}
(선택사항) 고급 맞춤설정
AG2Agent
템플릿은 Google Cloud에서 사용 가능한 모든 파운데이션 모델에 대한 액세스를 제공하므로 기본적으로 api_type=="google"
를 사용합니다. api_type=="google"
를 통해 사용할 수 없는 모델을 사용하려면 llm_config
매개변수를 맞춤설정하면 됩니다.
AG2에서 지원되는 모델과 기능의 목록은 모델 제공업체를 참고하세요.
llm_config=
에 지원되는 값 집합은 각 채팅 모델에 따라 다르므로 자세한 내용은 해당 문서를 참고하세요.
Gemini
기본적으로 설치되어 있습니다.
llm_config
인수를 생략하면 AG2Agent
템플릿에서 사용됩니다. 예를 들면 다음과 같습니다.
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name # Required.
)
Anthropic
먼저 문서에 따라 계정을 설정하고 패키지를 설치합니다.
다음으로 llm_config
를 정의합니다.
llm_config = {
"config_list": [{
"model": "claude-3-5-sonnet-20240620", # Required.
"api_key": "ANTHROPIC_API_KEY", # Required.
"api_type": "anthropic", # Required.
}]
}
마지막으로 다음 코드를 사용하여 AG2Agent
템플릿에서 사용합니다.
agent = agent_engines.AG2Agent(
model="claude-3-5-sonnet-20240620", # Required.
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
OpenAI
OpenAI
를 Gemini의 ChatCompletions API와 함께 사용할 수 있습니다.
먼저 llm_config
를 정의합니다.
import google.auth
from google.cloud.aiplatform.aiplatform import initializer
project = initializer.global_config.project
location = initializer.global_config.location
base_url = f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project}/locations/{location}/endpoints/openapi"
# Note: the credential lives for 1 hour by default.
# After expiration, it must be refreshed.
creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
llm_config = {
"config_list": [{
"model": "google/gemini-1.5-flash-001", # Required.
"api_type": "openai", # Required.
"base_url": base_url, # Required.
"api_key": creds.token, # Required.
}]
}
마지막으로 다음 코드를 사용하여 AG2Agent
템플릿에서 사용합니다.
agent = agent_engines.AG2Agent(
model="google/gemini-1.5-flash-001", # Or "meta/llama3-405b-instruct-maas".
runnable_name=runnable_name, # Required.
llm_config=llm_config, # Optional.
)
2단계: 도구 정의 및 사용
모델을 정의한 후 다음 단계는 추론을 위해 모델에 사용되는 도구를 정의하는 것입니다. 도구는 AG2 도구 또는 Python 함수일 수 있습니다.
함수를 정의할 때는 함수 매개변수, 함수 기능 및 함수 반환값을 완전히 명확하게 기술하는 설명을 포함하는 것이 중요합니다. 이 정보는 모델이 사용할 함수를 결정하기 위해 사용됩니다. 또한 함수를 로컬로 테스트하여 작동하는지 확인해야 합니다.
다음 코드를 사용하여 환율을 반환하는 함수를 정의합니다.
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': '2024-02-22', 'rates': {'SEK': 10.3043}}
AG2Agent
템플릿 내에서 도구를 사용하려면 도구를 tools=
인수 아래의 도구 목록에 추가합니다.
agent = agent_engines.AG2Agent(
model=model, # Required.
runnable_name=runnable_name, # Required.
tools=[get_exchange_rate], # Optional.
)
테스트 쿼리를 실행하여 로컬에서 에이전트를 테스트할 수 있습니다. 다음 명령어를 실행하여 US 달러와 스웨덴 크로나를 사용해 로컬에서 에이전트를 테스트합니다.
response = agent.query(input="What is the exchange rate from US dollars to Swedish currency?", max_turns=2)
응답은 다음과 유사한 딕셔너리입니다.
{'chat_id': None,
'chat_history': [{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': '',
'tool_calls': [{'id': '2285',
'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
'name': 'get_exchange_rate'},
'type': 'function'}],
'role': 'assistant'},
{'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
'tool_responses': [{'tool_call_id': '2285',
'role': 'tool',
'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
'role': 'tool',
'name': 'user'},
{'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'role': 'user',
'name': 'Get Exchange Rate Agent'},
{'content': 'What is the exchange rate from US dollars to Swedish currency?',
'role': 'assistant',
'name': 'user'},
{'content': '',
'tool_calls': [{'id': '4270',
'function': {'arguments': '{"currency_from": "USD", "currency_to": "SEK"}',
'name': 'get_exchange_rate'},
'type': 'function'}],
'role': 'assistant'},
{'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}",
'tool_responses': [{'tool_call_id': '4270',
'role': 'tool',
'content': "{'amount': 1.0, 'base': 'USD', 'date': '2025-02-27', 'rates': {'SEK': 10.6509}}"}],
'role': 'tool',
'name': 'user'},
{'content': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'role': 'user',
'name': 'Get Exchange Rate Agent'}],
'summary': 'The current exchange rate is 1 USD to 10.6509 SEK. \n',
'cost': {'usage_including_cached_inference': {'total_cost': 0.0002790625,
'gemini-1.5-flash-001': {'cost': 0.0002790625,
'prompt_tokens': 757,
'completion_tokens': 34,
'total_tokens': 791}},
'usage_excluding_cached_inference': {'total_cost': 0.0002790625,
'gemini-1.5-flash-001': {'cost': 0.0002790625,
'prompt_tokens': 757,
'completion_tokens': 34,
'total_tokens': 791}}},
'human_input': []}
3단계: 조정 맞춤설정
모든 AG2 에이전트는 조정의 입력 및 출력 스키마를 제공하는 ConversableAgent 인터페이스를 구현합니다. AG2Agent
가 쿼리에 응답하면 실행 파일을 빌드해야 합니다. 기본적으로 AG2Agent
는 도구로 모델을 바인딩하여 이러한 실행 파일을 빌드합니다.
(i) 모델로 작업을 해결하는 어시스턴트 에이전트를 구현하거나 (ii) 코드를 실행하고 다른 에이전트에 의견을 제공할 수 있는 사용자 프록시 에이전트를 구현하거나 (iii) 모델 및 사고 트리 추론으로 작업을 해결하는 추론 에이전트를 구현하려는 경우 조정을 맞춤설정하는 것이 좋습니다.
이렇게 하려면 다음 서명의 Python 함수로 runnable_builder=
인수를 지정하여 AG2Agent
를 만들 때 기본 실행 파일을 재정의해야 합니다.
def runnable_builder(
**runnable_kwargs,
):
이를 통해 조정 로직을 맞춤설정할 수 있는 다양한 옵션이 제공됩니다.
어시스턴트 상담사
가장 간단한 경우 조정 없이 어시스턴트 에이전트를 만들려면 AG2Agent
의 runnable_builder
를 재정의하면 됩니다.
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.AssistantAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)
사용자 프록시 에이전트
가장 간단한 경우 조정 없이 어시스턴트 에이전트를 만들려면 AG2Agent
의 runnable_builder
를 재정의하면 됩니다.
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.UserProxyAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)
추론 에이전트
가장 간단한 경우 조정 없이 추론 에이전트를 만들려면 AG2Agent
의 runnable_builder
를 재정의하면 됩니다.
def runnable_builder(**kwargs):
from autogen import agentchat
return agentchat.ReasoningAgent(**kwargs)
agent = agent_engines.AG2Agent(
model=model,
runnable_name=runnable_name,
runnable_builder=runnable_builder,
)