Lim0011 commited on
Commit
eddff80
·
1 Parent(s): 96b72ac

update interaction

Browse files
.history/app_20250403234225.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to load")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=[paper_text_input],
241
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250403234226.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to load")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=[paper_text_input],
241
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404000830.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=[paper_text_input],
241
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404000859.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ # inputs=[paper_text_input],
241
+ # outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ # fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404000900.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ # inputs=[paper_text_input],
241
+ # outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ # fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404000955.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=[paper_text_input],
241
+ # outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ # fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404001019.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=example_text,
241
+ # outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ # fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404001125.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ return "", "", "", ""
80
+ example = example_data[index_ex]
81
+ tasks = example['research_tasks']
82
+ gaps = example['research_gaps']
83
+ keywords = example['keywords']
84
+ recent_works = "\n".join(example['recent_works'])
85
+ return tasks, gaps, keywords, recent_works
86
+
87
+
88
+ # Step 2: Generate Research Hypothesis and Experiment Plan
89
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
90
+ if (not state_extract or not state_example or paper_text == ""):
91
+ return "", "", "", ""
92
+ global state_generate, index_ex
93
+ state_generate = True
94
+ hypothesis = example_data[index_ex]['hypothesis']
95
+ experiment_plan = example_data[index_ex]['experiment_plan']
96
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
97
+
98
+ ########## Phase 2 & 3 ##############
99
+ def start_experiment_agent(hypothesis, plan):
100
+ if (not state_extract or not state_generate or not state_example):
101
+ return "", "", ""
102
+ global state_agent, step_index, state_complete
103
+ state_agent = True
104
+ step_index = 0
105
+ state_complete = False
106
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
107
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
108
+
109
+ def submit_feedback(user_feedback, history, previous_response):
110
+ if (not state_extract or not state_generate or not state_agent or not state_example):
111
+ return "", "", ""
112
+ global step_index, state_complete
113
+ step_index += 1
114
+ msg = history
115
+ if step_index < len(process_steps):
116
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
117
+ response_info = process_steps[step_index]
118
+ response = info_to_message(response_info) # Convert dictionary to formatted string
119
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
120
+ step_index += 1
121
+ msg += response
122
+ else:
123
+ state_complete = True
124
+ response = "Agent Finished."
125
+
126
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
127
+
128
+ def load_phase_2_inputs(hypothesis, plan):
129
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
130
+
131
+
132
+
133
+ predefined_action_log = """
134
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
135
+ [Action]: Inspect Script (train.py)
136
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
137
+ Objective: Understand the training script, including data processing, [...]
138
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
139
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
140
+ """
141
+
142
+
143
+ predefined_observation = """
144
+ Epoch [1/10],
145
+ Train MSE: 0.543,
146
+ Test MSE: 0.688
147
+ Epoch [2/10],
148
+ Train MSE: 0.242,
149
+ Test MSE: 0.493\n
150
+ """
151
+
152
+ # Initialize the global step_index and history
153
+ process_steps = [
154
+ {
155
+ "Action": "Inspect Script Lines (train.py)",
156
+ "Observation": (
157
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
158
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
159
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
160
+ "predict exist without implementations."
161
+ ),
162
+ },
163
+ {
164
+ "Action": "Execute Script (train.py)",
165
+ "Observation": (
166
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
167
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
168
+ ),
169
+ },
170
+ {
171
+ "Action": "Edit Script (train.py)",
172
+ "Observation": (
173
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
174
+ "The edited train.py now has clearly defined functions"
175
+ "for data loading (load_data), model definition (build_model), "
176
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
177
+ ),
178
+ },
179
+ {
180
+ "Action": "Retrieve Model",
181
+ "Observation": "CNN and BiLSTM retrieved.",
182
+ },
183
+ {
184
+ "Action": "Execute Script (train.py)",
185
+ "Observation": (
186
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
187
+ "the decrease in loss indicates improved model performance."
188
+ )
189
+ },
190
+ {
191
+ "Action": "Evaluation",
192
+ "Observation": predefined_observation,
193
+ }
194
+ ]
195
+ def info_to_message(info):
196
+ msg = ""
197
+ for k, v in info.items():
198
+ if isinstance(v, dict):
199
+ tempv = v
200
+ v = ""
201
+ for k2, v2 in tempv.items():
202
+ v += f"{k2}:\n {v2}\n"
203
+ v = User.indent_text(v, 2)
204
+ msg += '-' * 64
205
+ msg += '\n'
206
+ msg += f"{k}:\n{v}\n"
207
+ return msg
208
+
209
+
210
+ def handle_example_click(example_index):
211
+ global index_ex
212
+ index_ex = example_index
213
+ return load_example(index_ex) # Simply return the text to display it in the textbox
214
+
215
+ # Gradio Interface
216
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
217
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
218
+ gr.Markdown("### ")
219
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
220
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
221
+
222
+
223
+
224
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
+
226
+
227
+
228
+
229
+ # Use state variables to store generated hypothesis and experiment plan
230
+ hypothesis_state = gr.State("")
231
+ experiment_plan_state = gr.State("")
232
+
233
+ ########## Phase 1: Research Idea Generation Tab ##############
234
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
235
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
+ gr.Markdown("## ⬇️Click an example to start")
237
+
238
+ gr.Examples(
239
+ examples=example_text,
240
+ inputs=[paper_text_input],
241
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
242
+ fn=load_example_and_set_index,
243
+ run_on_click = True,
244
+ # label="⬇️ Click an example to load"
245
+ )
246
+
247
+ with gr.Row():
248
+ with gr.Column():
249
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
250
+
251
+ extract_button = gr.Button("🔍 Extract Research Elements")
252
+ with gr.Row():
253
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
254
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
255
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
256
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
257
+ with gr.Column():
258
+ with gr.Row(): # Move the button to the top
259
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
260
+ with gr.Group():
261
+ gr.Markdown("### 🌟 Research Idea")
262
+ with gr.Row():
263
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
264
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
265
+
266
+
267
+ # Step 1: Extract Research Elements
268
+ extract_button.click(
269
+ fn=extract_research_elements,
270
+ inputs=paper_text_input,
271
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
272
+ )
273
+
274
+ generate_button.click(
275
+ fn=generate_and_store,
276
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
277
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
+ )
279
+
280
+
281
+
282
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
283
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
284
+ gr.Markdown("### Interact with the ExperimentAgent")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ with gr.Group():
289
+ gr.Markdown("### 🌟 Generated Research Idea")
290
+ with gr.Row():
291
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
292
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
293
+
294
+ with gr.Column():
295
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
296
+ with gr.Group():
297
+ gr.Markdown("### Implementation + Execution Log")
298
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
299
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
300
+
301
+ with gr.Column():
302
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
303
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
304
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
305
+
306
+ hypothesis_state.change(
307
+ fn=load_phase_2_inputs,
308
+ inputs=[hypothesis_state, experiment_plan_state],
309
+ outputs=[idea_input, plan_input, code_display]
310
+ )
311
+
312
+ # Start research agent
313
+ start_exp_agnet.click(
314
+ fn=start_experiment_agent,
315
+ inputs=[hypothesis_state, experiment_plan_state],
316
+ outputs=[code_display, log, response, feedback]
317
+ )
318
+
319
+ submit_button.click(
320
+ fn=submit_feedback,
321
+ inputs=[feedback, log, response],
322
+ outputs=[log, response, code_display, feedback]
323
+ )
324
+
325
+ # Test
326
+ if __name__ == "__main__":
327
+ step_index = 0
328
+ app.launch(share=True)
.history/app_20250404131115.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ gr.Examples(
240
+ examples=example_text,
241
+ inputs=[paper_text_input],
242
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
243
+ fn=load_example_and_set_index,
244
+ run_on_click = True,
245
+ # label="⬇️ Click an example to load"
246
+ )
247
+
248
+ with gr.Row():
249
+ with gr.Column():
250
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
251
+
252
+ extract_button = gr.Button("🔍 Extract Research Elements")
253
+ with gr.Row():
254
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
255
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
256
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
257
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
258
+ with gr.Column():
259
+ with gr.Row(): # Move the button to the top
260
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
261
+ with gr.Group():
262
+ gr.Markdown("### 🌟 Research Idea")
263
+ with gr.Row():
264
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
265
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
266
+
267
+
268
+ # Step 1: Extract Research Elements
269
+ extract_button.click(
270
+ fn=extract_research_elements,
271
+ inputs=paper_text_input,
272
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
273
+ )
274
+
275
+ generate_button.click(
276
+ fn=generate_and_store,
277
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
278
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
279
+ )
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404160325.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ gr.Examples(
240
+ examples=example_text,
241
+ inputs=[paper_text_input],
242
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
243
+ fn=load_example_and_set_index,
244
+ run_on_click = True,
245
+ # label="⬇️ Click an example to load"
246
+ )
247
+
248
+ with gr.Row():
249
+ with gr.Column():
250
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
251
+
252
+ extract_button = gr.Button("🔍 Extract Research Elements")
253
+ with gr.Row():
254
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
255
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
256
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
257
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
258
+ with gr.Column():
259
+ with gr.Row(): # Move the button to the top
260
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
261
+ with gr.Group():
262
+ gr.Markdown("### 🌟 Research Idea")
263
+ with gr.Row():
264
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
265
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
266
+
267
+
268
+ # Step 1: Extract Research Elements
269
+ extract_button.click(
270
+ fn=extract_research_elements,
271
+ inputs=paper_text_input,
272
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
273
+ )
274
+
275
+ generate_button.click(
276
+ fn=generate_and_store,
277
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
278
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
279
+ )
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404160326.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ gr.Examples(
240
+ examples=example_text,
241
+ inputs=[paper_text_input],
242
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
243
+ fn=load_example_and_set_index,
244
+ run_on_click = True,
245
+ # label="⬇️ Click an example to load"
246
+ )
247
+
248
+ with gr.Row():
249
+ with gr.Column():
250
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
251
+
252
+ extract_button = gr.Button("🔍 Extract Research Elements")
253
+ with gr.Row():
254
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
255
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
256
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
257
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
258
+ with gr.Column():
259
+ with gr.Row(): # Move the button to the top
260
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
261
+ with gr.Group():
262
+ gr.Markdown("### 🌟 Research Idea")
263
+ with gr.Row():
264
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
265
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
266
+
267
+
268
+ # Step 1: Extract Research Elements
269
+ extract_button.click(
270
+ fn=extract_research_elements,
271
+ inputs=paper_text_input,
272
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
273
+ )
274
+
275
+ generate_button.click(
276
+ fn=generate_and_store,
277
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
278
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
279
+ )
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404160630.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ gr.Examples(
240
+ examples=example_text,
241
+ inputs=[],
242
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
243
+ fn=load_example_and_set_index,
244
+ run_on_click = True,
245
+ # label="⬇️ Click an example to load"
246
+ )
247
+
248
+ with gr.Row():
249
+ with gr.Column():
250
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
251
+
252
+ extract_button = gr.Button("🔍 Extract Research Elements")
253
+ with gr.Row():
254
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
255
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
256
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
257
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
258
+ with gr.Column():
259
+ with gr.Row(): # Move the button to the top
260
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
261
+ with gr.Group():
262
+ gr.Markdown("### 🌟 Research Idea")
263
+ with gr.Row():
264
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
265
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
266
+
267
+
268
+ # Step 1: Extract Research Elements
269
+ extract_button.click(
270
+ fn=extract_research_elements,
271
+ inputs=paper_text_input,
272
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
273
+ )
274
+
275
+ generate_button.click(
276
+ fn=generate_and_store,
277
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
278
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
279
+ )
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404162650.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ with gr.Row():
240
+ with gr.Column():
241
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
242
+
243
+ extract_button = gr.Button("🔍 Extract Research Elements")
244
+ with gr.Row():
245
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
246
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
247
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
248
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
249
+ with gr.Column():
250
+ with gr.Row(): # Move the button to the top
251
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
252
+ with gr.Group():
253
+ gr.Markdown("### 🌟 Research Idea")
254
+ with gr.Row():
255
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
256
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
257
+
258
+
259
+ # Step 1: Extract Research Elements
260
+ extract_button.click(
261
+ fn=extract_research_elements,
262
+ inputs=paper_text_input,
263
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
264
+ )
265
+
266
+ generate_button.click(
267
+ fn=generate_and_store,
268
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
269
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
270
+ )
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404162651.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ with gr.Row():
240
+ with gr.Column():
241
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
242
+
243
+ extract_button = gr.Button("🔍 Extract Research Elements")
244
+ with gr.Row():
245
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
246
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
247
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
248
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
249
+ with gr.Column():
250
+ with gr.Row(): # Move the button to the top
251
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
252
+ with gr.Group():
253
+ gr.Markdown("### 🌟 Research Idea")
254
+ with gr.Row():
255
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
256
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
257
+
258
+
259
+ # Step 1: Extract Research Elements
260
+ extract_button.click(
261
+ fn=extract_research_elements,
262
+ inputs=paper_text_input,
263
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
264
+ )
265
+
266
+ generate_button.click(
267
+ fn=generate_and_store,
268
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
269
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
270
+ )
271
+
272
+ gr.Examples(
273
+ examples=example_text,
274
+ inputs=[],
275
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
276
+ fn=load_example_and_set_index,
277
+ run_on_click = True,
278
+ # label="⬇️ Click an example to load"
279
+ )
280
+
281
+
282
+
283
+
284
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
285
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
286
+ gr.Markdown("### Interact with the ExperimentAgent")
287
+
288
+ with gr.Row():
289
+ with gr.Column():
290
+ with gr.Group():
291
+ gr.Markdown("### 🌟 Generated Research Idea")
292
+ with gr.Row():
293
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
294
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
295
+
296
+ with gr.Column():
297
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
298
+ with gr.Group():
299
+ gr.Markdown("### Implementation + Execution Log")
300
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
301
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
302
+
303
+ with gr.Column():
304
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
305
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
306
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
307
+
308
+ hypothesis_state.change(
309
+ fn=load_phase_2_inputs,
310
+ inputs=[hypothesis_state, experiment_plan_state],
311
+ outputs=[idea_input, plan_input, code_display]
312
+ )
313
+
314
+ # Start research agent
315
+ start_exp_agnet.click(
316
+ fn=start_experiment_agent,
317
+ inputs=[hypothesis_state, experiment_plan_state],
318
+ outputs=[code_display, log, response, feedback]
319
+ )
320
+
321
+ submit_button.click(
322
+ fn=submit_feedback,
323
+ inputs=[feedback, log, response],
324
+ outputs=[log, response, code_display, feedback]
325
+ )
326
+
327
+ # Test
328
+ if __name__ == "__main__":
329
+ step_index = 0
330
+ app.launch(share=True)
.history/app_20250404162708.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+
229
+
230
+ # Use state variables to store generated hypothesis and experiment plan
231
+ hypothesis_state = gr.State("")
232
+ experiment_plan_state = gr.State("")
233
+
234
+ ########## Phase 1: Research Idea Generation Tab ##############
235
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
236
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
237
+ gr.Markdown("## ⬇️Click an example to start")
238
+
239
+ with gr.Row():
240
+ with gr.Column():
241
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
242
+
243
+ extract_button = gr.Button("🔍 Extract Research Elements")
244
+ with gr.Row():
245
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
246
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
247
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
248
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
249
+ with gr.Column():
250
+ with gr.Row(): # Move the button to the top
251
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
252
+ with gr.Group():
253
+ gr.Markdown("### 🌟 Research Idea")
254
+ with gr.Row():
255
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
256
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
257
+
258
+
259
+ # Step 1: Extract Research Elements
260
+ extract_button.click(
261
+ fn=extract_research_elements,
262
+ inputs=paper_text_input,
263
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
264
+ )
265
+
266
+ generate_button.click(
267
+ fn=generate_and_store,
268
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
269
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
270
+ )
271
+
272
+ gr.Examples(
273
+ examples=example_text,
274
+ inputs=[paper_text_input],
275
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
276
+ fn=load_example_and_set_index,
277
+ run_on_click = True,
278
+ # label="⬇️ Click an example to load"
279
+ )
280
+
281
+
282
+
283
+
284
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
285
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
286
+ gr.Markdown("### Interact with the ExperimentAgent")
287
+
288
+ with gr.Row():
289
+ with gr.Column():
290
+ with gr.Group():
291
+ gr.Markdown("### 🌟 Generated Research Idea")
292
+ with gr.Row():
293
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
294
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
295
+
296
+ with gr.Column():
297
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
298
+ with gr.Group():
299
+ gr.Markdown("### Implementation + Execution Log")
300
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
301
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
302
+
303
+ with gr.Column():
304
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
305
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
306
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
307
+
308
+ hypothesis_state.change(
309
+ fn=load_phase_2_inputs,
310
+ inputs=[hypothesis_state, experiment_plan_state],
311
+ outputs=[idea_input, plan_input, code_display]
312
+ )
313
+
314
+ # Start research agent
315
+ start_exp_agnet.click(
316
+ fn=start_experiment_agent,
317
+ inputs=[hypothesis_state, experiment_plan_state],
318
+ outputs=[code_display, log, response, feedback]
319
+ )
320
+
321
+ submit_button.click(
322
+ fn=submit_feedback,
323
+ inputs=[feedback, log, response],
324
+ outputs=[log, response, code_display, feedback]
325
+ )
326
+
327
+ # Test
328
+ if __name__ == "__main__":
329
+ step_index = 0
330
+ app.launch(share=True)
.history/app_20250404163102.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163103.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163106.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163316.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=False)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=False)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=False)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=False)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163317.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=False)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=False)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=False)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=False)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163318.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=False)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=False)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=False)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=False)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
.history/app_20250404163321.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pathlib import Path
3
+ from reactagent.environment import Environment
4
+ from reactagent.agents.agent_research import ResearchAgent
5
+ from reactagent.runner import create_parser
6
+ from reactagent import llm
7
+ from reactagent.users.user import User
8
+ import os
9
+ import json
10
+
11
+
12
+ # Global variables to store session state
13
+ env = None
14
+ agent = None
15
+ state_example = False
16
+ state_extract = False
17
+ state_generate = False
18
+ state_agent = False
19
+ state_complete = False
20
+ index_ex = "1"
21
+
22
+ example_text = [
23
+ "Research Paper 1: Dataset and Baseline for Automatic Student Feedback Analysis",
24
+ "Research Paper 2: An Empirical Study on the Impact of Code Review on Software Quality"
25
+ ]
26
+
27
+ # Load example JSON file
28
+ def load_example_data():
29
+ with open("example/example_data.json", "r") as json_file:
30
+ example_data = json.load(json_file)
31
+
32
+ for idx in example_data.keys():
33
+ try:
34
+ file = example_data[idx]["code_init"]
35
+ with open(os.path.join("example", file), "r") as f:
36
+ example_data[idx]["code_init"] = f.read()
37
+ except FileNotFoundError:
38
+ print(f"File not found: {file}. Skipping key: {idx}")
39
+ try:
40
+ file = example_data[idx]["code_final"]
41
+ with open(os.path.join("example", file), "r") as f:
42
+ example_data[idx]["code_final"] = f.read()
43
+ except FileNotFoundError:
44
+ print(f"File not found: {file}. Skipping key: {idx}")
45
+ return example_data
46
+
47
+ example_data = load_example_data()
48
+
49
+ # Function to handle the selection of an example and populate the respective fields
50
+ def load_example(example_id):
51
+ global index_ex
52
+ index_ex = str(example_id)
53
+ example = example_data[index_ex]
54
+ paper_text = 'Title:\t' + example['title'] + '\n\nAbstract:\t' + example['abstract']
55
+ return paper_text
56
+
57
+ example_text = [load_example(1), load_example(2)]
58
+
59
+ # Function to handle example clicks
60
+ def load_example_and_set_index(paper_text_input):
61
+ global index_ex, state_example
62
+ state_example = True
63
+ index_ex = str(example_text.index(paper_text_input) + 1)
64
+ paper_text = load_example(index_ex)
65
+
66
+ return paper_text, "", "", "", "", "", ""
67
+
68
+
69
+
70
+ ########## Phase 1 ##############
71
+
72
+ def extract_research_elements(paper_text):
73
+ global state_extract, index_ex, state_example
74
+ if not state_example or paper_text == "":
75
+ return "", "", "", ""
76
+ state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
+ print("Mismatch detected.")
79
+ print(paper_text)
80
+ return "", "", "", ""
81
+ example = example_data[index_ex]
82
+ tasks = example['research_tasks']
83
+ gaps = example['research_gaps']
84
+ keywords = example['keywords']
85
+ recent_works = "\n".join(example['recent_works'])
86
+ return tasks, gaps, keywords, recent_works
87
+
88
+
89
+ # Step 2: Generate Research Hypothesis and Experiment Plan
90
+ def generate_and_store(paper_text, tasks, gaps, keywords, recent_works):
91
+ if (not state_extract or not state_example or paper_text == ""):
92
+ return "", "", "", ""
93
+ global state_generate, index_ex
94
+ state_generate = True
95
+ hypothesis = example_data[index_ex]['hypothesis']
96
+ experiment_plan = example_data[index_ex]['experiment_plan']
97
+ return hypothesis, experiment_plan, hypothesis, experiment_plan
98
+
99
+ ########## Phase 2 & 3 ##############
100
+ def start_experiment_agent(hypothesis, plan):
101
+ if (not state_extract or not state_generate or not state_example):
102
+ return "", "", ""
103
+ global state_agent, step_index, state_complete
104
+ state_agent = True
105
+ step_index = 0
106
+ state_complete = False
107
+ # predefined_message = f"Implement the following hypothesis and experiment plan:\n\nHypothesis:\n{hypothesis}\n\nExperiment Plan:\n{plan}"
108
+ return example_data[index_ex]['code_init'], predefined_action_log, "", ""
109
+
110
+ def submit_feedback(user_feedback, history, previous_response):
111
+ if (not state_extract or not state_generate or not state_agent or not state_example):
112
+ return "", "", ""
113
+ global step_index, state_complete
114
+ step_index += 1
115
+ msg = history
116
+ if step_index < len(process_steps):
117
+ msg += previous_response + "\nUser feedback:" + user_feedback + "\n\n"
118
+ response_info = process_steps[step_index]
119
+ response = info_to_message(response_info) # Convert dictionary to formatted string
120
+ response += "Please provide feedback based on the history, response entries, and observation, and questions: "
121
+ step_index += 1
122
+ msg += response
123
+ else:
124
+ state_complete = True
125
+ response = "Agent Finished."
126
+
127
+ return msg, response, example_data[index_ex]['code_init'] if state_complete else example_data[index_ex]['code_final'], ""
128
+
129
+ def load_phase_2_inputs(hypothesis, plan):
130
+ return hypothesis, plan, "# Code implementation will be displayed here after Start ExperimentAgent."
131
+
132
+
133
+
134
+ predefined_action_log = """
135
+ [Reasoning]: To understand the initial structure and functionality of train.py for effective improvements.
136
+ [Action]: Inspect Script (train.py)
137
+ Input: {"script_name": "train.py", "start_line_number": "1", "end_line_number": "74"}
138
+ Objective: Understand the training script, including data processing, [...]
139
+ [Observation]: The train.py script imports [...]. Sets random seeds [...]. Defines [...] Placeholder functions [...] exist without implementation. [...]
140
+ [Feedback]: The script structure is clear, but key functions (train_model, predict) need proper implementation for proposed model training and prediction.\n
141
+ """
142
+
143
+
144
+ predefined_observation = """
145
+ Epoch [1/10],
146
+ Train MSE: 0.543,
147
+ Test MSE: 0.688
148
+ Epoch [2/10],
149
+ Train MSE: 0.242,
150
+ Test MSE: 0.493\n
151
+ """
152
+
153
+ # Initialize the global step_index and history
154
+ process_steps = [
155
+ {
156
+ "Action": "Inspect Script Lines (train.py)",
157
+ "Observation": (
158
+ "The train.py script imports necessary libraries (e.g., pandas, sklearn, torch). "
159
+ "Sets random seeds for reproducibility. Defines compute_metrics_for_regression function "
160
+ "to calculate RMSE for different dimensions. Placeholder functions train_model and "
161
+ "predict exist without implementations."
162
+ ),
163
+ },
164
+ {
165
+ "Action": "Execute Script (train.py)",
166
+ "Observation": (
167
+ "The script executed successfully. Generated embeddings using the BERT model. Completed "
168
+ "the training process without errors. Metrics calculation placeholders indicated areas needing implementation."
169
+ ),
170
+ },
171
+ {
172
+ "Action": "Edit Script (train.py)",
173
+ "Observation": (
174
+ "Edited train.py to separate data loading, model definition, training loop, and evaluation into distinct functions. "
175
+ "The edited train.py now has clearly defined functions"
176
+ "for data loading (load_data), model definition (build_model), "
177
+ "training (train_model), and evaluation (evaluate_model). Similarly, eval.py is reorganized to load the model and perform predictions efficiently."
178
+ ),
179
+ },
180
+ {
181
+ "Action": "Retrieve Model",
182
+ "Observation": "CNN and BiLSTM retrieved.",
183
+ },
184
+ {
185
+ "Action": "Execute Script (train.py)",
186
+ "Observation": (
187
+ "The model trained over the specified number of epochs. Training and validation loss values are recorded for each epoch, "
188
+ "the decrease in loss indicates improved model performance."
189
+ )
190
+ },
191
+ {
192
+ "Action": "Evaluation",
193
+ "Observation": predefined_observation,
194
+ }
195
+ ]
196
+ def info_to_message(info):
197
+ msg = ""
198
+ for k, v in info.items():
199
+ if isinstance(v, dict):
200
+ tempv = v
201
+ v = ""
202
+ for k2, v2 in tempv.items():
203
+ v += f"{k2}:\n {v2}\n"
204
+ v = User.indent_text(v, 2)
205
+ msg += '-' * 64
206
+ msg += '\n'
207
+ msg += f"{k}:\n{v}\n"
208
+ return msg
209
+
210
+
211
+ def handle_example_click(example_index):
212
+ global index_ex
213
+ index_ex = example_index
214
+ return load_example(index_ex) # Simply return the text to display it in the textbox
215
+
216
+ # Gradio Interface
217
+ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Default()) as app:
218
+ gr.Markdown("# MLR- Copilot: Machine Learning Research based on LLM Agents")
219
+ gr.Markdown("### ")
220
+ gr.Markdown("## <span style='color:Orange;'> This UI is for predefined example demo only.</span>")
221
+ gr.Markdown("## <span style='color:Orange;'> To reproduce the results please use [Github](https://github.com/du-nlp-lab/MLR-Copilot/)</span>")
222
+
223
+
224
+
225
+ gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
+
227
+
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
+
230
+
231
+ # Use state variables to store generated hypothesis and experiment plan
232
+ hypothesis_state = gr.State("")
233
+ experiment_plan_state = gr.State("")
234
+
235
+ ########## Phase 1: Research Idea Generation Tab ##############
236
+ with gr.Tab("💡Stage 1: Research Idea Generation"):
237
+ gr.Markdown("### Extract Research Elements and Generate Research Ideas")
238
+ with gr.Row():
239
+ with gr.Column():
240
+ paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
+
242
+ extract_button = gr.Button("🔍 Extract Research Elements")
243
+ with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=False)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=False)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=False)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=False)
248
+ with gr.Column():
249
+ with gr.Row(): # Move the button to the top
250
+ generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
251
+ with gr.Group():
252
+ gr.Markdown("### 🌟 Research Idea")
253
+ with gr.Row():
254
+ hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
+ experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
+
257
+
258
+ # Step 1: Extract Research Elements
259
+ extract_button.click(
260
+ fn=extract_research_elements,
261
+ inputs=paper_text_input,
262
+ outputs=[tasks_output, gaps_output, keywords_output, recent_works_output]
263
+ )
264
+
265
+ generate_button.click(
266
+ fn=generate_and_store,
267
+ inputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output],
268
+ outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
+ )
270
+
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
+
282
+
283
+ ########## Phase 2 & 3: Experiment implementation and execution ##############
284
+ with gr.Tab("🧪 Stage 2 & Stage 3: Experiment implementation and execution"):
285
+ gr.Markdown("### Interact with the ExperimentAgent")
286
+
287
+ with gr.Row():
288
+ with gr.Column():
289
+ with gr.Group():
290
+ gr.Markdown("### 🌟 Generated Research Idea")
291
+ with gr.Row():
292
+ idea_input = gr.Textbox(label="Generated Research Hypothesis", lines=30, interactive=False)
293
+ plan_input = gr.Textbox(label="Generated Experiment Plan", lines=30, interactive=False)
294
+
295
+ with gr.Column():
296
+ start_exp_agnet = gr.Button("⚙️ Start / Reset ExperimentAgent", elem_classes=["agent-btn"])
297
+ with gr.Group():
298
+ gr.Markdown("### Implementation + Execution Log")
299
+ log = gr.Textbox(label="📖 Execution Log", lines=20, interactive=False)
300
+ code_display = gr.Code(label="🧑‍💻 Implementation", language="python", interactive=False)
301
+
302
+ with gr.Column():
303
+ response = gr.Textbox(label="🤖 ExperimentAgent Response", lines=30, interactive=False)
304
+ feedback = gr.Textbox(placeholder="N/A", label="🧑‍🔬 User Feedback", lines=3, interactive=True)
305
+ submit_button = gr.Button("Submit", elem_classes=["Submit-btn"])
306
+
307
+ hypothesis_state.change(
308
+ fn=load_phase_2_inputs,
309
+ inputs=[hypothesis_state, experiment_plan_state],
310
+ outputs=[idea_input, plan_input, code_display]
311
+ )
312
+
313
+ # Start research agent
314
+ start_exp_agnet.click(
315
+ fn=start_experiment_agent,
316
+ inputs=[hypothesis_state, experiment_plan_state],
317
+ outputs=[code_display, log, response, feedback]
318
+ )
319
+
320
+ submit_button.click(
321
+ fn=submit_feedback,
322
+ inputs=[feedback, log, response],
323
+ outputs=[log, response, code_display, feedback]
324
+ )
325
+
326
+ # Test
327
+ if __name__ == "__main__":
328
+ step_index = 0
329
+ app.launch(share=True)
app.py CHANGED
@@ -74,8 +74,9 @@ def extract_research_elements(paper_text):
74
  if not state_example or paper_text == "":
75
  return "", "", "", ""
76
  state_extract = True
77
- if not paper_text.startswith("Title:\t" + example_data[index_ex]["title"]):
78
  print("Mismatch detected.")
 
79
  return "", "", "", ""
80
  example = example_data[index_ex]
81
  tasks = example['research_tasks']
@@ -224,6 +225,7 @@ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Defaul
224
  gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
225
 
226
 
 
227
 
228
 
229
  # Use state variables to store generated hypothesis and experiment plan
@@ -233,17 +235,16 @@ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Defaul
233
  ########## Phase 1: Research Idea Generation Tab ##############
234
  with gr.Tab("💡Stage 1: Research Idea Generation"):
235
  gr.Markdown("### Extract Research Elements and Generate Research Ideas")
236
-
237
  with gr.Row():
238
  with gr.Column():
239
  paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
240
 
241
  extract_button = gr.Button("🔍 Extract Research Elements")
242
  with gr.Row():
243
- tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=True)
244
- gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=True)
245
- keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=True)
246
- recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=True)
247
  with gr.Column():
248
  with gr.Row(): # Move the button to the top
249
  generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
@@ -253,16 +254,6 @@ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Defaul
253
  hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
254
  experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
255
 
256
- gr.Markdown("## ⬇️Click an example to load")
257
-
258
- gr.Examples(
259
- examples=example_text,
260
- inputs=[paper_text_input],
261
- outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
262
- fn=load_example_and_set_index,
263
- run_on_click = True,
264
- # label="⬇️ Click an example to load"
265
- )
266
 
267
  # Step 1: Extract Research Elements
268
  extract_button.click(
@@ -277,6 +268,16 @@ with gr.Blocks(css=".gr-examples-label {display: none;}", theme=gr.themes.Defaul
277
  outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
278
  )
279
 
 
 
 
 
 
 
 
 
 
 
280
 
281
 
282
  ########## Phase 2 & 3: Experiment implementation and execution ##############
 
74
  if not state_example or paper_text == "":
75
  return "", "", "", ""
76
  state_extract = True
77
+ if not paper_text.strip().startswith("Title:\t" + example_data[index_ex]["title"]):
78
  print("Mismatch detected.")
79
+ print(paper_text)
80
  return "", "", "", ""
81
  example = example_data[index_ex]
82
  tasks = example['research_tasks']
 
225
  gr.Markdown("MLR-Copilot is a framework where LLMs mimic researchers’ thought processes, designed to enhance the productivity of machine learning research by automating the generation and implementation of research ideas. It begins with a research paper, autonomously generating and validating these ideas, while incorporating human feedback to help reach executable research outcomes.")
226
 
227
 
228
+ gr.Markdown("## ⬇️Click an example at bottom to start")
229
 
230
 
231
  # Use state variables to store generated hypothesis and experiment plan
 
235
  ########## Phase 1: Research Idea Generation Tab ##############
236
  with gr.Tab("💡Stage 1: Research Idea Generation"):
237
  gr.Markdown("### Extract Research Elements and Generate Research Ideas")
 
238
  with gr.Row():
239
  with gr.Column():
240
  paper_text_input = gr.Textbox(value="", lines=10, label="📑 Research Paper Text", interactive=False)
241
 
242
  extract_button = gr.Button("🔍 Extract Research Elements")
243
  with gr.Row():
244
+ tasks_output = gr.Textbox(placeholder="Research task definition", label="Research Tasks", lines=2, interactive=False)
245
+ gaps_output = gr.Textbox(placeholder="Research gaps of current works", label="Research Gaps", lines=2, interactive=False)
246
+ keywords_output = gr.Textbox(placeholder="Paper keywords", label="Keywords", lines=2, interactive=False)
247
+ recent_works_output = gr.Textbox(placeholder="Recent works extracted from Semantic Scholar", label="Recent Works", lines=2, interactive=False)
248
  with gr.Column():
249
  with gr.Row(): # Move the button to the top
250
  generate_button = gr.Button("✍️ Generate Research Hypothesis & Experiment Plan")
 
254
  hypothesis_output = gr.Textbox(label="Generated Hypothesis", lines=20, interactive=False)
255
  experiment_plan_output = gr.Textbox(label="Generated Experiment Plan", lines=20, interactive=False)
256
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  # Step 1: Extract Research Elements
259
  extract_button.click(
 
268
  outputs=[hypothesis_output, experiment_plan_output, hypothesis_state, experiment_plan_state]
269
  )
270
 
271
+ gr.Examples(
272
+ examples=example_text,
273
+ inputs=[paper_text_input],
274
+ outputs=[paper_text_input, tasks_output, gaps_output, keywords_output, recent_works_output, hypothesis_output, experiment_plan_output],
275
+ fn=load_example_and_set_index,
276
+ run_on_click = True,
277
+ # label="⬇️ Click an example to load"
278
+ )
279
+
280
+
281
 
282
 
283
  ########## Phase 2 & 3: Experiment implementation and execution ##############