Cascade Bot commited on
Commit
6435f9a
·
1 Parent(s): 2443dcb

refactor: update chat interface initialization

Browse files

- Moved async initialization to background tasks
- Fixed event loop issues
- Integrated FastAPI routes into ChatInterface
- Removed duplicate VentureUI class
- Improved error handling and logging

Files changed (1) hide show
  1. app.py +241 -230
app.py CHANGED
@@ -88,35 +88,250 @@ def check_network(max_attempts=3):
88
  return False
89
 
90
  class ChatInterface:
 
 
91
  def __init__(self):
 
92
  # Check network connectivity
93
  if not check_network():
94
- logger.warning("Network connectivity issues detected - continuing with degraded functionality")
95
-
96
- # Initialize core components with consistent configuration
97
- config = {
98
- "min_confidence": 0.7,
99
- "parallel_threshold": 3,
100
- "learning_rate": 0.1,
101
- "strategy_weights": {
102
- "LOCAL_LLM": 0.8,
103
- "CHAIN_OF_THOUGHT": 0.6,
104
- "TREE_OF_THOUGHTS": 0.5,
105
- "META_LEARNING": 0.4
106
- }
107
- }
108
-
109
- self.orchestrator = AgentOrchestrator(config)
110
- self.agentic_system = AgenticSystem(config)
111
  self.team_manager = TeamManager(self.orchestrator)
112
- self.chat_history = []
113
- self.active_objectives = {}
114
 
115
- # Set up network session
116
- self.session = setup_requests_session()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- # Initialize teams
119
- asyncio.run(self.team_manager.initialize_team_agents())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
  async def process_message(
122
  self,
@@ -174,7 +389,7 @@ class ChatInterface:
174
  """Analyze user message intent with error handling."""
175
  try:
176
  # Use reasoning engine to analyze intent
177
- analysis = await self.orchestrator.reasoning_engine.reason(
178
  query=message,
179
  context={
180
  "chat_history": self.chat_history,
@@ -256,7 +471,7 @@ class ChatInterface:
256
  """Handle general chat interactions with error recovery."""
257
  try:
258
  # Use reasoning engine for response generation
259
- response = await self.orchestrator.reasoning_engine.reason(
260
  query=message,
261
  context={
262
  "chat_history": self.chat_history,
@@ -408,152 +623,10 @@ class ChatInterface:
408
  logger.error(f"Error formatting status: {str(e)}")
409
  return "Error formatting status information."
410
 
411
- class VentureUI:
412
- def __init__(self, app):
413
- self.app = app
414
-
415
- def create_interface(self):
416
- """Create the Gradio interface."""
417
- with gr.Blocks(
418
- theme=gr.themes.Soft(),
419
- analytics_enabled=False,
420
- title="Advanced Agentic System"
421
- ) as interface:
422
- # Verify Gradio version
423
- gr.Markdown(f"""
424
- # Advanced Agentic System Chat Interface v{gr.__version__}
425
-
426
- Chat with our autonomous agent teams:
427
- - Team A: Coders (App/Software Developers)
428
- - Team B: Business (Entrepreneurs)
429
- - Team C: Research (Deep Online Research)
430
- - Team D: Crypto & Sports Trading
431
-
432
- You can:
433
- 1. Ask questions
434
- 2. Create new objectives
435
- 3. Check status of teams and objectives
436
- 4. Get insights and recommendations
437
- """)
438
-
439
- chatbot = gr.Chatbot(
440
- label="Chat History",
441
- height=400,
442
- bubble_full_width=False,
443
- show_copy_button=True,
444
- render_markdown=True
445
- )
446
-
447
- with gr.Row():
448
- msg = gr.Textbox(
449
- label="Message",
450
- placeholder="Chat with the Agentic System...",
451
- lines=2,
452
- scale=9,
453
- autofocus=True,
454
- container=True
455
- )
456
- submit = gr.Button(
457
- "Send",
458
- scale=1,
459
- variant="primary"
460
- )
461
-
462
- with gr.Row():
463
- clear = gr.ClearButton(
464
- [msg, chatbot],
465
- value="Clear Chat",
466
- variant="secondary",
467
- scale=1
468
- )
469
- retry = gr.Button(
470
- "Retry Last",
471
- variant="secondary",
472
- scale=1
473
- )
474
-
475
- async def respond(message, history):
476
- try:
477
- # Convert history to the format expected by process_message
478
- history_list = [[x, y] for x, y in history] if history else []
479
- response, history_list = await self.app(message, history_list)
480
-
481
- # Update history
482
- if history is None:
483
- history = []
484
- history.append((message, response))
485
-
486
- return "", history
487
- except Exception as e:
488
- logger.error(f"Error in chat response: {str(e)}")
489
- error_msg = "I apologize, but I encountered an error. Please try again."
490
-
491
- if history is None:
492
- history = []
493
- history.append((message, error_msg))
494
-
495
- return "", history
496
-
497
- async def retry_last(history):
498
- if not history:
499
- return history
500
- last_user_msg = history[-1][0]
501
- history = history[:-1] # Remove last exchange
502
- return await respond(last_user_msg, history)
503
-
504
- msg.submit(
505
- respond,
506
- [msg, chatbot],
507
- [msg, chatbot],
508
- api_name="chat"
509
- ).then(
510
- lambda: gr.update(interactive=True),
511
- None,
512
- [msg, submit],
513
- queue=False
514
- )
515
-
516
- submit.click(
517
- respond,
518
- [msg, chatbot],
519
- [msg, chatbot],
520
- api_name="submit"
521
- ).then(
522
- lambda: gr.update(interactive=True),
523
- None,
524
- [msg, submit],
525
- queue=False
526
- )
527
-
528
- retry.click(
529
- retry_last,
530
- [chatbot],
531
- [chatbot],
532
- api_name="retry"
533
- )
534
-
535
- # Event handlers for better UX
536
- msg.change(lambda x: gr.update(interactive=bool(x.strip())), [msg], [submit])
537
-
538
- # Add example inputs
539
- gr.Examples(
540
- examples=[
541
- "What can Team A (Coders) help me with?",
542
- "Create a new objective: Analyze market trends",
543
- "What's the status of all teams?",
544
- "Give me insights about recent developments"
545
- ],
546
- inputs=msg,
547
- label="Example Queries"
548
- )
549
-
550
- return interface
551
-
552
  def create_chat_interface() -> gr.Blocks:
553
  """Create Gradio chat interface."""
554
  chat = ChatInterface()
555
- ui = VentureUI(chat.process_message)
556
- return ui.create_interface()
557
 
558
  # Initialize FastAPI
559
  app = FastAPI(
@@ -562,68 +635,6 @@ app = FastAPI(
562
  version="1.0.0"
563
  )
564
 
565
- # Add CORS middleware
566
- app.add_middleware(
567
- CORSMiddleware,
568
- allow_origins=["*"],
569
- allow_credentials=True,
570
- allow_methods=["*"],
571
- allow_headers=["*"],
572
- )
573
-
574
- # Include OpenAI-compatible routes
575
- from api.openai_compatible import OpenAICompatibleAPI
576
- reasoning_engine = UnifiedReasoningEngine()
577
- openai_api = OpenAICompatibleAPI(reasoning_engine)
578
- app.include_router(openai_api.router, tags=["OpenAI Compatible"])
579
-
580
- # Original API routes
581
- @app.get("/api/health")
582
- async def health_check():
583
- """Health check endpoint."""
584
- return {
585
- "status": "healthy",
586
- "version": "1.0.0",
587
- "endpoints": {
588
- "openai_compatible": "/v1/chat/completions",
589
- "venture": "/api/venture",
590
- "ui": "/"
591
- }
592
- }
593
-
594
- @app.post("/api/reason")
595
- async def reason(query: str, context: Optional[Dict[str, Any]] = None):
596
- """Reasoning endpoint."""
597
- try:
598
- result = await reasoning_engine.reason(query, context or {})
599
- return result
600
- except Exception as e:
601
- logger.error(f"Reasoning error: {e}")
602
- raise HTTPException(status_code=500, detail=str(e))
603
-
604
- @app.post("/api/venture/analyze")
605
- async def analyze_venture(
606
- venture_type: str,
607
- description: str,
608
- metrics: Optional[Dict[str, Any]] = None
609
- ):
610
- """Venture analysis endpoint."""
611
- try:
612
- result = await VentureAPI(reasoning_engine).analyze_venture(
613
- venture_type=venture_type,
614
- description=description,
615
- metrics=metrics or {}
616
- )
617
- return result
618
- except Exception as e:
619
- logger.error(f"Analysis error: {e}")
620
- raise HTTPException(status_code=500, detail=str(e))
621
-
622
- @app.get("/api/venture/types")
623
- async def get_venture_types():
624
- """Get available venture types."""
625
- return VentureAPI(reasoning_engine).get_venture_types()
626
-
627
  # Create Gradio interface
628
  interface = create_chat_interface()
629
 
 
88
  return False
89
 
90
  class ChatInterface:
91
+ """Chat interface for interacting with the agentic system."""
92
+
93
  def __init__(self):
94
+ """Initialize the chat interface."""
95
  # Check network connectivity
96
  if not check_network():
97
+ raise ConnectionError("No network connectivity. Please check your connection.")
98
+
99
+ # Initialize core components
100
+ self.orchestrator = AgentOrchestrator()
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  self.team_manager = TeamManager(self.orchestrator)
 
 
102
 
103
+ # Initialize reasoning engine
104
+ self.reasoning_engine = UnifiedReasoningEngine()
105
+
106
+ # Set up the agentic system
107
+ self.agentic_system = AgenticSystem(
108
+ orchestrator=self.orchestrator,
109
+ team_manager=self.team_manager,
110
+ reasoning_engine=self.reasoning_engine
111
+ )
112
+
113
+ # Initialize FastAPI app
114
+ self.app = FastAPI()
115
+ self.setup_cors()
116
+ self.setup_routes()
117
+
118
+ # Create Gradio interface
119
+ self.interface = self.create_interface()
120
+
121
+ # Launch background tasks
122
+ self.background_tasks = []
123
+ self.launch_background_tasks()
124
+
125
+ async def initialize(self):
126
+ """Initialize async components."""
127
+ await self.team_manager.initialize_team_agents()
128
 
129
+ def launch_background_tasks(self):
130
+ """Launch background tasks."""
131
+ loop = asyncio.get_event_loop()
132
+ self.background_tasks.append(
133
+ loop.create_task(self.initialize())
134
+ )
135
+
136
+ def setup_cors(self):
137
+ """Set up CORS middleware."""
138
+ self.app.add_middleware(
139
+ CORSMiddleware,
140
+ allow_origins=["*"],
141
+ allow_credentials=True,
142
+ allow_methods=["*"],
143
+ allow_headers=["*"],
144
+ )
145
+
146
+ def setup_routes(self):
147
+ """Set up API routes."""
148
+ # Include OpenAI-compatible routes
149
+ openai_api = OpenAICompatibleAPI(self.reasoning_engine)
150
+ self.app.include_router(openai_api.router, tags=["OpenAI Compatible"])
151
+
152
+ # Original API routes
153
+ @self.app.get("/api/health")
154
+ async def health_check():
155
+ """Health check endpoint."""
156
+ return {
157
+ "status": "healthy",
158
+ "version": "1.0.0",
159
+ "endpoints": {
160
+ "openai_compatible": "/v1/chat/completions",
161
+ "venture": "/api/venture",
162
+ "ui": "/"
163
+ }
164
+ }
165
+
166
+ @self.app.post("/api/reason")
167
+ async def reason(query: str, context: Optional[Dict[str, Any]] = None):
168
+ """Reasoning endpoint."""
169
+ try:
170
+ result = await self.reasoning_engine.reason(query, context or {})
171
+ return result
172
+ except Exception as e:
173
+ logger.error(f"Reasoning error: {e}")
174
+ raise HTTPException(status_code=500, detail=str(e))
175
+
176
+ @self.app.post("/api/venture/analyze")
177
+ async def analyze_venture(
178
+ venture_type: str,
179
+ description: str,
180
+ metrics: Optional[Dict[str, Any]] = None
181
+ ):
182
+ """Venture analysis endpoint."""
183
+ try:
184
+ result = await VentureAPI(self.reasoning_engine).analyze_venture(
185
+ venture_type=venture_type,
186
+ description=description,
187
+ metrics=metrics or {}
188
+ )
189
+ return result
190
+ except Exception as e:
191
+ logger.error(f"Analysis error: {e}")
192
+ raise HTTPException(status_code=500, detail=str(e))
193
+
194
+ @self.app.get("/api/venture/types")
195
+ async def get_venture_types():
196
+ """Get available venture types."""
197
+ return VentureAPI(self.reasoning_engine).get_venture_types()
198
+
199
+ def create_interface(self):
200
+ """Create the Gradio interface."""
201
+ with gr.Blocks(
202
+ theme=gr.themes.Soft(),
203
+ analytics_enabled=False,
204
+ title="Advanced Agentic System"
205
+ ) as interface:
206
+ # Verify Gradio version
207
+ gr.Markdown(f"""
208
+ # Advanced Agentic System Chat Interface v{gr.__version__}
209
+
210
+ Chat with our autonomous agent teams:
211
+ - Team A: Coders (App/Software Developers)
212
+ - Team B: Business (Entrepreneurs)
213
+ - Team C: Research (Deep Online Research)
214
+ - Team D: Crypto & Sports Trading
215
+
216
+ You can:
217
+ 1. Ask questions
218
+ 2. Create new objectives
219
+ 3. Check status of teams and objectives
220
+ 4. Get insights and recommendations
221
+ """)
222
+
223
+ chatbot = gr.Chatbot(
224
+ label="Chat History",
225
+ height=400,
226
+ bubble_full_width=False,
227
+ show_copy_button=True,
228
+ render_markdown=True
229
+ )
230
+
231
+ with gr.Row():
232
+ msg = gr.Textbox(
233
+ label="Message",
234
+ placeholder="Chat with the Agentic System...",
235
+ lines=2,
236
+ scale=9,
237
+ autofocus=True,
238
+ container=True
239
+ )
240
+ submit = gr.Button(
241
+ "Send",
242
+ scale=1,
243
+ variant="primary"
244
+ )
245
+
246
+ with gr.Row():
247
+ clear = gr.ClearButton(
248
+ [msg, chatbot],
249
+ value="Clear Chat",
250
+ variant="secondary",
251
+ scale=1
252
+ )
253
+ retry = gr.Button(
254
+ "Retry Last",
255
+ variant="secondary",
256
+ scale=1
257
+ )
258
+
259
+ async def respond(message, history):
260
+ try:
261
+ # Convert history to the format expected by process_message
262
+ history_list = [[x, y] for x, y in history] if history else []
263
+ response, history_list = await self.process_message(message, history_list)
264
+
265
+ # Update history
266
+ if history is None:
267
+ history = []
268
+ history.append((message, response))
269
+
270
+ return "", history
271
+ except Exception as e:
272
+ logger.error(f"Error in chat response: {str(e)}")
273
+ error_msg = "I apologize, but I encountered an error. Please try again."
274
+
275
+ if history is None:
276
+ history = []
277
+ history.append((message, error_msg))
278
+
279
+ return "", history
280
+
281
+ async def retry_last(history):
282
+ if not history:
283
+ return history
284
+ last_user_msg = history[-1][0]
285
+ history = history[:-1] # Remove last exchange
286
+ return await respond(last_user_msg, history)
287
+
288
+ msg.submit(
289
+ respond,
290
+ [msg, chatbot],
291
+ [msg, chatbot],
292
+ api_name="chat"
293
+ ).then(
294
+ lambda: gr.update(interactive=True),
295
+ None,
296
+ [msg, submit],
297
+ queue=False
298
+ )
299
+
300
+ submit.click(
301
+ respond,
302
+ [msg, chatbot],
303
+ [msg, chatbot],
304
+ api_name="submit"
305
+ ).then(
306
+ lambda: gr.update(interactive=True),
307
+ None,
308
+ [msg, submit],
309
+ queue=False
310
+ )
311
+
312
+ retry.click(
313
+ retry_last,
314
+ [chatbot],
315
+ [chatbot],
316
+ api_name="retry"
317
+ )
318
+
319
+ # Event handlers for better UX
320
+ msg.change(lambda x: gr.update(interactive=bool(x.strip())), [msg], [submit])
321
+
322
+ # Add example inputs
323
+ gr.Examples(
324
+ examples=[
325
+ "What can Team A (Coders) help me with?",
326
+ "Create a new objective: Analyze market trends",
327
+ "What's the status of all teams?",
328
+ "Give me insights about recent developments"
329
+ ],
330
+ inputs=msg,
331
+ label="Example Queries"
332
+ )
333
+
334
+ return interface
335
 
336
  async def process_message(
337
  self,
 
389
  """Analyze user message intent with error handling."""
390
  try:
391
  # Use reasoning engine to analyze intent
392
+ analysis = await self.reasoning_engine.reason(
393
  query=message,
394
  context={
395
  "chat_history": self.chat_history,
 
471
  """Handle general chat interactions with error recovery."""
472
  try:
473
  # Use reasoning engine for response generation
474
+ response = await self.reasoning_engine.reason(
475
  query=message,
476
  context={
477
  "chat_history": self.chat_history,
 
623
  logger.error(f"Error formatting status: {str(e)}")
624
  return "Error formatting status information."
625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
626
  def create_chat_interface() -> gr.Blocks:
627
  """Create Gradio chat interface."""
628
  chat = ChatInterface()
629
+ return chat.interface
 
630
 
631
  # Initialize FastAPI
632
  app = FastAPI(
 
635
  version="1.0.0"
636
  )
637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  # Create Gradio interface
639
  interface = create_chat_interface()
640