# Project export: x-rAI

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: Army of AI Agents. Xplainable Reinforcement AI
- Devpost: https://devpost.com/software/x-rai
- GitHub: https://github.com/rkat7/xAI-MoE
- Video: https://www.youtube.com/embed/Ag9mlwWvJmI?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 4 GitHub contributor(s) — sai krishna rohith k (6 commits), Rahul Singhal (4 commits), Ishika Mittal (1 commits), Anass El Hallaoui (1 commits)

## Devpost submission (written by the team)

### Inspiration

AI is evolving at an incredible pace, but one major challenge remains—how do we ensure AI models are not just powerful but also explainable and efficient? As AI is increasingly used in high-stakes environments, from finance to healthcare, understanding why and how it makes decisions is crucial. We wanted to build a solution that optimizes AI performance while maintaining transparency and adaptability.

### What it does

x-rAI is an AI inference system that uses a Mixture of Experts approach combined with adaptive learning to optimize processing at the token level. It dynamically allocates resources, ensuring efficient computation without compromising accuracy. Our system also employs an auxiliary load balancer and caches at the expert cluster level to accelerate inference speed. This results in faster, more reliable, and scalable AI decision-making. One of the most powerful applications of x-rAI is in accelerating software development cycles. Traditionally, teams spend weeks or even months defining Agile and Scrum stories, mapping out processes, and planning ceremonies. With x-rAI, we can bring this down to minutes by automatically generating Agile story templates, defining sprint goals, and optimizing backlog grooming based on past project data. Our AI system intelligently understands team dynamics, past velocity, and project goals to automate the planning phase, allowing developers to focus on execution rather than time-consuming administrative tasks.

### How we built it

We started by implementing a Mixture of Experts architecture, allowing different specialized models to process different types of inputs. Then, we optimized inference by caching frequently used computations at the cluster level, reducing redundant processing. The system also incorporates an adaptive learning mechanism, refining expert assignments based on real-time feedback. By leveraging efficient resource allocation and caching, we significantly improved performance while keeping computational costs in check. The Judge Agent validates the results, ensuring accuracy & explainability. To accelerate Agile workflows, we trained our model on extensive historical project management data, enabling it to generate precise and actionable Agile stories, sprint plans, and Scrum templates in real time. The system continuously learns from team feedback, making recommendations more accurate and relevant with each iteration.

### Challenges we ran into

Balancing speed and accuracy: Finding the right trade-off between optimizing for speed and maintaining high-quality predictions was tricky. Caching efficiently: Implementing an intelligent caching mechanism at the expert cluster level required careful resource management to avoid bottlenecks. Caching efficiently: Implementing an intelligent caching mechanism at the expert cluster level required careful resource management to avoid bottlenecks. Dynamic load balancing: Ensuring smooth transitions between expert models without causing inference slowdowns was another key challenge. Handling diverse Agile methodologies: Teams follow different processes, so ensuring our model could adapt to Scrum, Kanban, SAFe, and hybrid frameworks was critical. ##

### Accomplishments we're proud of

• Successfully implementing a token-level optimization strategy, which significantly improved inference speed. • Building an adaptive learning system that dynamically refines expert selection for better efficiency. • Designing an intelligent caching system that reduces redundant computations, making the model more cost-effective. • Bringing down Agile story creation time from months to minutes, proving x-rAI’s ability to accelerate software development lifecycles.

### What's next

We plan to expand x-rAI’s capabilities by integrating more robust explainability features, allowing users to better understand why specific expert models were chosen for different inputs. Additionally, we aim to explore real-world deployment scenarios, testing x-rAI in industries like finance and healthcare where speed, accuracy, and explainability are critical. For software development teams, we want to refine Agile automation by integrating real-time AI-powered retrospective analysis, predictive backlog grooming, and automated sprint planning, making project management seamless and hyper-efficient.

## README (from the GitHub repository)

# X-rAI (Xplainable Reinforcement Artificial Intelligence for SuperHuman Builder)

## Introduction
AI is evolving at an incredible pace, but one major challenge remains—how do we ensure AI models are not just powerful but also explainable and efficient? As AI is increasingly used in high-stakes environments, from finance to healthcare, understanding why and how it makes decisions is crucial. x-rAI optimizes AI performance while maintaining transparency and adaptability.

## What is x-rAI?
x-rAI is an AI inference system that leverages a Mixture of Experts (MoE) approach combined with adaptive learning to optimize processing at the token level. It dynamically allocates computational resources, ensuring efficient inference without compromising accuracy. Our system employs an auxiliary load balancer and caching mechanisms at the expert cluster level, resulting in faster, more reliable, and scalable AI decision-making.

### Key Features
- **Mixture of Experts Architecture**: Specializes AI models to process different types of inputs efficiently.
- **Adaptive Learning Mechanism**: Dynamically refines expert assignments based on real-time feedback.
- **Intelligent Caching System**: Reduces redundant computations to improve inference speed and cost-effectiveness.
- **AI-driven Agile Automation**: Reduces Agile planning time from weeks to minutes by generating Agile story templates, sprint goals, and backlog grooming insights.

## How It Works
1. **Optimized AI Inference**
   - Uses a token-level MoE strategy to allocate computational power dynamically.
   - Implements caching at the expert cluster level to reduce redundant processing.
   - Includes a Judge Agent to validate results, ensuring accuracy and explainability.

2. **Accelerating Agile Workflows**
   - Trains on historical project management data to generate precise Agile stories and sprint plans.
   - Learns from team feedback to improve planning recommendations.
   - Supports Scrum, Kanban, SAFe, and hybrid Agile methodologies.

## Challenges We Overcame
- **Balancing Speed & Accuracy**: Optimizing model efficiency without sacrificing prediction quality.
- **Efficient Caching**: Managing an intelligent caching system to prevent processing bottlenecks.
- **Dynamic Load Balancing**: Ensuring seamless transitions between expert models for smooth inference.
- **Handling Diverse Agile Methodologies**: Adapting to various team workflows and project management styles.

## Accomplishments
- Successfully implemented a token-level optimization strategy to boost inference speed.
- Developed an adaptive learning system for efficient expert model selection.
- Designed an intelligent caching system that minimizes redundant computations.
- Reduced Agile story creation time from months to minutes, significantly accelerating development cycles.

## Getting Started
### Prerequisites
- Python 3.8+
- TensorFlow / PyTorch
- Redis (for caching)
- Docker (for deployment)

Clone the repository:
```bash
git clone https://github.com/your-repo/x-rAI.git
cd x-rAI
```

## What We Learned
- Efficient resource allocation is key to optimizing AI inference.
- Properly designed caching mechanisms can dramatically improve performance.
- Adaptive learning improves model responsiveness and efficiency over time.
- AI-driven Agile automation can transform project management by reducing planning overhead.

## What's Next?
- **Enhanced Explainability**: Adding features to help users understand why specific expert models were chosen.
- **Real-world Deployment**: Testing x-rAI in industries like finance and healthcare where accuracy, speed, and transparency are crucial.
- **Agile Process Refinement**: Integrating AI-powered retrospective analysis, predictive backlog grooming, and automated sprint planning for a seamless workflow.


## Detected evidence (automated analysis)

Indexed codebase: 33 recognized source files, 95 KB.
- CSS (language) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- LangChain (technology) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Streamlit (technology) — detected in the code
- Docker (technology) — claimed on Devpost, not found in the code
- Mistral AI (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (39 of 39)

```
.idea/.gitignore
.idea/inspectionProfiles/profiles_settings.xml
.idea/inspectionProfiles/Project_Default.xml
.idea/metaAligner.iml
.idea/misc.xml
.idea/modules.xml
.idea/vcs.xml
adaptive_router.py
dain_agent.py
dashboard.py
health_agent.py
judge_agent.py
main_workflow.py
market_agent.py
meeting_agent.py
naturallang_to_workflow.py
README.md
report_agent.py
Requirements.txt
slc-xlr8/package.json
slc-xlr8/public/index.html
slc-xlr8/public/manifest.json
slc-xlr8/public/robots.txt
slc-xlr8/README.md
slc-xlr8/src/App.css
slc-xlr8/src/App.js
slc-xlr8/src/helper.js
slc-xlr8/src/index.css
slc-xlr8/src/index.js
slc-xlr8/src/Loader.css
slc-xlr8/src/Loader.js
slc-xlr8/src/prompts/data_analyzer.js
slc-xlr8/src/prompts/epics.js
slc-xlr8/src/prompts/rfp_analyzer.js
slc-xlr8/src/prompts/screen_mockup.js
slc-xlr8/src/prompts/technical_design.js
slc-xlr8/src/services/openaiService.js
slc-xlr8/vite.config.js
workflow_parser.py
```

### Dependencies

- Requirements.txt: elasticsearch, intersystems_irispython, langchain, openai, pyjwt, requests, streamlit
- slc-xlr8/package.json: @testing-library/jest-dom@^5.17.0, @testing-library/react@^13.4.0, @testing-library/user-event@^13.5.0, axios@^1.7.7, bootstrap@^5.3.3, bootstrap-icons@^1.11.3, file-saver@^2.0.5, plantuml-encoder@^1.4.0, react@^18.3.1, react-dom@^18.3.1, react-scripts@5.0.1, web-vitals@^2.1.4, xlsx@^0.18.5

### Recent commits (newest first)

- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- Update README.md
- final commmit
- Update README.md
- Uploading SLC-XLR8 agent
- Update README.md
- updated code
- mistral-update
- mistral-update
- Initial dump to remote
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### Requirements.txt

```
langchain
openai
requests
elasticsearch
streamlit
pyjwt
intersystems_irispython
```

### slc-xlr8/package.json

```
{
  "name": "workai",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.7.7",
    "bootstrap": "^5.3.3",
    "bootstrap-icons": "^1.11.3",
    "file-saver": "^2.0.5",
    "plantuml-encoder": "^1.4.0",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4",
    "xlsx": "^0.18.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

```

### slc-xlr8/src/index.js

```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);



```

### slc-xlr8/src/App.js

```javascript
import React, { useState, useEffect } from "react";
import "./App.css";
import { getOpenAIResponse } from "./services/openaiService";
import { readExcelFile, readTextFile, generateUmlUrl } from "./helper";
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import "bootstrap-icons/font/bootstrap-icons.css"; // Import Bootstrap Icons
import Loader from "./Loader";

function App() {
  const [page, setPage] = useState(0);
  const [visitedPages, setVisitedPages] = useState([
    true,
    false,
    false,
    false,
    false,
    false,
  ]);

  const [isLoading, setIsLoading] = useState(false); // Loader state
  const [txtFile, setTxtFile] = useState(null);
  const [excelFile, setExcelFile] = useState(null);
  const [plantUMLCode, setPlantUMLCode] = useState(`
    @startuml
    actor User
    User -> System : Uploads Project Requirements
    System -> User : Provides Workflow Steps
    @enduml
  `);
  const [htmlContent, setHtmlContent] = useState(
    "<h1></h1><p>This is an example HTML content.</p>"
  );
  const [additionalHtmlContent, setAdditionalHtmlContent] = useState(
    "<h1></h1><p>This is additional HTML content.</p>"
  );
  const [additionalHtmlContent1, setAdditionalHtmlContent1] = useState(
    "<h1>Additional HTML Content</h1><p>This is additional HTML content.</p>"
  );
  const [assistantResponse, setAssistantResponse] = useState("");
  const [umlUrl, setUmlUrl] = useState("");
  // const [fileType, setFileType] = useState("");
  const [rfd, setRfd] = useState("");

  const nextPage = async (e) => {
    e.preventDefault();
    setAssistantResponse("");
    setIsLoading(true);
    try {
      let fileContent;
      let prompt;

    // -------------------------------------------------------------------------------------------
    // TIMEOUT TO TEST LOADER!!!
    //   await new Promise((resolve) => setTimeout(resolve, 3000));

    // // Instead of the real response, you can set a mock response here
    // const mockResponse = "This is a simulated response for testing purposes.";
    // setAssistantResponse(mockResponse);
    // -------------------------------------------------------------------------------------------

      if (page === 0 && txtFile) {
        fileContent = await readTextFile(txtFile);
        prompt = "rfp_analyzer";
      } else if (page === 1 && excelFile) {
        fileContent = await readExcelFile(excelFile);
        prompt = "data_analyzer";
      } else if (page === 2) {
        fileContent = rfd + plantUMLCode;
        prompt = "epics";
      } else if (page === 3) {
        fileContent = htmlContent;
        prompt = "technical_design";
      } else if (page === 4) {
        fileContent = additionalHtmlContent;
        prompt = "screen_mockup";
      }
      debugger;

      const response = await getOpenAIResponse(fileContent, prompt);
      // let response = "";
      if (page === 0) {
        // response = `{ "epics": [ { "Epic": "Listing Management", "Features": [ "Product Catalog Integration: Enable seamless integration of seller's product catalog for easier listing management.", "Multi-format Listing Support: Allow listings in multiple formats including auctions and fixed-price sales for increased selling flexibility.", "Category-based Organization: Implement category-based organization of listings for improved product discoverability." ] }, { "Epic": "Inventory Management", "Features": [ "Real-time Inventory Sync: Maintain real-time inventory levels across all sales channels to prevent overselling.", "Minimum Threshold Alerts: Enable automated alerts for low stock levels to ensure timely replenishment.", "Automated Restock Triggers: Implement automated triggers for restocking items based on inventory levels and sales velocity." ] }, { "Epic": "Pricing System", "Features": [ "Dynamic Pricing Algorithms: Implement dynamic pricing algorithms to optimize listing prices based on market conditions and demand.", "Auction Management: Enable management of auction-style listings with automated bidding and closing processes.", "Bulk Pricing Updates: Allow sellers to update prices in bulk for efficient listing management." ] }, { "Epic": "Buyer Experience", "Features": [ "Advanced Search Functionality: Implement advanced search capabilities to help buyers find desired products easily.", "Secure Checkout Process: Ensure a secure checkout process with multiple payment methods for improved conversion rates.", "Order Tracking: Provide buyers with real-time tracking of their orders to enhance post-purchase experience." ] }, { "Epic": "Security", "Features": [ "Multi-factor Authentication: Implement multi-factor authentication for user accounts to enhance security.", "Encrypted Communications: Ensure all communications are encrypted to protect sensitive user data.", "Fraud Detection: Implement automated fraud detection mechanisms to protect users and maintain platform integrity." ] }, { "Epic": "Integration", "Features": [ "Third-Party System Integration: Enable integration with key third-party systems such as payment gateways, shipping carriers, and inventory management.", "RESTful API Architecture: Implement a RESTful API architecture to facilitate seamless integration and data exchange with external systems." ] }, { "Epic": "Compliance", "Features": [ "GDPR Compliance: Ensure platform complies with GDPR for data privacy and protection.", "PCI DSS Standards: Adhere to PCI DSS standards for secure payment processing and cardholder data protection." ] }, { "Epic": "Performance", "Features": [ "High Availability: Maintain 99.99% platform uptime for consistent user experience.", "Fast Load Time: Ensure page load time is under 2 seconds for improved user experience and SEO." ] } ] }`;
        setRfd(response);
      } else if (page === 1) {
        //         response = `@startuml
        // skinparam class {
        // BackgroundColor White
        // ArrowColor Black
        // BorderColor Black
        // }
        // entity "Customer" as C
[truncated — 22508 more characters]
```

### judge_agent.py

```python
#!/usr/bin/env python
"""
judge_agent.py
Implements the Judge Agent that validates outputs from various agents.
Perform basic validation checks and returns validation messages.
"""

def validate_output(output_type, output_data):
    if output_type == "health":
        if output_data.get("heart_rate", 0) > 100:
            return False, "Heart rate too high; please re-run health analysis."
    elif output_type == "report":
        if "report" not in output_data.lower():
            return False, "Generated report invalid; please regenerate."
    return True, "Output validated successfully."

if __name__ == "__main__":
    dummy_health = {"heart_rate": 120}
    valid, message = validate_output("health", dummy_health)
    print("Health Validation:", message)

```

### naturallang_to_workflow.py

```python
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

def parse_workflow(user_input):
    prompt = PromptTemplate(
        input_variables=["workflow"],
        template=("Decompose the following workflow into JSON subtasks with 'task' "
                  "and 'type' fields (e.g., health, meeting, report):\n\n{workflow}")
    )
    chain = LLMChain(llm=OpenAI(model="gpt-4"), prompt=prompt)
    response = chain.run(workflow=user_input)
    return response

# Example usage
if __name__ == "__main__":
    user_input = ("Assess squad readiness using wearable data, "
                  "schedule a review meeting, "
                  "and generate a mission report.")
    print(parse_workflow(user_input))

```

### market_agent.py

```python
#!/usr/bin/env python
"""
market_agent.py
Simulates the Market Analysis Agent.
Retrieves context from a simulated Elasticsearch backend and generates market insights.
"""

def elastic_retrieve(query):
    # Dummy retrieval simulating an Elasticsearch query.
    dummy_documents = [
        "Market trends show rising investments in AI healthcare startups.",
        "Funding rounds in this sector have increased significantly.",
        "Competitive dynamics are rapidly changing with new entrants emerging."
    ]
    return " ".join(dummy_documents)

def market_analysis(task_description):
    context = elastic_retrieve(task_description)
    insight = f"Market Analysis Insight: Based on the data ({context}), the analysis for '{task_description}' indicates strong growth potential."
    return insight

if __name__ == "__main__":
    description = "Analyze market trends for AI healthcare startups."
    result = market_analysis(description)
    print("Market Analysis Result:", result)

```

### workflow_parser.py

```python
#!/usr/bin/env python
"""
workflow_parser.py
Parses a natural language workflow into actionable JSON subtasks using LangChain and GPT-4.
"""

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

def parse_workflow(user_input):
    # Define a prompt template to decompose the workflow into JSON subtasks.
    prompt = PromptTemplate(
        input_variables=["workflow"],
        template=("Decompose the following workflow into JSON subtasks with 'task' and 'type' fields. "
                  "Valid types are 'health', 'market', 'meeting', or 'report'.\n\n{workflow}\n")
    )
    chain = LLMChain(llm=OpenAI(model="gpt-4"), prompt=prompt)
    response = chain.run(workflow=user_input)
    return response

if __name__ == "__main__":
    user_input = ("Assess squad readiness using wearable data, schedule a review meeting, and generate a mission report.")
    parsed = parse_workflow(user_input)
    print("Parsed Workflow:", parsed)

```

### dain_agent.py

```python
#!/usr/bin/env python
"""
dain_agent.py
Implements the DAIN Agent to enrich the final report using multi-modal data.
Fetches simulated image, audio, and text data, and incorporates these insights.
"""

def fetch_multimodal_data(user_id):
    # Simulated multi-modal data; in a real solution, integrate real APIs.
    multimodal_data = {
        "images": "Image analysis indicates clear conditions and high team morale.",
        "audio": "Audio transcript reveals low ambient noise and calm communication.",
        "text": "Text analytics confirm high levels of preparedness and strategic planning."
    }
    return multimodal_data

def enhance_analysis(initial_report, user_id):
    multimodal_data = fetch_multimodal_data(user_id)
    enhanced_report = (
        initial_report +
        "\n\nEnhanced Multi-Modal Insights:\n" +
        f"- Visual: {multimodal_data['images']}\n" +
        f"- Audio: {multimodal_data['audio']}\n" +
        f"- Text: {multimodal_data['text']}\n" +
        "Overall, multi-modal analysis confirms mission readiness with high confidence."
    )
    return enhanced_report

if __name__ == "__main__":
    dummy_report = "Mission Report: All metrics indicate readiness."
    user_id = "demo_user_001"
    final_report = enhance_analysis(dummy_report, user_id)
    print("Enhanced Analysis Report:")
    print(final_report)

```

### dashboard.py

```python
#!/usr/bin/env python
"""
dashboard.py
A Streamlit dashboard that provides a real-time view of the entire workflow,
including live IRIS metrics and results from multi-agent workflow execution.
"""

import streamlit as st
from main_workflow import main_workflow
from intersystems_iris.dbapi._DBAPI import connect as iris_connect

IRIS_CONFIG = {
    "hostname": "localhost",
    "port": 1972,
    "namespace": "USER",
    "username": "_SYSTEM",
    "password": "demo12345"
}

def ensure_executionlog_table(config):
    try:
        with iris_connect(**config) as conn:
            with conn.cursor() as cursor:
                create_query = (
                    "CREATE TABLE ExecutionLog ("
                    "id INT IDENTITY PRIMARY KEY, "
                    "latency INT"
                    ")"
                )
                insert_query = (
                    "INSERT INTO ExecutionLog (latency)"
                    "VALUES(250);"
                ")"
                )
                cursor.execute(create_query)
                cursor.execute(insert_query)
                conn.commit()
                st.info("ExecutionLog table created.")
    except Exception as e:
        if "already exists" in str(e) or "Duplicate" in str(e):
            # st.info("ExecutionLog table already exists.")
            pass
        else:
            st.error(f"Error creating ExecutionLog table: {e}")

def fetch_live_metrics():
    ensure_executionlog_table(IRIS_CONFIG)
    avg_latency = None
    try:
        with iris_connect(**IRIS_CONFIG) as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT AVG(latency) FROM ExecutionLog")
                result = cursor.fetchone()
                if result is not None:
                    avg_latency = result[0]
    except Exception as e:
        st.error(f"Error fetching metrics from IRIS: {e}")
        avg_latency = None
    return avg_latency

st.set_page_config(layout="wide")
st.title("MetaAligner SquadOps Dashboard")
st.markdown("Unified System for Squad-Level Health Command Operations with Judge & DAIN Agent Integration")

st.subheader("Live IRIS Metrics")
latency = fetch_live_metrics()
if latency is None:
    st.write("No metrics available. Ensure the 'ExecutionLog' table exists and is populated.")
else:
    st.write(f"Current average latency: {latency} ms")

user_input = st.text_area("Enter your workflow:", "Assess squad readiness using wearable data, schedule a review meeting, and generate a mission report.")
user_id = st.text_input("Enter your User ID:", "demo_user_001")

if st.button("Run Workflow"):
    st.write("Processing workflow, please wait...")
    results = main_workflow(user_input, user_id)
    st.subheader("Workflow Results")
    st.json(results)

```

[23 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]