sam133 commited on
Commit
23a57ae
Β·
1 Parent(s): 9bd5e83

BREAKTHROUGH: Implement working MCP pattern with ChatInterface (no complex components)

Browse files
Files changed (1) hide show
  1. app.py +79 -137
app.py CHANGED
@@ -1,150 +1,92 @@
1
  #!/usr/bin/env python3
2
  """
3
- Agent2Robot - Debug Step 8: Remove Explicit Value Parameters (Working Repo Pattern)
 
4
  """
5
 
 
 
6
  import gradio as gr
7
 
8
- # Step 8: Test removing explicit value parameters (following working repo pattern)
9
- with gr.Blocks(
10
- title="πŸ€–πŸš Agent2Robot - MCP Hackathon 2024",
11
- theme=gr.themes.Soft(),
12
- css="""
13
- .gradio-button.primary {
14
- background: linear-gradient(90deg, #667eea 0%, #764ba2 100%) !important;
15
- border: none !important;
16
- border-radius: 25px !important;
17
- }
18
- .current-specs {
19
- background: #fff3cd !important;
20
- border: 2px solid #ffc107 !important;
21
- border-radius: 8px !important;
22
- }
23
- .final-specs {
24
- background: #d1edff !important;
25
- border: 2px solid #0066cc !important;
26
- border-radius: 8px !important;
27
- }
28
- """
29
- ) as demo:
30
-
31
- # HTML header component
32
- gr.HTML("""
33
- <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
34
- <h1>πŸ€–πŸš Agent2Robot Design Assistant</h1>
35
- <p>Step 8: Remove Explicit Value Parameters (Working Repo Pattern)</p>
36
- <p><strong>MCP Hackathon 2024 Submission</strong></p>
37
- </div>
38
- """)
39
 
40
- with gr.Row():
41
- with gr.Column():
42
- gr.Markdown("## Input Section")
43
-
44
- vehicle_type = gr.Dropdown(
45
- choices=["Robot", "Drone", "Autonomous Vehicle", "Robotic Arm"],
46
- label="πŸš€ Vehicle Type",
47
- value="Robot"
48
- )
49
-
50
- description = gr.Textbox(
51
- label="πŸ“ Design Requirements",
52
- lines=6,
53
- placeholder="Describe your requirements...",
54
- value="Design a robot for warehouse navigation",
55
- interactive=True,
56
- show_copy_button=True
57
- )
58
-
59
- generate_btn = gr.Button(
60
- "πŸš€ Generate Design",
61
- variant="primary",
62
- size="lg"
63
- )
64
-
65
- with gr.Column():
66
- gr.Markdown("## Output Section")
67
-
68
- process_log = gr.Textbox(
69
- label="Process Log",
70
- lines=10,
71
- interactive=False
72
- )
73
 
74
- # JSON components - CRITICAL CHANGE: Remove explicit value parameters
75
- with gr.Row():
76
- with gr.Column():
77
- gr.Markdown("### Current Specs (JSON)")
78
- current_specs_output = gr.JSON(
79
- label="Current Design",
80
- elem_classes=["current-specs"]
81
- # NO value parameter - let Gradio use default!
82
- )
83
 
84
- with gr.Column():
85
- gr.Markdown("### Final Specs (JSON)")
86
- final_specs_output = gr.JSON(
87
- label="Final Design",
88
- elem_classes=["final-specs"]
89
- # NO value parameter - let Gradio use default!
90
- )
91
-
92
- # File component - CRITICAL CHANGE: Remove explicit value parameter
93
- with gr.Row():
94
- with gr.Column():
95
- gr.Markdown("### Download Section")
96
-
97
- gr.HTML("""
98
- <div style="background: #e8f5e8; padding: 15px; border-radius: 10px; border: 2px solid #28a745; margin-bottom: 10px;">
99
- <h4 style="margin: 0; color: #155724;">🎯 Design Outputs</h4>
100
- <p style="margin: 5px 0 0 0; color: #155724;">Download final specifications</p>
101
- </div>
102
- """)
103
-
104
- download_file_output = gr.File(
105
- label="Download Specs",
106
- file_count="single",
107
- interactive=False,
108
- visible=False
109
- # NO value parameter - let Gradio use default!
110
- )
111
-
112
- # Generator function
113
- def test_generator(vehicle_type, description):
114
- """Simple test generator to verify function connection works"""
115
- import time
116
 
117
- steps = [
118
- f"πŸš€ Starting design for {vehicle_type}...",
119
- f"πŸ“ Processing: {description[:50]}...",
120
- "πŸ”„ Generating specifications...",
121
- "πŸ“Š Creating final design...",
122
- "βœ… Complete!"
123
- ]
124
 
125
- for i, step in enumerate(steps):
126
- time.sleep(0.5) # Simulate processing
127
-
128
- current_spec = {"step": i+1, "vehicle": vehicle_type} if i < 3 else None
129
- final_spec = {"vehicle_type": vehicle_type, "status": "completed"} if i == len(steps)-1 else {}
130
-
131
- yield [
132
- step, # process_log
133
- current_spec, # current_specs_output
134
- final_spec, # final_specs_output
135
- None # download_file_output
136
- ]
 
 
 
 
 
 
 
137
 
138
- # Connect the function to the button
139
- generate_btn.click(
140
- fn=test_generator,
141
- inputs=[vehicle_type, description],
142
- outputs=[
143
- process_log,
144
- current_specs_output,
145
- final_specs_output,
146
- download_file_output
147
- ]
148
- )
149
 
150
- demo.launch()
 
 
 
 
 
 
1
  #!/usr/bin/env python3
2
  """
3
+ Agent2Robot - MCP Hackathon 2024 Submission
4
+ Following Working MCP Client Pattern
5
  """
6
 
7
+ import os
8
+ import datetime
9
  import gradio as gr
10
 
11
+ # Try to import our modules - fallback to mock if not available
12
+ try:
13
+ from design_tools import VehicleDesigner
14
+ import main_orchestrator
15
+ MCP_AVAILABLE = True
16
+ except ImportError:
17
+ MCP_AVAILABLE = False
18
+ print("MCP modules not available - using mock mode")
19
+
20
+ # Current time for agent context
21
+ time = datetime.datetime.now().astimezone().isoformat()
22
+
23
+ SYSTEM_PROMPT = """You are an AI-powered vehicle design assistant specializing in robotics, drones, and autonomous vehicles.
24
+ You help users design and optimize vehicles through iterative processes including:
25
+ - Requirements analysis and specification generation
26
+ - Physics simulation and performance modeling
27
+ - Design optimization and validation
28
+ - Technical documentation and downloads
29
+
30
+ Be helpful, technical, and thorough in your responses.
31
+ Current time (ISO 8601): {time}"""
32
+
33
+ def agent_chat(message: str, history: list):
34
+ """Main chat function that processes user messages and returns responses"""
 
 
 
 
 
 
 
35
 
36
+ if not MCP_AVAILABLE:
37
+ # Mock response when MCP is not available
38
+ return f"πŸ€– **Agent2Robot Design Assistant**\n\n**Your Request:** {message}\n\n**Mock Response:**\nI would help you design a {message.lower()} vehicle with the following approach:\n\n1. **πŸ“‹ Requirements Analysis**\n - Parse your specifications\n - Identify key performance metrics\n\n2. **🎯 Design Generation**\n - Create initial specifications\n - Apply engineering constraints\n\n3. **πŸ“Š Simulation & Validation**\n - Run physics simulations\n - Optimize performance\n\n4. **πŸ“ Final Deliverables**\n - Complete technical specifications\n - Performance reports\n - Download packages\n\n*Note: MCP server integration will be available when properly configured.*"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Real MCP integration when available
41
+ try:
42
+ # Format message with system prompt and history
43
+ formatted_message = f"{SYSTEM_PROMPT.format(time=time)}\n"
44
+ formatted_message += "\n".join([f"{x['role']}: {x['content']}" for x in history])
45
+ formatted_message += f"\nUser Request: {message}"
 
 
 
46
 
47
+ # Process through main orchestrator
48
+ result = ""
49
+ for update in main_orchestrator.process_design_request("Robot", message):
50
+ if update.get("process_log"):
51
+ result += update["process_log"] + "\n"
52
+ if update.get("final_specs"):
53
+ result += f"\n**Final Specifications:**\n{update['final_specs']}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ return result if result else "Design process completed successfully!"
 
 
 
 
 
 
56
 
57
+ except Exception as e:
58
+ return f"🚨 **Error:** {str(e)}\n\nFalling back to mock mode. Please check MCP server configuration."
59
+
60
+ # Create the main interface following working pattern
61
+ chat_interface = gr.ChatInterface(
62
+ fn=agent_chat,
63
+ type="messages",
64
+ examples=[
65
+ "Design a warehouse robot for package delivery with 50kg payload capacity",
66
+ "Create a drone for aerial surveillance with 2-hour flight time",
67
+ "Design an autonomous vehicle for urban navigation",
68
+ "Build a robotic arm for precision manufacturing tasks"
69
+ ],
70
+ title="πŸ€–πŸš Agent2Robot - AI Vehicle Design Assistant",
71
+ description="""
72
+ **MCP Hackathon 2024 Submission**
73
+
74
+ AI-powered vehicle design assistant with real-time specification generation,
75
+ physics simulation, and optimization. Supports robots, drones, autonomous vehicles, and more.
76
 
77
+ **Features:**
78
+ β€’ 🎯 Intelligent requirements analysis
79
+ β€’ πŸ”„ Iterative design optimization
80
+ β€’ πŸ“Š Physics simulation and validation
81
+ β€’ πŸ“ Complete technical documentation
82
+ β€’ πŸ’Ύ Downloadable specifications
83
+ """,
84
+ theme=gr.themes.Soft()
85
+ )
 
 
86
 
87
+ # Main execution following working pattern
88
+ if __name__ == "__main__":
89
+ chat_interface.launch()
90
+ else:
91
+ # For HuggingFace Spaces automatic detection
92
+ demo = chat_interface