File size: 19,512 Bytes
1d75522
 
 
 
 
 
 
 
 
 
ccf96e3
2443dcb
1d75522
 
 
 
 
 
 
 
 
 
7cdc849
1d75522
a7a0958
1d75522
 
4e9058a
 
a7a0958
 
 
 
 
 
 
4439b52
1d75522
 
 
 
 
 
b4bc78c
1d75522
b4bc78c
 
 
 
1d75522
b4bc78c
 
1d75522
 
b4bc78c
 
 
 
 
 
 
 
1d75522
b4bc78c
 
 
 
 
 
 
 
1d75522
 
6435f9a
 
1d75522
6435f9a
1d75522
 
6435f9a
 
72416ea
 
 
 
 
 
 
 
 
 
 
 
1d75522
b4bc78c
 
 
 
72416ea
 
 
6435f9a
4439b52
6435f9a
 
72416ea
6435f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d75522
6435f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5901371
6435f9a
 
c855a5a
 
 
6435f9a
5901371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6435f9a
 
 
c855a5a
 
d2d63a6
c855a5a
 
 
6435f9a
 
 
 
d2d63a6
6435f9a
c855a5a
 
6435f9a
d2d63a6
6435f9a
677ea96
d2d63a6
 
 
6435f9a
5901371
6435f9a
 
b065baa
b4bc78c
6435f9a
5901371
 
 
b065baa
 
 
 
 
6435f9a
 
 
 
b065baa
 
 
 
6435f9a
 
5901371
6435f9a
 
b065baa
 
6435f9a
 
5901371
 
 
 
 
 
6435f9a
b4bc78c
6435f9a
b4bc78c
6435f9a
 
5901371
 
 
 
 
 
6435f9a
b4bc78c
6435f9a
b4bc78c
6435f9a
 
5901371
6435f9a
5901371
 
 
 
6435f9a
 
5901371
b4bc78c
5901371
 
 
 
b4bc78c
 
 
6435f9a
5901371
6435f9a
 
5901371
 
 
 
6435f9a
 
5901371
 
6435f9a
 
 
1d75522
 
 
 
b4bc78c
 
 
1d75522
b4bc78c
 
 
 
1d75522
 
 
b4bc78c
1d75522
 
b4bc78c
 
 
 
 
 
 
1d75522
b4bc78c
 
 
 
1d75522
b4bc78c
 
1d75522
 
 
 
 
4ac9be9
1d75522
 
 
 
 
 
 
4ac9be9
 
 
 
 
 
 
 
 
 
 
1d75522
 
b4bc78c
4ac9be9
1d75522
b4bc78c
 
1d75522
b4bc78c
 
 
 
 
 
 
 
 
1d75522
b4bc78c
 
1d75522
b4bc78c
1d75522
 
b4bc78c
 
1d75522
b4bc78c
1d75522
 
4439b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d75522
 
b4bc78c
 
1d75522
b4bc78c
 
1d75522
b4bc78c
 
1d75522
b4bc78c
 
1d75522
b4bc78c
 
1d75522
b4bc78c
 
 
 
 
 
1d75522
b4bc78c
 
 
 
 
 
1d75522
b4bc78c
1d75522
 
 
 
 
 
 
 
6435f9a
1d75522
 
 
b4bc78c
 
1d75522
 
 
 
 
 
 
 
 
 
c855a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
1d75522
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
"""
Advanced Agentic System Interface
-------------------------------
Provides a chat interface to interact with the autonomous agent teams:
- Team A: Coders (App/Software Developers)
- Team B: Business (Entrepreneurs)
- Team C: Research (Deep Online Research)
- Team D: Crypto & Sports Trading
"""

import os
import socket
import gradio as gr
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from typing import Dict, Any, List, Tuple, Optional
import logging
from pathlib import Path
import asyncio
from datetime import datetime
import json
import requests
from requests.adapters import HTTPAdapter, Retry
from dataclasses import dataclass

from agentic_system import AgenticSystem
from orchestrator import AgentOrchestrator
from team_management import TeamManager, TeamType
from reasoning import (
    UnifiedReasoningEngine,
    StrategyType,
    UnifiedResult
)
from api.openai_compatible import OpenAICompatibleAPI
from api.venture_api import VentureAPI
from api.groq_api import GroqAPI

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def setup_requests_session():
    """Set up requests session with retries."""
    session = requests.Session()
    retries = Retry(
        total=5,
        backoff_factor=0.1,
        status_forcelist=[500, 502, 503, 504]
    )
    session.mount('http://', HTTPAdapter(max_retries=retries))
    session.mount('https://', HTTPAdapter(max_retries=retries))
    return session

def check_network():
    """Check network connectivity."""
    try:
        # Try DNS resolution first
        socket.gethostbyname('huggingface.co')
        return True
    except socket.gaierror:
        logger.warning("DNS resolution failed")
    
    try:
        # Try HTTP request as backup
        session = setup_requests_session()
        response = session.get('https://huggingface.co', timeout=5)
        return response.status_code == 200
    except (requests.RequestException, socket.gaierror) as e:
        logger.warning(f"Network connectivity check failed: {e}")
        return False

class ChatInterface:
    """Chat interface for interacting with the agentic system."""
    
    def __init__(self):
        """Initialize the chat interface."""
        # Check network connectivity
        if not check_network():
            raise ConnectionError("No network connectivity. Please check your connection.")
            
        # Initialize core components with consistent configuration
        config = {
            "min_confidence": 0.7,
            "parallel_threshold": 3,
            "learning_rate": 0.1,
            "strategy_weights": {
                "LOCAL_LLM": 0.8,
                "CHAIN_OF_THOUGHT": 0.6,
                "TREE_OF_THOUGHTS": 0.5,
                "META_LEARNING": 0.4
            }
        }
        
        # Initialize chat state
        self.chat_history = []
        self.active_objectives = {}
        
        # Initialize components
        self.orchestrator = AgentOrchestrator(config)
        self.team_manager = TeamManager(self.orchestrator)
        self.reasoning_engine = UnifiedReasoningEngine()
        self.groq_api = GroqAPI()
        
        # Set up the agentic system
        self.agentic_system = AgenticSystem(config)
        
        # Initialize FastAPI app
        self.app = FastAPI()
        self.setup_cors()
        self.setup_routes()
        
        # Create Gradio interface
        self.interface = self.create_interface()
        
        # Launch background tasks
        self.background_tasks = []
        self.launch_background_tasks()
        
    async def initialize(self):
        """Initialize async components."""
        await self.team_manager.initialize_team_agents()
        
    def launch_background_tasks(self):
        """Launch background tasks."""
        loop = asyncio.get_event_loop()
        self.background_tasks.append(
            loop.create_task(self.initialize())
        )

    def setup_cors(self):
        """Set up CORS middleware."""
        self.app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    def setup_routes(self):
        """Set up API routes."""
        # Include OpenAI-compatible routes
        openai_api = OpenAICompatibleAPI(self.reasoning_engine)
        self.app.include_router(openai_api.router, tags=["OpenAI Compatible"])

        # Original API routes
        @self.app.get("/api/health")
        async def health_check():
            """Health check endpoint."""
            return {
                "status": "healthy",
                "version": "1.0.0",
                "endpoints": {
                    "openai_compatible": "/v1/chat/completions",
                    "venture": "/api/venture",
                    "ui": "/"
                }
            }

        @self.app.post("/api/reason")
        async def reason(query: str, context: Optional[Dict[str, Any]] = None):
            """Reasoning endpoint."""
            try:
                result = await self.reasoning_engine.reason(query, context or {})
                return result
            except Exception as e:
                logger.error(f"Reasoning error: {e}")
                raise HTTPException(status_code=500, detail=str(e))

        @self.app.post("/api/venture/analyze")
        async def analyze_venture(
            venture_type: str,
            description: str,
            metrics: Optional[Dict[str, Any]] = None
        ):
            """Venture analysis endpoint."""
            try:
                result = await VentureAPI(self.reasoning_engine).analyze_venture(
                    venture_type=venture_type,
                    description=description,
                    metrics=metrics or {}
                )
                return result
            except Exception as e:
                logger.error(f"Analysis error: {e}")
                raise HTTPException(status_code=500, detail=str(e))

        @self.app.get("/api/venture/types")
        async def get_venture_types():
            """Get available venture types."""
            return VentureAPI(self.reasoning_engine).get_venture_types()

    def create_interface(self) -> gr.Blocks:
        """Create the Gradio interface."""
        with gr.Blocks(
            title="Advanced Agentic System",
            css=None,  # Disable custom CSS
            theme=gr.themes.Soft(),  # Use built-in theme
        ) as interface:
            gr.Markdown("""
                # πŸ€– Advanced Agentic System Chat Interface
                
                Welcome to our AI-powered autonomous agent teams! Each team specializes in different domains:
                
                - πŸ’» **Team A: Coders** - Expert software developers and architects
                - πŸ’Ό **Team B: Business** - Strategic entrepreneurs and analysts
                - πŸ” **Team C: Research** - Deep online research specialists
                - πŸ“ˆ **Team D: Trading** - Crypto & sports trading experts
                
                You can:
                1. Ask questions about any domain
                2. Create new objectives for teams
                3. Check status of ongoing work
                4. Get insights and recommendations
                
                ---
            """)
            
            chatbot = gr.Chatbot(
                value=[],  # Initialize with empty list
                type="messages",  # Use OpenAI-style message format
                height=500,
                show_label=False,
                render_markdown=True,
                avatar_images=None,  # Disable avatars to prevent asset loading issues
            )
            
            with gr.Row():
                msg = gr.Textbox(
                    show_label=False,
                    placeholder="Chat with the Agentic System...",
                    container=False,
                    autofocus=True,
                )
                submit = gr.Button("Send πŸš€")
            
            with gr.Row():
                clear = gr.ClearButton([msg, chatbot], value="Clear")
                retry = gr.Button("Retry")
            
            async def respond(message, history):
                """Handle chat responses with proper formatting."""
                try:
                    # Convert history to the format expected by process_message
                    history_list = [[msg["content"] for msg in exchange] for exchange in history] if history else []
                    response = await self.process_message(message, history_list)
                    
                    # Format response for markdown rendering
                    formatted_response = response.replace('```', '\n```\n')
                    
                    # Update history with the new message format
                    return "", history + [
                        {"role": "user", "content": message},
                        {"role": "assistant", "content": formatted_response}
                    ]
                except Exception as e:
                    logger.error(f"Error in chat response: {str(e)}")
                    error_msg = "I apologize, but I encountered an error. Please try again."
                    
                    return "", history + [
                        {"role": "user", "content": message},
                        {"role": "assistant", "content": error_msg}
                    ]

            async def retry_last(history):
                """Retry the last message with proper formatting."""
                if not history:
                    return history
                last_user_msg = history[-2]["content"]  # Get the last user message
                history = history[:-2]  # Remove last exchange
                return await respond(last_user_msg, history)

            # Submit handlers with loading states
            submit_event = msg.submit(
                fn=respond,
                inputs=[msg, chatbot],
                outputs=[msg, chatbot],
                api_name=False
            ).then(
                lambda: (gr.update(value="", interactive=True), gr.update(interactive=True)),
                None,
                [msg, submit]
            )

            # Click handlers with loading states
            click_event = submit.click(
                fn=respond,
                inputs=[msg, chatbot],
                outputs=[msg, chatbot],
                api_name=False
            ).then(
                lambda: (gr.update(value="", interactive=True), gr.update(interactive=True)),
                None,
                [msg, submit]
            )

            # Retry handler
            retry.click(
                fn=retry_last,
                inputs=[chatbot],
                outputs=[chatbot],
                api_name=False
            )

            # Auto-focus and dynamic submit button state
            msg.change(
                lambda x: (
                    gr.update(interactive=bool(x.strip())), 
                    gr.update(interactive=bool(x.strip()), variant="primary" if x.strip() else "secondary")
                ),
                [msg],
                [msg, submit]
            )
            
            # Example queries with emojis
            gr.Examples(
                examples=[
                    "πŸ’» Can Team A help me build a web application?",
                    "πŸ’Ό Create a new objective: Analyze market trends for AI startups",
                    "πŸ” Research the latest developments in quantum computing",
                    "πŸ“ˆ What's the current status of all teams?"
                ],
                inputs=msg,
                label="Example Queries",
                examples_per_page=4
            )

        return interface

    async def process_message(
        self,
        message: str,
        history: List[List[str]] = None
    ) -> str:
        """Process a user message."""
        try:
            # Initialize history if None
            if history is None:
                history = []
            
            # Update chat history
            self.chat_history = history
            
            # Analyze message intent
            intent = await self._analyze_intent(message)
            
            # Process based on intent
            if intent.get('type') == 'objective':
                response = await self._handle_objective(message, intent)
            elif intent.get('type') == 'status':
                response = await self._get_status()
            elif intent.get('type') == 'chat':
                response = await self._handle_chat(message)
            else:
                response = await self._handle_chat(message)  # Default to chat handler
            
            return response
            
        except Exception as e:
            logger.error(f"Error processing message: {str(e)}")
            return "I encountered an error processing your message. Please try again."

    async def _analyze_intent(self, message: str) -> Dict[str, Any]:
        """Analyze user message intent with error handling."""
        try:
            # Use reasoning engine to analyze intent
            result = await self.reasoning_engine.reason(
                query=message,
                context={
                    "chat_history": self.chat_history,
                    "active_objectives": self.active_objectives
                }
            )
            
            # Handle UnifiedResult object
            if isinstance(result, UnifiedResult):
                return {
                    "type": "chat",
                    "confidence": getattr(result, 'confidence', 0.5),
                    "metadata": getattr(result, 'metadata', {})
                }
            elif isinstance(result, dict):
                return result
            else:
                return {"type": "chat", "confidence": 0.5}
            
        except Exception as e:
            logger.error(f"Error analyzing intent: {str(e)}")
            return {"type": "chat", "error": str(e)}

    async def _handle_objective(self, message: str, intent: Dict[str, Any]) -> str:
        """Handle objective creation and management."""
        try:
            # Extract objective details
            objective = intent.get('objective', {})
            
            # Create objective
            objective_id = await self.team_manager.create_cross_team_objective(
                objective=objective.get('description', message),
                required_teams=objective.get('teams', []),
                priority=objective.get('priority', 'MEDIUM')
            )
            
            # Monitor progress
            status = await self.team_manager.monitor_objective_progress(objective_id)
            
            return f"Created objective {objective_id}. Current status: {status}"
            
        except Exception as e:
            logger.error(f"Error handling objective: {str(e)}")
            return "Failed to create objective. Please try again."

    async def _handle_chat(self, message: str) -> str:
        """Handle general chat interactions with error recovery."""
        try:
            # First try using the reasoning engine
            try:
                result = await self.reasoning_engine.reason(
                    query=message,
                    context={
                        "chat_history": self.chat_history,
                        "active_objectives": self.active_objectives,
                        "groq_api": self.groq_api
                    }
                )
                
                # Handle UnifiedResult object
                if isinstance(result, UnifiedResult):
                    if not result.success:
                        # If reasoning engine fails, fallback to Groq API
                        groq_result = await self.groq_api.predict(message)
                        if groq_result["success"]:
                            return groq_result["answer"]
                        else:
                            return "I encountered an error. Please try rephrasing your question."
                    return result.answer if hasattr(result, 'answer') else str(result)
                elif isinstance(result, dict):
                    return result.get('response', str(result))
                else:
                    return str(result)
                
            except Exception as reasoning_error:
                logger.error(f"Reasoning engine error: {str(reasoning_error)}")
                # Fallback to Groq API
                groq_result = await self.groq_api.predict(message)
                if groq_result["success"]:
                    return groq_result["answer"]
                else:
                    raise Exception(f"Both reasoning engine and Groq API failed: {groq_result.get('error')}")
            
        except Exception as e:
            logger.error(f"Error in chat response: {str(e)}")
            return "I encountered an error generating a response. Please try again."

    async def _get_status(self) -> str:
        """Get system status information."""
        try:
            # Get team status
            team_status = await self.team_manager.get_team_status()
            
            # Get objective status
            objective_status = await self.team_manager.get_objective_status()
            
            # Format status information
            status = "Current System Status:\n\n"
            
            # Add team information
            status += "Teams:\n"
            for team, info in team_status.items():
                status += f"- {team}: {info['status']}\n"
                status += f"  Active Projects: {info['active_projects']}\n"
                status += f"  Success Rate: {info['success_rate']}%\n\n"
            
            # Add objective information
            status += "\nActive Objectives:\n"
            for obj, info in objective_status.items():
                status += f"- {obj}: {info['status']}\n"
                status += f"  Progress: {info['progress']}%\n"
                status += f"  Teams: {', '.join(info['teams'])}\n\n"
            
            return status
            
        except Exception as e:
            logger.error(f"Error formatting status: {str(e)}")
            return "Error formatting status information."

def create_chat_interface() -> gr.Blocks:
    """Create Gradio chat interface."""
    chat = ChatInterface()
    return chat.interface

# Initialize FastAPI
app = FastAPI(
    title="Advanced Agentic System API",
    description="API for interacting with the autonomous agent teams",
    version="1.0.0"
)

# Create Gradio interface
interface = create_chat_interface()

# Mount Gradio app to FastAPI
app = gr.mount_gradio_app(app, interface, path="/")

if __name__ == "__main__":
    chat_interface = ChatInterface()
    interface = chat_interface.create_interface()
    interface.queue()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True,
        enable_queue=True,
        show_error=True,
        favicon_path=None,  # Disable favicon to prevent 404
        show_api=False,  # Disable API docs to reduce asset loading
        reload=False,  # Disable auto-reload to use workers properly
        max_threads=40,
    )