"""
Gradio web interface for Felix Framework.
This module provides a comprehensive web interface for the helix-based multi-agent
cognitive architecture, enabling users to interact with, visualize, and understand
the Felix Framework in an educational and intuitive way.
Key Features:
- Real-time 3D helix visualization
- Interactive agent spawning and monitoring
- Task input and result visualization
- Performance dashboard and statistics
- Educational guided tours and explanations
- Export and sharing capabilities
- Mobile-responsive design
The interface maintains the research integrity of Felix Framework while making
it accessible to a broader audience through modern web technologies.
"""
import asyncio
import json
import logging
import time
from typing import Dict, List, Optional, Tuple, Any
from dataclasses import dataclass, asdict
import numpy as np
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from datetime import datetime
# Felix Framework imports
from ..core.helix_geometry import HelixGeometry, generate_helix_points
from ..agents.specialized_agents import ResearchAgent, AnalysisAgent, SynthesisAgent, CriticAgent
from ..agents.agent import AgentState
from ..communication.central_post import CentralPost, Message, MessageType
from ..llm.huggingface_client import HuggingFaceClient, ModelType, create_felix_hf_client
from ..comparison.statistical_analysis import StatisticalAnalyzer
from ..memory.knowledge_graph import KnowledgeGraph
logger = logging.getLogger(__name__)
@dataclass
class FelixSession:
"""Session state for Felix Framework web interface."""
session_id: str
start_time: datetime
helix_geometry: HelixGeometry
central_post: CentralPost
hf_client: Optional[HuggingFaceClient]
knowledge_graph: KnowledgeGraph
agents: Dict[str, Any]
active_tasks: Dict[str, Dict]
results: List[Dict]
performance_metrics: Dict[str, Any]
def to_dict(self) -> Dict[str, Any]:
"""Convert session to dictionary for JSON serialization."""
return {
"session_id": self.session_id,
"start_time": self.start_time.isoformat(),
"agents_count": len(self.agents),
"active_tasks_count": len(self.active_tasks),
"results_count": len(self.results),
"performance_metrics": self.performance_metrics
}
class FelixGradioInterface:
"""
Comprehensive Gradio interface for Felix Framework.
Provides educational, interactive, and research-focused web interface
for exploring helix-based multi-agent cognitive architecture.
"""
def __init__(self,
enable_llm: bool = True,
token_budget: int = 25000,
max_agents: int = 20,
session_timeout: int = 3600):
"""
Initialize Felix Gradio interface.
Args:
enable_llm: Whether to enable LLM-powered agents
token_budget: Token budget for HF API usage
max_agents: Maximum number of agents per session
session_timeout: Session timeout in seconds
"""
self.enable_llm = enable_llm
self.token_budget = token_budget
self.max_agents = max_agents
self.session_timeout = session_timeout
# Initialize core Felix components
self._init_felix_components()
# Session management
self.sessions: Dict[str, FelixSession] = {}
self.current_session: Optional[FelixSession] = None
# Interface state
self.demo: Optional[gr.Blocks] = None
self.plot_update_queue = asyncio.Queue()
# Educational content
self._init_educational_content()
def _init_felix_components(self):
"""Initialize core Felix Framework components."""
# Default helix geometry (Felix Framework standard)
self.default_helix = HelixGeometry(
top_radius=33.0,
bottom_radius=0.001,
height=100.0,
turns=33
)
# HuggingFace client (if enabled)
self.hf_client = None
if self.enable_llm:
try:
self.hf_client = create_felix_hf_client(
token_budget=self.token_budget,
concurrent_requests=3
)
logger.info("HuggingFace client initialized successfully")
except Exception as e:
logger.warning(f"Failed to initialize HF client: {e}")
self.enable_llm = False
def _init_educational_content(self):
"""Initialize educational content and guided tours."""
self.educational_content = {
"introduction": {
"title": "Welcome to Felix Framework",
"content": """
Felix Framework revolutionizes multi-agent systems through helix-based cognitive architecture.
Instead of traditional graph-based coordination, agents naturally converge along geometric spiral paths.
**Key Concepts:**
- **Helix Path**: Non-linear processing pipeline where agents traverse from broad (top) to focused (bottom)
- **Agent Specialization**: Different agent types spawn at different times with unique capabilities
- **Spoke Communication**: O(N) communication complexity vs O(N²) for traditional mesh systems
- **Natural Focusing**: Geometric tapering provides automatic attention concentration
This interface lets you explore these concepts interactively with real agent coordination.
"""
},
"mathematical_model": {
"title": "Mathematical Foundation",
"content": """
The Felix helix is defined by precise parametric equations:
**Position Vector:** r(t) = (R(t)cos(θ(t)), R(t)sin(θ(t)), Ht)
**Radius Function:** R(t) = R_bottom × (R_top/R_bottom)^t
**Angular Function:** θ(t) = 2πnt
**Parameters:**
- t ∈ [0,1]: Parameter where t=0 is top, t=1 is bottom
- n = 33: Number of complete turns
- R_top = 33: Top radius (broad exploration)
- R_bottom = 0.001: Bottom radius (focused synthesis)
- H = 100: Total height
**Concentration Ratio:** 33/0.001 = 33,000x focusing power
**Mathematical Precision:** Validated to <1e-12 error against OpenSCAD prototype
"""
},
"agent_types": {
"title": "Agent Specialization",
"content": """
Felix Framework includes four specialized agent types:
**🔍 ResearchAgent**
- **Spawn Time**: Early (high helix position)
- **Temperature**: 0.9 (high creativity)
- **Focus**: Broad exploration and idea generation
**🧠 AnalysisAgent**
- **Spawn Time**: Mid-stage spawning
- **Temperature**: 0.5 (balanced reasoning)
- **Focus**: Critical analysis and evaluation
**🎨 SynthesisAgent**
- **Spawn Time**: Late (low helix position)
- **Temperature**: 0.1 (high precision)
- **Focus**: Quality output and synthesis
**🔎 CriticAgent**
- **Spawn Time**: On-demand spawning
- **Temperature**: 0.3 (focused validation)
- **Focus**: Quality assurance and validation
Each agent type uses different LLM models optimized for their specific cognitive role.
"""
},
"research_results": {
"title": "Research Validation",
"content": """
Felix Framework has been validated through rigorous research methodology:
**Statistical Results:**
- **H1 SUPPORTED** (p=0.0441): Superior task distribution efficiency vs linear pipeline
- **H2 INCONCLUSIVE**: Communication overhead requires further study
- **H3 NOT SUPPORTED**: Empirical validation differs from mathematical theory
**Performance Benchmarks:**
- **Memory Efficiency**: 75% reduction vs mesh topology (1,200 vs 4,800 units)
- **Scalability**: Linear performance up to 133+ agents
- **Communication**: O(N) spoke vs O(N²) mesh complexity
**Test Coverage:**
- 107+ passing unit tests
- Mathematical precision validation
- Integration and performance testing
- Statistical significance testing
The framework demonstrates measurable advantages in specific domains while
providing a novel "spiral to consensus" mental model for multi-agent coordination.
"""
}
}
async def create_session(self, session_id: Optional[str] = None) -> FelixSession:
"""Create new Felix session with initialized components."""
if session_id is None:
session_id = f"felix_{int(time.time())}"
# Initialize core components
central_post = CentralPost()
knowledge_graph = KnowledgeGraph()
session = FelixSession(
session_id=session_id,
start_time=datetime.now(),
helix_geometry=self.default_helix,
central_post=central_post,
hf_client=self.hf_client,
knowledge_graph=knowledge_graph,
agents={},
active_tasks={},
results=[],
performance_metrics={}
)
self.sessions[session_id] = session
self.current_session = session
logger.info(f"Created Felix session: {session_id}")
return session
def create_helix_visualization(self,
agents_data: Optional[List[Dict]] = None,
highlight_active: bool = True) -> go.Figure:
"""
Create 3D helix visualization with agent positions.
Args:
agents_data: List of agent data with positions and states
highlight_active: Whether to highlight active agents
Returns:
Plotly 3D figure with helix and agents
"""
# Generate helix points for visualization
t_values = np.linspace(0, 1, 500)
helix_points = []
for t in t_values:
x, y, z = self.default_helix.get_position_at_t(t)
helix_points.append([x, y, z])
helix_points = np.array(helix_points)
# Create figure
fig = go.Figure()
# Add helix spiral
fig.add_trace(go.Scatter3d(
x=helix_points[:, 0],
y=helix_points[:, 1],
z=helix_points[:, 2],
mode='lines',
name='Helix Path',
line=dict(
color='rgba(100, 150, 200, 0.6)',
width=3
),
hovertemplate='Helix Path
Position: (%{x:.2f}, %{y:.2f}, %{z:.2f})
'
f'State: {state}
'
f'Position: ({x:.2f}, {y:.2f}, {z:.2f})
'
f'
Helix-Based Multi-Agent Cognitive Architecture
Felix Framework © 2025 | GitHub | Research-validated helix-based multi-agent cognitive architecture