컴포넌트 직렬화
컴포넌트 직렬화 (Serializing Components)
에이전트를 만들다 보면 "이 설정을 파일로 저장해서 나중에 다시 쓰거나, 팀원과 공유할 수 없을까?"라는 생각이 들 때가 있어요. AutoGen은 이 문제를 컴포넌트 직렬화로 해결해요. Component 설정 클래스가 컴포넌트를 **선언적 사양(declarative specification)**으로 직렬화/역직렬화하는 동작을 정의하거든요. .dump_component()과 .load_component()를 호출하는 것만으로요. 이 기능은 디버깅, 시각화, 그리고 작업을 다른 사람과 공유할 때 특히 유용해요.
경고: 컴포넌트를 신뢰할 수 있는 소스에서만 로드하세요.
직렬화된 컴포넌트는 각자 '어떻게 직렬화되고 역직렬화되는지'에 대한 로직을 구현하고 있어요. 즉 선언적 사양이 어떻게 생성되고, 어떻게 다시 객체로 변환되는지를 스스로 안다는 뜻이에요. 일부 경우 객체를 만드는 과정에서 코드 실행(예: 직렬화된 함수)이 포함될 수 있어요. 신뢰할 수 없는 컴포넌트를 로드하면 그 코드가 실행될 위험이 있으므로, 반드시 신뢰된 소스에서만 로드해야 해요.
참고:
selector_func는 직렬화할 수 없어서 직렬화/역직렬화 과정에서 무시돼요.
종료 조건 예제 (Termination Condition)
아래 예제는 종료 조건(에이전트 팀의 일부)을 Python으로 정의하고, 이를 딕셔너리/JSON으로 내보낸 뒤, 다시 그 객체로 로드하는 과정을 보여줘요.
from autogen_agentchat.conditions import MaxMessageTermination, StopMessageTermination
max_termination = MaxMessageTermination(5)
stop_termination = StopMessageTermination()
or_termination = max_termination | stop_termination
or_term_config = or_termination.dump_component()
print("Config:", or_term_config.model_dump_json())
new_or_termination = or_termination.load_component(or_term_config)
출력된 Config는 JSON으로, MaxMessageTermination(max_messages=5)와 StopMessageTermination을 OrTerminationCondition으로 묶은 구조예요. 이 JSON을 저장해 두었다가 어디서든 동일한 종료 조건을 다시 만들 수 있어요.
에이전트 예제
이번에는 에이전트를 만든 뒤 직렬화하는 예제예요.
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(model="gpt-4o")
agent = AssistantAgent(
name="assistant",
model_client=model_client,
handoffs=["flights_refunder", "user"],
system_message="Use tools to solve tasks.",
)
user_proxy = UserProxyAgent(name="user")
agent.dump_component().model_dump_json()을 호출하면 에이전트 설정이 JSON으로 출력돼요. 이 JSON에는 provider, component_type, version, 그리고 config가 들어 있어요. config 안에는 모델 클라이언트 설정, handoff 대상, 모델 컨텍스트, system_message 등이 중첩 구조로 표현돼요. agent.load_component(agent_config)로 다시 객체로 복원할 수 있죠. MultimodalWebSurfer 에이전트도 같은 방식으로 직렬화할 수 있어요.
팀 예제 (Team)
팀도 마찬가지예요. RoundRobinGroupChat 팀을 만들고 team.dump_component()으로 직렬화하면, 참여자(participants) 에이전트들과 종료 조건(termination_condition)이 전부 중첩된 JSON으로 나와요. 저장해 두었다가 team.load_component(team_config)로 재현할 수 있어요.
핵심 포인트는, 커스텀 빌딩 블록(에이전트·팀·종료조건)을 하나의 자기완결적 JSON 사양으로 표현할 수 있다는 거예요. 그래서 같은 앱을 다른 환경이나 다른 사람에게 그대로 옮겨 재현하는 일이 아주 쉬워져요.