AutoGen > Old Blog (Archived) > StateFlow
https://microsoft.github.io/autogen/0.2/blog/2024/02/29/StateFlow/
복잡한 작업을 해결하기 위해 대규모 언어 모델(LLM)을 사용하는 것이 하나의 뚜렷한 추세로 자리 잡고 있다. 이러한 작업은 일련의 행동과 도구 및 외부 환경과의 동적 상호작용이 필요한 경우가 많다. 본 논문에서는 StateFlow 라는 새로운 LLM 기반 task 해결 패러다임을 제안한다. StateFlow는 복잡한 작업 해결 과정을 state machine(상태 머신, 상태 기계) 로 개념화한다. 이 접근 방식은 프로세스 기반화(process grounding)를 상태(state)와 상태 전이(state transition)를 통해 수행하고, 하위 작업 해결(sub-task solving)은 상태 내에서의 작업(action)을 통해 수행함으로써, 작업 해결 절차에 대한 제어력과 해석 가능성을 향상 시킨다.
여기서 State(상태)는 실행 중인 프로세스의 현재 상황을 나타낸다. 상태 간 전이는 휴리스틱 규칙(heuristic rules) 또는 LLM이 내린 결정에 의해 제어되며, 이를 통해 동적이고 적응적인 진행이 가능하다. State에 진입하면 일련의 작업이 실행되며, 여기에는 다양한 프롬프트로 유도된 LLM 호출뿐만 아니라 필요에 따라 외부 도구의 활용도 포함된다.
유한 상태 기계(Finite State Machine, FSM)는 예를 들어 교통 신호 제어와 같은 실제 응용 프로그램을 모니터링하는 제어 시스템으로 사용된다. 정의된 상태 기계는 현재 상태를 기준으로 무엇을 해야 할지를 결정하는 행동 모델이다. 상태는 FSM이 있을 수 있는 하나의 상화을 나타낸다. 이러한 개념을 바탕으로, 우리는 LLM의 작업 해결 과정을 모델링하는 데 FSM을 사용하고자 한다.
LLM을 사용하여 여러 단계를 거쳐 해결해야 하는 작업이 주어졌을 때, 작업 해결 프로세스의 각 단계를 하나의 상태로 매핑할 수 있다.
예를 들어 SQL 작업을 생각해 보자. (아래의 그림 참고)
이 작업에 대한 바람직한 절차는 다음과 같아.
(1) 데이터베이스 내의 테이블 및 컬럼에 대한 정보 수집
(2) 원하는 정보를 조회하는 쿼리 구성
(3) 작업이 해결되었는지 검증하고, 프로세스를 종료
각 단계에 대해 대응하는 상태를 생성하고, 실패 상황을 처리하기 위한 오류 상태(error state)도 정의한다. 그림에서는 실행 결과에 따라 빨간 화살표(실패)와 초록 화살표(성공)가 상태 전이를 나타낸다. 상태간 전이는 특정 규칙에 기반한다. 예를 들어 "Submit" 명령이 성공적으로 수행되면 모델은 "종료 상태(End state)"로 전이한다.
상태에 도달하면, 정의된 출력함수(output functions)의 일련의 작업이 실행된다. 예를 들어 M_i -> E은 모델을 먼저 호출하고 그 이후 SQL 명령을 실행함을 의미한다.

위 그림은 SQL Task와 Bash Task에서의 에이전트 작업 흐름을 시각적으로 표현한 다이어그램이다. 각 작업에서 **LLM(Large Language Model)이 특정 instruciton을 가진 에이전트로 동작하면서 오류를 탐지하고 수정하면서 해결하는 과정이다.
각 기호들은 다음과 같다.
[SQL Task]
SQL Task의 전체 흐름은 Init 단계에서 시작해서 Observe(M_1->E)로 데이터를 관찰한다. Select (M_2->E) 로 쿼리를 선택하고 Verify(M_3->E) 선택한 쿼리를 검증한다. 그 후에 End로 제출하면 성공적인 종료이다.
이 때, 중간에 오류가 발생하면 오류 처리 플로우로 빠지는데 Obseve,Select, Verify 단계에서 Error(M_4->E)로 전환될 수 있다. Error는 자체 루프를 돌며 재시도가 가능하고, Error에서 Select나 Verify로 복귀할 수 있다.
해당 로직에서 Select <-> Verify 에서 Select, Desc 키워드를 기반으로 상호 피드백을 진행한다.
[Bash Task]
Bash Task의 전체흐름은 Init에서 시작해서 Solve(M_1->E) 에서 문제 해결을 시도한다. 그리고 Verify(M_2->E)로 실행 결과를 확인한 후에 End로 제출하면 성공적인 종료이다.
이 때, 중간에 오류가 발생하면 Solve, Verify 단계에서 Error(M_3->E)로 전환한다. Error는 역시 루프로 반복 가능하다. 오류 발생 시 다시 Verity로 돌아가거나, 처음부터 다시 Sovle로 돌아갈 수 있다.
위의 로직들의 핵심 차이점은 SQL task는 주요단계가 Observe->Select->Verify 이고, Bash Task는 주요단계가 Solve -> Verify 이다. SQL task는 검증-선택의 반복 단계에서 SELECT/DESC로 상호 피드백을 진행하고 Bash Task는 단방향 흐름 중심이다.
이 다이어그램은 에이전트 기반 문제 해결 프로세스에서 다단계 피드백 루프, 오류 처리 로직, 역할 분리된 모델 사용 전략을 보여주고 있다. 특히 SQL 문제 해결은 탐색-선택-검증의 명확한 단계화를 통해 구조적 문제를 해결을 강조하고, Bash는 실행 중심의 간단한 흐름으로 실용적인 접근을 보여준다.
InterCode : 여기서는 InterCode 벤치마크의 SQL 작업과 Bash 작업에서 StateFlow를 평가하며, GPT-3.5-Turbo와 GPT-4-Turbo 모두를 사용했다. 포괄적인 비교를 위해 다양한 지표를 기록했다.
'SR(성공률)'은 성능을 측정하고, 'Truns(턴수)'는 환경과의 상호작용 횟수를 나타내며, 'Error Rate(오류율)'는 실행된 명령어 중 오류가 발생한 비율을 나타낸다. 또한 LLM 사용 비용도 기록하였다.
다음과 같은 기준 방법으로 비교를 진행하였는데,
(1) ReAct : 모델이 생각과 행동을 생성하도록 유도하는 few-shot 프롬프트 방식
(2) Plan & Solve : 먼저 모델에게 계획을 제안하게 한 다음, 이를 실행하게 하는 두 단계 프롬프트 전략
Bash 작업에 대한 결과는 아래에 제시되어 있다.

ALFWorld : 여기서는 TextWorld 환경에서 구현된 텍스트 기반의 합성 게임인 ALFWorld 벤치마크에서도 실험을 수행했다. GPT-3.5-Turbo를 사용했으며, 평균 3회의 시도에서 결과를 측정했다. 다음의 방법들로 함께 평가를 진행했다.
(1) ReAct : ReAct의 two-shot 프롬프트를 사용하였으며, 각 작업 유형에 따라 별도의 프롬프트를 사용한다.
(2) ALFChat (2 에이전트): AutoGen의 설정을 따른 두 개의 에이전트 시스템으로, 보조 에이전트와 실행 에이전트로 구성된다. ALFChat은 ReAct를 기반으로 하며, 프롬프트를 대화 형식으로 수정한 방식이다.
(3) ALFChat (3 에이전트) : 2-에이전트 시스템을 기반으로 하여, 보조 에이전트가 동일한 행동을 세 번 연속 출력할 경우 상식 정보를 제공하는 grounding 에이전트를 추가한 방식이다.
두 작업 모두에서 StateFlow는 가장 높은 성능과 가장 낮은 비용을 달성했다. 자세한 내용은 본 논문을 참고 !
paper : StateFlow: Enhancing LLM Task-Solving through State-Driven Workflows
https://arxiv.org/abs/2403.11322
여기서는 GroupChat을 사용해 StateFlow를 구축하는 방법을 설명한다. FSM Group Chat에서는 에이전트 간 전환을 제약할 수 있는 transition graph) 전이 그래프를 입력하는 새로운 GroupChat 기능을 소개했다. 이 기능은 에이전트의 설명(description) 파마미터에 상태 전이 조건을 자연어로 기술 해야 하며, LLM이 해당 설명을 받아 다음 에이전트를 결정하게 된다.
FSM Group Chat
https://microsoft.github.io/autogen/0.2/blog/2024/02/11/FSM-GroupChat/
여기서는 GroupChat 객체의 speaker_selection_method에 전달할 수 있는 사용자 지정 발화자 선택 함수(custom speaker selection function)을 사용한다. 이 함수는 에이전트 간의 전이 로직을 사용자 정의할 수 있게 해주며, FSM Group Chat에서 소개된 전이 그래프와 함께 사용할 수 있다. 현재 StateFlow 구현은 사용자가 전이 그래프를 직접 덮어쓸 수 있도록도 지원한다. 이러한 전이는 현재 발화자(speaker)와 컨텍스트 히스토리의 정적 검사(예: 마지막 메시지에 'Error'가 포함되어 있는지 확인)를 기반으로 정의될 수 있다.
GroupChat을 사용해서 state-oriented workflow(상태 지향 워크플로우)를 구성하는 예제를 제시한다. 여기서는 speaker_selection_method 파라미터에 전달될 사용자 정의 발화 선택 함수를 정의한다. 이 예제의 작업은 주어진 주제와 관련된 연구 논문을 검색하고, 해당 논문들을 마크다운 테이블 형식으로 정리하는 것이다.

위는 코드를 생성하고 실행해서 추가 연구를 통해 작업을 완성하는 일련의 프로세스를 설명하는 다이어그램이다.
Init 프로세스를 시작하는 초기화 단계에서 시작해서 Retrieve(C->E) 코드를 작성(Coder)하고 코드를 실행한다(Coe Executor). Research(R) 성공적으로 결과를 얻으면 추가적인 리서치를 진행한다. 연구가 끝나면 End(Exit) 작업을 종료한다.
위 로직에서 Coder가 코드를 작성하고 Code Executor라 이를 실행해서 실행에 성공하면 Research 단계로, 오류 발생시 Retrieve 단계로 다시 돌아가서 재 시도한다. (Error 루프)
여기서는 다음과 같은 에이전트를 정의했다.
import autogen
from config import settings
api_key = settings.openai_api_key.get_secret_value()
llm_config = {
"config_list":
[
{
"model" : "gpt-4o-mini",
"api_key" : api_key
}
]}
initializer = autogen.UserProxyAgent(
name="init",
llm_config=llm_config,
)
coder = autogen.AssistantAgent(
name="Coder",
system_message="""You are the Coder. Write Python Code to retrieve papers from arxiv.""",
llm_config=llm_config,
)
executor = autogen.UserProxyAgent(
name="Executor",
system_message="""Executor. Execute the code written by the Coder and report the result.""",
llm_config=llm_config,
)
scientist = autogen.AssistantAgent(
name="Scientist",
system_message = """You are the Scientist. Please categorize papers after seeing their abstracts printed and create a markdown table with Domain, Title, Authors, Summary and Link.
Return 'TERMINATE' in the end.""",
llm_config=llm_config,)
위 그림에서는 다음 같이 4개의 상태를 가진 간단한 연구 워크플로우를 정의한다. Init, Retreive, Research, End
def state_transition(last_speaker, groupchat):
messages = groupchat.messages
if last_speaker is initializer:
return coder
elif last_speaker is coder:
return executor
elif last_speaker is executor:
if messages[-1]["content"] == "exitcode: 1":
return coder
else:
return scientist
elif last_speaker == "Scientist":
return None
groupchat = autogen.GroupChat(
agents=[initializer, coder, executor, scientist],
messages=[],
max_round=20,
speaker_selection_method=state_transition,
)
각 상태에서는 다른 에이전트를 호출해서 작업을 수행한다.
Initializer를 호출하여 워크플로우를 시작한다. coder를 호출해 코드를 작성하고, 이어서 executor를 호출해 해당 코드를 실행한다.scientist를 호출해서 논문을 읽고 요약을 작성한다.각 화자의 전환 로직을 사용자 정의 함수에서 구현하는 것을 권장한다. state machine(상태 기계)에 비유하자면, 상태 전이 함수는 현재 상태와 입력에 따라 다음 상태를 결정한다. 다음 화자를 나타내는 Agent 클래스를 반환하는 대신, 기본적으로 사용할 방법을 선택하기 위해 ['auto', 'manual', 'random', 'round_robin'] 중 하나의 문자열을 반환할 수도 있다. 예를 들어, 항상 기본 내장된 auto 방식을 사용하도록 설정하면, LLM 기반의 그룹 채팅 매니저가 다음 화자를 선택하게 된다. None을 반환하면 그룹 채팅이 반환된다. "initializer" -> "coder"와 같은 일부 전환은 전이 그래프(transition graph)를 통해 정의할 수 있다.
manager = autogen.GroupChatManager(groupchat=groupchat)
initializer.initiate_chat(manager)
결과는 'gpt-4o-mini'. rlwns
init (to chat_manager):
--------------------------------------------------------------------------------
Next speaker: Coder
Coder (to chat_manager):
To retrieve papers from arXiv, you can use the `arxiv` API, which allows you to search for and fetch papers in a variety of formats. Below is a simple example of how to use the `arxiv` Python package to retrieve papers. Make sure to install the package first if you haven't done so:
```bash
pip install arxi```
Here's a sample code snippet to search for papers on arXiv:
```python
import arxiv
def search_arxiv(query, max_results=5):
# Create a search object with the specified query and max results
search = arxiv.Search(
query=query,
max_results=max_results,
sort_by=arxiv.SortCriterion.Relevance
)
# Iterate through the search results and print paper details
for result in search.results():
print(f'Title: {result.title}')
print(f'Authors: {", ".join([author.name for author in result.authors])}')
print(f'Summary: {result.summary}')
print(f'Published: {result.published}')
print(f'PDF Link: {result.pdf_url}')
print('---')
# Example usage
search_query = "machine learning"
search_arxiv(search_query)```
### Explanation:
1. **Import the `arxiv` package**: This allows you to access the arXiv API.
2. **Define a function `search_arxiv()`**: This function takes a query string and an optional maximum number of results to return.
3. **Create a search object**: Using the `arxiv.Search` constructor, initialize the search parameters.
4. **Iterate through the results**: For each result, print the title, authors, summary, publication date, and PDF link.
5. **Call the function with a search query**: The example usage searches for papers related to "machine learning".
You can customize the search query as needed, and modify the `max_results` parameter to control how many papers you retrieve.
--------------------------------------------------------------------------------
Next speaker: Executor
>>>>>>>> NO HUMAN INPUT RECEIVED.
>>>>>>>> USING AUTO REPLY...
>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is bash)...
>>>>>>>> EXECUTING CODE BLOCK 1 (inferred language is python)...
Executor (to chat_manager):
exitcode: 0 (execution succeeded)
Code output:
Collecting arxiv
Downloading arxiv-2.2.0-py3-none-any.whl.metadata (6.3 kB)
Collecting feedparser~=6.0.10 (from arxiv)
Downloading feedparser-6.0.11-py3-none-any.whl.metadata (2.4 kB)
Collecting requests~=2.32.0 (from arxiv)
Downloading requests-2.32.3-py3-none-any.whl.metadata (4.6 kB)
Collecting sgmllib3k (from feedparser~=6.0.10->arxiv)
Downloading sgmllib3k-1.0.0.tar.gz (5.8 kB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'done'
Collecting charset-normalizer<4,>=2 (from requests~=2.32.0->arxiv)
Downloading charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.metadata (35 kB)
Collecting idna<4,>=2.5 (from requests~=2.32.0->arxiv)
Downloading idna-3.10-py3-none-any.whl.metadata (10 kB)
Collecting urllib3<3,>=1.21.1 (from requests~=2.32.0->arxiv)
Downloading urllib3-2.4.0-py3-none-any.whl.metadata (6.5 kB)
Collecting certifi>=2017.4.17 (from requests~=2.32.0->arxiv)
Downloading certifi-2025.4.26-py3-none-any.whl.metadata (2.5 kB)
Downloading arxiv-2.2.0-py3-none-any.whl (11 kB)
Downloading feedparser-6.0.11-py3-none-any.whl (81 kB)
Downloading requests-2.32.3-py3-none-any.whl (64 kB)
Downloading certifi-2025.4.26-py3-none-any.whl (159 kB)
Downloading charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (140 kB)
Downloading idna-3.10-py3-none-any.whl (70 kB)
Downloading urllib3-2.4.0-py3-none-any.whl (128 kB)
Building wheels for collected packages: sgmllib3k
Building wheel for sgmllib3k (pyproject.toml): started
Building wheel for sgmllib3k (pyproject.toml): finished with status 'done'
Created wheel for sgmllib3k: filename=sgmllib3k-1.0.0-py3-none-any.whl size=6089 sha256=215b88500d4ad59697ef2a7426ea42e9f85bbf2fbb4cfc5d51b04425636884be
Stored in directory: /root/.cache/pip/wheels/3d/4d/ef/37cdccc18d6fd7e0dd7817dcdf9146d4d6789c32a227a28134
Successfully built sgmllib3k
Installing collected packages: sgmllib3k, urllib3, idna, feedparser, charset-normalizer, certifi, requests, arxiv
Successfully installed arxiv-2.2.0 certifi-2025.4.26 charset-normalizer-3.4.1 feedparser-6.0.11 idna-3.10 requests-2.32.3 sgmllib3k-1.0.0 urllib3-2.4.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.
[notice] A new release of pip is available: 25.0.1 -> 25.1
[notice] To update, run: pip install --upgrade pip
/workspace/tmp_code_6ba0332eafac3c5006cb56c5a92f91cd.py:12: DeprecationWarning: The 'Search.results' method is deprecated, use 'Client.results' instead
for result in search.results():
Title: Lecture Notes: Optimization for Machine Learning
Authors: Elad Hazan
Summary: Lecture notes on optimization for machine learning, derived from a course at
Princeton University and tutorials given in MLSS, Buenos Aires, as well as
Simons Foundation, Berkeley.
Published: 2019-09-08 21:49:42+00:00
PDF Link: http://arxiv.org/pdf/1909.03550v1
---
Title: An Optimal Control View of Adversarial Machine Learning
Authors: Xiaojin Zhu
Summary: I describe an optimal control view of adversarial machine learning, where the
dynamical system is the machine learner, the input are adversarial actions, and
the control costs are defined by the adversary's goals to do harm and be hard
to detect. This view encompasses many types of adversarial machine learning,
including test-item attacks, training-data poisoning, and adversarial reward
shaping. The view encourages adversarial machine learning researcher to utilize
advances in control theory and reinforcement learning.
Published: 2018-11-11 14:28:34+00:00
PDF Link: http://arxiv.org/pdf/1811.04422v1
---
Title: Minimax deviation strategies for machine learning and recognition with short learning samples
Authors: Michail Schlesinger, Evgeniy Vodolazskiy
Summary: The article is devoted to the problem of small learning samples in machine
learning. The flaws of maximum likelihood learning and minimax learning are
looked into and the concept of minimax deviation learning is introduced that is
free of those flaws.
Published: 2017-07-16 09:15:08+00:00
PDF Link: http://arxiv.org/pdf/1707.04849v1
---
Title: Machine Learning for Clinical Predictive Analytics
Authors: Wei-Hung Weng
Summary: In this chapter, we provide a brief overview of applying machine learning
techniques for clinical prediction tasks. We begin with a quick introduction to
the concepts of machine learning and outline some of the most common machine
learning algorithms. Next, we demonstrate how to apply the algorithms with
appropriate toolkits to conduct machine learning experiments for clinical
prediction tasks. The objectives of this chapter are to (1) understand the
basics of machine learning techniques and the reasons behind why they are
useful for solving clinical prediction problems, (2) understand the intuition
behind some machine learning models, including regression, decision trees, and
support vector machines, and (3) understand how to apply these models to
clinical prediction problems using publicly available datasets via case
studies.
Published: 2019-09-19 22:02:00+00:00
PDF Link: http://arxiv.org/pdf/1909.09246v1
---
Title: Towards Modular Machine Learning Solution Development: Benefits and Trade-offs
Authors: Samiyuru Menik, Lakshmish Ramaswamy
Summary: Machine learning technologies have demonstrated immense capabilities in
various domains. They play a key role in the success of modern businesses.
However, adoption of machine learning technologies has a lot of untouched
potential. Cost of developing custom machine learning solutions that solve
unique business problems is a major inhibitor to far-reaching adoption of
machine learning technologies. We recognize that the monolithic nature
prevalent in today's machine learning applications stands in the way of
efficient and cost effective customized machine learning solution development.
In this work we explore the benefits of modular machine learning solutions and
discuss how modular machine learning solutions can overcome some of the major
solution engineering limitations of monolithic machine learning solutions. We
analyze the trade-offs between modular and monolithic machine learning
solutions through three deep learning problems; one text based and the two
image based. Our experimental results show that modular machine learning
solutions have a promising potential to reap the solution engineering
advantages of modularity while gaining performance and data advantages in a way
the monolithic machine learning solutions do not permit.
Published: 2023-01-23 22:54:34+00:00
PDF Link: http://arxiv.org/pdf/2301.09753v1
---
--------------------------------------------------------------------------------
Next speaker: Scientist
Scientist (to chat_manager):
Here is a markdown table summarizing the identified papers based on their abstracts:
```markdown
| Domain | Title | Authors | Summary | Link |
|---------------------------|-----------------------------------------------------------------------|-----------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------|
| Machine Learning | Lecture Notes: Optimization for Machine Learning | Elad Hazan | Lecture notes on optimization for machine learning, derived from a course at Princeton University and tutorials given in MLSS, Buenos Aires, as well as Simons Foundation, Berkeley. | [PDF Link](http://arxiv.org/pdf/1909.03550v1) |
| Adversarial Machine Learning| An Optimal Control View of Adversarial Machine Learning | Xiaojin Zhu | An optimal control view of adversarial machine learning, encompassing many types of adversarial machine learning, including test-item attacks, training-data poisoning, and adversarial reward shaping, encouraging researchers to utilize advances in control theory and reinforcement learning. | [PDF Link](http://arxiv.org/pdf/1811.04422v1) |
| Machine Learning | Minimax deviation strategies for machine learning and recognition with short learning samples | Michail Schlesinger, Evgeniy Vodolazskiy | This article addresses the problem of small learning samples in machine learning, introducing the concept of minimax deviation learning that is free of flaws inherent in maximum likelihood and minimax learning. | [PDF Link](http://arxiv.org/pdf/1707.04849v1) |
| Clinical Predictive Analytics| Machine Learning for Clinical Predictive Analytics | Wei-Hung Weng | Overview of applying machine learning techniques for clinical prediction, discussing common algorithms and demonstrating their application through case studies to understand their usefulness and intuition for clinical prediction problems. | [PDF Link](http://arxiv.org/pdf/1909.09246v1) |
| Modular Machine Learning | Towards Modular Machine Learning Solution Development: Benefits and Trade-offs | Samiyuru Menik, Lakshmish Ramaswamy | Discusses the potential of modular machine learning solutions to overcome limitations of monolithic applications, analyzing trade-offs through experiments on deep learning problems and showing promise in solution engineering advantages. | [PDF Link](http://arxiv.org/pdf/2301.09753v1) |```
TERMINATE
--------------------------------------------------------------------------------
>>>>>>>> TERMINATING RUN (110ac18e-3cd4-4bd1-bd91-c68458e17ade): No next speaker selected
https://microsoft.github.io/autogen/0.2/docs/notebooks/agentchat_groupchat_stateflow/
https://microsoft.github.io/autogen/0.2/docs/notebooks/agentchat_groupchat_customized/
https://microsoft.github.io/autogen/0.2/blog/2024/02/11/FSM-GroupChat/
https://microsoft.github.io/autogen/0.2/docs/Getting-Started/