eaglelandsonce commited on
Commit
e1f24e1
Β·
verified Β·
1 Parent(s): 049b114

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +240 -77
app.py CHANGED
@@ -7,12 +7,46 @@ import queue
7
  import threading
8
  import os
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  class AgentMessageQueue:
11
  def __init__(self):
12
  self.message_queue = queue.Queue()
13
  self.last_agent = None
14
 
15
  def add_message(self, message: Dict):
 
16
  self.message_queue.put(message)
17
 
18
  def get_messages(self) -> List[Dict]:
@@ -21,101 +55,198 @@ class AgentMessageQueue:
21
  messages.append(self.message_queue.get())
22
  return messages
23
 
24
- class SpaceSystemCrew:
25
  def __init__(self, api_key: str = None):
26
  self.api_key = api_key
27
  self.message_queue = AgentMessageQueue()
28
- self.system_architect = None
29
- self.mechanical_engineer = None
30
- self.aerospace_manager = None
31
  self.current_agent = None
32
- self.final_refined_text = None
33
 
34
- def initialize_agents(self, space_system_description: str):
35
  if not self.api_key:
36
  raise ValueError("OpenAI API key is required")
37
-
38
  os.environ["OPENAI_API_KEY"] = self.api_key
39
  llm = ChatOpenAI(temperature=0.7, model="gpt-4")
40
 
41
- self.system_architect = Agent(
42
- role="System Architect",
43
- goal="Analyze and refine the space system concept based on the provided description",
44
- backstory="Expert in space system design, ensuring logical consistency and feasibility",
 
45
  allow_delegation=False,
46
  verbose=True,
47
  llm=llm
48
  )
49
 
50
- self.mechanical_engineer = Agent(
51
- role="Mechanical Engineer",
52
- goal="Refine structural and propulsion mechanisms based on the provided description",
53
- backstory="Specialist in high-velocity launch systems and orbital stabilization",
 
54
  allow_delegation=False,
55
  verbose=True,
56
  llm=llm
57
  )
58
 
59
- self.aerospace_manager = Agent(
60
- role="Aerospace Mission Manager",
61
- goal="Ensure mission feasibility and refine execution details based on the provided description",
62
- backstory="Oversees project feasibility, mission planning, and ensures integration with existing aerospace infrastructure",
 
63
  allow_delegation=False,
64
  verbose=True,
65
  llm=llm
66
  )
67
 
68
- def create_tasks(self, space_system_description: str) -> List[Task]:
69
- architect_task = Task(
70
- description="""Analyze and refine the provided space system concept, ensuring:
71
- 1. Logical consistency and feasibility
72
- 2. Integration with existing space infrastructure
73
- 3. Improved clarity and technical accuracy""",
74
- expected_output="A refined version of the space system concept",
75
- agent=self.system_architect
 
 
 
76
  )
77
 
78
- mechanical_task = Task(
79
- description="""Enhance the structural and propulsion aspects described in the provided description, including:
80
- 1. Refining spin-launcher specifications
81
- 2. Optimizing payload stabilization and orbital insertion methods
82
- 3. Ensuring energy efficiency and mechanical reliability""",
83
- expected_output="Refined propulsion and structural details",
84
- agent=self.mechanical_engineer
 
85
  )
86
 
87
- aerospace_task = Task(
88
- description="""Evaluate and refine mission execution strategies based on the provided description, ensuring:
89
- 1. Practical feasibility of launch and docking operations
90
- 2. Safety enhancements and risk mitigation measures
91
- 3. Seamless operational procedures for post-docking activities""",
92
- expected_output="A refined mission feasibility and execution plan",
93
- agent=self.aerospace_manager
 
94
  )
95
 
96
- return [architect_task, mechanical_task, aerospace_task]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
- async def process_design(self, space_system_description: str) -> Generator[List[Dict], None, None]:
99
  try:
100
- self.initialize_agents(space_system_description)
101
- self.current_agent = "System Architect"
102
 
 
103
  yield [{
104
  "role": "assistant",
105
- "content": "Starting analysis and refinement of the space system...",
106
  "metadata": {"title": "πŸš€ Process Started"}
107
  }]
108
 
 
 
 
 
 
 
 
 
109
  crew = Crew(
110
- agents=[self.system_architect, self.mechanical_engineer, self.aerospace_manager],
111
- tasks=self.create_tasks(space_system_description),
112
- verbose=True
 
 
113
  )
114
 
115
  def run_crew():
116
  try:
117
  crew.kickoff()
118
  except Exception as e:
 
119
  self.message_queue.add_message({
120
  "role": "assistant",
121
  "content": f"An error occurred: {str(e)}",
@@ -128,31 +259,24 @@ class SpaceSystemCrew:
128
  while thread.is_alive() or not self.message_queue.message_queue.empty():
129
  messages = self.message_queue.get_messages()
130
  if messages:
 
131
  yield messages
132
  await asyncio.sleep(0.1)
133
 
134
- refined_messages = [msg["content"] for msg in self.message_queue.get_messages() if msg["role"] == "assistant"]
135
- if refined_messages:
136
- self.final_refined_text = "\n\n".join(refined_messages)
137
- print("Final Refined Space System Design:")
138
- print(self.final_refined_text)
139
- else:
140
- print("No refined text available.")
141
-
142
  except Exception as e:
 
143
  yield [{
144
  "role": "assistant",
145
  "content": f"An error occurred: {str(e)}",
146
  "metadata": {"title": "❌ Error"}
147
  }]
148
 
149
-
150
  def create_demo():
151
- space_crew = None
152
 
153
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
154
- gr.Markdown("# πŸš€ AI Space System Refinement Crew")
155
-
156
  openai_api_key = gr.Textbox(
157
  label='OpenAI API Key',
158
  type='password',
@@ -160,28 +284,67 @@ def create_demo():
160
  interactive=True
161
  )
162
 
163
- space_system_description = gr.Textbox(
164
- label="Space System Description",
165
- placeholder="Enter space system details...",
166
- lines=10,
167
- interactive=True
 
 
 
168
  )
169
 
170
- btn = gr.Button("Refine System", variant="primary")
 
 
 
 
 
 
 
171
 
172
- async def process_input(space_system_description, history, api_key):
173
- nonlocal space_crew
174
  if not api_key:
175
- yield [{"role": "assistant", "content": "Please provide an OpenAI API key."}]
 
 
 
 
 
 
176
  return
177
 
178
- if space_crew is None:
179
- space_crew = SpaceSystemCrew(api_key=api_key)
180
-
181
- async for messages in space_crew.process_design(space_system_description):
182
- yield messages
183
-
184
- btn.click(process_input, [space_system_description, openai_api_key], [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  return demo
187
 
 
7
  import threading
8
  import os
9
 
10
+ # (Optional) Example system summary text for reference
11
+ analysis_text = """
12
+ Stage 1: Ground-Based Spin-Up and Launch Initiation
13
+ β€’ Concept:
14
+ A large, energy‑efficient, electrically powered centrifuge is built on the ground. This β€œspin launcher” uses renewable energy (for example, solar‑assisted electricity) to accelerate a specially designed payload assembly along a rotating arm or in a long circular tunnel.
15
+ β€’ Benefits:
16
+ Because most of the kinetic energy is imparted mechanically (rather than via chemical propellant), the system drastically reduces the need for traditional, polluting rocket propellants. This stage is also relatively low‑cost because the β€œengine” is essentially an electromagnetic drive rather than a rocket motor.
17
+ Stage 2: Controlled Payload Release and Orbital Injection
18
+ β€’ Concept:
19
+ At a pre‑calculated high tangential velocity, the payload is released from the spin launcher. A very short, minimal‑burn liquid or electric thruster (if needed) β€œtunes” the trajectory so that the payload enters a stable, low‑Earth orbit.
20
+ β€’ Benefits:
21
+ The primary acceleration is mechanical, so only a tiny amount of propellant is required for orbital insertion. This greatly cuts both cost and the environmental impact typically associated with rocket launches.
22
+ Stage 3: Autonomous On-Orbit Stabilization and Despinning
23
+ β€’ Concept:
24
+ Once in orbit, the payload’s onboard guidance and control systems (such as small reaction control thrusters or a yo-yo de-spin mechanism) despin and stabilize the payload. Integrated sensors and attitude-control software adjust the payload’s orientation and gently circularize the orbit.
25
+ β€’ Benefits:
26
+ Autonomous stabilization minimizes additional propellant use and prepares the payload for a safe, predictable rendezvous. The controlled despinning ensures that the payload’s docking adapter remains in the proper orientation for subsequent attachment.
27
+ Stage 4: Rendezvous and Docking with the Manned Vehicle
28
+ β€’ Concept:
29
+ A separately launched or pre‑positioned manned spacecraft (or space station) maneuvers to intercept the payload. The payload is equipped with a dedicated docking adapter (for instance, a magnetic or mechanical latch system engineered for high‑precision contact under low‑g conditions).
30
+ β€’ Benefits:
31
+ This phase uses conventional low‑delta‑V maneuvers that are far less expensive than a full chemical orbital insertion burn. The docking system is designed to absorb minor mismatches in velocity or attitude, allowing the crew to safely β€œhook on” to the payload. This minimizes extra propellant usage during the rendezvous phase.
32
+ Stage 5: Integrated Mission Operations and Continued Space Activity
33
+ β€’ Concept:
34
+ Once docked, the combined systemβ€”the manned vehicle with the attached spin-delivered payloadβ€”continues its mission. The payload might provide additional resources (such as extra fuel, scientific instruments, or habitat modules) that augment the manned vehicle’s capabilities.
35
+ β€’ Benefits:
36
+ With the payload permanently attached, mission operations (such as orbital adjustments, inter-station transfers, or even on-orbit assembly of larger structures) proceed with enhanced capabilities. The system’s reliance on mechanical acceleration for the bulk of the launch cut both launch costs and the environmental footprint, leaving only minor orbital maneuvers to be performed with conventional thrusters.
37
+ Summary
38
+ This five-stage system marries a ground-based spin acceleration concept with in-space docking and integration to achieve a β€œpropellant-light” method for delivering payloads into orbit. By using a spin launcher to achieve high velocity on the ground (Stage 1) and minimizing onboard chemical propellant (Stage 2), the payload is inserted into orbit economically and with reduced environmental impact. On-orbit stabilization (Stage 3) prepares it for rendezvous with a manned vehicle (Stage 4), after which the combined system carries out the mission (Stage 5).
39
+ """
40
+
41
+ # The provided summary can be input by the user via the Gradio interface.
42
+
43
  class AgentMessageQueue:
44
  def __init__(self):
45
  self.message_queue = queue.Queue()
46
  self.last_agent = None
47
 
48
  def add_message(self, message: Dict):
49
+ print(f"Adding message to queue: {message}") # Debug print
50
  self.message_queue.put(message)
51
 
52
  def get_messages(self) -> List[Dict]:
 
55
  messages.append(self.message_queue.get())
56
  return messages
57
 
58
+ class LaunchSystemCrew:
59
  def __init__(self, api_key: str = None):
60
  self.api_key = api_key
61
  self.message_queue = AgentMessageQueue()
62
+ self.analyst = None
63
+ self.engineer = None
64
+ self.reviewer = None
65
  self.current_agent = None
66
+ self.final_design = None
67
 
68
+ def initialize_agents(self, system_summary: str):
69
  if not self.api_key:
70
  raise ValueError("OpenAI API key is required")
 
71
  os.environ["OPENAI_API_KEY"] = self.api_key
72
  llm = ChatOpenAI(temperature=0.7, model="gpt-4")
73
 
74
+ # Agent 1: System Analyst – reviews and critiques the current design
75
+ self.analyst = Agent(
76
+ role="System Analyst",
77
+ goal=f"Analyze the provided space launch system summary and identify strengths, weaknesses, technical challenges, and areas for improvement.",
78
+ backstory="Expert systems analyst with a background in aerospace engineering and space systems design.",
79
  allow_delegation=False,
80
  verbose=True,
81
  llm=llm
82
  )
83
 
84
+ # Agent 2: Design Engineer – proposes technical refinements based on the analysis
85
+ self.engineer = Agent(
86
+ role="Design Engineer",
87
+ goal=f"Propose detailed technical refinements to improve the space launch system based on the analysis provided.",
88
+ backstory="Skilled design engineer with expertise in aerospace system design and optimization.",
89
  allow_delegation=False,
90
  verbose=True,
91
  llm=llm
92
  )
93
 
94
+ # Agent 3: Review Engineer – reviews and finalizes the refined design
95
+ self.reviewer = Agent(
96
+ role="Review Engineer",
97
+ goal="Critically review the proposed design refinements, ensuring technical feasibility, safety, and integration of the system.",
98
+ backstory="Experienced review engineer with a critical eye for technical details and system integration.",
99
  allow_delegation=False,
100
  verbose=True,
101
  llm=llm
102
  )
103
 
104
+ def create_tasks(self, system_summary: str) -> List[Task]:
105
+ analyst_task = Task(
106
+ description=f"""Analyze the provided space launch system summary:
107
+ 1. Identify the system's strengths and weaknesses.
108
+ 2. Highlight any technical challenges or potential risks.
109
+ 3. Suggest preliminary areas for improvement.
110
+ Include detailed explanations and any relevant technical insights.
111
+ System Summary:
112
+ {system_summary}""",
113
+ expected_output="A detailed analysis report including insights and recommendations.",
114
+ agent=self.analyst
115
  )
116
 
117
+ engineer_task = Task(
118
+ description="""Based on the analysis:
119
+ 1. Propose concrete design refinements and modifications.
120
+ 2. Provide technical justifications for each recommendation.
121
+ 3. Suggest improvements that enhance performance, safety, and cost-effectiveness.
122
+ Detail any engineering trade-offs or considerations.""",
123
+ expected_output="A refined design proposal with detailed technical recommendations.",
124
+ agent=self.engineer
125
  )
126
 
127
+ reviewer_task = Task(
128
+ description="""Review the proposed design refinements:
129
+ 1. Evaluate the proposals for technical feasibility and system integration.
130
+ 2. Identify any potential issues or further improvements.
131
+ 3. Summarize the final, refined space launch system design.
132
+ Ensure the final summary meets high engineering standards.""",
133
+ expected_output="A final refined system summary ready for further development or implementation.",
134
+ agent=self.reviewer
135
  )
136
 
137
+ return [analyst_task, engineer_task, reviewer_task]
138
+
139
+ async def process_system(self, system_summary: str) -> Generator[List[Dict], None, None]:
140
+ def add_agent_messages(agent_name: str, tasks: str, emoji: str = "πŸ€–"):
141
+ # Add agent header
142
+ self.message_queue.add_message({
143
+ "role": "assistant",
144
+ "content": agent_name,
145
+ "metadata": {"title": f"{emoji} {agent_name}"}
146
+ })
147
+
148
+ # Add task description
149
+ self.message_queue.add_message({
150
+ "role": "assistant",
151
+ "content": tasks,
152
+ "metadata": {"title": f"πŸ“‹ Task for {agent_name}"}
153
+ })
154
+
155
+ def setup_next_agent(current_agent: str) -> None:
156
+ agent_sequence = {
157
+ "System Analyst": ("Design Engineer",
158
+ """Based on the analysis, propose design refinements by:
159
+ 1. Outlining improvements and modifications.
160
+ 2. Providing technical justifications for each recommendation.
161
+ 3. Ensuring enhanced performance, safety, and cost-effectiveness."""
162
+ ),
163
+ "Design Engineer": ("Review Engineer",
164
+ """Review the proposed design refinements by:
165
+ 1. Evaluating technical feasibility and integration.
166
+ 2. Identifying potential issues or additional improvements.
167
+ 3. Summarizing the final refined system design."""
168
+ )
169
+ }
170
+ if current_agent in agent_sequence:
171
+ next_agent, tasks = agent_sequence[current_agent]
172
+ self.current_agent = next_agent
173
+ add_agent_messages(next_agent, tasks)
174
+
175
+ def task_callback(task_output) -> None:
176
+ print(f"Task callback received: {task_output}") # Debug print
177
+
178
+ # Extract content from raw output
179
+ raw_output = task_output.raw
180
+ if "## Final Answer:" in raw_output:
181
+ content = raw_output.split("## Final Answer:")[1].strip()
182
+ else:
183
+ content = raw_output.strip()
184
+
185
+ # Handle the output based on the current agent
186
+ if self.current_agent == "Review Engineer":
187
+ self.message_queue.add_message({
188
+ "role": "assistant",
189
+ "content": "Final refined system design is ready!",
190
+ "metadata": {"title": "πŸ“ Final Design"}
191
+ })
192
+
193
+ # Optionally reformat markdown if needed
194
+ formatted_content = content.replace("\n#", "\n\n#")
195
+ formatted_content = formatted_content.replace("\n-", "\n\n-")
196
+ formatted_content = formatted_content.replace("\n*", "\n\n*")
197
+ formatted_content = formatted_content.replace("\n1.", "\n\n1.")
198
+ formatted_content = formatted_content.replace("\n\n\n", "\n\n")
199
+
200
+ self.message_queue.add_message({
201
+ "role": "assistant",
202
+ "content": formatted_content
203
+ })
204
+ else:
205
+ self.message_queue.add_message({
206
+ "role": "assistant",
207
+ "content": content,
208
+ "metadata": {"title": f"✨ Output from {self.current_agent}"}
209
+ })
210
+ # Set up the next agent in the sequence
211
+ setup_next_agent(self.current_agent)
212
+
213
+ def step_callback(output: Any) -> None:
214
+ print(f"Step callback received: {output}") # Debug print
215
+ # Currently used only for logging purposes.
216
+ pass
217
 
 
218
  try:
219
+ self.initialize_agents(system_summary)
220
+ self.current_agent = "System Analyst"
221
 
222
+ # Start the process
223
  yield [{
224
  "role": "assistant",
225
+ "content": "Starting analysis and refinement of your space launch system...",
226
  "metadata": {"title": "πŸš€ Process Started"}
227
  }]
228
 
229
+ # Initialize first agent with their task instructions
230
+ add_agent_messages("System Analyst",
231
+ """Analyze the provided space launch system summary by:
232
+ 1. Identifying strengths, weaknesses, and technical challenges.
233
+ 2. Suggesting preliminary areas for improvement.
234
+ Review the summary carefully before proceeding."""
235
+ )
236
+
237
  crew = Crew(
238
+ agents=[self.analyst, self.engineer, self.reviewer],
239
+ tasks=self.create_tasks(system_summary),
240
+ verbose=True,
241
+ step_callback=step_callback,
242
+ task_callback=task_callback
243
  )
244
 
245
  def run_crew():
246
  try:
247
  crew.kickoff()
248
  except Exception as e:
249
+ print(f"Error in crew execution: {str(e)}") # Debug print
250
  self.message_queue.add_message({
251
  "role": "assistant",
252
  "content": f"An error occurred: {str(e)}",
 
259
  while thread.is_alive() or not self.message_queue.message_queue.empty():
260
  messages = self.message_queue.get_messages()
261
  if messages:
262
+ print(f"Yielding messages: {messages}") # Debug print
263
  yield messages
264
  await asyncio.sleep(0.1)
265
 
 
 
 
 
 
 
 
 
266
  except Exception as e:
267
+ print(f"Error in process_system: {str(e)}") # Debug print
268
  yield [{
269
  "role": "assistant",
270
  "content": f"An error occurred: {str(e)}",
271
  "metadata": {"title": "❌ Error"}
272
  }]
273
 
 
274
  def create_demo():
275
+ launch_crew = None
276
 
277
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
278
+ gr.Markdown("# πŸš€ Space Launch System Analysis and Refinement Crew")
279
+
280
  openai_api_key = gr.Textbox(
281
  label='OpenAI API Key',
282
  type='password',
 
284
  interactive=True
285
  )
286
 
287
+ chatbot = gr.Chatbot(
288
+ label="Refinement Process",
289
+ height=700,
290
+ type="messages",
291
+ show_label=True,
292
+ visible=False,
293
+ avatar_images=(None, "https://avatars.githubusercontent.com/u/170677839?v=4"),
294
+ render_markdown=True
295
  )
296
 
297
+ with gr.Row(equal_height=True):
298
+ system_summary = gr.Textbox(
299
+ label="System Summary",
300
+ placeholder="Enter the space launch system summary...",
301
+ scale=4,
302
+ visible=False
303
+ )
304
+ btn = gr.Button("Refine System Design", variant="primary", scale=1, visible=False)
305
 
306
+ async def process_input(system_summary, history, api_key):
307
+ nonlocal launch_crew
308
  if not api_key:
309
+ history = history or []
310
+ history.append({
311
+ "role": "assistant",
312
+ "content": "Please provide an OpenAI API key.",
313
+ "metadata": {"title": "❌ Error"}
314
+ })
315
+ yield history
316
  return
317
 
318
+ if launch_crew is None:
319
+ launch_crew = LaunchSystemCrew(api_key=api_key)
320
+
321
+ history = history or []
322
+ history.append({"role": "user", "content": f"Analyze and refine the following space launch system summary:\n\n{system_summary}"})
323
+ yield history
324
+
325
+ try:
326
+ async for messages in launch_crew.process_system(system_summary):
327
+ history.extend(messages)
328
+ yield history
329
+ except Exception as e:
330
+ history.append({
331
+ "role": "assistant",
332
+ "content": f"An error occurred: {str(e)}",
333
+ "metadata": {"title": "❌ Error"}
334
+ })
335
+ yield history
336
+
337
+ def show_interface():
338
+ return {
339
+ openai_api_key: gr.Textbox(visible=False),
340
+ chatbot: gr.Chatbot(visible=True),
341
+ system_summary: gr.Textbox(visible=True),
342
+ btn: gr.Button(visible=True)
343
+ }
344
+
345
+ openai_api_key.submit(show_interface, None, [openai_api_key, chatbot, system_summary, btn])
346
+ btn.click(process_input, [system_summary, chatbot, openai_api_key], [chatbot])
347
+ system_summary.submit(process_input, [system_summary, chatbot, openai_api_key], [chatbot])
348
 
349
  return demo
350