Autogen

목표

AIOS에서 제공하는 AI모델을 활용해 Autogen AI Agent 애플리케이션을 생성합니다.

참고
Autogen
Autogen은 LLM 기반 다중 에이전트 협업과 이벤트 기반 자동화 워크플로우를 손쉽게 구축, 관리할 수 있는 오픈소스 프레임워크입니다.

환경

이 튜토리얼을 진행하려면 아래와 같은 환경이 준비되어 있어야 합니다.

시스템 환경

  • Python 3.10 +
  • pip

설치 필요 패키지

배경색 변경
pip install autogen-agentchat==0.6.1 autogen-ext[openai,mcp]==0.6.1 mcp-server-time==0.6.2
pip install autogen-agentchat==0.6.1 autogen-ext[openai,mcp]==0.6.1 mcp-server-time==0.6.2
코드 블럭. autogen, mcp 서버 패키지 설치

시스템 아키텍처

다중 AI 에이전트 아키텍처 및 MCP를 활용한 에이전트 아키텍처의 전체 흐름을 보여줍니다.

Travel Planning Agent Flow

그림1

  1. 사용자가 3일간의 네팔 여행 계획을 세워달라고 요청
  2. Groupchat manger는 등록된 에이전트(여행 계획, 로컬 정보, 여행 회화, 종합 요약)의 실행 순서를 조정
  3. 각각의 에이전트는 각자의 역할에 맞게 주어진 작업을 협업하여 수행
  4. 최종적으로 여행 계획 결과물이 도출되면 사용자에게 전달

MCP Flow

그림2

참고

MCP
MCP(Model Context Protocol)는 모델과 외부 데이터나 도구와의 상호작용을 조율하는 개방형 표준 프로토콜입니다.

MCP 서버는 이를 구현한 서버로, 도구 메타데이터를 활용해 함수 호출을 중계, 실행합니다.

  1. 사용자가 한국의 현재 시각에 대해 질의
  2. mcp_server_time 서버를 통해 현재 시각을 가져올 수 있는 도구의 메타데이터를 포함하여 모델 요청
  3. get_current_time 함수를 호출하는 tool calls 메시지 생성
  4. MCP 서버를 통해 get_current_time 함수를 실행하여 결과물을 모델 요청으로 전달하면 최종 응답을 생성하여 사용자에게 전달

구현

Travel Planning Agent

참고
  • 코드 내 AIOS_BASE_URL인 AIOS_LLM_Private_Endpoint와 MODEL의 MODEL_IDLLM 이용 가이드를 참고해주세요.

autogen_travel_planning.py

배경색 변경
from urllib.parse import urljoin

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelFamily


# 모델 접근을 위한 API URL과 모델 이름을 설정합니다.
AIOS_BASE_URL = "AIOS_LLM_Private_Endpoint"
MODEL = "MODEL_ID"

# OpenAIChatCompletionClient를 사용하여 모델 클라이언트를 생성합니다.
model_client = OpenAIChatCompletionClient(
    model=MODEL,
    base_url=urljoin(AIOS_BASE_URL, "v1"),
    api_key="EMPTY_KEY",
    model_info={
        # 이미지를 지원하는 경우 True로 설정합니다.
        "vision": False,
        # 함수 호출을 지원하는 경우 True로 설정합니다.
        "function_calling": True,
        # JSON 출력을 지원하는 경우 True로 설정합니다.
        "json_output": True,
        # 사용하고자 하는 모델이 ModelFamily에서 제공하지 않는 경우 UNKNOWN을 사용합니다.
        # "family": ModelFamily.UNKNOWN,
        "family": ModelFamily.LLAMA_3_3_70B,
        # 구조화된 출력을 지원하는 경우 True로 설정합니다.
        "structured_output": True,
    },
)

# 여러 에이전트를 생성합니다.
# 각 에이전트는 여행 계획, 지역 활동 추천, 언어 팁 제공, 여행 계획 요약 등의 역할을 수행합니다.
planner_agent = AssistantAgent(
    "planner_agent",
    model_client=model_client,
    description="A helpful assistant that can plan trips.",
    system_message=("You are a helpful assistant that can suggest a travel plan "
                    "for a user based on their request."),
)

local_agent = AssistantAgent(
    "local_agent",
    model_client=model_client,
    description="A local assistant that can suggest local activities or places to visit.",
    system_message=("You are a helpful assistant that can suggest authentic and "
                    "interesting local activities or places to visit for a user "
                    "and can utilize any context information provided."),
)

language_agent = AssistantAgent(
    "language_agent",
    model_client=model_client,
    description="A helpful assistant that can provide language tips for a given destination.",
    system_message=("You are a helpful assistant that can review travel plans, "
                    "providing feedback on important/critical tips about how best to address "
                    "language or communication challenges for the given destination. "
                    "If the plan already includes language tips, "
                    "you can mention that the plan is satisfactory, with rationale."),
)

travel_summary_agent = AssistantAgent(
    "travel_summary_agent",
    model_client=model_client,
    description="A helpful assistant that can summarize the travel plan.",
    system_message=("You are a helpful assistant that can take in all of the suggestions "
                    "and advice from the other agents and provide a detailed final travel plan. "
                    "You must ensure that the final plan is integrated and complete. "
                    "YOUR FINAL RESPONSE MUST BE THE COMPLETE PLAN. "
                    "When the plan is complete and all perspectives are integrated, "
                    "you can respond with TERMINATE."),
)

# 에이전트들을 그룹으로 묶어 RoundRobinGroupChat을 생성합니다.
# RoundRobinGroupChat은 에이전트들이 등록된 순서대로 돌아가면서 작업을 수행하도록 조정합니다.
# 이 그룹은 에이전트들이 상호작용하며 여행 계획을 세울 수 있도록 합니다.
# 종료 조건은 TextMentionTermination을 사용하여 "TERMINATE"라는 텍스트가 언급될 때 그룹 채팅을 종료합니다.
termination = TextMentionTermination("TERMINATE")
group_chat = RoundRobinGroupChat(
    [planner_agent, local_agent, language_agent, travel_summary_agent],
    termination_condition=termination,
)

async def main():
    """메인 함수로, 그룹 채팅을 실행하고 여행 계획을 세웁니다."""
    # 그룹 채팅을 실행하여 여행 계획을 세웁니다.
    # 사용자가 "Plan a 3 day trip to Nepal."라는 작업을 요청합니다.
    # Console을 사용하여 결과를 출력합니다.
    await Console(group_chat.run_stream(task="Plan a 3 day trip to Nepal."))
    await model_client.close()


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())
from urllib.parse import urljoin

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelFamily


# 모델 접근을 위한 API URL과 모델 이름을 설정합니다.
AIOS_BASE_URL = "AIOS_LLM_Private_Endpoint"
MODEL = "MODEL_ID"

# OpenAIChatCompletionClient를 사용하여 모델 클라이언트를 생성합니다.
model_client = OpenAIChatCompletionClient(
    model=MODEL,
    base_url=urljoin(AIOS_BASE_URL, "v1"),
    api_key="EMPTY_KEY",
    model_info={
        # 이미지를 지원하는 경우 True로 설정합니다.
        "vision": False,
        # 함수 호출을 지원하는 경우 True로 설정합니다.
        "function_calling": True,
        # JSON 출력을 지원하는 경우 True로 설정합니다.
        "json_output": True,
        # 사용하고자 하는 모델이 ModelFamily에서 제공하지 않는 경우 UNKNOWN을 사용합니다.
        # "family": ModelFamily.UNKNOWN,
        "family": ModelFamily.LLAMA_3_3_70B,
        # 구조화된 출력을 지원하는 경우 True로 설정합니다.
        "structured_output": True,
    },
)

# 여러 에이전트를 생성합니다.
# 각 에이전트는 여행 계획, 지역 활동 추천, 언어 팁 제공, 여행 계획 요약 등의 역할을 수행합니다.
planner_agent = AssistantAgent(
    "planner_agent",
    model_client=model_client,
    description="A helpful assistant that can plan trips.",
    system_message=("You are a helpful assistant that can suggest a travel plan "
                    "for a user based on their request."),
)

local_agent = AssistantAgent(
    "local_agent",
    model_client=model_client,
    description="A local assistant that can suggest local activities or places to visit.",
    system_message=("You are a helpful assistant that can suggest authentic and "
                    "interesting local activities or places to visit for a user "
                    "and can utilize any context information provided."),
)

language_agent = AssistantAgent(
    "language_agent",
    model_client=model_client,
    description="A helpful assistant that can provide language tips for a given destination.",
    system_message=("You are a helpful assistant that can review travel plans, "
                    "providing feedback on important/critical tips about how best to address "
                    "language or communication challenges for the given destination. "
                    "If the plan already includes language tips, "
                    "you can mention that the plan is satisfactory, with rationale."),
)

travel_summary_agent = AssistantAgent(
    "travel_summary_agent",
    model_client=model_client,
    description="A helpful assistant that can summarize the travel plan.",
    system_message=("You are a helpful assistant that can take in all of the suggestions "
                    "and advice from the other agents and provide a detailed final travel plan. "
                    "You must ensure that the final plan is integrated and complete. "
                    "YOUR FINAL RESPONSE MUST BE THE COMPLETE PLAN. "
                    "When the plan is complete and all perspectives are integrated, "
                    "you can respond with TERMINATE."),
)

# 에이전트들을 그룹으로 묶어 RoundRobinGroupChat을 생성합니다.
# RoundRobinGroupChat은 에이전트들이 등록된 순서대로 돌아가면서 작업을 수행하도록 조정합니다.
# 이 그룹은 에이전트들이 상호작용하며 여행 계획을 세울 수 있도록 합니다.
# 종료 조건은 TextMentionTermination을 사용하여 "TERMINATE"라는 텍스트가 언급될 때 그룹 채팅을 종료합니다.
termination = TextMentionTermination("TERMINATE")
group_chat = RoundRobinGroupChat(
    [planner_agent, local_agent, language_agent, travel_summary_agent],
    termination_condition=termination,
)

async def main():
    """메인 함수로, 그룹 채팅을 실행하고 여행 계획을 세웁니다."""
    # 그룹 채팅을 실행하여 여행 계획을 세웁니다.
    # 사용자가 "Plan a 3 day trip to Nepal."라는 작업을 요청합니다.
    # Console을 사용하여 결과를 출력합니다.
    await Console(group_chat.run_stream(task="Plan a 3 day trip to Nepal."))
    await model_client.close()


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())
코드 블럭. autogen_travel_planning.py

python을 이용하여 파일을 실행하면 하나의 태스크를 위해 여러 개의 에이전트가 함께 각각의 역할을 수행하는 모습을 확인할 수 있습니다.

배경색 변경
python autogen_travel_planning.py
python autogen_travel_planning.py
코드 블럭. autogen 여행 계획 에이전트 실행

실행결과

---------- TextMessage (user) ----------
Plan a 3 day trip to Nepal.
---------- TextMessage (planner_agent) ----------
Nepal! A country with a rich cultural heritage, breathtaking natural beauty, and warm hospitality. Here's a suggested 3-day itinerary for your trip to Nepal:

**Day 1: Arrival in Kathmandu and Exploration of the City**

* Arrive at Tribhuvan International Airport in Kathmandu, the capital city of Nepal.
* Check-in to your hotel and freshen up.
* Visit the famous **Boudhanath Stupa**, one of the largest Buddhist stupas in the world.
* Explore the **Thamel** area, a popular tourist hub known for its narrow streets, shops, and restaurants.
* In the evening, enjoy a traditional Nepali dinner and watch a cultural performance at a local restaurant.

**Day 2: Kathmandu Valley Tour**

* Start the day with a visit to the **Pashupatinath Temple**, a sacred Hindu temple dedicated to Lord Shiva.
* Next, head to the **Kathmandu Durbar Square**, a UNESCO World Heritage Site and the former royal palace of the Malla kings.
* Visit the **Swayambhunath Stupa**, also known as the Monkey Temple, which offers stunning views of the city.
* In the afternoon, take a short drive to the **Patan City**, known for its rich cultural heritage and traditional crafts.
* Explore the **Patan Durbar Square** and visit the **Krishna Temple**, a beautiful example of Nepali architecture.

**Day 3: Bhaktapur and Nagarkot**

* Drive to **Bhaktapur**, a medieval town and a UNESCO World Heritage Site (approximately 1 hour).
* Explore the **Bhaktapur Durbar Square**, which features stunning architecture, temples, and palaces.
* Visit the **Pottery Square**, where you can see traditional pottery-making techniques.
* In the afternoon, drive to **Nagarkot**, a scenic hill station with breathtaking views of the Himalayas (approximately 1.5 hours).
* Watch the sunset over the Himalayas and enjoy the peaceful atmosphere.

**Additional Tips:**

* Make sure to try some local Nepali cuisine, such as momos, dal bhat, and gorkhali lamb.
* Bargain while shopping in the markets, as it's a common practice in Nepal.
* Respect local customs and traditions, especially when visiting temples and cultural sites.
* Stay hydrated and bring sunscreen, as the sun can be strong in Nepal.

**Accommodation:**

Kathmandu has a wide range of accommodation options, from budget-friendly guesthouses to luxury hotels. Some popular areas to stay include Thamel, Lazimpat, and Boudha.

**Transportation:**

You can hire a taxi or a private vehicle for the day to travel between destinations. Alternatively, you can use public transportation, such as buses or microbuses, which are affordable and convenient.

**Budget:**

The budget for a 3-day trip to Nepal can vary depending on your accommodation choices, transportation, and activities. However, here's a rough estimate:

* Accommodation: $20-50 per night
* Transportation: $10-20 per day
* Food: $10-20 per meal
* Activities: $10-20 per person

Total estimated budget for 3 days: $200-500 per person

I hope this helps, and you have a wonderful trip to Nepal!
---------- TextMessage (local_agent) ----------
Your 3-day itinerary for Nepal is well-planned and covers many of the country's cultural and natural highlights. Here are a few additional suggestions and tips to enhance your trip:

**Day 1:**

* After visiting the Boudhanath Stupa, consider exploring the surrounding streets, which are filled with Tibetan shops, restaurants, and monasteries.
* In the Thamel area, be sure to try some of the local street food, such as momos or sel roti.
* For dinner, consider trying a traditional Nepali restaurant, such as the Kathmandu Guest House or the Northfield Cafe.

**Day 2:**

* At the Pashupatinath Temple, be respectful of the Hindu rituals and customs. You can also take a stroll along the Bagmati River, which runs through the temple complex.
* At the Kathmandu Durbar Square, consider hiring a guide to provide more insight into the history and significance of the temples and palaces.
* In the afternoon, visit the Patan Museum, which showcases the art and culture of the Kathmandu Valley.

**Day 3:**

* In Bhaktapur, be sure to try some of the local pottery and handicrafts. You can also visit the Bhaktapur National Art Gallery, which features traditional Nepali art.
* At Nagarkot, consider taking a short hike to the nearby villages, which offer stunning views of the Himalayas.
* For sunset, find a spot with a clear view of the mountains, and enjoy the peaceful atmosphere.

**Additional Tips:**

* Nepal is a relatively conservative country, so dress modestly and respect local customs.
* Try to learn some basic Nepali phrases, such as "namaste" (hello) and "dhanyabaad" (thank you).
* Be prepared for crowds and chaos in the cities, especially in Thamel and Kathmandu Durbar Square.
* Consider purchasing a local SIM card or portable Wi-Fi hotspot to stay connected during your trip.

**Accommodation:**

* Consider staying in a hotel or guesthouse that is centrally located and has good reviews.
* Look for accommodations that offer amenities such as free Wi-Fi, hot water, and a restaurant or cafe.

**Transportation:**

* Consider hiring a private vehicle or taxi for the day, as this will give you more flexibility and convenience.
* Be sure to negotiate the price and agree on the itinerary before setting off.

**Budget:**

* Be prepared for variable prices and exchange rates, and have some local currency (Nepali rupees) on hand.
* Consider budgeting extra for unexpected expenses, such as transportation or food.

Overall, your itinerary provides a good balance of culture, history, and natural beauty, and with these additional tips and suggestions, you'll be well-prepared for an unforgettable trip to Nepal!
---------- TextMessage (language_agent) ----------
Your 3-day itinerary for Nepal is well-planned and covers many of the country's cultural and natural highlights. The additional suggestions and tips you provided are excellent and will help enhance the trip experience.

One aspect that is well-covered in your plan is the cultural and historical significance of the destinations. You have included a mix of temples, stupas, and cultural sites, which will give visitors a good understanding of Nepal's rich heritage.

Regarding language and communication challenges, your tip to "try to learn some basic Nepali phrases, such as 'namaste' (hello) and 'dhanyabaad' (thank you)" is excellent. This will help visitors show respect for the local culture and people, and can also facilitate interactions with locals.

Additionally, your suggestion to "consider purchasing a local SIM card or portable Wi-Fi hotspot to stay connected during your trip" is practical and will help visitors stay in touch with family and friends back home, as well as navigate the local area.

Your plan is satisfactory, and with the additional tips and suggestions, visitors will be well-prepared for an unforgettable trip to Nepal. The itinerary provides a good balance of culture, history, and natural beauty, and the tips on language, communication, and logistics will help ensure a smooth and enjoyable journey.

Overall, your plan is well-thought-out, and the additional suggestions and tips will help visitors make the most of their trip to Nepal. Well done!

However, one minor suggestion I might make is to consider including a few phrases in the local language for emergency situations, such as "where is the hospital?" or "how do I get to the airport?" This can help visitors in case of an unexpected situation, and can also give them more confidence when navigating unfamiliar areas.

But overall, your plan is excellent, and with these minor suggestions, it can be even more comprehensive and helpful for visitors to Nepal.
---------- TextMessage (travel_summary_agent) ----------
TERMINATE

Here is the complete and integrated 3-day travel plan to Nepal:

**Day 1: Arrival in Kathmandu and Exploration of the City**

* Arrive at Tribhuvan International Airport in Kathmandu, the capital city of Nepal.
* Check-in to your hotel and freshen up.
* Visit the famous **Boudhanath Stupa**, one of the largest Buddhist stupas in the world.
* Explore the surrounding streets, which are filled with Tibetan shops, restaurants, and monasteries.
* Explore the **Thamel** area, a popular tourist hub known for its narrow streets, shops, and restaurants. Be sure to try some of the local street food, such as momos or sel roti.
* In the evening, enjoy a traditional Nepali dinner and watch a cultural performance at a local restaurant, such as the Kathmandu Guest House or the Northfield Cafe.

**Day 2: Kathmandu Valley Tour**

* Start the day with a visit to the **Pashupatinath Temple**, a sacred Hindu temple dedicated to Lord Shiva. Be respectful of the Hindu rituals and customs, and take a stroll along the Bagmati River, which runs through the temple complex.
* Next, head to the **Kathmandu Durbar Square**, a UNESCO World Heritage Site and the former royal palace of the Malla kings. Consider hiring a guide to provide more insight into the history and significance of the temples and palaces.
* Visit the **Swayambhunath Stupa**, also known as the Monkey Temple, which offers stunning views of the city.
* In the afternoon, visit the **Patan City**, known for its rich cultural heritage and traditional crafts. Explore the **Patan Durbar Square** and visit the **Krishna Temple**, a beautiful example of Nepali architecture. Also, visit the Patan Museum, which showcases the art and culture of the Kathmandu Valley.

**Day 3: Bhaktapur and Nagarkot**

* Drive to **Bhaktapur**, a medieval town and a UNESCO World Heritage Site (approximately 1 hour). Explore the **Bhaktapur Durbar Square**, which features stunning architecture, temples, and palaces. Be sure to try some of the local pottery and handicrafts, and visit the Bhaktapur National Art Gallery, which features traditional Nepali art.
* In the afternoon, drive to **Nagarkot**, a scenic hill station with breathtaking views of the Himalayas (approximately 1.5 hours). Consider taking a short hike to the nearby villages, which offer stunning views of the Himalayas. Find a spot with a clear view of the mountains, and enjoy the peaceful atmosphere during sunset.

**Additional Tips:**

* Make sure to try some local Nepali cuisine, such as momos, dal bhat, and gorkhali lamb.
* Bargain while shopping in the markets, as it's a common practice in Nepal.
* Respect local customs and traditions, especially when visiting temples and cultural sites.
* Stay hydrated and bring sunscreen, as the sun can be strong in Nepal.
* Dress modestly and respect local customs, as Nepal is a relatively conservative country.
* Try to learn some basic Nepali phrases, such as "namaste" (hello), "dhanyabaad" (thank you), "where is the hospital?" and "how do I get to the airport?".
* Consider purchasing a local SIM card or portable Wi-Fi hotspot to stay connected during your trip.
* Be prepared for crowds and chaos in the cities, especially in Thamel and Kathmandu Durbar Square.

**Accommodation:**

* Consider staying in a hotel or guesthouse that is centrally located and has good reviews.
* Look for accommodations that offer amenities such as free Wi-Fi, hot water, and a restaurant or cafe.

**Transportation:**

* Consider hiring a private vehicle or taxi for the day, as this will give you more flexibility and convenience.
* Be sure to negotiate the price and agree on the itinerary before setting off.

**Budget:**

* The budget for a 3-day trip to Nepal can vary depending on your accommodation choices, transportation, and activities. However, here's a rough estimate:
        + Accommodation: $20-50 per night
        + Transportation: $10-20 per day
        + Food: $10-20 per meal
        + Activities: $10-20 per person
* Total estimated budget for 3 days: $200-500 per person
* Be prepared for variable prices and exchange rates, and have some local currency (Nepali rupees) on hand.
* Consider budgeting extra for unexpected expenses, such as transportation or food.

에이전트별 대화내용 요약

에이전트대화 내용 요약
planner_agent네팔 3일 여행 일정을 제안합니다.
  • 1일차: 카트만두 도착 및 도시 탐험

  • 2일차: 카트만두 계곡 투어

  • 3일차: 박타푸르와 나가르코트 방문

  • 추가 팁: 현지 풍습 존중, 현지 음식 시도, 교통 수단 선택 등
    local_agentplanner_agent의 3일 여행 일정을 기반으로 추가적인 제안과 팁을 제공합니다.
  • 1일차: 부다나트 스투파 주변 탐험,

  • 2일차: 파슈파티나트 사원에서 힌두 의식 존중

  • 3일차: 박타푸르의 도자기와 수공예품 시도

  • 추가 팁: 현지 풍습 존중, 기본 네팔어 학습, 현지 시설 이용 등
    language_agent여행 일정을 평가하고, 추가적인 제안을 제공합니다.
    기본 네팔어 학습, 현지 시설 이용, 비상 상황에 대비한 언어 준비 등
    travel_summary_agent전체적인 3일 여행 계획을 요약합니다.
  • 1일차: 카트만두 도착 및 도시 탐험

  • 2일차: 카트만두 계곡 투어

  • 3일차: 박타푸르와 나가르코트 방문

  • 추가 팁: 현지 풍습 존중, 현지 음식 시도, 교통 수단 선택 등

    MCP 활용 Agent

    참고
    • 코드 내 AIOS_BASE_URL인 AIOS_LLM_Private_Endpoint와 MODEL의 MODEL_IDLLM 이용 가이드를 참고해주세요.

    autogen_mcp.py

    배경색 변경
    from urllib.parse import urljoin
    
    from autogen_core.models import ModelFamily
    from autogen_ext.models.openai import OpenAIChatCompletionClient
    from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams
    from autogen_agentchat.agents import AssistantAgent
    from autogen_agentchat.ui import Console
    
    # 모델 접근을 위한 API URL과 모델 이름을 설정합니다.
    AIOS_BASE_URL = "AIOS_LLM_Private_Endpoint"
    MODEL = "MODEL_ID"
    
    # OpenAIChatCompletionClient를 사용하여 모델 클라이언트를 생성합니다.
    model_client = OpenAIChatCompletionClient(
        model=MODEL,
        base_url=urljoin(AIOS_BASE_URL, "v1"),
        api_key="EMPTY_KEY",
        model_info={
            # 이미지를 지원하는 경우 True로 설정합니다.
            "vision": False,
            # 함수 호출을 지원하는 경우 True로 설정합니다.
            "function_calling": True,
            # JSON 출력을 지원하는 경우 True로 설정합니다.
            "json_output": True,
            # 사용하고자 하는 모델이 ModelFamily에서 제공하지 않는 경우 UNKNOWN을 사용합니다.
            # "family": ModelFamily.UNKNOWN,
            "family": ModelFamily.LLAMA_3_3_70B,
            # 구조화된 출력을 지원하는 경우 True로 설정합니다.
            "structured_output": True,
        }
    )
    
    # MCP 서버 파라미터를 설정합니다.
    # mcp_server_time은 python으로 구현된 MCP 서버로, 
    # 내부에 현재 시각을 알려주는 get_current_time, 시간대를 변환해 주는 convert_time 함수가 포함됩니다.
    # 이 파라미터는 MCP 서버를 로컬 타임존으로 설정하여 시간을 확인할 수 있도록 합니다.
    # 예를 들어, "Asia/Seoul"로 설정하면 한국 시간대에 맞춰 시간을 확인할 수 있습니다.
    mcp_server_params = StdioServerParams(
        command="python",
        args=["-m", "mcp_server_time", "--local-timezone", "Asia/Seoul"],
    )
    
    async def main():
        """메인 함수로, MCP 워크벤치를 사용하여 시간을 확인하는 에이전트를 실행합니다."""
        # MCP 워크벤치를 사용하여 시간을 확인하는 에이전트를 생성하고 실행합니다.
        # 에이전트는 "What time is it now in South Korea?"라는 작업을 수행합니다.
        # Console을 사용하여 결과를 출력합니다.
        # MCP 워크벤치가 실행되는 동안 에이전트는 시간을 확인하고
        # 결과를 스트리밍 방식으로 출력합니다.
        # MCP 워크벤치가 종료되면 에이전트도 종료됩니다.
        async with McpWorkbench(mcp_server_params) as workbench:
            time_agent = AssistantAgent(
                "time_assistant",
                model_client=model_client,
                workbench=workbench,
                reflect_on_tool_use=True,
            )
            await Console(time_agent.run_stream(task="What time is it now in South Korea?"))
        await model_client.close()
    
    if __name__ == "__main__":
        import asyncio
        asyncio.run(main())
    from urllib.parse import urljoin
    
    from autogen_core.models import ModelFamily
    from autogen_ext.models.openai import OpenAIChatCompletionClient
    from autogen_ext.tools.mcp import McpWorkbench, StdioServerParams
    from autogen_agentchat.agents import AssistantAgent
    from autogen_agentchat.ui import Console
    
    # 모델 접근을 위한 API URL과 모델 이름을 설정합니다.
    AIOS_BASE_URL = "AIOS_LLM_Private_Endpoint"
    MODEL = "MODEL_ID"
    
    # OpenAIChatCompletionClient를 사용하여 모델 클라이언트를 생성합니다.
    model_client = OpenAIChatCompletionClient(
        model=MODEL,
        base_url=urljoin(AIOS_BASE_URL, "v1"),
        api_key="EMPTY_KEY",
        model_info={
            # 이미지를 지원하는 경우 True로 설정합니다.
            "vision": False,
            # 함수 호출을 지원하는 경우 True로 설정합니다.
            "function_calling": True,
            # JSON 출력을 지원하는 경우 True로 설정합니다.
            "json_output": True,
            # 사용하고자 하는 모델이 ModelFamily에서 제공하지 않는 경우 UNKNOWN을 사용합니다.
            # "family": ModelFamily.UNKNOWN,
            "family": ModelFamily.LLAMA_3_3_70B,
            # 구조화된 출력을 지원하는 경우 True로 설정합니다.
            "structured_output": True,
        }
    )
    
    # MCP 서버 파라미터를 설정합니다.
    # mcp_server_time은 python으로 구현된 MCP 서버로, 
    # 내부에 현재 시각을 알려주는 get_current_time, 시간대를 변환해 주는 convert_time 함수가 포함됩니다.
    # 이 파라미터는 MCP 서버를 로컬 타임존으로 설정하여 시간을 확인할 수 있도록 합니다.
    # 예를 들어, "Asia/Seoul"로 설정하면 한국 시간대에 맞춰 시간을 확인할 수 있습니다.
    mcp_server_params = StdioServerParams(
        command="python",
        args=["-m", "mcp_server_time", "--local-timezone", "Asia/Seoul"],
    )
    
    async def main():
        """메인 함수로, MCP 워크벤치를 사용하여 시간을 확인하는 에이전트를 실행합니다."""
        # MCP 워크벤치를 사용하여 시간을 확인하는 에이전트를 생성하고 실행합니다.
        # 에이전트는 "What time is it now in South Korea?"라는 작업을 수행합니다.
        # Console을 사용하여 결과를 출력합니다.
        # MCP 워크벤치가 실행되는 동안 에이전트는 시간을 확인하고
        # 결과를 스트리밍 방식으로 출력합니다.
        # MCP 워크벤치가 종료되면 에이전트도 종료됩니다.
        async with McpWorkbench(mcp_server_params) as workbench:
            time_agent = AssistantAgent(
                "time_assistant",
                model_client=model_client,
                workbench=workbench,
                reflect_on_tool_use=True,
            )
            await Console(time_agent.run_stream(task="What time is it now in South Korea?"))
        await model_client.close()
    
    if __name__ == "__main__":
        import asyncio
        asyncio.run(main())
    코드 블럭. autogen_mcp.py

    python을 이용하여 파일을 실행하면 MCP 서버로부터 도구의 메타데이터를 가져와서 모델을 호출하고, 모델이 tool calls 메시지를 생성하면 현재 시각을 조회하기 위해 get_current_time 함수를 실행하는 것을 확인할 수 있습니다.

    배경색 변경
    python autogen_mcp.py
    python autogen_mcp.py
    코드 블럭. autogen MCP 활용 에이전트 실행

    실행결과

    # TextMessage (user): 사용자가 준 입력 메시지 
    ---------- TextMessage (user) ----------
    What time is it now in South Korea?
    # MCP 서버에서 사용할 수 있는 도구들의 메타데이터 조회 
    INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
    ...생략...
    INFO:autogen_core.events:{
      # MCP 서버에서 사용 가능한 도구들의 메타데이터
      "tools": [
        {
          "type": "function",
          "function": {
            "name": "get_current_time",
            "description": "Get current time in a specific timezones",
            "parameters": {
              "type": "object",
              "properties": {
                "timezone": {
                  "type": "string",
                  "description": "IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use 'Asia/Seoul' as local timezone if no timezone provided by the user."
                }
              },
              "required": [
                "timezone"
              ],
              "additionalProperties": false
            },
            "strict": false
          }
        },
        {
          "type": "function",
          "function": {
            "name": "convert_time",
            "description": "Convert time between timezones",
            "parameters": {
              "type": "object",
              "properties": {
                "source_timezone": {
                  "type": "string",
                  "description": "Source IANA timezone name (e.g., 'America/New_York', 'Europe/London'). Use 'Asia/Seoul' as local timezone if no source timezone provided by the user."
                },
                "time": {
                  "type": "string",
                  "description": "Time to convert in 24-hour format (HH:MM)"
                },
                "target_timezone": {
                  "type": "string",
                  "description": "Target IANA timezone name (e.g., 'Asia/Tokyo', 'America/San_Francisco'). Use 'Asia/Seoul' as local timezone if no target timezone provided by the user."
                }
              },
              "required": [
                "source_timezone",
                "time",
                "target_timezone"
              ],
              "additionalProperties": false
            },
            "strict": false
          }
        }
      ],
      "type": "LLMCall",
      # 입력 메시지 
      "messages": [
        {
          "content": "You are a helpful AI assistant. Solve tasks using your tools. Reply with TERMINATE when the task has been completed.",
          "role": "system"
        },
        {
          "role": "user",
          "name": "user",
          "content": "What time is it now in South Korea?"
        }
      ],
      # 모델 응답 
      "response": {
        "id": "chatcmpl-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "choices": [
          {
            "finish_reason": "tool_calls",
            "index": 0,
            "logprobs": null,
            "message": {
              "content": null,
              "refusal": null,
              "role": "assistant",
              "annotations": null,
              "audio": null,
              "function_call": null,
              "tool_calls": [
                {
                  "id": "chatcmpl-tool-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                  "function": {
                    "arguments": "{\"timezone\": \"Asia/Seoul\"}",
                    "name": "get_current_time"
                  },
                  "type": "function"
                }
              ],
              "reasoning_content": null
            },
            "stop_reason": 128008
          }
        ],
        "created": 1751278737,
        "model": "MODEL_ID",
        "object": "chat.completion",
        "service_tier": null,
        "system_fingerprint": null,
        "usage": {
          "completion_tokens": 21,
          "prompt_tokens": 508,
          "total_tokens": 529,
          "completion_tokens_details": null,
          "prompt_tokens_details": null
        },
        "prompt_logprobs": null
      },
      "prompt_tokens": 508,
      "completion_tokens": 21,
      "agent_id": null
    }
    # ToolCallRequestEvent: 모델로부터 tool call 메시지를 받음
    ---------- ToolCallRequestEvent (time_assistant) ----------
    [FunctionCall(id='chatcmpl-tool-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', arguments='{"timezone": "Asia/Seoul"}', name='get_current_time')]
    INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
    # MCP 서버를 통해 tool call 메시지의 함수 실행 
    INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
    # ToolCallExecutionEvent: 함수의 실행 결과를 모델에게 전달 
    ---------- ToolCallExecutionEvent (time_assistant) ----------
    [FunctionExecutionResult(content='{\n  "timezone": "Asia/Seoul",\n  "datetime": "2025-06-30T19:18:58+09:00",\n  "is_dst": false\n}', name='get_current_time', call_id='chatcmpl-tool-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', is_error=False)]
    ...생략...
    # TextMessage (time_assistant): 모델이 생성한 최종 답변 
    ---------- TextMessage (time_assistant) ----------
    The current time in South Korea is 19:18:58 KST.
    TERMINATE
    

    MCP 서버 시간 조회 시스템 로그 분석 결과

    MCP(Model Control Protocol) 서버를 통한 시간 조회 시스템의 실행 과정을 보여주는 로그 분석 결과입니다.

    요청 정보

    항목내용
    사용자 요청What time is it now in South Korea?
    요청 시간2025-06-30 19:18:58 KST
    처리 방식MCP 서버 도구 호출



    사용 가능한 도구

    도구명설명매개변수기본값
    get_current_time특정 시간대의 현재 시간 조회timezone (IANA 시간대 이름)Asia/Seoul
    convert_time시간대 간 시간 변환source_timezone, time, target_timezoneAsia/Seoul



    처리 과정

    단계액션상세 내용
    1도구 메타데이터 조회MCP 서버에서 사용 가능한 도구 목록 확인
    2AI 모델 응답get_current_time 함수를 Asia/Seoul 시간대로 호출
    3함수 실행MCP 서버가 시간 조회 도구 실행
    4결과 반환구조화된 JSON 형식으로 시간 정보 제공
    5최종 답변사용자에게 읽기 쉬운 형태로 시간 전달



    함수 호출 상세

    항목
    함수명get_current_time
    매개변수{"timezone": "Asia/Seoul"}
    호출 IDchatcmpl-tool-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    타입function



    실행 결과

    필드설명
    timezoneAsia/Seoul시간대
    datetime2025-06-30T19:18:58+09:00ISO 8601 형식 시간
    is_dstfalse서머타임 적용 여부



    최종 응답

    항목내용
    응답 메시지The current time in South Korea is 19:18:58 KST.
    완료 표시TERMINATE
    응답 시간19:18:58 KST



    사용량 지표표

    지표
    프롬프트 토큰508
    완료 토큰21
    총 토큰 사용량529
    처리 시간즉시 (실시간)



    주요 특징

    특징설명
    MCP 프로토콜 활용외부 도구와의 원활한 연동
    한국 시간대 기본 설정Asia/Seoul을 기본값으로 사용
    구조화된 응답JSON 형식의 명확한 데이터 반환
    자동 완료 표시TERMINATE로 작업 완료 알림
    실시간 정보 제공정확한 현재 시간 조회



    기술적 의의

    이는 AI 어시스턴트가 외부 시스템과 연동하여 실시간 정보를 제공하는 현대적인 아키텍처의 예시입니다. MCP를 통해 AI 모델이 다양한 외부 도구와 서비스에 접근할 수 있어, 더욱 실용적이고 동적인 응답이 가능합니다.

    마무리

    이번 튜토리얼에서는 AIOS에서 제공하는 AI 모델과 autogen을 활용하여 다중 에이전트를 이용하여 여행 일정을 세워 주는 애플리케이션, MCP 서버를 활용하여 외부 도구를 활용할 수 있는 에이전트 애플리케이션을 구현하였습니다. 이를 통해 각각의 관점을 가진 여러 에이전트를 통해 다각도로 문제를 해결하고 외부 도구를 활용할 수 있다는 것을 알게 되었습니다. 본 시스템은 다음과 같은 방식으로 사용자 환경에 맞게 확장 및 커스터마이징할 수 있습니다.

    • 에이전트 흐름 조절 : 작업을 진행할 에이전트를 선택할 때 다양한 기법을 활용할 수 있습니다. 신뢰성있는 결과를 위해 에이전트의 순서를 고정하여 구현할 수도 있고, 유연한 처리를 위해 AI 모델이 에이전트를 선택하게 할 수 있습니다. 또한 이벤트 기법을 이용하여 병렬적으로 복수의 에이전트가 작업을 처리하도록 구현할 수도 있습니다.
    • 다양한 MCP 서버 도입 : mcp_server_time 외에 이미 구현된 다양한 MCP 서버들이 존재합니다. 이를 활용하여 AI 모델이 유연하게 다양한 외부 도구를 활용하게 하여 유용한 애플리케이션을 구현할 수 있습니다.

    이번 튜토리얼을 기반으로 실제 서비스 목적에 따라 적합한 AIOS 기반 협업 도우미를 직접 구축해 보시길 바랍니다.

    참고 링크

    https://microsoft.github.io/autogen
    https://modelcontextprotocol.io/
    https://github.com/modelcontextprotocol/servers

    RAG
    Request Examples