From 07324f63a526512d65b0dd417e9bcfeb714aeeb3 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 21 Nov 2025 02:52:56 +0000 Subject: [PATCH 01/15] Initial plan From bf87f6c04575d7b8b45ff2157f2ad7d452ed7216 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 21 Nov 2025 03:05:33 +0000 Subject: [PATCH 02/15] Add complete Ragamuffin monorepo scaffold with LangFlow, FastAPI backend, and React frontend Co-authored-by: Stacey77 <54900383+Stacey77@users.noreply.github.com> --- .gitignore | 49 ++ README.md | 47 +- README_MONOREPO.md | 134 ++++ RUN_COMMANDS.md | 275 ++++++++ docker-compose.yml | 48 ++ langflow-backend/Dockerfile | 28 + langflow-backend/README.md | 294 +++++++++ langflow-backend/app/__init__.py | 2 + langflow-backend/app/main.py | 321 ++++++++++ langflow-backend/flows/.gitkeep | 2 + langflow-backend/requirements.txt | 4 + langflow/Dockerfile | 19 + langflow/README.md | 156 +++++ start-dev.sh | 44 ++ stop-dev.sh | 23 + web-client/.env | 1 + web-client/.gitignore | 32 + web-client/Dockerfile | 31 + web-client/README.md | 275 ++++++++ web-client/index.html | 16 + web-client/package.json | 29 + web-client/src/App.tsx | 24 + web-client/src/components/AIBrain.tsx | 32 + web-client/src/components/Conversation.tsx | 96 +++ web-client/src/components/SectionAgent.tsx | 39 ++ web-client/src/components/Sidebar.css | 119 ++++ web-client/src/components/Sidebar.tsx | 44 ++ web-client/src/main.tsx | 13 + web-client/src/pages/AgentBuilder.tsx | 281 +++++++++ web-client/src/pages/Dashboard.tsx | 67 ++ web-client/src/pages/Datasets.tsx | 134 ++++ web-client/src/pages/Playground.tsx | 68 ++ web-client/src/styles.css | 699 +++++++++++++++++++++ web-client/tsconfig.json | 25 + web-client/tsconfig.node.json | 10 + web-client/vite.config.ts | 15 + 36 files changed, 3495 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 README_MONOREPO.md create mode 100644 RUN_COMMANDS.md create mode 100644 docker-compose.yml create mode 100644 langflow-backend/Dockerfile create mode 100644 langflow-backend/README.md create mode 100644 langflow-backend/app/__init__.py create mode 100644 langflow-backend/app/main.py create mode 100644 langflow-backend/flows/.gitkeep create mode 100644 langflow-backend/requirements.txt create mode 100644 langflow/Dockerfile create mode 100644 langflow/README.md create mode 100755 start-dev.sh create mode 100755 stop-dev.sh create mode 100644 web-client/.env create mode 100644 web-client/.gitignore create mode 100644 web-client/Dockerfile create mode 100644 web-client/README.md create mode 100644 web-client/index.html create mode 100644 web-client/package.json create mode 100644 web-client/src/App.tsx create mode 100644 web-client/src/components/AIBrain.tsx create mode 100644 web-client/src/components/Conversation.tsx create mode 100644 web-client/src/components/SectionAgent.tsx create mode 100644 web-client/src/components/Sidebar.css create mode 100644 web-client/src/components/Sidebar.tsx create mode 100644 web-client/src/main.tsx create mode 100644 web-client/src/pages/AgentBuilder.tsx create mode 100644 web-client/src/pages/Dashboard.tsx create mode 100644 web-client/src/pages/Datasets.tsx create mode 100644 web-client/src/pages/Playground.tsx create mode 100644 web-client/src/styles.css create mode 100644 web-client/tsconfig.json create mode 100644 web-client/tsconfig.node.json create mode 100644 web-client/vite.config.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..555e010 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +env/ +venv/ +ENV/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# Node +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# IDEs +.vscode/ +.idea/ +*.swp +*.swo +*~ +.DS_Store + +# Docker +*.log + +# Local environment +.env.local +.env.production + +# Flows directory (keep structure but ignore contents) +langflow-backend/flows/* +!langflow-backend/flows/.gitkeep diff --git a/README.md b/README.md index f5a8ce3..5d15ce8 100644 --- a/README.md +++ b/README.md @@ -1 +1,46 @@ -# rag7 \ No newline at end of file +# Ragamuffin Platform + +![Ragamuffin UI Inspiration]() + +**Ragamuffin** is an advanced AI orchestration platform that combines LangFlow for visual flow design, a FastAPI backend for flow management and execution, and a modern React + TypeScript web interface with a cyberpunk-inspired design. + +## Project Name +**Ragamuffin** - A powerful monorepo platform for building, managing, and deploying AI agent workflows. + +## Architecture Overview +This monorepo contains three main components: +- **LangFlow Container**: Visual AI flow designer (port 7860) +- **FastAPI Backend**: Flow persistence and execution API (port 8000) +- **Web Client**: React + TypeScript frontend with Vite (port 8080) + +## Quick Start +```bash +# Start all services +./start-dev.sh + +# Stop all services +./stop-dev.sh +``` + +## Access Points +- **Frontend**: http://localhost:8080 +- **Backend API**: http://localhost:8000 +- **LangFlow UI**: http://localhost:7860 + +## Documentation +- See [README_MONOREPO.md](./README_MONOREPO.md) for detailed monorepo structure +- See [RUN_COMMANDS.md](./RUN_COMMANDS.md) for comprehensive run instructions +- Individual service READMEs in each service directory + +## UI Inspiration +The web client features a cyberpunk-inspired design with the Orbitron font and modern React components: + +![UI Reference]() + +## Next Steps +After setup, consider: +- Implementing authentication and authorization +- Securing CORS for production +- Adding flow validation and sandboxing +- Setting up persistent storage for flows +- Implementing user management \ No newline at end of file diff --git a/README_MONOREPO.md b/README_MONOREPO.md new file mode 100644 index 0000000..e67732d --- /dev/null +++ b/README_MONOREPO.md @@ -0,0 +1,134 @@ +# Ragamuffin Monorepo Documentation + +![Platform Overview]() + +## Overview +Ragamuffin is a comprehensive AI orchestration platform built as a monorepo. It provides a complete solution for designing, managing, and executing AI agent workflows through visual flow design, a robust backend API, and an intuitive web interface. + +## Monorepo Structure + +``` +rag7/ +├── docker-compose.yml # Orchestrates all services +├── README.md # Top-level project summary +├── README_MONOREPO.md # This file - detailed monorepo docs +├── RUN_COMMANDS.md # Step-by-step commands +├── start-dev.sh # Quick start script +├── stop-dev.sh # Quick stop script +│ +├── langflow/ # LangFlow service +│ ├── Dockerfile # LangFlow container definition +│ └── README.md # LangFlow documentation +│ +├── langflow-backend/ # FastAPI backend service +│ ├── Dockerfile # Backend container definition +│ ├── requirements.txt # Python dependencies +│ ├── flows/ # Persisted flow files +│ ├── app/ +│ │ ├── __init__.py +│ │ └── main.py # FastAPI application +│ └── README.md # Backend documentation +│ +└── web-client/ # React + TypeScript frontend + ├── Dockerfile # Multi-stage build with nginx + ├── nginx.conf # Nginx configuration (optional) + ├── package.json # Node dependencies + ├── tsconfig.json # TypeScript configuration + ├── vite.config.ts # Vite build configuration + ├── index.html # Entry HTML + ├── .env # Environment variables + ├── src/ + │ ├── main.tsx # Application entry point + │ ├── App.tsx # Root component + │ ├── styles.css # Global styles (Orbitron font, cyberpunk theme) + │ ├── components/ + │ │ ├── Sidebar.tsx + │ │ ├── AIBrain.tsx + │ │ ├── SectionAgent.tsx + │ │ └── Conversation.tsx # STT/TTS support + │ └── pages/ + │ ├── Dashboard.tsx + │ ├── Playground.tsx + │ ├── Datasets.tsx + │ └── AgentBuilder.tsx # Flow management integration + └── README.md # Frontend documentation +``` + +## Service Architecture + +### LangFlow Container (Port 7860) +- Visual AI flow designer +- Drag-and-drop interface for building AI workflows +- Runs on port 7860 + +### FastAPI Backend (Port 8000) +- RESTful API for flow management +- Endpoints: + - `POST /save_flow/` - Upload and save flow JSON files + - `GET /list_flows/` - List all saved flows + - `GET /get_flow/{flow_name}` - Retrieve flow content + - `POST /run_flow/` - Execute a flow with user input +- CORS enabled for localhost development +- Graceful fallback when LangFlow runtime unavailable + +### Web Client (Port 8080) +- Modern React + TypeScript SPA +- Vite for fast development and optimized builds +- Cyberpunk-inspired UI with Orbitron font +- Real-time flow management through AgentBuilder page +- Multi-page architecture with routing + +## Quick Start + +### Prerequisites +- Docker and Docker Compose installed +- Ports 7860, 8000, and 8080 available + +### Running the Platform +```bash +# Make scripts executable (first time only) +chmod +x start-dev.sh stop-dev.sh + +# Start all services +./start-dev.sh + +# Access the platform +# Frontend: http://localhost:8080 +# Backend API: http://localhost:8000/docs +# LangFlow: http://localhost:7860 +``` + +### Stopping the Platform +```bash +./stop-dev.sh +``` + +## Development Workflow + +1. **Design Flows**: Use LangFlow UI (port 7860) to visually design AI workflows +2. **Save Flows**: Export flows as JSON and upload via backend API or AgentBuilder UI +3. **Execute Flows**: Run flows through the backend API with custom inputs +4. **Monitor**: View flow execution results in the web interface + +## Data Persistence +- Flow files are stored in `./langflow-backend/flows/` +- This directory is mounted into the backend container +- Files persist across container restarts + +## Security Considerations +⚠️ **Important**: This scaffold is for development only. For production: +- Implement authentication and authorization +- Validate and sandbox flow execution +- Secure CORS configuration +- Add rate limiting and input validation +- Use HTTPS/TLS +- Implement proper secret management +- Review and audit all uploaded flows + +## Next Steps +1. Test the basic setup +2. Customize the UI components +3. Add authentication layer +4. Implement flow validation +5. Set up production-grade storage +6. Configure monitoring and logging diff --git a/RUN_COMMANDS.md b/RUN_COMMANDS.md new file mode 100644 index 0000000..516e021 --- /dev/null +++ b/RUN_COMMANDS.md @@ -0,0 +1,275 @@ +# Ragamuffin Platform - Run Commands + +This document provides step-by-step commands for running and developing the Ragamuffin platform. + +## Prerequisites Check + +### 1. Verify Docker Installation +```bash +docker --version +docker-compose --version +``` +Expected: Docker 20.10+ and Docker Compose 1.29+ + +### 2. Check Port Availability +```bash +# Check if required ports are free +netstat -an | grep -E ':(7860|8000|8080)' +``` +If ports are in use, stop the conflicting services or modify port mappings in `docker-compose.yml`. + +## First-Time Setup + +### 1. Clone Repository +```bash +git clone https://github.com/Stacey77/rag7.git +cd rag7 +git checkout ragamuffin-scaffold +``` + +### 2. Make Scripts Executable +```bash +chmod +x start-dev.sh stop-dev.sh +``` + +### 3. Create Required Directories +```bash +mkdir -p langflow-backend/flows +``` + +## Starting the Platform + +### Option 1: Using the Quick Start Script +```bash +./start-dev.sh +``` +This will: +- Build all Docker images +- Start all services (langflow, backend, frontend) +- Automatically create the network + +### Option 2: Manual Docker Compose +```bash +# Build and start all services +docker-compose up --build + +# Or run in detached mode +docker-compose up --build -d +``` + +### Option 3: Start Individual Services +```bash +# Start only langflow +docker-compose up langflow + +# Start only backend +docker-compose up backend + +# Start only frontend +docker-compose up frontend +``` + +## Accessing Services + +Once services are running: + +- **Web Frontend**: http://localhost:8080 +- **Backend API**: http://localhost:8000 +- **Backend API Docs**: http://localhost:8000/docs (Swagger UI) +- **Backend API Redoc**: http://localhost:8000/redoc +- **LangFlow UI**: http://localhost:7860 + +## Development Commands + +### View Logs +```bash +# All services +docker-compose logs -f + +# Specific service +docker-compose logs -f backend +docker-compose logs -f frontend +docker-compose logs -f langflow +``` + +### Rebuild After Code Changes +```bash +# Rebuild all services +docker-compose up --build + +# Rebuild specific service +docker-compose up --build backend +``` + +### Execute Commands in Containers +```bash +# Access backend container shell +docker exec -it ragamuffin-backend bash + +# Access frontend container shell +docker exec -it ragamuffin-frontend sh + +# Access langflow container shell +docker exec -it ragamuffin-langflow bash +``` + +### Check Container Status +```bash +docker-compose ps +``` + +### View Resource Usage +```bash +docker stats +``` + +## Backend API Testing + +### Test Backend Endpoints +```bash +# List flows +curl http://localhost:8000/list_flows/ + +# Get specific flow +curl http://localhost:8000/get_flow/my_flow.json + +# Upload a flow (create a test flow first) +echo '{"nodes": [], "edges": []}' > test_flow.json +curl -X POST -F "flow_file=@test_flow.json" http://localhost:8000/save_flow/ + +# Run a flow +curl -X POST -F "flow_file=@test_flow.json" -F "user_input=Hello" http://localhost:8000/run_flow/ +``` + +## Stopping the Platform + +### Option 1: Using the Stop Script +```bash +./stop-dev.sh +``` + +### Option 2: Manual Docker Compose +```bash +# Stop all services +docker-compose down + +# Stop and remove volumes (careful: deletes data!) +docker-compose down -v +``` + +### Option 3: Stop Without Removing Containers +```bash +docker-compose stop +``` + +## Development Workflow + +### Frontend Development +```bash +# If you want to develop frontend without Docker: +cd web-client +npm install +npm run dev +# Access at http://localhost:5173 +# Update .env to point to backend: VITE_API_URL=http://localhost:8000 +``` + +### Backend Development +```bash +# If you want to develop backend without Docker: +cd langflow-backend +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +pip install -r requirements.txt +uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 +``` + +### LangFlow Development +```bash +# Run LangFlow directly: +pip install langflow +langflow run --host 0.0.0.0 --port 7860 +``` + +## Troubleshooting + +### Port Already in Use +```bash +# Find process using port +lsof -i :8080 # or :8000, :7860 + +# Kill the process +kill -9 +``` + +### Docker Build Issues +```bash +# Clear Docker cache +docker-compose build --no-cache + +# Remove all containers and rebuild +docker-compose down +docker-compose up --build +``` + +### Permission Issues +```bash +# Fix permissions for flows directory +sudo chown -R $USER:$USER langflow-backend/flows +chmod -R 755 langflow-backend/flows +``` + +### Container Won't Start +```bash +# Check logs for specific service +docker-compose logs backend + +# Inspect container +docker inspect ragamuffin-backend + +# Remove and recreate +docker-compose rm -f backend +docker-compose up --build backend +``` + +### Network Issues +```bash +# Recreate network +docker-compose down +docker network prune +docker-compose up +``` + +## Production Deployment Considerations + +For production deployment: + +1. **Environment Variables**: Use `.env` files or secret management +2. **Reverse Proxy**: Add nginx/traefik in front of services +3. **HTTPS**: Configure TLS certificates +4. **Authentication**: Implement OAuth2/JWT +5. **Monitoring**: Add Prometheus, Grafana +6. **Logging**: Centralized logging with ELK/Loki +7. **Backups**: Regular backups of flows directory +8. **Scaling**: Use Docker Swarm or Kubernetes + +## Clean Up + +### Remove Everything +```bash +# Stop and remove containers, networks, volumes +docker-compose down -v + +# Remove images +docker rmi $(docker images 'ragamuffin*' -q) + +# Remove dangling images +docker image prune -f +``` + +## Getting Help + +- Check service logs: `docker-compose logs -f ` +- Verify network connectivity: `docker network inspect rag7_ragamuffin-network` +- Review API documentation: http://localhost:8000/docs +- Test endpoints with Swagger UI: http://localhost:8000/docs diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fc0ccdc --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,48 @@ +version: '3.8' + +services: + langflow: + build: + context: ./langflow + dockerfile: Dockerfile + ports: + - "7860:7860" + container_name: ragamuffin-langflow + restart: unless-stopped + networks: + - ragamuffin-network + + backend: + build: + context: ./langflow-backend + dockerfile: Dockerfile + ports: + - "8000:8000" + container_name: ragamuffin-backend + volumes: + - ./langflow-backend/flows:/app/flows + environment: + - LANGFLOW_HOST=langflow + - LANGFLOW_PORT=7860 + depends_on: + - langflow + restart: unless-stopped + networks: + - ragamuffin-network + + frontend: + build: + context: ./web-client + dockerfile: Dockerfile + ports: + - "8080:80" + container_name: ragamuffin-frontend + depends_on: + - backend + restart: unless-stopped + networks: + - ragamuffin-network + +networks: + ragamuffin-network: + driver: bridge diff --git a/langflow-backend/Dockerfile b/langflow-backend/Dockerfile new file mode 100644 index 0000000..d53bbf1 --- /dev/null +++ b/langflow-backend/Dockerfile @@ -0,0 +1,28 @@ +FROM python:3.11-slim + +# Set working directory +WORKDIR /app + +# Install system dependencies +RUN apt-get update && apt-get install -y \ + build-essential \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Copy requirements first for better caching +COPY requirements.txt . + +# Install Python dependencies +RUN pip install --no-cache-dir -r requirements.txt + +# Copy application code +COPY app/ ./app/ + +# Create flows directory +RUN mkdir -p /app/flows + +# Expose backend port +EXPOSE 8000 + +# Run FastAPI application +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/langflow-backend/README.md b/langflow-backend/README.md new file mode 100644 index 0000000..cc17e57 --- /dev/null +++ b/langflow-backend/README.md @@ -0,0 +1,294 @@ +# LangFlow Backend + +## Overview +FastAPI backend service for the Ragamuffin platform. Provides RESTful API endpoints for saving, listing, retrieving, and executing LangFlow JSON flows. + +## Features +- **Flow Management**: Save, list, retrieve, and delete flow files +- **Flow Execution**: Execute flows with user input +- **CORS Enabled**: Configured for localhost development +- **Graceful Fallback**: Returns simulated responses when LangFlow is unavailable +- **OpenAPI Documentation**: Auto-generated at `/docs` and `/redoc` + +## API Endpoints + +### GET / +Root endpoint with API information + +### GET /health +Health check endpoint + +### POST /save_flow/ +Upload and save a flow JSON file +- **Input**: `flow_file` (multipart/form-data, .json file) +- **Output**: Confirmation with filename and path + +Example: +```bash +curl -X POST -F "flow_file=@my_flow.json" http://localhost:8000/save_flow/ +``` + +### GET /list_flows/ +List all saved flow files with metadata +- **Output**: Array of flows with name, size, and modification time + +Example: +```bash +curl http://localhost:8000/list_flows/ +``` + +### GET /get_flow/{flow_name} +Retrieve a specific flow file by name +- **Input**: `flow_name` (path parameter) +- **Output**: Flow JSON content + +Example: +```bash +curl http://localhost:8000/get_flow/my_flow.json +``` + +### POST /run_flow/ +Execute a flow with user input +- **Input**: + - `flow_file` (multipart/form-data, .json file) + - `user_input` (form field, string) +- **Output**: Execution result + +Example: +```bash +curl -X POST \ + -F "flow_file=@my_flow.json" \ + -F "user_input=Hello, how are you?" \ + http://localhost:8000/run_flow/ +``` + +### DELETE /delete_flow/{flow_name} +Delete a specific flow file +- **Input**: `flow_name` (path parameter) +- **Output**: Confirmation message + +Example: +```bash +curl -X DELETE http://localhost:8000/delete_flow/my_flow.json +``` + +## Running the Backend + +### With Docker (Recommended) +```bash +# From project root +docker-compose up backend + +# Or with rebuild +docker-compose up --build backend +``` + +### Standalone Development +```bash +cd langflow-backend + +# Create virtual environment +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate + +# Install dependencies +pip install -r requirements.txt + +# Run server +uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 +``` + +## Access +- **API**: http://localhost:8000 +- **Swagger UI**: http://localhost:8000/docs +- **ReDoc**: http://localhost:8000/redoc + +## Environment Variables + +### Available Variables +```bash +# LangFlow connection (for future use) +LANGFLOW_HOST=langflow +LANGFLOW_PORT=7860 + +# Flow storage (default: /app/flows) +FLOWS_DIR=/app/flows +``` + +## Flow Storage +- Flows are persisted in the `flows/` directory +- Directory is mounted from host in Docker Compose +- Files survive container restarts + +## Security Considerations + +⚠️ **CRITICAL SECURITY WARNINGS** + +This is a development scaffold. For production deployment: + +### 1. Authentication & Authorization +```python +# Add dependencies +from fastapi.security import OAuth2PasswordBearer + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +@app.post("/save_flow/") +async def save_flow( + flow_file: UploadFile = File(...), + token: str = Depends(oauth2_scheme) +): + # Verify token and user permissions + ... +``` + +### 2. Flow Validation +```python +# Validate flow structure and content +def validate_flow(flow_data: dict) -> bool: + # Check for required fields + # Validate node types + # Scan for suspicious patterns + # Check against whitelist + return True +``` + +### 3. Sandboxed Execution +- Use Docker containers for flow execution +- Implement resource limits (CPU, memory, time) +- Run in isolated network namespace +- Use read-only filesystem where possible + +### 4. Input Validation +- Validate all file uploads +- Sanitize user input +- Check file sizes and types +- Prevent path traversal attacks + +### 5. Rate Limiting +```python +from slowapi import Limiter + +limiter = Limiter(key_func=get_remote_address) + +@app.post("/run_flow/") +@limiter.limit("10/minute") +async def run_flow(...): + ... +``` + +### 6. CORS Configuration +```python +# Restrict origins in production +app.add_middleware( + CORSMiddleware, + allow_origins=["https://yourdomain.com"], + allow_credentials=True, + allow_methods=["GET", "POST"], + allow_headers=["Authorization"], +) +``` + +### 7. Logging & Monitoring +- Log all flow executions +- Monitor for suspicious activity +- Track resource usage +- Set up alerts + +### 8. Error Handling +- Don't expose internal errors to clients +- Log detailed errors server-side +- Return generic error messages + +## LangFlow Integration + +### When LangFlow is Available +The backend can execute flows using the LangFlow runtime: +```python +from langflow.load import load_flow_from_json + +flow = load_flow_from_json("path/to/flow.json") +result = flow(user_input) +``` + +### When LangFlow is Unavailable +The backend gracefully falls back to simulated responses: +- Logs a warning message +- Returns mock response with user input echoed +- Indicates execution mode as "simulated" + +## Troubleshooting + +### Import Error: langflow not found +```bash +# LangFlow is optional - backend will use simulated mode +# To install LangFlow: +pip install langflow +``` + +### Port 8000 Already in Use +```bash +# Find process +lsof -i :8000 +kill -9 + +# Or change port +uvicorn app.main:app --port 8001 +``` + +### CORS Errors +- Ensure frontend URL is in `allow_origins` list +- Check browser console for specific CORS errors +- Verify credentials mode matches + +### File Permission Errors +```bash +# Fix flows directory permissions +chmod -R 755 flows/ +chown -R $USER:$USER flows/ +``` + +## Development Tips + +### Hot Reload +Use `--reload` flag for automatic restart on code changes: +```bash +uvicorn app.main:app --reload +``` + +### Debug Logging +```python +import logging +logging.basicConfig(level=logging.DEBUG) +``` + +### Testing with curl +```bash +# Save a test flow +echo '{"nodes": [], "edges": []}' > test.json +curl -X POST -F "flow_file=@test.json" http://localhost:8000/save_flow/ + +# List flows +curl http://localhost:8000/list_flows/ + +# Run flow +curl -X POST \ + -F "flow_file=@test.json" \ + -F "user_input=test" \ + http://localhost:8000/run_flow/ +``` + +## Dependencies +- **FastAPI**: Modern, fast web framework +- **Uvicorn**: ASGI server +- **LangFlow**: Flow execution runtime (optional) +- **python-multipart**: File upload support + +## Next Steps +1. Implement authentication +2. Add flow validation +3. Set up database for metadata +4. Implement versioning +5. Add user management +6. Configure monitoring +7. Set up CI/CD pipeline diff --git a/langflow-backend/app/__init__.py b/langflow-backend/app/__init__.py new file mode 100644 index 0000000..106a046 --- /dev/null +++ b/langflow-backend/app/__init__.py @@ -0,0 +1,2 @@ +# LangFlow Backend Package +__version__ = "0.1.0" diff --git a/langflow-backend/app/main.py b/langflow-backend/app/main.py new file mode 100644 index 0000000..0934d6b --- /dev/null +++ b/langflow-backend/app/main.py @@ -0,0 +1,321 @@ +""" +Ragamuffin Backend API + +FastAPI backend for managing and executing LangFlow flows. + +⚠️ SECURITY WARNING: +This is a development scaffold. For production: +- Add authentication and authorization +- Validate all flow JSON inputs +- Sandbox flow execution +- Implement rate limiting +- Review and audit uploaded flows +- Use proper secret management +""" + +import os +import json +import logging +from pathlib import Path +from typing import Optional, Dict, Any +from fastapi import FastAPI, File, UploadFile, Form, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Initialize FastAPI app +app = FastAPI( + title="Ragamuffin Backend API", + description="Flow management and execution API for the Ragamuffin platform", + version="0.1.0" +) + +# SECURITY NOTE: CORS configuration is permissive for development +# In production, restrict origins to specific domains +app.add_middleware( + CORSMiddleware, + allow_origins=["http://localhost:8080", "http://localhost:5173", "http://localhost:3000"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Flows directory +FLOWS_DIR = Path("/app/flows") +FLOWS_DIR.mkdir(exist_ok=True) + +# Check if langflow is available +LANGFLOW_AVAILABLE = False +try: + from langflow.load import load_flow_from_json + LANGFLOW_AVAILABLE = True + logger.info("✓ LangFlow runtime available") +except ImportError: + logger.warning("⚠️ LangFlow runtime not available - will use simulated responses") + + +@app.get("/") +async def root(): + """Root endpoint with API information""" + return { + "name": "Ragamuffin Backend API", + "version": "0.1.0", + "status": "running", + "langflow_available": LANGFLOW_AVAILABLE, + "endpoints": { + "docs": "/docs", + "save_flow": "POST /save_flow/", + "list_flows": "GET /list_flows/", + "get_flow": "GET /get_flow/{flow_name}", + "run_flow": "POST /run_flow/" + } + } + + +@app.get("/health") +async def health_check(): + """Health check endpoint""" + return { + "status": "healthy", + "langflow_available": LANGFLOW_AVAILABLE + } + + +@app.post("/save_flow/") +async def save_flow(flow_file: UploadFile = File(...)): + """ + Save a LangFlow JSON file to the flows directory. + + SECURITY NOTE: In production, validate flow content before saving. + Untrusted flows may contain malicious code. + """ + try: + # SECURITY: Validate filename to prevent path traversal + filename = os.path.basename(flow_file.filename) + if not filename.endswith('.json'): + raise HTTPException(status_code=400, detail="Only .json files are allowed") + + # Read file content + content = await flow_file.read() + + # SECURITY: Validate JSON structure + try: + flow_data = json.loads(content) + except json.JSONDecodeError: + raise HTTPException(status_code=400, detail="Invalid JSON format") + + # Save to flows directory + file_path = FLOWS_DIR / filename + with open(file_path, 'wb') as f: + f.write(content) + + logger.info(f"✓ Saved flow: {filename}") + + return { + "status": "success", + "filename": filename, + "path": str(file_path), + "size": len(content) + } + + except HTTPException: + raise + except Exception as e: + logger.error(f"Error saving flow: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to save flow: {str(e)}") + + +@app.get("/list_flows/") +async def list_flows(): + """ + List all saved flow JSON files. + """ + try: + flows = [] + for file_path in FLOWS_DIR.glob("*.json"): + stat = file_path.stat() + flows.append({ + "name": file_path.name, + "size": stat.st_size, + "modified": stat.st_mtime, + "path": str(file_path) + }) + + # Sort by modified time, newest first + flows.sort(key=lambda x: x['modified'], reverse=True) + + return { + "status": "success", + "count": len(flows), + "flows": flows + } + + except Exception as e: + logger.error(f"Error listing flows: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to list flows: {str(e)}") + + +@app.get("/get_flow/{flow_name}") +async def get_flow(flow_name: str): + """ + Retrieve a specific flow file by name. + + SECURITY NOTE: Validate flow_name to prevent path traversal attacks. + """ + try: + # SECURITY: Validate filename + filename = os.path.basename(flow_name) + if not filename.endswith('.json'): + raise HTTPException(status_code=400, detail="Only .json files are allowed") + + file_path = FLOWS_DIR / filename + + if not file_path.exists(): + raise HTTPException(status_code=404, detail=f"Flow not found: {flow_name}") + + # Read and return flow content + with open(file_path, 'r') as f: + flow_data = json.load(f) + + return { + "status": "success", + "filename": filename, + "content": flow_data + } + + except HTTPException: + raise + except json.JSONDecodeError: + raise HTTPException(status_code=500, detail="Invalid JSON in flow file") + except Exception as e: + logger.error(f"Error getting flow: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to get flow: {str(e)}") + + +@app.post("/run_flow/") +async def run_flow( + flow_file: UploadFile = File(...), + user_input: str = Form(...) +): + """ + Execute a flow with user input. + + ⚠️ CRITICAL SECURITY WARNINGS: + - This endpoint executes arbitrary code from uploaded flows + - In production, implement strict validation and sandboxing + - Consider using containerized execution + - Implement authentication and authorization + - Add rate limiting + - Audit all flow executions + + If LangFlow is not available, returns a simulated response. + """ + try: + # Read flow file + content = await flow_file.read() + + # Validate JSON + try: + flow_data = json.loads(content) + except json.JSONDecodeError: + raise HTTPException(status_code=400, detail="Invalid JSON format") + + # Save temporary flow file + temp_filename = f"temp_{flow_file.filename}" + temp_path = FLOWS_DIR / temp_filename + with open(temp_path, 'wb') as f: + f.write(content) + + # Execute flow + if LANGFLOW_AVAILABLE: + try: + # SECURITY WARNING: This executes potentially untrusted code + # Implement proper sandboxing in production + logger.info(f"Executing flow with LangFlow: {flow_file.filename}") + + # Load and run flow + flow = load_flow_from_json(str(temp_path)) + result = flow(user_input) + + # Clean up temp file + temp_path.unlink() + + return { + "status": "success", + "flow": flow_file.filename, + "input": user_input, + "output": str(result), + "execution_mode": "langflow" + } + + except Exception as e: + logger.error(f"Error executing flow with LangFlow: {str(e)}") + # Clean up temp file + if temp_path.exists(): + temp_path.unlink() + raise HTTPException(status_code=500, detail=f"Flow execution failed: {str(e)}") + + else: + # LangFlow not available - return simulated response + logger.warning(f"⚠️ Simulating flow execution (LangFlow not available): {flow_file.filename}") + + # Clean up temp file + temp_path.unlink() + + return { + "status": "success", + "flow": flow_file.filename, + "input": user_input, + "output": f"[SIMULATED] This is a simulated response. LangFlow runtime is not available. Your input was: '{user_input}'", + "execution_mode": "simulated", + "warning": "LangFlow runtime not available - using simulated response" + } + + except HTTPException: + raise + except Exception as e: + logger.error(f"Error in run_flow: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to run flow: {str(e)}") + + +@app.delete("/delete_flow/{flow_name}") +async def delete_flow(flow_name: str): + """ + Delete a specific flow file. + + SECURITY NOTE: Implement authorization before allowing deletions. + """ + try: + # SECURITY: Validate filename + filename = os.path.basename(flow_name) + if not filename.endswith('.json'): + raise HTTPException(status_code=400, detail="Only .json files are allowed") + + file_path = FLOWS_DIR / filename + + if not file_path.exists(): + raise HTTPException(status_code=404, detail=f"Flow not found: {flow_name}") + + # Delete file + file_path.unlink() + + logger.info(f"✓ Deleted flow: {filename}") + + return { + "status": "success", + "message": f"Flow deleted: {filename}" + } + + except HTTPException: + raise + except Exception as e: + logger.error(f"Error deleting flow: {str(e)}") + raise HTTPException(status_code=500, detail=f"Failed to delete flow: {str(e)}") + + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/langflow-backend/flows/.gitkeep b/langflow-backend/flows/.gitkeep new file mode 100644 index 0000000..0b19109 --- /dev/null +++ b/langflow-backend/flows/.gitkeep @@ -0,0 +1,2 @@ +# This file keeps the flows directory in git +# Flow JSON files will be stored here diff --git a/langflow-backend/requirements.txt b/langflow-backend/requirements.txt new file mode 100644 index 0000000..71f92a6 --- /dev/null +++ b/langflow-backend/requirements.txt @@ -0,0 +1,4 @@ +fastapi>=0.104.0 +uvicorn[standard]>=0.24.0 +langflow>=0.6.0 +python-multipart>=0.0.6 diff --git a/langflow/Dockerfile b/langflow/Dockerfile new file mode 100644 index 0000000..b8a9f5e --- /dev/null +++ b/langflow/Dockerfile @@ -0,0 +1,19 @@ +FROM python:3.11-slim + +# Set working directory +WORKDIR /app + +# Install system dependencies +RUN apt-get update && apt-get install -y \ + build-essential \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Install langflow +RUN pip install --no-cache-dir langflow + +# Expose LangFlow port +EXPOSE 7860 + +# Run LangFlow +CMD ["langflow", "run", "--host", "0.0.0.0", "--port", "7860"] diff --git a/langflow/README.md b/langflow/README.md new file mode 100644 index 0000000..65cbcd2 --- /dev/null +++ b/langflow/README.md @@ -0,0 +1,156 @@ +# LangFlow Service + +## Overview +This directory contains the LangFlow service for the Ragamuffin platform. LangFlow provides a visual interface for designing and testing AI agent workflows. + +## What is LangFlow? +LangFlow is a UI for LangChain, designed with react-flow to provide an effortless way to experiment and prototype flows. It offers a drag-and-drop interface for building complex AI workflows. + +## Running LangFlow + +### With Docker (Recommended) +```bash +# From project root +docker-compose up langflow +``` + +### Standalone +```bash +pip install langflow +langflow run --host 0.0.0.0 --port 7860 +``` + +## Access +- **URL**: http://localhost:7860 +- **Port**: 7860 (configurable in docker-compose.yml) + +## Usage + +1. **Access UI**: Open http://localhost:7860 in your browser +2. **Create Flows**: Use the drag-and-drop interface to build AI workflows +3. **Test Flows**: Test your flows directly in the LangFlow UI +4. **Export Flows**: Export your flows as JSON files +5. **Save to Backend**: Upload exported JSON to the backend via the AgentBuilder page or API + +## Flow Management + +### Exporting Flows +1. Design your flow in LangFlow UI +2. Click "Export" button +3. Save the JSON file +4. Upload to backend using `POST /save_flow/` endpoint + +### Running Flows +Flows can be executed through: +- LangFlow UI (for testing) +- Backend API `POST /run_flow/` endpoint +- Web Client AgentBuilder page + +## Security Considerations + +⚠️ **Important Security Notes**: + +1. **Authentication**: LangFlow UI has no built-in authentication in this setup + - Consider adding a reverse proxy with auth + - Use VPN or firewall rules in production + - Implement OAuth2 or basic auth + +2. **Network Exposure**: + - Current setup exposes port 7860 to localhost only + - Do NOT expose to public internet without authentication + - Use internal networks in production + +3. **Flow Validation**: + - Review all flows before execution + - Untrusted flows can execute arbitrary code + - Implement sandboxing for production + +4. **Resource Limits**: + - LangFlow can consume significant resources + - Set memory and CPU limits in docker-compose + - Monitor resource usage + +## Configuration + +### Environment Variables +Add to docker-compose.yml service definition: + +```yaml +environment: + - LANGFLOW_DATABASE_URL=sqlite:///./langflow.db + - LANGFLOW_CACHE_TYPE=memory + - LANGFLOW_LOG_LEVEL=INFO +``` + +### Resource Limits +Add to docker-compose.yml: + +```yaml +deploy: + resources: + limits: + cpus: '2' + memory: 4G +``` + +## Troubleshooting + +### Port Already in Use +```bash +# Find process using port 7860 +lsof -i :7860 +# Kill process or change port in docker-compose.yml +``` + +### Container Won't Start +```bash +# Check logs +docker-compose logs langflow + +# Rebuild image +docker-compose build --no-cache langflow +docker-compose up langflow +``` + +### Performance Issues +- Increase memory allocation in docker-compose.yml +- Use faster storage for Docker volumes +- Consider using GPU support for LangChain models + +## Advanced Configuration + +### Persistent Storage +To persist LangFlow data: + +```yaml +volumes: + - ./langflow-data:/root/.langflow +``` + +### Custom Components +Place custom components in mounted volume: + +```yaml +volumes: + - ./langflow-components:/app/components +``` + +## Integration with Backend + +The backend service can execute flows programmatically: +1. Backend receives flow JSON via API +2. Backend saves flow to `flows/` directory +3. Backend can execute flow using LangFlow runtime +4. Results returned to frontend + +## Resources +- [LangFlow Documentation](https://docs.langflow.org/) +- [LangChain Documentation](https://python.langchain.com/) +- [GitHub Repository](https://github.com/logspace-ai/langflow) + +## Next Steps +1. Secure the LangFlow UI +2. Create reusable flow templates +3. Document flow design patterns +4. Implement flow versioning +5. Add flow validation rules diff --git a/start-dev.sh b/start-dev.sh new file mode 100755 index 0000000..992b0e7 --- /dev/null +++ b/start-dev.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +# Ragamuffin Platform - Start Development Environment +# This script starts all services using Docker Compose + +echo "🚀 Starting Ragamuffin Platform..." +echo "==================================" + +# Check if Docker is installed +if ! command -v docker &> /dev/null; then + echo "❌ Error: Docker is not installed" + exit 1 +fi + +# Check if Docker Compose is installed +if ! command -v docker-compose &> /dev/null; then + echo "❌ Error: Docker Compose is not installed" + exit 1 +fi + +# Create flows directory if it doesn't exist +mkdir -p langflow-backend/flows +echo "✓ Flows directory ready" + +# Start services +echo "" +echo "Building and starting services..." +echo "This may take a few minutes on first run..." +echo "" + +docker-compose up --build + +echo "" +echo "==================================" +echo "✓ Ragamuffin Platform started!" +echo "" +echo "Access points:" +echo " • Frontend: http://localhost:8080" +echo " • Backend: http://localhost:8000" +echo " • API Docs: http://localhost:8000/docs" +echo " • LangFlow: http://localhost:7860" +echo "" +echo "Press Ctrl+C to stop all services" +echo "Or run ./stop-dev.sh in another terminal" diff --git a/stop-dev.sh b/stop-dev.sh new file mode 100755 index 0000000..74d7f6d --- /dev/null +++ b/stop-dev.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Ragamuffin Platform - Stop Development Environment +# This script stops all services + +echo "🛑 Stopping Ragamuffin Platform..." +echo "==================================" + +# Check if Docker Compose is installed +if ! command -v docker-compose &> /dev/null; then + echo "❌ Error: Docker Compose is not installed" + exit 1 +fi + +# Stop services +docker-compose down + +echo "" +echo "==================================" +echo "✓ Ragamuffin Platform stopped!" +echo "" +echo "To restart: ./start-dev.sh" +echo "To remove volumes: docker-compose down -v" diff --git a/web-client/.env b/web-client/.env new file mode 100644 index 0000000..5934e2e --- /dev/null +++ b/web-client/.env @@ -0,0 +1 @@ +VITE_API_URL=http://localhost:8000 diff --git a/web-client/.gitignore b/web-client/.gitignore new file mode 100644 index 0000000..b991158 --- /dev/null +++ b/web-client/.gitignore @@ -0,0 +1,32 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +loglevel.log* + +# Dependency directories +node_modules/ +jspm_packages/ + +# Build output +dist/ +dist-ssr/ +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# Environment variables (keep .env for template) +.env.local +.env.production diff --git a/web-client/Dockerfile b/web-client/Dockerfile new file mode 100644 index 0000000..042636b --- /dev/null +++ b/web-client/Dockerfile @@ -0,0 +1,31 @@ +# Build stage +FROM node:18-alpine AS builder + +WORKDIR /app + +# Copy package files +COPY package.json package-lock.json* ./ + +# Install dependencies +RUN npm install + +# Copy source code +COPY . . + +# Build application +RUN npm run build + +# Production stage +FROM nginx:alpine + +# Copy built assets from builder +COPY --from=builder /app/dist /usr/share/nginx/html + +# Copy nginx configuration if exists +# COPY nginx.conf /etc/nginx/conf.d/default.conf + +# Expose port 80 +EXPOSE 80 + +# Start nginx +CMD ["nginx", "-g", "daemon off;"] diff --git a/web-client/README.md b/web-client/README.md new file mode 100644 index 0000000..ee5dab4 --- /dev/null +++ b/web-client/README.md @@ -0,0 +1,275 @@ +# Ragamuffin Web Client + +## Overview +Modern React + TypeScript web interface for the Ragamuffin AI orchestration platform. Features a cyberpunk-inspired design with the Orbitron font. + +## Tech Stack +- **React 18**: UI framework +- **TypeScript**: Type safety +- **Vite**: Fast build tool and dev server +- **React Router**: Client-side routing +- **Axios**: HTTP client for API calls + +## Features +- **Dashboard**: System overview and agent status +- **Playground**: Interactive AI conversation interface with STT/TTS +- **Datasets**: Data management and storage +- **Agent Builder**: Flow management - upload, list, and execute LangFlow JSON files + +## Development + +### Prerequisites +- Node.js 18+ +- npm or yarn + +### Setup +```bash +cd web-client +npm install +``` + +### Run Development Server +```bash +npm run dev +``` +Access at http://localhost:5173 + +### Build for Production +```bash +npm run build +``` +Output in `dist/` directory + +### Preview Production Build +```bash +npm run preview +``` + +## Docker + +### Build Image +```bash +docker build -t ragamuffin-frontend . +``` + +### Run Container +```bash +docker run -p 8080:80 ragamuffin-frontend +``` + +## Environment Variables + +Create a `.env` file: +``` +VITE_API_URL=http://localhost:8000 +``` + +## Project Structure + +``` +web-client/ +├── src/ +│ ├── main.tsx # Entry point +│ ├── App.tsx # Root component with routing +│ ├── styles.css # Global styles (Orbitron font, cyberpunk theme) +│ ├── components/ +│ │ ├── Sidebar.tsx # Navigation sidebar +│ │ ├── Sidebar.css # Sidebar styles +│ │ ├── AIBrain.tsx # Animated AI status indicator +│ │ ├── SectionAgent.tsx # Agent status card +│ │ └── Conversation.tsx # Chat interface with STT/TTS +│ └── pages/ +│ ├── Dashboard.tsx # Main dashboard +│ ├── Playground.tsx # AI interaction playground +│ ├── Datasets.tsx # Dataset management +│ └── AgentBuilder.tsx # Flow builder interface +├── index.html +├── package.json +├── tsconfig.json +├── vite.config.ts +├── Dockerfile +└── .env +``` + +## Pages + +### Dashboard (`/`) +- System status overview +- AI brain visualization +- Active agents display +- Quick statistics + +### Playground (`/playground`) +- Interactive conversation interface +- Real-time AI responses +- Configuration panel +- Recent interactions log + +### Datasets (`/datasets`) +- Dataset listing and search +- Upload/download functionality +- Storage usage metrics +- Status indicators + +### Agent Builder (`/agent-builder`) +- Upload LangFlow JSON files +- List saved flows +- Execute flows with input +- View execution results +- Integration with backend API + +## API Integration + +The Agent Builder page integrates with the backend API: + +```typescript +// List flows +GET ${API_URL}/list_flows/ + +// Save flow +POST ${API_URL}/save_flow/ +FormData: { flow_file: File } + +// Get flow +GET ${API_URL}/get_flow/{flow_name} + +// Run flow +POST ${API_URL}/run_flow/ +FormData: { flow_file: File, user_input: string } +``` + +## Styling + +### Theme Colors +- **Primary BG**: `#0a0e27` +- **Secondary BG**: `#1a1e3e` +- **Accent Cyan**: `#00fff9` +- **Accent Purple**: `#b026ff` +- **Accent Pink**: `#ff006e` + +### Typography +- **Font**: Orbitron (Google Fonts) +- **Weights**: 400, 500, 600, 700, 800, 900 + +### Components +All components follow the cyberpunk aesthetic with: +- Glowing effects +- Gradient accents +- Card-based layouts +- Smooth animations + +## Speech Features + +### Text-to-Speech (TTS) +Uses Web Speech API: +```typescript +const utterance = new SpeechSynthesisUtterance(text) +window.speechSynthesis.speak(utterance) +``` + +### Speech-to-Text (STT) +Placeholder for future implementation using Web Speech API or external service. + +## Customization + +### Change Theme Colors +Edit `src/styles.css` `:root` variables: +```css +:root { + --primary-bg: #0a0e27; + --accent-cyan: #00fff9; + /* ... */ +} +``` + +### Add New Page +1. Create component in `src/pages/` +2. Add route in `src/App.tsx` +3. Add nav link in `src/components/Sidebar.tsx` + +### Modify API URL +Update `.env`: +``` +VITE_API_URL=https://your-api.com +``` + +## Troubleshooting + +### Port 5173 Already in Use +Change port in `vite.config.ts`: +```typescript +server: { + port: 3000 +} +``` + +### API Connection Failed +- Check backend is running on port 8000 +- Verify CORS settings in backend +- Check `VITE_API_URL` in `.env` + +### Build Errors +```bash +# Clear cache and rebuild +rm -rf node_modules dist +npm install +npm run build +``` + +### Docker Build Issues +```bash +# Build without cache +docker build --no-cache -t ragamuffin-frontend . +``` + +## Production Deployment + +### Build Optimization +```bash +npm run build +``` + +### Serve with Nginx +The Dockerfile uses nginx to serve the built application: +- Static files in `/usr/share/nginx/html` +- Default port 80 +- Can customize with `nginx.conf` + +### Environment Variables in Production +For production, set environment variables before build: +```bash +VITE_API_URL=https://api.production.com npm run build +``` + +Or use runtime configuration with nginx substitution. + +## Browser Support +- Chrome/Edge: Latest 2 versions +- Firefox: Latest 2 versions +- Safari: Latest 2 versions + +## Performance +- Vite provides fast HMR in development +- Production build is optimized and minified +- Code splitting for efficient loading +- Tree shaking removes unused code + +## Security Notes +⚠️ **Development Setup**: This is configured for local development + +For production: +- Configure proper CORS origins +- Use HTTPS +- Implement authentication +- Add CSP headers +- Sanitize user inputs +- Enable rate limiting + +## Contributing +1. Follow TypeScript strict mode +2. Use functional components with hooks +3. Maintain cyberpunk design aesthetic +4. Add proper types for all props and state + +## License +Part of the Ragamuffin platform diff --git a/web-client/index.html b/web-client/index.html new file mode 100644 index 0000000..68a572d --- /dev/null +++ b/web-client/index.html @@ -0,0 +1,16 @@ + + + + + + + Ragamuffin - AI Orchestration Platform + + + + + +
+ + + diff --git a/web-client/package.json b/web-client/package.json new file mode 100644 index 0000000..f12ca00 --- /dev/null +++ b/web-client/package.json @@ -0,0 +1,29 @@ +{ + "name": "ragamuffin-web-client", + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0" + }, + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-router-dom": "^6.20.0", + "axios": "^1.6.2" + }, + "devDependencies": { + "@types/react": "^18.2.43", + "@types/react-dom": "^18.2.17", + "@typescript-eslint/eslint-plugin": "^6.14.0", + "@typescript-eslint/parser": "^6.14.0", + "@vitejs/plugin-react": "^4.2.1", + "eslint": "^8.55.0", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-react-refresh": "^0.4.5", + "typescript": "^5.3.3", + "vite": "^5.0.8" + } +} diff --git a/web-client/src/App.tsx b/web-client/src/App.tsx new file mode 100644 index 0000000..53d52f9 --- /dev/null +++ b/web-client/src/App.tsx @@ -0,0 +1,24 @@ +import { Routes, Route } from 'react-router-dom' +import Sidebar from './components/Sidebar' +import Dashboard from './pages/Dashboard' +import Playground from './pages/Playground' +import Datasets from './pages/Datasets' +import AgentBuilder from './pages/AgentBuilder' + +function App() { + return ( +
+ +
+ + } /> + } /> + } /> + } /> + +
+
+ ) +} + +export default App diff --git a/web-client/src/components/AIBrain.tsx b/web-client/src/components/AIBrain.tsx new file mode 100644 index 0000000..7e480b4 --- /dev/null +++ b/web-client/src/components/AIBrain.tsx @@ -0,0 +1,32 @@ +import { useState, useEffect } from 'react' + +interface AIBrainProps { + status?: 'active' | 'thinking' | 'idle' +} + +function AIBrain({ status = 'idle' }: AIBrainProps) { + const [pulse, setPulse] = useState(false) + + useEffect(() => { + if (status === 'thinking') { + const interval = setInterval(() => { + setPulse(prev => !prev) + }, 1000) + return () => clearInterval(interval) + } + }, [status]) + + return ( +
+
+
+
+
+
+
+

{status.toUpperCase()}

+
+ ) +} + +export default AIBrain diff --git a/web-client/src/components/Conversation.tsx b/web-client/src/components/Conversation.tsx new file mode 100644 index 0000000..428501d --- /dev/null +++ b/web-client/src/components/Conversation.tsx @@ -0,0 +1,96 @@ +import { useState } from 'react' + +function Conversation() { + const [messages, setMessages] = useState>([]) + const [input, setInput] = useState('') + const [isRecording, setIsRecording] = useState(false) + + const handleSend = () => { + if (!input.trim()) return + + setMessages([...messages, { role: 'user', content: input }]) + + // Simulate AI response + setTimeout(() => { + setMessages(prev => [...prev, { + role: 'assistant', + content: `I received your message: "${input}". This is a demo response. Connect to the backend API for real responses.` + }]) + }, 1000) + + setInput('') + } + + const handleKeyPress = (e: React.KeyboardEvent) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault() + handleSend() + } + } + + const toggleRecording = () => { + // STT functionality placeholder + setIsRecording(!isRecording) + console.log('Speech-to-Text:', isRecording ? 'Stopped' : 'Started') + } + + const handleSpeak = (text: string) => { + // TTS functionality placeholder + console.log('Text-to-Speech:', text) + if ('speechSynthesis' in window) { + const utterance = new SpeechSynthesisUtterance(text) + window.speechSynthesis.speak(utterance) + } + } + + return ( +
+
+ {messages.length === 0 ? ( +
+

Start a conversation with the AI agent

+
+ ) : ( + messages.map((msg, idx) => ( +
+
+ {msg.content} +
+ {msg.role === 'assistant' && ( + + )} +
+ )) + )} +
+ +
+