본문 바로가기
  • 컴공생의 공부 일기
  • 공부보단 일기에 가까운 것 같은
  • 블로그
🤖 AI/AI

🎠 AutoGen 공식문서 following : intro, model, messages, agents, Teams

by 정람지 2025. 2. 10.
 

AutoGen — AutoGen

An event-driven programming framework for building scalable multi-agent AI systems. Example scenarios: Deterministic and dynamic agentic workflows for business processes. Research on multi-agent collaboration. Distributed agents for multi-language applicat

microsoft.github.io


🎠 install

 

Installation — AutoGen

Create and activate: python3 -m venv .venv source .venv/bin/activate To deactivate later, run: Install Conda if you have not already. Create and activate: conda create -n autogen python=3.12 conda activate autogen To deactivate later, run:

microsoft.github.io

Python 3.10.12 버전 사용 중

굿

가상환경 켜기

pip install -U "autogen-agentchat"
pip install "autogen-ext[openai]"

 

 

 pip show autogen-agentchat

Name: autogen-agentchat Version: 0.4.5

0.4.5 스테이블 버전 겟챠


🎠 Quickstart

 single tool-use agent 코드 만들어 보기

 

날씨를 알려주는 에이전트

- gpt-4o 모델 사용 AssistantAgent

- get_weather라는 함수를 도구(Tool) 로 등록 : 특정 기능(날씨 정보 제공)을 수행

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
import asyncio

# Define a tool
async def get_weather(city: str) -> str:
    return f"The weather in {city} is 73 degrees and Sunny."


async def main() -> None:
    # Define an agent
    weather_agent = AssistantAgent(
        name="weather_agent",
        model_client=OpenAIChatCompletionClient(
            model="gpt-4o-2024-08-06",
            # api_key="YOUR_API_KEY",
        ),
        tools=[get_weather],
    )

    # Define a team with a single agent and maximum auto-gen turns of 1.
    agent_team = RoundRobinGroupChat([weather_agent], max_turns=1)

    while True:
        # Get user input from the console.
        user_input = input("Enter a message (type 'exit' to leave): ")
        if user_input.strip().lower() == "exit":
            break
        # Run the team and stream messages to the console.
        stream = agent_team.run_stream(task=user_input)
        await Console(stream)


# NOTE: if running this inside a Python script you'll need to use asyncio.run(main()).
# Run the async function
if __name__ == "__main__":
    asyncio.run(main())

 RoundRobinGroupChat

 

autogen_agentchat.teams — AutoGen

autogen_agentchat.teams This module provides implementation of various pre-defined multi-agent teams. Each team inherits from the BaseGroupChat class. class BaseGroupChat(participants: List[ChatAgent], group_chat_manager_class: type[SequentialRoutedAgent],

microsoft.github.io

라운드 로빈~오랜만

 

 

결과

 

(venv)  ✘ viuron@viuron-70  ~/Documents/newscraper  ↱ main ±  python3 ai/agent_manager.py 

 


Enter a message (type 'exit' to leave): what is the weather of korea?
---------- user ----------
what is the weather of korea?
---------- weather_agent ----------
[FunctionCall(id='call_LGi4r4y8DJwHbB9pQ1sGxwsg', arguments='{"city":"Seoul"}', name='get_weather')]
---------- weather_agent ----------
[FunctionExecutionResult(content='The weather in Seoul is 73 degrees and Sunny.', call_id='call_LGi4r4y8DJwHbB9pQ1sGxwsg')]
---------- weather_agent ----------
The weather in Seoul is 73 degrees and Sunny.

 


Enter a message (type 'exit' to leave): what is the weather of USA?
---------- user ----------
what is the weather of USA?
---------- weather_agent ----------
The USA is a large country with diverse climates, so the weather can vary significantly depending on the specific location. Could you please specify a city or state in the USA for more accurate weather information?
Enter a message (type 'exit' to leave): new-york?       
---------- user ----------
new-york?
---------- weather_agent ----------
[FunctionCall(id='call_pN13fiP3BTX8UjONzlxhp8g4', arguments='{"city":"New York"}', name='get_weather')]
---------- weather_agent ----------
[FunctionExecutionResult(content='The weather in New York is 73 degrees and Sunny.', call_id='call_pN13fiP3BTX8UjONzlxhp8g4')]
---------- weather_agent ----------
The weather in New York is 73 degrees and Sunny.

 


Enter a message (type 'exit' to leave): why do you didn't ask about the Korea's city? there are other cities in Korea except Seoul. Do you have any reasons?
---------- user ----------
why didn't you ask about Korea's city? there are other cities in Korea except Seoul. Do you have any reasons?
---------- weather_agent ----------
I apologize for not specifying Seoul initially. When referring to the weather for "Korea," I chose Seoul because it's the capital and a major city. However, you are absolutely right that there are many other cities in Korea, and the weather can vary between them.
If there is a specific city in Korea you're interested in, feel free to let me know, and I can provide the weather information for that city.

 


Enter a message (type 'exit' to leave): exit

 

 

오 신기방기

알아서 tool 실행하고 - 펑션콜 기능 쓰는 듯

부족한 사항 있으면 재질문하고

머라고 하면 사과함

사실 우리나라가 작아서 날씨 하나 했고 미국은 너무 넓어서 그랬다~ 이럴 줄

 

api는 환경변수에 있던 거 알아서 잘 들어간 듯


🎠 Models

다양한 모델 api를 사용 가능한 모델 클라이언트

OpenAI / Azure OpenAI / Azure AI Foundry / Ollama / Gemini (experimental) / Semantic Kernel Adapter

 

OpenAI

모델 설정

from autogen_ext.models.openai import OpenAIChatCompletionClient

openai_model_client = OpenAIChatCompletionClient(
    model="gpt-4o-2024-08-06",
    # api_key="sk-...", # Optional if you have an OPENAI_API_KEY environment variable set.
)

 

모델 테스트

from autogen_core.models import UserMessage

result = await openai_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)

 

+

Azure OpenAI :  OpenAI API와 동일한 모델을 제공하지만, 기업 환경과 엔터프라이즈급 애플리케이션에서 더 유리한 기능을 제공

 

 

 

Models — AutoGen

Models In many cases, agents need access to LLM model services such as OpenAI, Azure OpenAI, or local models. Since there are many different providers with different APIs, autogen-core implements a protocol for model clients and autogen-ext implements a se

microsoft.github.io

나머지 모델도 모델 설정 + 모델 테스트 코드 확인 가능


🎠 Messages

facilitate communication and information exchange

with other agents, orchestrators, and applications

오 여러 에이전트, 오케스트레이터, 에플리케이션 사이의 소통 지원해주는 애

 

AgentChat supports various message types, each designed for specific purposes.

여러 메세지 타입 허용

 

Agent-Agent Messages

allows both text and multimodal communication and subsumes other message types

 

autogen_agentchat.messages — AutoGen

autogen_agentchat.messages This module defines various message types used for agent-to-agent communication. Each message type inherits either from the BaseChatMessage class or BaseAgentEvent class and includes specific fields relevant to the type of messag

microsoft.github.io

기본 chatagent

 

from io import BytesIO

import requests
from autogen_agentchat.messages import MultiModalMessage
from autogen_core import Image as AGImage
from PIL import Image

pil_image = Image.open(BytesIO(requests.get("https://picsum.photos/300/200").content))
img = AGImage(pil_image)
multi_modal_message = MultiModalMessage(content=["Can you describe the content of this image?", img], source="User")
img

멀티모달 메세지 사용 예시

 

 

Internal Events

communicate events and information on actions within the agent itself

상담원 내부의 메세지

ToolCallRequestEvent, which indicates that a request was made to call a tool,

ToolCallExecutionEvent, which contains the results of tool calls.


🎠 Agents

with variations in how an agent might respond to messages

 

attributes and methods

name : 상담원의 고유 이름
description : 상담원에 대한 설명
on_messages() : 상담원에게 ChatMessage 응답을 받는 시퀀스를 보냄

on_messages_stream() : on_messages()와 동일하지만 마지막 항목으로 응답이 뒤따르는 AgentEvent 또는 ChatMessage의 이터레이터를 반환
on_reset() : 에이전트를 초기 상태로 재설정
run() , run_stream() : 각각 on_messages() 및 on_messages_stream()을 호출

 

 

Assistant Agent

built-in agent that uses a language model and has the ability to use tools.

 

# Define a tool that searches the web for information.
async def web_search(query: str) -> str:
    """Find information on the web"""
    return "AutoGen is a programming framework for building multi-agent applications."


# Create an agent that uses the OpenAI GPT-4o model.
model_client = OpenAIChatCompletionClient(
    model="gpt-4o",
    # api_key="YOUR_API_KEY",
)
agent = AssistantAgent(
    name="assistant",
    model_client=model_client,
    tools=[web_search],
    system_message="Use tools to solve tasks.",
)

툴 설정모델 설정에이전트 설정 ( 툴, 모델 전달)

 

 

Getting Responses

on_messages() method to get the agent response to a given message.

async def assistant_run() -> None:
    response = await agent.on_messages(
        [TextMessage(content="Find information on AutoGen", source="user")],
        cancellation_token=CancellationToken(),
    )
    print(response.inner_messages)
    print(response.chat_message)


# Use asyncio.run(assistant_run()) when running in a script.
await assistant_run()

에이전트 - on_messages()로 실행하기

 

 

Streaming Messages

We can also stream each message as it is generated by the agent

by using the on_messages_stream() method

 

and use Console to print the messages as they appear to the console.

 

스트리밍. 에이전트한테 생성되는 메세지 가져오고 콘솔로 찍어볼 수 있다

async def assistant_run_stream() -> None:
    # Option 1: read each message from the stream (as shown in the previous example).
    # async for message in agent.on_messages_stream(
    #     [TextMessage(content="Find information on AutoGen", source="user")],
    #     cancellation_token=CancellationToken(),
    # ):
    #     print(message)

    # Option 2: use Console to print all messages as they appear.
    await Console(
        agent.on_messages_stream(
            [TextMessage(content="Find information on AutoGen", source="user")],
            cancellation_token=CancellationToken(),
        )
    )


# Use asyncio.run(assistant_run_stream()) when running in a script.
await assistant_run_stream()

함수 실행하는 거, 함수 결과값, 함수 결과값으로 만든 실제 응답, 다 스트리밍으로 볼 수 있음.

 

Using Tools

web_search tool

 

autogen_agentchat.agents — AutoGen

autogen_agentchat.agents This module initializes various pre-defined agents provided by the package. BaseChatAgent is the base class for all agents in AgentChat. class AssistantAgent(name: str, model_client: ChatCompletionClient, *, tools: List[BaseTool[An

microsoft.github.io

 ToolCallSummaryMessage

등 이용 가능

Langchain Tools

you can also use tools from the Langchain library by wrapping them in LangChainToolAdapter

저 메소드로 감싸서 랭체인도 쓸 수 있는 듯

 

Parallel Tool Calls

병렬 도구 호출 지원.

model_client_no_parallel_tool_call = OpenAIChatCompletionClient(
    model="gpt-4o",
    parallel_tool_calls=False,  # type: ignore
)
agent_no_parallel_tool_call = AssistantAgent(
    name="assistant",
    model_client=model_client_no_parallel_tool_call,
    tools=[web_search],
    system_message="Use tools to solve tasks.",
)

원하지 않는다면 False 설정 가능

 

Structured Output

return structured JSON text with pre-defined schema provided by the application

제이슨 말고 다른 건 안 됨?

 

Structured output is also useful for incorporating Chain-of-Thought reasoning

cot~

 

 

그냥 프롬프트에만 구조화된 출력을 해 달라고 말하기만 하면 되는 거..?

그럼 이렇게 굳이 섹션을 나눌 필요가 있었을까..

 

Streaming Tokens

openai의 스트리밍 같은 기능도 지원

토큰별로 쭉쭉 나오는 거

model_client_stream=True

 

Using Model Context

모델에 전송되는 컨텍스트를 제한하기 위해 BufferedChatCompletionContext와 같은 다른 모델 컨텍스트를 사용할 수 있음

from autogen_core.model_context import BufferedChatCompletionContext

# Create an agent that uses only the last 5 messages in the context to generate responses.
agent = AssistantAgent(
    name="assistant",
    model_client=model_client,
    tools=[web_search],
    system_message="Use tools to solve tasks.",
    model_context=BufferedChatCompletionContext(buffer_size=5),  # Only use the last 5 messages in the context.
)

최근 대화 5개 저장하여 맥락 유지

 

Other Preset Agents

  • UserProxyAgent: 사용자 입력을 받아 응답으로 반환하는 에이전트. 
  • CodeExecutorAgent:  코드를 실행할 수 있는 에이전트.
  • OpenAIAssistantAgent: 사용자 지정 도구를 사용할 수 있는 OpenAI 어시스턴트의 지원을 받는 에이전트
  • MultimodalWebSurfer: 웹을 검색하고 웹 페이지를 방문하여 정보를 찾을 수 있는 멀티모달 에이전트
  • FileSurfer: 로컬 파일을 검색하고 정보를 찾아볼 수 있는 에이전트
  • VideoSurfer: 동영상을 보고 정보를 얻을 수 있는 에이전트

 

 

AssistantAgent 보기!

 

autogen_agentchat.agents — AutoGen

autogen_agentchat.agents This module initializes various pre-defined agents provided by the package. BaseChatAgent is the base class for all agents in AgentChat. class AssistantAgent(name: str, model_client: ChatCompletionClient, *, tools: List[BaseTool[An

microsoft.github.io


🎠 Teams

create a multi-agent team

에이전트가 여러 개 있는 팀!

Teams are for complex tasks that require collaboration and diverse expertise

더 복잡한 작업과 콜라보레이션이 필요할 때 사용

 

create and run a team

observe the team’s behavior

operations to control the team’s behavior

 

Creating a Team

RoundRobinGroupChat

all agents share the same context and take turns responding in a round-robin fashion

 

 

Running a Team

all the run() method to start the team with a task.

런 메소드 이용

 

 

Observing a Team

on_messages_stream() method, you can stream the team’s messages while it is running by calling the run_stream() method

Resetting a Team

reset the team by calling the reset() method

clear the team’s state, including all agents.

 

Stopping a Team

Apart from automatic termination conditions such as TextMentionTermination that stops the team based on the internal state of the team, you can also stop the team from outside by using the ExternalTermination.

자동 종료 조건을 사용한 종료 말고도 외부 종료 가능

 

Calling set() on ExternalTermination will stop the team when the current agent’s turn is over. 

외부 종료에서 set()을 호출하면 현재 에이전트의 차례가 끝날 시 팀이 종료

Resuming a Team

팀은 상태 저장형이며 팀을 재설정하지 않는 한 각 실행 후 대화 기록과 컨텍스트를 유지

새 작업 없이 run() 또는 run_stream() 메서드를 다시 호출하여 팀을 재개하여 중단된 지점부터 계속할 수 있음

 

라운드 로빈 그룹 채팅은 라운드 로빈 순서에 따라 다음 에이전트부터 계속됨

Aborting a Team

중단

abort a call to run() or run_stream() during execution by setting a CancellationToken passed to the cancellation_token parameter

 

 

stopping이랑 달리 바로 중지