AutoGen-Automatic-Essay-Modification

English Essay Revision with Agentic Workflow

Github Repo

Introduction

TBD

Codes and demonstrations

Updated: Version 2

Time: 2025/04/13

  • Autogen sucks… In multi-agent collaboration and communication, the packaging of Autogen is too rigid, making it difficult to customize a flexible framework for agent communication.
  • I may turn to Camel-AI instead in the future.
  • This logging is too simple, I will fix it later.😊😘

construct.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Author: Xiyuan Yang xiyuan_yang@outlook.com
Date: 2025-04-11 14:50:06
LastEditors: Xiyuan Yang xiyuan_yang@outlook.com
LastEditTime: 2025-04-13 11:20:52
FilePath: /Autogen-English-Essay/construct.py
Description:
Do you code and make progress today?
Copyright (c) 2025 by Xiyuan Yang, All Rights Reserved.
"""

# Constructing file structures.

import os
from datetime import *


def read_file(filename="Original.txt"):
"""_summary_ :read file contents, especially for getting the original text

Args:
filename (str): file name for the original text
"""
with open(filename, "r", encoding="utf-8") as file:
return file.read().strip()


def write_file(content: str, filename="Final.txt"):
"""_summary_ :write file contents, especially for getting the original text

Args:
filename (str): file name for the original text
content (str): contents to be written into
"""
with open(filename, "w", encoding="utf-8") as file:
file.write(content)


def create_dirs(log_folder: str):
"""_summary_: create the log folder for the settings

Args:
log_folder (str): The name of the file folder
"""
# create the 'log' file folder if it doesn't exist
if not os.path.exists(log_folder):
# create new folder
print("Constructing new folder...")
os.makedirs(log_folder)
else:
print("Constructed already.")

print("Finish!")


def get_log_filename(log_dir="log") -> str:
"""Generate timestamp-based log filename"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return os.path.join(log_dir, f"log_{timestamp}.txt")


def log_conversation(message: str, log_dir="log"):
"""Record conversation to log file"""
log_file = get_log_filename(log_dir)
with open(log_file, "a", encoding="utf-8") as f:
f.write(message + "\n\n")


def print_progress(message: str):
"""Print progress message and log it"""
print(f"[PROGRESS] {message}")
log_conversation(f"[SYSTEM] {message}")


if __name__ == "__main__":
print("Testing...")
else:
print("Constructing all files...")

prompts.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Author: Xiyuan Yang xiyuan_yang@outlook.com
Date: 2025-04-11 14:50:06
LastEditors: Xiyuan Yang xiyuan_yang@outlook.com
LastEditTime: 2025-04-13 11:20:52
FilePath: /Autogen-English-Essay/construct.py
Description:
Do you code and make progress today?
Copyright (c) 2025 by Xiyuan Yang, All Rights Reserved.
"""

# Constructing file structures.

import os
from datetime import *


def read_file(filename="Original.txt"):
"""_summary_ :read file contents, especially for getting the original text

Args:
filename (str): file name for the original text
"""
with open(filename, "r", encoding="utf-8") as file:
return file.read().strip()


def write_file(content: str, filename="Final.txt"):
"""_summary_ :write file contents, especially for getting the original text

Args:
filename (str): file name for the original text
content (str): contents to be written into
"""
with open(filename, "w", encoding="utf-8") as file:
file.write(content)


def create_dirs(log_folder: str):
"""_summary_: create the log folder for the settings

Args:
log_folder (str): The name of the file folder
"""
# create the 'log' file folder if it doesn't exist
if not os.path.exists(log_folder):
# create new folder
print("Constructing new folder...")
os.makedirs(log_folder)
else:
print("Constructed already.")

print("Finish!")


def get_log_filename(log_dir="log") -> str:
"""Generate timestamp-based log filename"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return os.path.join(log_dir, f"log_{timestamp}.txt")


def log_conversation(message: str, log_dir="log"):
"""Record conversation to log file"""
log_file = get_log_filename(log_dir)
with open(log_file, "a", encoding="utf-8") as f:
f.write(message + "\n\n")


def print_progress(message: str):
"""Print progress message and log it"""
print(f"[PROGRESS] {message}")
log_conversation(f"[SYSTEM] {message}")


if __name__ == "__main__":
print("Testing...")
else:
print("Constructing all files...")

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# Import required modules
from prompts import *
from construct import *
from autogen import (
AssistantAgent,
UserProxyAgent,
GroupChat,
GroupChatManager,
config_list_from_json,
)


"""
The intuition:
1.We use for agents to make the revision task:
1.Task decomposer:
Given the original text and the original prompts, and let the agent to generate the promblems and issues strictly (no actual revisions will be made during this process.)
The agent needs to return a simple report pointing several problems that the passage have faced.
2.Editor Conservative and Editor Creative
Where actual revisions take place. Set different temperatures for the "imagination"
!The two editor will not influence each other, works parallelly.
3.integrator:
Integrate for both two passage to make better improvements
To make better improvements and allow more diversity, we allow the maxlength of current passage is the 1.5*max_length
4.Reporter
Check the format and restrict words.( \le maxlength)

2.For the first version, we will just make one round conversation:
User -> Task decomposer -> Editor Conservative -> Integrator -> Reporter
-> Editor Creative ->
3. To avoid information loss, we will pass total_prompt and the original text for all agents.
"""

# Configure Pydantic model settings
# BaseModel.model_config = {"protected_namespaces": ()}


class AutoGenArticleEditor:
def __init__(self):
create_dirs("log")

# Initialize configuration
self.config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST.json")
self.original_article = read_file()
self.log_filename = get_log_filename("log")
self.max_length = 200

# Initialize agents
self.task_decomposer = None
self.editor1 = None
self.editor2 = None
self.integrator = None
self.reporter = None
self.user_proxy = None
self.group_chat = None
self._setup_agents()

def _setup_agents(self):
"""Configure all agent instances"""

# User proxy agent (human admin simulator)
self.user_proxy = UserProxyAgent(
name="Admin",
system_message="A human admin who provides the article and requirements.",
human_input_mode="NEVER",
code_execution_config=False,
default_auto_reply="Task received. Passing to the team...",
max_consecutive_auto_reply=1,
)

# Task decomposition agent
self.task_decomposer = AssistantAgent(
name="Task_Decomposer",
system_message=f"""
The total task: {total_prompt}


You are an expert in task decomposition. Your responsibilities:
1. Analyze requirements: \n{requirements}\n
2. Read the original passage, the passage is shown below\n:{self.original_article}\n
3. You need to provide a more specific modification plan based on the requirements,
combining it with the original text, but without making specific changes.
For example: the relative clause in a certain sentence does not conform to specific grammatical rules and needs to be revised;
or the word choice in a certain part is too simplistic and needs to be optimized;
or the logic in a certain section needs to be further strengthened.
4. More detailed modification requirements are needed, covering all aspects such as grammar, logic, word choice, and sentence structure.


Response format:
### Specific Requirements
[Return specified and modified requirements]

""",
llm_config={
"config_list": self.config_list,
"temperature": 0.3,
},
)

# Conservative editor agent
self.editor1 = AssistantAgent(
name="Editor_Conservative",
system_message=f"""

{total_prompt}\n
You will receive the specific requirements from the previous agents.\n
The original text: {self.original_article}\n

Attention!!!, particularly for you, as a more meticulous writer, your revisions should focus on the logic and organizational structure of the article, making it more coherent.

Provide complete edited text and brief feedback (<50 words).
Ensure native English usage and <{1.2*self.max_length} word limit.

Response format:
### Version ###
[full edited text]

### Feedback ###
[comments]
""",
llm_config={"config_list": self.config_list, "temperature": 0.2},
)

# Creative editor agent
self.editor2 = AssistantAgent(
name="Editor_Creative",
system_message=f"""
{total_prompt}\n
For the specified requirements: {specified_requirements}\n
The original text: {self.original_article}\n

Attention!!!, Note that, particularly for you, as a free-spirited and imaginative writer, your revisions should focus on the innovative sentence structures and rhetorical techniques in the article, making it more creative and eye-catching.
Provide complete edited text and brief feedback (<50 words).
Ensure native English usage and <{1.2*self.max_length} word limit.

Response format:
### Version ###
[full edited text]

### Feedback ###
[comments]
""",
llm_config={"config_list": self.config_list, "temperature": 0.8},
)

# Integration agent
self.integrator = AssistantAgent(
name="Integrator",
system_message=f"""
{total_prompt}\n
You are the final integrator. Your responsibilities:
1.You will receive three documents: the original article and two modified articles by two editors(one conservative and one creative)
2.You need to take an overall perspective to compare the highlights of the two revised drafts against the original manuscript, and integrate the two articles, taking the strengths from each.
3.!!Attention: You need to make sure your passage (after integrated) is no more than {1.5*self.max_length} words.

Response format:
### Final Version ###
[text after integrated]

### Feedback ###
[comments]
""",
llm_config={
"config_list": self.config_list,
"temperature": 0.5, # Balanced randomness
},
)

self.reporter = AssistantAgent(
name="Reporter",
system_message=f"""
{total_prompt},\n
The original article is: {self.original_article}\n
You are the final reporter, you will receive the final scripts modified, and make the last modifications:
1. Make sure all your modifications adhere to the English Usage.
2. Make sure the total length is no more than {self.max_length} words.

Response format:
### Final version ###
[final text]

### Feedback ###
In this section, you are asked to generate a report about the modifications between the final version and the original version.
""",
llm_config={
"config_list": self.config_list,
"temperature": 0.1,
},
)

# Configure group chat without custom_speaker_order
self.group_chat = GroupChat(
agents=[
self.user_proxy,
self.task_decomposer,
self.editor1,
self.editor2,
self.integrator,
self.reporter,
],
messages=[],
max_round=6,
speaker_selection_method="round_robin",
)

# Group chat manager
self.manager = GroupChatManager(
groupchat=self.group_chat, llm_config={"config_list": self.config_list}
)

def run(self):
"""Execute the editing workflow"""
print_progress("Starting article editing process...")

self.user_proxy.initiate_chat(
self.manager,
message=f"""
Article to edit:
{self.original_article}

Requirements:
{requirements}

Please begin editing process.
""",
)

# Process final output
final_message = self.group_chat.messages[-1]["content"]
if "### Final Version ###" in final_message:
final_text = (
final_message.split("### Final Version ###")[1]
.split("### Feedback ###")[0]
.strip()
)
write_file(final_text)
print_progress(f"Final article saved to Final.txt.")
else:
print_progress(
"Process completed but final version format invalid. Check logs."
)

print_progress(f"Conversation log saved to {self.log_filename}")


if __name__ == "__main__":
editor = AutoGenArticleEditor()
editor.run()

AutoGen-Automatic-Essay-Modification
https://xiyuanyang-code.github.io/posts/AutoGen-automatic-essay-modification/
Author
Xiyuan Yang
Posted on
April 11, 2025
Updated on
April 13, 2025
Licensed under