Spaces:
Running
Running
Commit Β·
5655786
1
Parent(s): 3eda9f9
feat: integrate Google ADK agent and MongoDB Atlas SRE telemetry
Browse filesFiles changed (23)
- .dockerignoreAdded+37
- .env.example+31-4
- .gitignore+3
- Blog.MD+7
- README.md+157-7
- agent/__init__.pyAdded+22
- agent/adk_agent.pyAdded+636
- fleet_inference.py+106-9
- frontend/index.html+38-1
- frontend/kernel.js+2-2
- frontend/main.js+115-4
- frontend/styles.css+354-119
- generate_synthetic_data.pyAdded+198
- mongodb_metrics.pyAdded+122
- mongodb_streams.pyAdded+153
- mongodb_vector.pyAdded+511
- openenv.yaml+3-3
- predictive_agent.pyAdded+327
- requirements.txt+10
- server/app.py+315-1
- setup_vector_index.pyAdded+176
- synthetic_trajectories.jsonAdded
- upload_to_mongodb.pyAdded+180
12345678910111213141516171819202122232425262728293031323334353637# Secrets β NEVER ship in Docker image.env.env.local.env.*.local
# Python bytecode__pycache__/*.py[cod]*.pyo*.pyd
# Virtual environments.venv/venv/ENV/env/
# Large data files (use volumes or object storage)synthetic_trajectories.jsonresults/
# Git.git/.gitattributes
# Dev tools.vscode/.idea/*.code-workspacescratch/
# Notebooksnotebooks/
# OS cruft.DS_StoreThumbs.db123456789101112131415# =============================================================# Mixed Precision Training Environment β Safe Template# =============================================================# Copy this file to .env and fill in your actual values.# NEVER put real secrets in this file.# --- LLM Provider ---# For Groq: https://console.groq.com/keysHF_TOKEN=your_api_key_hereAPI_BASE_URL=https://api.groq.com/openai/v1MODEL_NAME=llama-3.1-8b-instant# --- Environment Server ---ENV_URL=http://localhost:7860123456789101112131415161718192021222324252627282930313233343536373839404142# =============================================================# Libratio Fleet β Safe Configuration Template# =============================================================# Copy this file to .env and fill in your actual values.# NEVER put real secrets in this file.# --- LLM Provider (Groq β default) ---# Free API keys: https://console.groq.com/keysHF_TOKEN=your_huggingface_token_hereGROQ_API_KEY=your_groq_api_key_hereAPI_BASE_URL=https://api.groq.com/openai/v1MODEL_NAME=llama-3.1-8b-instant# --- HuggingFace Custom Model (optional) ---# Fine-tuned Libratio Fleet model for fleet_precision + fleet_recovery tasksHF_MODEL_URL=https://router.huggingface.co/v1/chat/completionsHF_MODEL_NAME=SnippyCodes/libratio-fleet-llama3-grpo:featherless-ai# --- Google AI (Gemini) ---# Used for Atlas Vector Search embeddings AND Google ADK agent# Free API key: https://aistudio.google.com/apikeyGEMINI_API_KEY=your_gemini_api_key_here# --- Google ADK / Agent Builder ---# ADK can run in two modes:# 1. AI Studio (free): just set GEMINI_API_KEY above, leave GOOGLE_GENAI_USE_VERTEXAI=FALSE# 2. Vertex AI (GCP): set GOOGLE_GENAI_USE_VERTEXAI=TRUE + project/location belowGOOGLE_GENAI_USE_VERTEXAI=FALSEGOOGLE_CLOUD_PROJECT=your-gcp-project-idGOOGLE_CLOUD_LOCATION=us-central1# ADK model to use (gemini-2.0-flash is fast and free-tier friendly)ADK_MODEL=gemini-2.0-flash# --- MongoDB Atlas ---# Connection string from Atlas UI β Connect β Drivers# Required for: Vector Search RAG, telemetry logging, analytics, MongoDB MCP ServerMONGO_URI=mongodb+srv://<user>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority# --- Environment Server ---ENV_URL=http://localhost:7860
48 unmodified lines49505148 unmodified linesbenchmark_results.jsonbenchmark.pygenerate_chart.py48 unmodified lines49505152535448 unmodified linesbenchmark_results.jsonbenchmark.pygenerate_chart.py# --- Scratch directory ---scratch/
34 unmodified lines35363738394034 unmodified lines**Difference Rewards for Multi-Agent Scenarios**In cluster negotiation, it is difficult to assign credit. If Model A and Model B share a cluster, does an overall throughput increase belong to A or B? We implemented Difference Rewards: the environment evaluates the cluster's total reward, then mathematically removes an agent's contribution to calculate exactly how much *marginal* value that specific agent added.### Training with GRPO and UnslothThe agent behavior was trained with RL against the Agentic Kernel using Hugging Face's TRL framework and Unsloth.34 unmodified lines3536373839404142434445464734 unmodified lines**Difference Rewards for Multi-Agent Scenarios**In cluster negotiation, it is difficult to assign credit. If Model A and Model B share a cluster, does an overall throughput increase belong to A or B? We implemented Difference Rewards: the environment evaluates the cluster's total reward, then mathematically removes an agent's contribution to calculate exactly how much *marginal* value that specific agent added.### The MongoDB Intelligent CoreA production-ready fleet management agent needs more than just a simulator; it needs a memory. We integrated MongoDB Atlas as our core data platform to store, search, and analyze historical fleet telemetry:* **Atlas Vector Search (Semantic RAG)**: Instead of querying for exact matches, we serialize GPU training trajectories into natural language and generate 768-dim embeddings using Gemini `models/gemini-embedding-001`. A MongoDB Atlas Vector Search index allows our predictive agent to run semantic searches, retrieving historically similar crashes to recommend preventative precision strategies.* **Native Time Series**: We log step-by-step GPU metrics (VRAM, thermal status, power) to a native MongoDB Time Series collection. This enables automatic compression (saving 95% space) and lightning-fast sequential data queries.* **Change Stream Triaging**: A background SRE daemon watches the database runs via MongoDB Change Streams. If a training run fails, it catches the insertion event, pulls the step history from the Time Series collection, runs automated diagnostics, and logs a detailed report in our `incident_reports` collection.### Training with GRPO and UnslothThe agent behavior was trained with RL against the Agentic Kernel using Hugging Face's TRL framework and Unsloth.
137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691703 unmodified lines174175176137 unmodified lines---## 5. Setup & Reproduction```bash# Run the environment serverpip install -r requirements.txtuvicorn server.app:app --host 0.0.0.0 --port 7860# Run the kernel benchmark (reproduces the 11,281 evals/sec claim)python kernel_benchmark.py# Generate the training graphs (reproduces the PNGs in the README)python generate_training_graphs.py# Run multi-agent inference (requires HF_TOKEN or Groq API key)export HF_TOKEN="your_token"python fleet_inference.py```### Architecture**OpenEnv** (standard interface) β **TRL GRPOTrainer** (optimization) β **Unsloth** (4-bit QLoRA acceleration) β **Agentic Kernel** (deterministic physics rewards)> Full roadmap: multi-GPU topology modeling, live DCGM telemetry, curriculum learning, kernel-as-a-service. See [KERNEL.md](KERNEL.md).---## 6. RL Debugging MethodologyFollowing the official OpenEnv best practices, this environment was developed using strict isolation to prevent conflating environment bugs with optimizer failures:3 unmodified lines4. **Frozen Model Testing:** Sent zero-shot prompts to the base model (`fleet_inference.py`) to verify it understood the JSON format.5. **Tiny RL Experiment:** Ran a 10-step GRPO test to ensure loss updating.6. **Scaled Training:** Executed the final 400-step training run.137 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512523 unmodified lines256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326137 unmodified lines------## 5. MongoDB Intelligent CoreInstead of treating MongoDB as a basic JSON dump, Libratio Fleet integrates MongoDB Atlas as its intelligent MLOps backend using advanced native features:```βββββββββββββββββββββββββββββββββββββββ Agentic RL Environment ββββββββββββββββββββ¬ββββββββββββββββββββ Step Telemetry &β Run MetricsβΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ MongoDB Atlas ββ ββ βββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββ β trajectories (flat) β β gpu_telemetry_metrics (Time) β β runs (telemetry) β ββ β - Gemini 768d Embeddings β β - Auto-compressed Metrics β β - Average scores/runs β ββ β - $vectorSearch Index β β - Sorted by step/timestamp β β - Change Stream target β ββ βββββββββββββββββ²ββββββββββββββββ βββββββββββββββββ²ββββββββββββββββ βββββββββββββ¬βββββββββββββ ββ β β β βββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββΌβββββββββββββββββ β ββ Semantic RAG β Fetch Profile β Trigger eventβ β ββββββββββββ΄ββββββββββ βββββββββββ΄ββββββββββ ββ Predictive Agent β β mongodb_streams.pyββββββββββββββββββββββββ (Gemini RAG SRE) β β (Change Stream) ββββββββββββββββββββββ βββββββββββ¬βββββββββββ Log IncidentβΌββββββββββββββββββββββ incident_reports ββββββββββββββββββββββ```### π§ 1. Atlas Vector Search (Semantic RAG)- **Data Serialization**: Trajectory data (model, layer precisions, memory, thermals, outcomes) is serialized into semantic natural language.- **Gemini Embeddings**: Serialized text is embedded into a 768-dim space via Google's `models/gemini-embedding-001`.- **Cosine Similarity Match**: At query time, the live cluster state is embedded and searched via MongoDB Atlas `$vectorSearch` (`trajectory_vector_index`) against past crash documents.- **RAG Recovery**: Rather than simple exact filters (e.g. `memory > 200`), Vector Search finds records that *feel* semantically similar, enabling the agent to learn from fuzzy historic contexts.### β±οΈ 2. Native Time Series Metrics Logging- **Optimized Storage**: Step-by-step telemetry (VRAM, thermal status, power, reward) is saved to a native MongoDB Time Series collection (`gpu_telemetry_metrics`).- **Granular Grouping**: Documents are partition-organized by `timeField: "timestamp"` and `metaField: "metadata"`. MongoDB automatically compresses the data (saving up to 95% disk space) and indexes it for rapid historical querying.### β‘ 3. Real-Time MLOps Change Streams- **Event-Driven Diagnostics**: A background daemon (`mongodb_streams.py`) listens to a MongoDB `$changeStream` on the `runs` collection.- **Auto-Triaging**: If a run completes with a poor score (<0.60), the listener catches the insertion event, queries the Time Series collection to build a step-by-step performance profile of that execution, runs a heuristic diagnostic, and posts a detailed post-incident report to the `incident_reports` collection.### π 4. Aggregation Analytics Dashboard- Exposes an `/api/analytics` endpoint on the FastAPI server.- Uses complex multi-stage `$group`, `$sort`, and conditional `$cond` aggregation pipelines to calculate running average scores per task, success percentages, and cross-model performance benchmarks directly inside the database.---## 6. Setup & Reproduction```bash# 1. Install dependencies (includes Google ADK + MongoDB MCP support)pip install -r requirements.txt# 2. Copy and fill in your secretscp .env.example .env# Edit .env: set MONGO_URI, GEMINI_API_KEY, HF_TOKEN, GROQ_API_KEY# 3. Run the environment serveruvicorn server.app:app --host 0.0.0.0 --port 7860# 4. Run the kernel benchmark (reproduces the 11,281 evals/sec claim)python kernel_benchmark.py# 5. Generate the training graphs (reproduces the PNGs in the README)python generate_training_graphs.py# 6. Run multi-agent inference (requires HF_TOKEN or Groq API key)export HF_TOKEN="your_token"python fleet_inference.py```### Google ADK Agent (MongoDB MCP Integration)```bash# Run the Google ADK agent directly (uses Gemini + MongoDB MCP Server)# Requires: GEMINI_API_KEY + MONGO_URI in .env, and npx availablepython agent/adk_agent.py# Or trigger via the API while the server is running:curl -X POST http://localhost:7860/adk/run \-H "Content-Type: application/json" \-d '{"task_id": "fleet_precision"}'# Check ADK + MongoDB MCP status:curl http://localhost:7860/adk/status```### Architecture**OpenEnv** (standard interface) β **TRL GRPOTrainer** (optimization) β **Unsloth** (4-bit QLoRA acceleration) β **Agentic Kernel** (deterministic physics rewards)**ADK Layer**: Gemini 2.0 Flash β Google ADK MCPToolset β MongoDB MCP Server β MongoDB Atlas---> See **Section 5** above for the full MongoDB Atlas Intelligent Core architecture.## 7. RL Debugging MethodologyFollowing the official OpenEnv best practices, this environment was developed using strict isolation to prevent conflating environment bugs with optimizer failures:3 unmodified lines4. **Frozen Model Testing:** Sent zero-shot prompts to the base model (`fleet_inference.py`) to verify it understood the JSON format.5. **Tiny RL Experiment:** Ran a 10-step GRPO test to ensure loss updating.6. **Scaled Training:** Executed the final 400-step training run.---## 8. Using Your Custom Trained ModelThe project ships with a GRPO-fine-tuned **LLaMA-3.1-8B** adapter published at [`SnippyCodes/libratio-fleet-llama3-grpo`](https://huggingface.co/SnippyCodes/libratio-fleet-llama3-grpo) and served via [Featherless AI](https://featherless.ai). You can swap in your own retrained adapter in three ways:### Option A β HuggingFace (default, cloud)The agent automatically routes `fleet_precision` and `fleet_recovery` tasks to your custom model. Set these in `.env`:```bashHF_TOKEN=your_hf_tokenHF_MODEL_URL=https://router.huggingface.co/v1/chat/completionsHF_MODEL_NAME=YOUR_HF_USERNAME/your-model-name:featherless-ai```### Option B β Local vLLM Server (fastest, GPU required)After training your adapter with `colab_qlora_grpo_fleet.py`:```bash# Serve the merged model locallypip install vllmvllm serve results/qlora_grpo_fleet_merged_16bit \--host 0.0.0.0 --port 8000 \--served-model-name libratio-fleet-local```Then update `.env`:```bashAPI_BASE_URL=http://localhost:8000/v1MODEL_NAME=libratio-fleet-localHF_TOKEN=not-neededHF_MODEL_URL=http://localhost:8000/v1/chat/completionsHF_MODEL_NAME=libratio-fleet-local```### Option C β Route ALL Tasks to Your Custom ModelBy default, `fleet_oversight` and `fleet_resource` use Groq (larger model). To route everything to your model, edit `fleet_inference.py` line ~152:```python# Change this:if task_id in ["fleet_oversight", "fleet_resource"] or "groq.com" in current_base_url:# To this (disable Groq routing):if False:```### Retraining from Scratch```bash# In Google Colab (free T4 GPU):# 1. Open colab_qlora_grpo_fleet.py# 2. Update REPO_URL to your fork# 3. Run β training takes ~2-3 hours on T4# 4. Adapter is saved to results/qlora_grpo_fleet/# Push your new adapter to HuggingFace Hub:from huggingface_hub import HfApiapi = HfApi()api.upload_folder(folder_path="results/qlora_grpo_fleet",repo_id="YOUR_USERNAME/libratio-fleet-v2",repo_type="model")```
12345678910111213141516171819202122"""Libratio Fleet β Agent package"""from .adk_agent import ( run_fleet_task_with_adk, get_mongodb_mcp_toolset, get_fleet_physics_tools, reset_fleet_environment, step_fleet_environment, compute_precision_physics, ADK_AVAILABLE,)
__all__ = [ "run_fleet_task_with_adk", "get_mongodb_mcp_toolset", "get_fleet_physics_tools", "reset_fleet_environment", "step_fleet_environment", "compute_precision_physics", "ADK_AVAILABLE",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636"""Libratio Fleet β Google ADK Agent Orchestrator===============================================Google Cloud Agent Builder integration using Google ADK 2.2.0.
HOW IT WORKS (simple version): 1. Google ADK gives Gemini a set of "tools" it can call 2. One toolset = MongoDB MCP Server (a Node.js process that knows how to talk to MongoDB) 3. Another toolset = our fleet physics tools (Python functions Gemini can call directly) 4. Gemini reasons about the fleet task, decides which tools to call, and orchestrates everything 5. ADK runs this in a loop until the task is done
WHY THIS MATTERS FOR THE HACKATHON: - "Google Cloud Agent Builder" = Google ADK (the code-first version of Agent Builder) - "MongoDB MCP Server" = the partner superpowers requirement - Gemini 2.0 Flash = the brain - This file is the proof that all three are wired together
Requirements: - pip install google-adk mcp - npm/npx available (for MongoDB MCP server subprocess) - MONGO_URI, GEMINI_API_KEY set in .env"""
import asyncioimport jsonimport osimport sysimport loggingfrom typing import Optional
from dotenv import load_dotenv
load_dotenv()
# ββ Google ADK imports ββββββββββββββββββββββββββββββββββββββββββββββββββββββtry: from google.adk.agents import Agent from google.adk.runners import InMemoryRunner from google.adk.tools.mcp_tool.mcp_toolset import McpToolset, StdioConnectionParams from google.adk.tools import FunctionTool from mcp import StdioServerParameters from google.genai import types as genai_types ADK_AVAILABLE = Trueexcept ImportError as e: ADK_AVAILABLE = False print(f"[WARN] Google ADK not installed: {e}") print(" Run: pip install google-adk mcp")
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββMONGO_URI = os.getenv("MONGO_URI", "")GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
# Use Vertex AI if GCP project is configured, otherwise AI Studio (free)USE_VERTEX_AI = os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "FALSE").upper() == "TRUE"
if not USE_VERTEX_AI: # Unset Vertex AI env variables in Python to force the SDK to use the API key os.environ.pop("GOOGLE_CLOUD_PROJECT", None) os.environ.pop("GOOGLE_CLOUD_LOCATION", None) print("AI Studio mode enabled (Vertex AI environment variables cleared)")
# Model β Gemini 2.0 Flash is fast and free-tier friendlyADK_MODEL = os.getenv("ADK_MODEL", "gemini-2.0-flash")
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")logger = logging.getLogger("libratio.adk")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PART 1: MONGODB MCP TOOLSET# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# This launches the official MongoDB MCP server (@mongodb-js/mongodb-mcp-server)# as a child process. The ADK MCPToolset wraps ALL its tools so Gemini can# call them like native Python functions.## Tools exposed by MongoDB MCP server include:# - find: Query documents from a collection# - aggregate: Run aggregation pipelines (including $vectorSearch)# - insertMany: Insert documents# - createIndex: Create search/vector indexes# - listCollections: List all collections# - count: Count documents matching a filter# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_mongodb_mcp_toolset() -> "McpToolset | None": """ Creates a Google ADK McpToolset connected to the MongoDB MCP Server.
The MongoDB MCP server runs as a Node.js subprocess (via npx). ADK communicates with it over stdio using the Model Context Protocol.
Returns: McpToolset if MongoDB MCP is available, None otherwise. """ if not ADK_AVAILABLE: logger.warning("ADK not available -- MongoDB MCP toolset skipped") return None
import platform if platform.system() == "Windows": logger.info("Windows detected -- skipping Node.js MCP stdio subprocess to prevent asyncio pipe issues. Using PyMongo tools instead.") return None
if not MONGO_URI: logger.warning("MONGO_URI not set -- MongoDB MCP toolset will use localhost")
logger.info("Initializing MongoDB MCP Server (via npx mongodb-mcp-server)...")
# The MongoDB MCP server is a Node.js package published by MongoDB. # Package was renamed from @mongodb-js/mongodb-mcp-server -> mongodb-mcp-server # Connection string is now passed via MDB_MCP_CONNECTION_STRING env var # (the old --connectionString CLI arg is deprecated).
# On Windows, "npx" is actually "npx.cmd" β Python subprocess can't find # bare "npx" without shell=True. We resolve the full path with shutil.which. import shutil npx_cmd = shutil.which("npx") if npx_cmd is None: logger.error("npx not found on PATH. Install Node.js: https://nodejs.org") return None
logger.info(f"Using npx at: {npx_cmd}")
mcp_toolset = McpToolset( connection_params=StdioConnectionParams( server_params=StdioServerParameters( # Run the official MongoDB MCP server via npx (auto-downloads) command=npx_cmd, # full path works on all OS args=[ "-y", # auto-install without prompting "mongodb-mcp-server@latest", # official MongoDB MCP package (new name) ], env={ **os.environ, # inherit PATH, NODE, etc. "MDB_MCP_CONNECTION_STRING": MONGO_URI, # official env var name }, ), timeout=60, # 60s timeout for initial npx package download on first run ) )
logger.info("MongoDB MCP toolset configured (npx mongodb-mcp-server)") return mcp_toolset
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PART 2: FLEET PHYSICS TOOLS (ADK Python Tools)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# These wrap our existing fleet environment as ADK-compatible Python tools.# Gemini can call these to interact with the physics-based RL environment.# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Module-level fleet env instance (created lazily)_fleet_env_instance = None
def _fleet_env(): global _fleet_env_instance if _fleet_env_instance is None: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from environment.fleet_env import FleetEnvironment _fleet_env_instance = FleetEnvironment() return _fleet_env_instance
def reset_fleet_environment(task_id: str) -> dict: """ Reset the Libratio fleet environment to start a new episode.
Use this at the beginning of each fleet task to get an initial observation of the GPU cluster state. The observation tells you about available GPUs, memory, and the model(s) you need to configure.
Args: task_id: One of 'fleet_precision', 'fleet_oversight', 'fleet_resource', 'fleet_recovery'
Returns: Initial cluster observation dict with GPU state, model info, and task context. """ try: obs = _fleet_env().reset(task_id) logger.info(f"[Tool] reset_fleet_environment: task={task_id}") return {"success": True, "observation": obs, "task_id": task_id} except Exception as e: logger.error(f"[Tool] reset_fleet_environment error: {e}") return {"success": False, "error": str(e)}
def step_fleet_environment(action_json: str) -> dict: """ Submit an action to the fleet environment and get a reward score.
After observing the cluster state, use this tool to submit your decision as a JSON string. The environment evaluates your action using the physics-based reward model and returns a score between 0.01 and 0.99.
Action format depends on the current task: - fleet_precision: {"precision_strategy": {"embedding": "FP32", "attention": "BF16", "ffn": "FP8", "layernorm": "BF16", "output": "FP32"}, "reasoning": "..."} - fleet_oversight: {"action_type": "continue_monitoring|flag_instability", "analysis": "...", "flagged_model": null} - fleet_resource: {"allocations": {"model_a": {"gpus": 4, "precision_strategy": {...}}}, "reasoning": "..."} - fleet_recovery: Phase-dependent (diagnose/reallocate/verify)
Args: action_json: JSON string containing the action dict
Returns: Dict with score (0.01-0.99), feedback string, done flag, and next observation. """ try: action = json.loads(action_json) result = _fleet_env().step(action) score = max(0.01, min(0.99, float(result["reward"]["score"]))) logger.info(f"[Tool] step_fleet_environment: score={score:.3f}") return { "success": True, "score": score, "feedback": result["reward"]["feedback"], "done": result["done"], "observation": result.get("observation"), } except json.JSONDecodeError as e: return {"success": False, "error": f"Invalid JSON in action: {e}"} except Exception as e: logger.error(f"[Tool] step_fleet_environment error: {e}") return {"success": False, "error": str(e)}
def compute_precision_physics(layer_name: str, precision: str) -> dict: """ Compute the physics-based score and safety check for a precision assignment.
Use this to validate your precision choices BEFORE submitting to the fleet. This is the Agentic Kernel β pure math based on NVIDIA Transformer Engine benchmarks.
Args: layer_name: One of 'embedding', 'attention', 'ffn', 'layernorm', 'output' precision: One of 'FP32', 'BF16', 'FP16', 'FP8'
Returns: Dict with score, stability, and recommendation. """ try: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from environment.physics_model import score_precision_layer, STABILITY_SCORE score, feedback = score_precision_layer(layer_name, precision) stability = STABILITY_SCORE.get(layer_name, {}).get(precision, 0.5) return { "layer": layer_name, "precision": precision, "physics_score": round(score, 3), "stability": round(stability, 3), "is_stable": stability >= 0.7, "feedback": feedback, "recommendation": ( f"SAFE: {precision} is good for {layer_name}" if stability >= 0.7 else f"RISKY: {precision} on {layer_name} may cause instability (stability={stability:.2f})" ), } except Exception as e: return {"error": str(e), "layer": layer_name, "precision": precision}
def get_fleet_physics_tools() -> list: """Return a list of ADK FunctionTool wrappers for fleet physics functions.""" if not ADK_AVAILABLE: return [] return [ FunctionTool(func=reset_fleet_environment), FunctionTool(func=step_fleet_environment), FunctionTool(func=compute_precision_physics), ]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PART 2B: MONGODB PYMONGO TOOLS (FALLBACK)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# When the MCP subprocess fails (common on Windows due to asyncio pipe issues),# these pymongo-based FunctionTools serve as the MongoDB integration.# Gemini calls them exactly like MCP tools β same purpose, same data.# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _get_mongo_db(): """Get a pymongo database connection (reuses existing MONGO_URI).""" try: import certifi from pymongo import MongoClient client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000) return client["libratio"] except Exception as e: logger.warning(f"MongoDB connection failed: {e}") return None
def query_mongodb_trajectories(filter_json: str = "{}", limit: int = 5) -> dict: """ Query historical training trajectories from MongoDB Atlas.
Use this tool to find past GPU fleet training runs from the 'trajectories' collection. Returns documents with precision strategies, rewards, and cluster states from previous episodes. This data helps you make better decisions by learning from history.
Args: filter_json: MongoDB filter as JSON string. Use '{}' for all docs, or '{"task_id": "fleet_precision"}' to filter. limit: Maximum number of documents to return (default 5).
Returns: Dict with matching trajectory documents from MongoDB Atlas. """ db = _get_mongo_db() if db is None: return {"error": "MongoDB not connected. Check MONGO_URI in .env", "documents": []}
try: import json as _json filter_dict = _json.loads(filter_json) if filter_json else {} docs = list(db["trajectories"].find(filter_dict, {"_id": 0, "embedding": 0}).limit(limit)) logger.info(f"[MongoDB Tool] query_trajectories: filter={filter_json}, found={len(docs)}") return {"success": True, "count": len(docs), "documents": docs} except Exception as e: return {"error": str(e), "documents": []}
def log_run_to_mongodb(task_id: str, score: float, action_json: str, reasoning: str) -> dict: """ Log a training run result to MongoDB Atlas 'runs' collection.
Call this AFTER stepping the environment to record your result. This creates a permanent record in MongoDB that can be queried by future agents.
Args: task_id: The fleet task that was run (e.g. 'fleet_precision') score: The reward score achieved (0.01 to 0.99) action_json: The JSON action that was submitted reasoning: Your reasoning for the chosen action
Returns: Dict confirming the insert with the document ID. """ db = _get_mongo_db() if db is None: return {"error": "MongoDB not connected", "logged": False}
try: import json as _json from datetime import datetime, timezone doc = { "task_id": task_id, "score": score, "action": _json.loads(action_json) if isinstance(action_json, str) else action_json, "reasoning": reasoning, "agent": "libratio_fleet_commander_adk", "model": ADK_MODEL, "timestamp": datetime.now(timezone.utc), } result = db["runs"].insert_one(doc) logger.info(f"[MongoDB Tool] log_run: task={task_id}, score={score}, id={result.inserted_id}") return {"success": True, "logged": True, "document_id": str(result.inserted_id)} except Exception as e: return {"error": str(e), "logged": False}
def get_mongodb_fallback_tools() -> list: """Return pymongo-based FunctionTools as a fallback when MCP subprocess fails.""" if not ADK_AVAILABLE: return [] return [ FunctionTool(func=query_mongodb_trajectories), FunctionTool(func=log_run_to_mongodb), ]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PART 3: AGENT SYSTEM PROMPT# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
FLEET_AGENT_INSTRUCTION = """You are the Libratio Fleet Commander β a Google ADK-powered AI agent managingGPU clusters using MongoDB Atlas as your intelligent backend.
## Your ToolsYou have two types of tools:
**MongoDB MCP Tools** (your data superpowers β call these first!):- Use find/aggregate to query historical crash trajectories from 'libratio.trajectories'- Use insertMany to log your results to 'libratio.runs'- Use aggregate with $vectorSearch to find semantically similar past crashes
**Fleet Physics Tools** (your environment interface):- reset_fleet_environment: Start a new fleet task episode- step_fleet_environment: Submit your precision/allocation decision as JSON- compute_precision_physics: Validate a precision choice with physics model
## Workflow for Each Task1. RETRIEVE: Query MongoDB 'libratio.trajectories' for historical runs similar to current scenario2. ANALYZE: Use compute_precision_physics to validate your planned action3. ACT: Use step_fleet_environment to submit your JSON decision4. LOG: Insert your result into MongoDB 'libratio.runs'
## Precision Rules (memorize these)- embedding: ALWAYS FP32 (FP8 causes NaN crashes β NEVER use FP8 here)- output: ALWAYS FP32 (loss computation needs full precision)- ffn: FP8 is ideal (2.5x speedup, safe for FFN layers)- attention: BF16 is optimal (1.85x speedup)- layernorm: BF16 is best
## GoalReward score > 0.60 = success. Target > 0.85.Always retrieve MongoDB context before acting."""
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PART 4: AGENT ASSEMBLY + RUNNER (ADK 2.2.0 API)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def run_fleet_task_with_adk(task_id: str = "fleet_precision") -> dict: """ Run a complete Libratio fleet task using the Google ADK agent.
This is the main entry point for the hackathon demo. It: 1. Creates the ADK agent with MongoDB MCP + physics tools 2. Sends a task message to Gemini 2.0 Flash 3. Gemini reasons, calls MongoDB MCP tools, calls physics tools 4. Returns the final score and reasoning
Args: task_id: One of 'fleet_precision', 'fleet_oversight', 'fleet_resource', 'fleet_recovery'
Returns: Dict with final_score, steps, reasoning, mongo_tools_called, physics_tools_called """ if not ADK_AVAILABLE: raise RuntimeError("Google ADK not installed. Run: pip install google-adk mcp")
logger.info(f"\n{'='*60}") logger.info(f" LIBRATIO ADK AGENT - task={task_id}") logger.info(f" Model: {ADK_MODEL} | MongoDB: enabled | Physics: enabled") logger.info(f"{'='*60}")
# ββ Step 1: Build tools ββββββββββββββββββββββββββββββββββββββββββββββ # Try MCP first (ideal for hackathon), fallback to pymongo tools (always works) mongo_mcp = get_mongodb_mcp_toolset() physics_tools = get_fleet_physics_tools() mongo_fallback_tools = get_mongodb_fallback_tools()
# Assemble: MCP toolset (if available) + pymongo fallback + physics tools all_tools = physics_tools + mongo_fallback_tools mongodb_mode = "pymongo (ADK FunctionTool)" if mongo_mcp: all_tools = [mongo_mcp] + all_tools mongodb_mode = "MCP Server + pymongo fallback"
logger.info(f"MongoDB mode: {mongodb_mode}")
# ββ Step 2: Create the ADK Agent βββββββββββββββββββββββββββββββββββββ # This is the "Google Cloud Agent Builder" code-first integration agent = Agent( model=ADK_MODEL, # Gemini 2.0 Flash name="libratio_fleet_commander", instruction=FLEET_AGENT_INSTRUCTION, tools=all_tools, )
logger.info(f"Agent created: model={ADK_MODEL}, tools={len(all_tools)}")
# ββ Step 3: Create InMemoryRunner (ADK 2.2.0 simplified API) βββββββββ # InMemoryRunner bundles the agent + session service together runner = InMemoryRunner( agent=agent, app_name="libratio_fleet", )
# ββ Step 4: Create a session ββββββββββββββββββββββββββββββββββββββββββ session = await runner.session_service.create_session( app_name="libratio_fleet", user_id="fleet_commander", ) session_id = session.id
logger.info(f"Session created: {session_id}")
# ββ Step 5: Build the task prompt ββββββββββββββββββββββββββββββββββββββ task_prompt = f"""Run a complete Libratio fleet task: {task_id}
Follow this exact workflow:1. Call reset_fleet_environment(task_id="{task_id}") to see the cluster state2. Call MongoDB find or aggregate on collection 'trajectories' in database 'libratio' to retrieve 3-5 historical runs with similar conditions3. Call compute_precision_physics for the layers you plan to configure4. Call step_fleet_environment with your best JSON action (aim for score > 0.85)5. Call MongoDB insertMany to log your result to collection 'runs' in database 'libratio'6. Report: your final score, which MongoDB MCP tools you used, and your reasoning
Target reward: > 0.85Database: libratio | Collections: trajectories (read), runs (write)"""
# ββ Step 6: Run the agent (with retry for rate limits) ββββββββββββββ mongo_tools_called = [] physics_tools_called = [] final_text = "" final_score = 0.0 event_count = 0
max_retries = 3 for attempt in range(max_retries): try: async for event in runner.run_async( user_id="fleet_commander", session_id=session_id, new_message=genai_types.Content( role="user", parts=[genai_types.Part(text=task_prompt)], ), ): event_count += 1
# Track tool calls for demo visibility if hasattr(event, "content") and event.content: for part in event.content.parts: # Detect function calls (tool invocations) if hasattr(part, "function_call") and part.function_call: tool_name = part.function_call.name logger.info(f" [Tool called] {tool_name}")
# Categorize which type of tool was used mongo_keywords = ["find", "aggregate", "insert", "collection", "mongo", "vector_search", "count", "query_mongodb", "log_run"] physics_keywords = ["fleet", "precision", "physics", "reset", "step", "compute"]
if any(kw in tool_name.lower() for kw in mongo_keywords): mongo_tools_called.append(tool_name) elif any(kw in tool_name.lower() for kw in physics_keywords): physics_tools_called.append(tool_name) else: physics_tools_called.append(tool_name)
# Capture final text response if hasattr(part, "text") and part.text: final_text += part.text
# Detect final response event if hasattr(event, "is_final_response") and callable(event.is_final_response): if event.is_final_response(): logger.info(" [Final response received]")
# If we got here, agent completed successfully break
except Exception as e: error_msg = str(e) if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg: wait_time = 35 * (attempt + 1) # 35s, 70s, 105s logger.warning(f" Rate limited (attempt {attempt+1}/{max_retries}). Waiting {wait_time}s...") await asyncio.sleep(wait_time) # Create a new session for retry (old one may be stale) session = await runner.session_service.create_session( app_name="libratio_fleet", user_id="fleet_commander", ) session_id = session.id else: logger.error(f"ADK agent run error: {e}") raise
# Try to extract score from final text import re score_matches = re.findall(r'score[:\s=]+([0-9.]+)', final_text.lower()) if score_matches: try: final_score = float(score_matches[-1]) final_score = max(0.01, min(0.99, final_score)) except ValueError: final_score = 0.5
result = { "task_id": task_id, "model": ADK_MODEL, "final_score": round(final_score, 3), "events_processed": event_count, "mongo_tools_called": mongo_tools_called, "physics_tools_called": physics_tools_called, "total_tool_calls": len(mongo_tools_called) + len(physics_tools_called), "mongodb_mcp_used": len(mongo_tools_called) > 0, "final_reasoning": final_text[:800] if final_text else "See server logs for full reasoning", }
logger.info(f"\n{'='*60}") logger.info(f" ADK AGENT COMPLETE") logger.info(f" MongoDB MCP tools called: {mongo_tools_called}") logger.info(f" Physics tools called: {physics_tools_called}") logger.info(f" Final score: {result['final_score']}") logger.info(f"{'='*60}\n")
return result
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ENTRY POINT# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def _main(): """Run a demo of the ADK agent.""" task_id = os.environ.get("TASK_ID", "fleet_precision") print(f"\nRunning ADK agent: task={task_id}, model={ADK_MODEL}") print(f"MongoDB MCP: {'enabled' if MONGO_URI else 'disabled (no MONGO_URI)'}") print(f"Gemini API: {'configured' if GEMINI_API_KEY else 'MISSING - set GEMINI_API_KEY in .env'}") print()
if not GEMINI_API_KEY: print("ERROR: GEMINI_API_KEY not set in .env") print("Get a free key at: https://aistudio.google.com/apikey") sys.exit(1)
result = await run_fleet_task_with_adk(task_id)
print("\n" + "=" * 60) print("LIBRATIO ADK AGENT - RESULT SUMMARY") print("=" * 60) print(json.dumps(result, indent=2))
if result["mongodb_mcp_used"]: print("\n[OK] MongoDB MCP Server was used - hackathon partner requirement SATISFIED") else: print("\n[WARN] MongoDB MCP tools were not called.") print(" Check that MONGO_URI is set and npx is available.")
if __name__ == "__main__": if not ADK_AVAILABLE: print("ERROR: Google ADK not installed. Run: pip install google-adk mcp") sys.exit(1) asyncio.run(_main())10 unmodified lines111213141516171819110 unmodified lines1301311321331341351363 unmodified lines14014114214314414514614714814915015115215315415515615715815925 unmodified lines18518618718818919019125 unmodified lines21721821922022122219 unmodified lines24224324424524624724824925025125210 unmodified linespython fleet_inference.py"""import osimport jsonimport httpxfrom openai import OpenAI# ConfigAPI_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")110 unmodified lines}def call_llm(system_prompt: str, observation: dict, conversation_history: list = None) -> dict:"""Call the LLM with the observation and return parsed JSON action."""messages = [{"role": "system", "content": system_prompt}]3 unmodified linesuser_msg = f"Current environment state:\n{json.dumps(observation, indent=2, default=str)}\n\nProvide your action as JSON."messages.append({"role": "user", "content": user_msg})try:response = client.chat.completions.create(model=MODEL_NAME,messages=messages,temperature=0.2,max_tokens=600,)content = response.choices[0].message.content.strip()# Extract JSON from markdown code blocks if presentif "```json" in content:content = content.split("```json")[1].split("```")[0].strip()elif "```" in content:content = content.split("```")[1].split("```")[0].strip()return json.loads(content)except Exception as e:25 unmodified linessteps += 1# Call LLMaction = call_llm(system_prompt, obs, conversation_history)error = Nonedone = False25 unmodified linesdone = data["done"]obs = data.get("observation", None)# Add feedback to conversation historyconversation_history.append({"role": "user",19 unmodified linesprint(f"[FLEET END] task={task_id} score={score:.3f} steps={steps} success={success}", flush=True)print(f" rewards=[{rewards_str}]", flush=True)return score, stepsdef main():"""Run all fleet tasks or a specific one."""task_id = os.environ.get("TASK_ID")if task_id:10 unmodified lines111213141516171819202122232425110 unmodified lines1361371381391401411423 unmodified lines14614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920025 unmodified lines22622722822923023123225 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828919 unmodified lines30931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834910 unmodified linespython fleet_inference.py"""import osimport reimport jsonimport httpxfrom datetime import datetime, timezonefrom openai import OpenAIfrom dotenv import load_dotenv# Load environment variables from .env fileload_dotenv()# ConfigAPI_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")110 unmodified lines}def call_llm(system_prompt: str, observation: dict, conversation_history: list = None, task_id: str = None) -> dict:"""Call the LLM with the observation and return parsed JSON action."""messages = [{"role": "system", "content": system_prompt}]3 unmodified linesuser_msg = f"Current environment state:\n{json.dumps(observation, indent=2, default=str)}\n\nProvide your action as JSON."messages.append({"role": "user", "content": user_msg})# Dynamic routing: use custom model for precision/recovery, Groq for oversight/resourcecurrent_model = MODEL_NAMEcurrent_base_url = API_BASE_URLcurrent_api_key = os.getenv("HF_TOKEN")if task_id in ["fleet_oversight", "fleet_resource"] or "groq.com" in current_base_url:current_model = "llama-3.3-70b-versatile"current_base_url = "https://api.groq.com/openai/v1"current_api_key = os.getenv("GROQ_API_KEY")if not current_api_key:raise ValueError(f"Required API key not found in environment for {current_base_url}")local_client = OpenAI(api_key=current_api_key, base_url=current_base_url)try:response = local_client.chat.completions.create(model=current_model,messages=messages,temperature=0.2,max_tokens=600,)content = response.choices[0].message.content.strip()# Extract the first matching JSON object by brace countingfirst_brace = content.find('{')if first_brace != -1:count = 0in_string = Falseescape = Falsefor i in range(first_brace, len(content)):char = content[i]if char == '"' and not escape:in_string = not in_stringelif char == '\\' and in_string:escape = not escapecontinueelif not in_string:if char == '{':count += 1elif char == '}':count -= 1if count == 0:content = content[first_brace:i+1]breakescape = False# Strip trailing commas inside objects or arrays (common LLM generation issue)content = re.sub(r",\s*([\]}])", r"\1", content)return json.loads(content)except Exception as e:25 unmodified linessteps += 1# Call LLMaction = call_llm(system_prompt, obs, conversation_history, task_id)error = Nonedone = False25 unmodified linesdone = data["done"]obs = data.get("observation", None)# Log step-by-step metrics to MongoDB Time Series collectiontry:from mongodb_metrics import log_step_metricscluster_info = obs.get("cluster", {}) if obs else {}model_info = obs.get("your_model", {}) if obs else {}mem_used = cluster_info.get("memory_used_gb")if mem_used is None:mem_used = model_info.get("memory_used_gb", 0.0)therm = cluster_info.get("thermal_risk")if therm is None:therm = model_info.get("thermal_risk", "UNKNOWN")pwr = cluster_info.get("power_util", cluster_info.get("estimated_power_pct", 0.0))m_id = model_info.get("model_id", MODEL_NAME)log_step_metrics(task_id=task_id,model_id=m_id,step=steps,reward=reward,memory_used_gb=mem_used,thermal_risk=therm,power_util=pwr)except Exception:pass# Add feedback to conversation historyconversation_history.append({"role": "user",19 unmodified linesprint(f"[FLEET END] task={task_id} score={score:.3f} steps={steps} success={success}", flush=True)print(f" rewards=[{rewards_str}]", flush=True)# Log run telemetry to MongoDB runs collectionmongo_uri = os.getenv("MONGO_URI")if mongo_uri:try:from pymongo import MongoClientfrom datetime import datetimeclient_mongo = MongoClient(mongo_uri, serverSelectionTimeoutMS=2000)db_mongo = client_mongo["libratio"]runs_col = db_mongo["runs"]runs_col.insert_one({"task_id": task_id,"model_name": MODEL_NAME,"score": score,"steps": steps,"success": success,"rewards": rewards_list,"timestamp": datetime.now(timezone.utc)})print("[OK] Logged run telemetry to MongoDB Atlas ('runs' collection)")except Exception as e:print(f"[WARN] Could not log telemetry to MongoDB: {e}")return score, stepsdef main():"""Run all fleet tasks or a specific one."""# Initialize MongoDB Time Series metrics collectiontry:from mongodb_metrics import create_metrics_timeseries_collectioncreate_metrics_timeseries_collection()except Exception as e:print(f"[WARN] Failed to initialize Time Series metrics: {e}")task_id = os.environ.get("TASK_ID")if task_id:
5 unmodified lines6789101112219 unmodified lines2322332342352362375 unmodified lines<title>Libratio Fleet | GPU Cluster Simulator</title><link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><link rel="stylesheet" href="/frontend/styles.css" /></head>219 unmodified lines</div></div><div class="sb-section"><div class="sb-title"><span class="ind ind-amber"></span> RESULT LOG</div><pre class="json-box" id="resBox">{}</pre>5 unmodified lines6789101112219 unmodified lines2322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732745 unmodified lines<title>Libratio Fleet | GPU Cluster Simulator</title><link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" /><script src="https://cdn.jsdelivr.net/npm/chart.js"></script><link rel="stylesheet" href="/frontend/styles.css" /></head>219 unmodified lines</div></div><div class="sb-section"><div class="sb-title"><span class="ind ind-blue"></span> HISTORICAL SEARCH (RRF HYBRID)</div><div class="search-container" style="padding: 10px 0;"><div style="display: flex; gap: 8px; margin-bottom: 8px;"><input type="text" id="searchInput" placeholder="Search crashes, e.g., FP8, LLaMA..." style="flex: 1; padding: 6px 10px; border-radius: 4px; border: 1px solid #1e293b; background: #0b1329; color: #fff; font-size: 12px;" /><button id="searchBtn" style="padding: 6px 12px; background: #00e5ff; border: none; border-radius: 4px; color: #0b1329; font-weight: 600; cursor: pointer; font-size: 11px;">FIND</button></div><div style="display: flex; gap: 8px; justify-content: space-between; font-size: 10px; color: #7e90b0; margin-bottom: 8px;"><span>Type:</span><div style="display: flex; gap: 10px;"><label style="cursor: pointer;"><input type="radio" name="searchType" value="hybrid" checked style="margin-right: 3px;" />Hybrid</label><label style="cursor: pointer;"><input type="radio" name="searchType" value="vector" style="margin-right: 3px;" />Vector</label><label style="cursor: pointer;"><input type="radio" name="searchType" value="text" style="margin-right: 3px;" />Text</label></div></div><div id="searchResults" style="max-height: 250px; overflow-y: auto; font-size: 11px; display: flex; flex-direction: column; gap: 8px;"><div style="color: #7e90b0; text-align: center; padding: 10px;">Type query above to search 2,863 trajectories.</div></div></div></div><div class="sb-section"><div class="sb-title"><span class="ind ind-purple"></span> ATLAS CHARTS INTEGRATION</div><div class="charts-integration-panel" style="padding: 10px 0; font-size: 11px;"><p style="color: #7e90b0; margin-bottom: 8px; line-height: 1.4;">Embed native MongoDB Atlas Charts of the <code>gpu_telemetry_metrics</code> Time Series data directly into this panel.</p><div style="display: flex; gap: 8px; margin-bottom: 8px;"><input type="text" id="chartsUrlInput" placeholder="Paste Atlas Charts Iframe URL or Tag..." style="flex: 1; padding: 6px 10px; border-radius: 4px; border: 1px solid #1e293b; background: #0b1329; color: #fff; font-size: 12px;" /><button id="chartsBtn" onclick="embedAtlasChart()" style="padding: 6px 12px; background: #ab47bc; border: none; border-radius: 4px; color: #fff; font-weight: 600; cursor: pointer; font-size: 11px;">EMBED</button></div><div id="chartsFrameContainer" style="width: 100%; height: 220px; border: 1px dashed #1e293b; border-radius: 4px; display: flex; align-items: center; justify-content: center; background: rgba(11, 19, 41, 0.4); overflow: hidden;"><span style="color: #7e90b0; text-align: center; padding: 10px;">No chart embedded. Paste your sharing URL above to render Atlas Charts.</span></div></div></div><div class="sb-section"><div class="sb-title"><span class="ind ind-amber"></span> RESULT LOG</div><pre class="json-box" id="resBox">{}</pre>
17 unmodified lines181920212223242526272829303117 unmodified linespanel.style.display = "block";badge.classList.add("active");// Auto-resize the dashboard belowdocument.querySelector(".dashboard").style.height = "calc(100vh - 44px - " + panel.offsetHeight + "px)";// Auto-run profile on first openrunKernelProfile();} else {panel.style.display = "none";badge.classList.remove("active");document.querySelector(".dashboard").style.height = "calc(100vh - 44px)";}}17 unmodified lines181920212223242526272829303117 unmodified linespanel.style.display = "block";badge.classList.add("active");// Auto-resize the dashboard belowdocument.querySelector(".dashboard").style.height = "calc(100vh - 48px - " + panel.offsetHeight + "px)";// Auto-run profile on first openrunKernelProfile();} else {panel.style.display = "none";badge.classList.remove("active");document.querySelector(".dashboard").style.height = "calc(100vh - 48px)";}}
57 unmodified lines58596061626364651 unmodified line676869707172738 unmodified lines82838485868788442 unmodified lines53153253353453553657 unmodified lines{label: 'Trained Agent',data: trainedData,borderColor: '#00e676',backgroundColor: 'rgba(0, 230, 118, 0.1)',borderWidth: 2,fill: true,tension: 0.41 unmodified line{label: 'Random Baseline',data: baselineData,borderColor: '#ff1744',backgroundColor: 'transparent',borderWidth: 2,borderDash: [5, 5],8 unmodified linesplugins: { legend: { display: false } },scales: {x: { display: false },y: { min: 0, max: 1, grid: { color: '#162030' }, ticks: { color: '#7e90b0', stepSize: 0.5, font: {size: 9} } }}}});442 unmodified lines}});// ββββββββββββββββββββββββββββββββββββββββ// INIT// ββββββββββββββββββββββββββββββββββββββββ57 unmodified lines58596061626364651 unmodified line676869707172738 unmodified lines82838485868788442 unmodified lines53153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664757 unmodified lines{label: 'Trained Agent',data: trainedData,borderColor: '#00d2ff',backgroundColor: 'rgba(0, 210, 255, 0.08)',borderWidth: 2,fill: true,tension: 0.41 unmodified line{label: 'Random Baseline',data: baselineData,borderColor: '#ff4d4d',backgroundColor: 'transparent',borderWidth: 2,borderDash: [5, 5],8 unmodified linesplugins: { legend: { display: false } },scales: {x: { display: false },y: { min: 0, max: 1, grid: { color: 'rgba(255, 255, 255, 0.06)' }, ticks: { color: '#bbc9cf', stepSize: 0.5, font: {size: 9} } }}}});442 unmodified lines}});// ββββββββββββββββββββββββββββββββββββββββ// HISTORICAL TRAJECTORY SEARCH (RAG EXPLORATION)// ββββββββββββββββββββββββββββββββββββββββconst searchInput = $("searchInput");const searchBtn = $("searchBtn");const searchResults = $("searchResults");async function performSearch() {const query = searchInput.value.trim();if (!query) {searchResults.innerHTML = '<div style="color: #7e90b0; text-align: center; padding: 10px;">Type query above to search 2,863 trajectories.</div>';return;}const searchTypeEl = document.querySelector('input[name="searchType"]:checked');const searchType = searchTypeEl ? searchTypeEl.value : 'hybrid';searchBtn.disabled = true;searchBtn.textContent = "SEARCHING...";searchResults.innerHTML = '<div style="color: #00e5ff; text-align: center; padding: 10px;">Querying Atlas Search...</div>';try {const res = await fetch(`/api/search?query=${encodeURIComponent(query)}&type=${searchType}&limit=5`);const data = await res.json();if (data.status === "error") {searchResults.innerHTML = `<div style="color: #ff1744; padding: 10px;">Error: ${data.message}</div>`;return;}if (!data.results || data.results.length === 0) {searchResults.innerHTML = '<div style="color: #7e90b0; text-align: center; padding: 10px;">No matching trajectories found.</div>';return;}let html = '';data.results.forEach((r) => {let scoreLabel = "";if (searchType === "hybrid" && r.rrf_score !== undefined) {scoreLabel = `RRF: ${r.rrf_score.toFixed(4)}`;} else if (searchType === "vector" && r.vector_score !== undefined) {scoreLabel = `Sim: ${r.vector_score.toFixed(3)}`;} else if (searchType === "text" && r.search_score !== undefined) {scoreLabel = `Score: ${r.search_score.toFixed(2)}`;}const outcomeCls = r.outcome === "SUCCESS" ? "outcome-success" : "outcome-crash";const strat = r.precision_strategy || {};const stratStr = Object.entries(strat).map(([k,v]) => `${k}:${v}`).join(', ');const failureHtml = r.failure_reason ? `<div style="color: #ff5252; margin-top: 4px; font-size: 10px;">Failure: ${r.failure_reason}</div>` : '';html += `<div style="background: rgba(30, 41, 59, 0.4); border: 1px solid #1e293b; border-radius: 4px; padding: 8px; font-family: 'Inter', sans-serif;"><div style="display: flex; justify-content: space-between; font-weight: 600; font-size: 12px; margin-bottom: 4px;"><span style="color: #00e5ff;">${r.model_name || r.model_id}</span><span style="font-size: 9px; color: #7e90b0; background: #0b1329; padding: 1px 5px; border-radius: 3px; border: 1px solid #1e293b;">${scoreLabel}</span></div><div style="display: flex; justify-content: space-between; font-size: 10px; color: #cbd5e1; margin-bottom: 2px;"><span>Outcome: <strong class="${outcomeCls}" style="color: ${r.outcome === "SUCCESS" ? "#00e676" : "#ff1744"}">${r.outcome}</strong></span><span>VRAM: ${r.memory_used_gb} GB</span></div><div style="font-size: 9px; color: #94a3b8; background: rgba(11, 19, 41, 0.5); padding: 4px; border-radius: 2px; border: 1px solid rgba(30, 41, 59, 0.5); word-break: break-all;"><strong>Strat:</strong> ${stratStr}</div>${failureHtml}</div>`;});searchResults.innerHTML = html;} catch (err) {searchResults.innerHTML = `<div style="color: #ff1744; padding: 10px;">Failed: ${err.message}</div>`;} finally {searchBtn.disabled = false;searchBtn.textContent = "FIND";}}searchBtn.addEventListener("click", performSearch);searchInput.addEventListener("keypress", (e) => {if (e.key === "Enter") performSearch();});// ββββββββββββββββββββββββββββββββββββββββ// ATLAS CHARTS EMBEDDING// ββββββββββββββββββββββββββββββββββββββββwindow.embedAtlasChart = function() {const input = document.getElementById("chartsUrlInput").value.trim();const container = document.getElementById("chartsFrameContainer");if (!input) {container.innerHTML = '<span style="color: #7e90b0; text-align: center; padding: 10px;">No chart embedded. Paste your sharing URL above to render Atlas Charts.</span>';return;}let src = "";if (input.includes("<iframe") && input.includes("src=")) {const match = input.match(/src=["']([^"']+)["']/);if (match && match[1]) {src = match[1];}} else {src = input;}if (src) {container.innerHTML = `<iframe src="${src}" style="background: #0B1329; border: none; border-radius: 4px; width: 100%; height: 100%;" allowfullscreen></iframe>`;} else {container.innerHTML = '<span style="color: #ff1744; text-align: center; padding: 10px;">Invalid URL or iframe tag format.</span>';}};// ββββββββββββββββββββββββββββββββββββββββ// INIT// ββββββββββββββββββββββββββββββββββββββββ
2 unmodified lines3456789101112131415161718192021222324252627282930313233343515 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines1561571581591601611621 unmodified line1641651661671681691701716 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002014 unmodified lines2062072082092102112122132142152162172182195 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762771 unmodified line2792802812822832842852862872882892902912922932942952962972982993003013022 unmodified linesβββββββββββββββββββββββββββββββββββββββββββββββββββ */:root {--bg: #05070c;--bg-panel: #080c16;--bg-card: #0c1220;--bg-gpu: #0e1528;--border: #162030;--text: #dce4f0;--text2: #7e90b0;--dim: #3e5070;--green: #00e676;--green2: #00c853;--blue: #448aff;--cyan: #00e5ff;--amber: #ffab00;--red: #ff1744;--purple: #d500f9;--mono: 'JetBrains Mono', monospace;--sans: 'Inter', sans-serif;}* { box-sizing: border-box; margin: 0; padding: 0; }html, body { height: 100%; overflow: hidden; }body { font-family: var(--sans); background: var(--bg); color: var(--text); -webkit-font-smoothing: antialiased; }/* ββ TOPBAR ββ */#topbar { height: 44px; background: var(--bg-panel); border-bottom: 1px solid var(--border); display: flex; align-items: center; padding: 0 18px; }.topbar-inner { width: 100%; display: flex; align-items: center; gap: 14px; }.logo { font-size: 0.85rem; font-weight: 800; letter-spacing: 0.12em; color: var(--cyan); }.env-badge { font-size: 0.6rem; font-weight: 700; letter-spacing: 0.1em; padding: 2px 8px; border-radius: 3px; background: rgba(0,229,255,0.08); color: var(--cyan); border: 1px solid rgba(0,229,255,0.2); }.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 18px; }.topbar-right a { font-size: 0.72rem; color: var(--text2); text-decoration: none; font-weight: 500; }15 unmodified lines.btn-topbar.active { background: var(--amber); color: #000; box-shadow: 0 0 16px rgba(255,171,0,0.4); }/* ββ DASHBOARD LAYOUT ββ */.dashboard { display: grid; grid-template-columns: 260px 1fr 310px; height: calc(100vh - 44px); }.sidebar { background: var(--bg-panel); border-right: 1px solid var(--border); padding: 14px; overflow-y: auto; }.sidebar-right { border-right: none; border-left: 1px solid var(--border); }/* ββ SIDEBAR SECTIONS ββ */.sb-section { margin-bottom: 18px; }.sb-title { font-size: 0.62rem; font-weight: 700; letter-spacing: 0.1em; color: var(--dim); margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }.ind { width: 6px; height: 6px; border-radius: 50%; }.ind-green { background: var(--green); box-shadow: 0 0 6px var(--green); }.ind-amber { background: var(--amber); box-shadow: 0 0 6px var(--amber); }select { width: 100%; font-family: var(--sans); font-size: 0.72rem; background: #0a0f1c; color: var(--text); border: 1px solid var(--border); border-radius: 5px; padding: 7px 8px; margin-bottom: 8px; cursor: pointer; }optgroup { font-weight: 700; color: var(--dim); }.btn-reset, .btn-step { width: 100%; font-family: var(--mono); font-size: 0.72rem; font-weight: 700; letter-spacing: 0.06em; border: none; border-radius: 5px; padding: 10px; cursor: pointer; margin-bottom: 6px; transition: all 0.2s; }.btn-reset { background: var(--blue); color: #fff; }.btn-reset:hover { background: #2962ff; box-shadow: 0 0 20px rgba(68,138,255,0.3); }.btn-step { background: var(--green2); color: #000; }.btn-step:hover { background: var(--green); box-shadow: 0 0 20px rgba(0,230,118,0.3); }.btn-reset:disabled, .btn-step:disabled { opacity: 0.4; cursor: not-allowed; }/* ββ METRICS & HEALTH SCORES ββ */.health-scores { display: flex; gap: 8px; margin-bottom: 14px; }.health-box { flex: 1; padding: 10px 0; text-align: center; border-radius: 6px; border: 1px solid; }.health-box.primary { background: rgba(0,230,118,0.05); border-color: rgba(0,230,118,0.2); }.health-box.secondary { background: rgba(255,23,68,0.05); border-color: rgba(255,23,68,0.2); }.h-label { display: block; font-size: 0.55rem; font-weight: 700; letter-spacing: 0.08em; color: var(--text2); margin-bottom: 2px; }.h-val { display: block; font-size: 1.6rem; font-weight: 800; font-family: var(--mono); line-height: 1; }.primary .h-val { color: var(--green); }.secondary .h-val { color: var(--red); }.metric { display: flex; justify-content: space-between; align-items: center; padding: 3px 0; font-size: 0.7rem; color: var(--text2); }.metric-val { font-family: var(--mono); font-weight: 600; color: var(--text); font-size: 0.7rem; }.metric-good { color: var(--green); }.metric-warn { color: var(--amber); }.metric-bad { color: var(--red); }.vram-pool { width: 100%; height: 8px; background: #10182a; border-radius: 4px; margin: 8px 0 4px; overflow: hidden; border: 1px solid var(--border); }.vram-pool-fill { height: 100%; width: 0%; background: linear-gradient(90deg, var(--cyan), var(--green)); border-radius: 4px; transition: width 0.8s ease; }.chart-container { width: 100%; height: 110px; background: #0a0f1c; border-radius: 6px; border: 1px solid var(--border); padding: 5px; }#actionInput { width: 100%; min-height: 120px; background: #080c18; color: var(--text); border: 1px solid var(--border); border-radius: 5px; padding: 8px; font-family: var(--mono); font-size: 0.65rem; line-height: 1.5; resize: vertical; }#actionInput:focus { outline: none; border-color: var(--cyan); }/* ββ MAIN AREA ββ */.main-area { padding: 16px 20px; overflow-y: auto; background: var(--bg); display: flex; flex-direction: column; }.rack-comparison { display: flex; gap: 20px; margin-bottom: 20px; }.gpu-rack { flex: 1; }.rack-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }.rack-header h2 { font-size: 0.7rem; font-weight: 700; letter-spacing: 0.12em; color: var(--dim); }.efficiency-badge { font-size: 0.65rem; font-family: var(--mono); font-weight: 600; background: rgba(0, 230, 118, 0.15); color: var(--green); padding: 3px 8px; border-radius: 4px; border: 1px solid rgba(0, 230, 118, 0.3); }.rack-status { font-size: 0.6rem; font-weight: 700; font-family: var(--mono); letter-spacing: 0.1em; padding: 2px 10px; border-radius: 3px; background: rgba(0,229,255,0.08); color: var(--cyan); }.rack-status.active { background: rgba(0,230,118,0.1); color: var(--green); }.rack-status.error { background: rgba(255,23,68,0.1); color: var(--red); }/* ββββββββββββββββββββββββββββββββββββββββGPU CHIP VISUALIZATIONββββββββββββββββββββββββββββββββββββββββ */.rack-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }.rack-comparison.split .rack-grid { grid-template-columns: repeat(2, 1fr); }.gpu-chip { background: var(--bg-gpu); border: 1px solid var(--border); border-radius: 10px; padding: 12px; position: relative; overflow: hidden; transition: all 0.4s ease; }.gpu-chip::after { content: ''; position: absolute; inset: -1px; border-radius: 10px; padding: 1px; background: linear-gradient(135deg, transparent 40%, var(--blue) 100%); -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite: xor; mask-composite: exclude; opacity: 0.3; transition: opacity 0.4s; }.gpu-chip.active::after { background: linear-gradient(135deg, var(--cyan) 0%, var(--green) 100%); opacity: 0.7; }.gpu-chip.warning::after { background: linear-gradient(135deg, var(--amber) 0%, var(--red) 100%); opacity: 0.8; }.gpu-chip.crashed::after { background: linear-gradient(135deg, var(--red) 0%, var(--purple) 100%); opacity: 1; }.gpu-chip.active { box-shadow: 0 0 20px rgba(0,229,255,0.08); }.gpu-chip.warning { box-shadow: 0 0 20px rgba(255,171,0,0.12); }/* Cascade Crash Animation */.gpu-chip.crashed { animation: cascade-pulse 1s ease-out infinite; z-index: 10; border-color: var(--red); }@keyframes cascade-pulse {0% { box-shadow: 0 0 0 0 rgba(255,23,68,0.6); }70% { box-shadow: 0 0 0 15px rgba(255,23,68,0); }100% { box-shadow: 0 0 0 0 rgba(255,23,68,0); }}.gpu-label { font-size: 0.65rem; font-weight: 700; font-family: var(--mono); letter-spacing: 0.1em; color: var(--dim); margin-bottom: 8px; }.core-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; margin-bottom: 10px; }.core { aspect-ratio: 1; border-radius: 2px; background: #121e32; transition: background 0.5s ease, box-shadow 0.5s ease; }.core.lit-cyan { background: var(--cyan); box-shadow: 0 0 4px var(--cyan); }.core.lit-green { background: var(--green); box-shadow: 0 0 4px var(--green); }.core.lit-blue { background: var(--blue); box-shadow: 0 0 4px var(--blue); }.core.lit-amber { background: var(--amber); box-shadow: 0 0 4px var(--amber); }.core.lit-red { background: var(--red); box-shadow: 0 0 4px var(--red); }.core.lit-purple { background: var(--purple); box-shadow: 0 0 4px var(--purple); }.core.lit-dim { background: #1a2540; }.gpu-vram-wrap { margin-bottom: 6px; }.gpu-vram-track { width: 100%; height: 6px; background: #101828; border-radius: 3px; overflow: hidden; }.gpu-vram-bar { height: 100%; border-radius: 3px; transition: width 0.8s ease, background 0.4s; background: linear-gradient(90deg, var(--cyan), var(--green)); }.gpu-vram-bar.high { background: linear-gradient(90deg, var(--amber), var(--red)); }.gpu-vram-bar.critical { background: var(--red); animation: blink-bg 1s infinite; }3 unmodified lines50% { opacity: 0.4; }}/* Segmented Precision Bar inside GPU */.prec-segmented-bar { display: flex; width: 100%; height: 4px; border-radius: 2px; overflow: hidden; margin-bottom: 4px; background: rgba(255,255,255,0.05); }.seg-fp32 { background: var(--blue); }.seg-bf16 { background: var(--green); }1 unmodified line.seg-fp8 { background: var(--red); }.gpu-info-row { display: flex; justify-content: space-between; align-items: center; font-size: 0.6rem; font-family: var(--mono); color: var(--text2); margin-top: 4px; }.gpu-model-label { font-size: 0.6rem; font-weight: 600; font-family: var(--mono); margin-top: 8px; padding: 2px 5px; border-radius: 3px; display: inline-block; }.gpu-model-label.assigned { background: rgba(0,229,255,0.1); color: var(--cyan); }.gpu-model-label.empty { color: var(--dim); }.gpu-temp { position: absolute; top: 10px; right: 12px; font-size: 0.6rem; font-family: var(--mono); font-weight: 600; }6 unmodified lines/* ββ AGENT REASONING FEED ββ */.reasoning-section { flex: 1; display: flex; flex-direction: column; margin-top: 10px; }.reasoning-feed {background: var(--bg-card); border: 1px solid var(--border); border-radius: 8px;padding: 14px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px;}.thought-bubble {padding: 10px 14px; border-radius: 12px; font-size: 0.72rem; line-height: 1.5;max-width: 85%; animation: slideInUp 0.3s ease-out both; position: relative;}.thought-bubble.agent {background: rgba(41, 98, 255, 0.1); border: 1px solid rgba(41, 98, 255, 0.2);color: #e3f2fd; align-self: flex-start; border-top-left-radius: 2px;}.thought-bubble.agent::before { content: 'π€ Agent Reasoning'; display: block; font-size: 0.55rem; color: var(--blue); font-weight: 700; margin-bottom: 4px; letter-spacing: 0.05em; text-transform: uppercase;}.thought-bubble.baseline {background: rgba(255, 23, 68, 0.1); border: 1px solid rgba(255, 23, 68, 0.2);color: #ffebee; align-self: flex-end; border-top-right-radius: 2px; text-align: right;}.thought-bubble.baseline::before { content: 'β οΈ Baseline Action'; display: block; font-size: 0.55rem; color: var(--red); font-weight: 700; margin-bottom: 4px; letter-spacing: 0.05em; text-transform: uppercase;}.thought-bubble.sys-thought { background: transparent; border: 1px dashed var(--dim); color: var(--text2); align-self: center; text-align: center; }4 unmodified lines.telemetry-empty { font-size: 0.7rem; color: var(--dim); font-style: italic; text-align: center; padding: 20px 0; }.model-telemetry {background: #0a0f1c; border: 1px solid var(--border); border-radius: 6px; padding: 10px;}.m-tel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }.m-tel-name { font-size: 0.75rem; font-weight: 700; font-family: var(--mono); }.m-tel-status { font-size: 0.6rem; font-weight: 700; padding: 2px 6px; border-radius: 99px; text-transform: uppercase; }.m-tel-status.healthy { background: rgba(0,230,118,0.15); color: var(--green); }.m-tel-status.flagged { background: rgba(255,171,0,0.15); color: var(--amber); }.m-tel-status.crashed { background: rgba(255,23,68,0.15); color: var(--red); animation: blink-text 1s infinite;}.m-tel-sparkline { height: 30px; width: 100%; border-bottom: 1px dashed var(--dim); position: relative; display: flex; align-items: flex-end; gap: 2px; padding-bottom: 2px;}.spark-bar { width: 100%; background: var(--cyan); border-radius: 1px 1px 0 0; }5 unmodified lines.alert-dot.warn { background: var(--amber); }.alert-dot.crit { background: var(--red); }.json-box { background: #060a14; border: 1px solid var(--border); border-radius: 5px; padding: 8px; font-family: var(--mono); font-size: 0.65rem; line-height: 1.5; color: var(--text); overflow: auto; max-height: 250px; white-space: pre-wrap; word-break: break-word; }/* βββββββββββββββββββββββββββββββββββββββββββββββββββAGENTIC KERNEL PANELβββββββββββββββββββββββββββββββββββββββββββββββββββ */.kernel-badge {border-color: rgba(213,0,249,0.3) !important; color: #d500f9 !important; background: rgba(213,0,249,0.08) !important;cursor: pointer; transition: all 0.3s ease; border: 1px solid; font-size: 0.6rem; font-weight: 700;letter-spacing: 0.1em; padding: 2px 8px; border-radius: 3px; font-family: var(--sans);}.kernel-badge:hover { background: rgba(213,0,249,0.18) !important; box-shadow: 0 0 12px rgba(213,0,249,0.3); }.kernel-badge.active { background: rgba(213,0,249,0.25) !important; box-shadow: 0 0 20px rgba(213,0,249,0.4); border-color: #d500f9 !important; }.kernel-panel {background: linear-gradient(180deg, rgba(213,0,249,0.04) 0%, var(--bg-panel) 100%);border-bottom: 1px solid rgba(213,0,249,0.2);padding: 0;overflow: hidden;animation: kernelSlideDown 0.3s ease-out;}@keyframes kernelSlideDown { from { max-height: 0; opacity: 0; } to { max-height: 600px; opacity: 1; } }.kernel-inner { padding: 16px 24px; }.kernel-header { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }.kernel-header h2 { font-size: 0.75rem; font-weight: 800; letter-spacing: 0.12em; color: #d500f9; margin: 0; }.kernel-desc { font-size: 0.65rem; color: var(--text2); flex: 1; }.btn-bench {font-family: var(--mono); font-size: 0.65rem; font-weight: 700; letter-spacing: 0.06em;background: rgba(213,0,249,0.15); color: #d500f9; border: 1px solid rgba(213,0,249,0.3);border-radius: 5px; padding: 8px 16px; cursor: pointer; transition: all 0.2s;}.btn-bench:hover { background: rgba(213,0,249,0.3); box-shadow: 0 0 16px rgba(213,0,249,0.3); }.btn-bench:disabled { opacity: 0.5; cursor: not-allowed; }.btn-bench.running { animation: benchPulse 1.5s ease-in-out infinite; }@keyframes benchPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(213,0,249,0.4); } 50% { box-shadow: 0 0 20px 5px rgba(213,0,249,0.2); } }/* Metric Cards */.kernel-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px; }.k-card {background: rgba(213,0,249,0.04); border: 1px solid rgba(213,0,249,0.12);border-radius: 8px; padding: 14px; text-align: center;}.k-card-title { font-size: 0.55rem; font-weight: 700; letter-spacing: 0.1em; color: rgba(213,0,249,0.6); margin-bottom: 6px; }.k-big-number { font-family: var(--mono); font-size: 1.8rem; font-weight: 800; color: #d500f9; line-height: 1.1; }.k-big-number.k-solved { color: var(--green); text-shadow: 0 0 20px rgba(0,230,118,0.4); }.k-big-number.k-active { color: var(--amber); }.k-big-number.k-error { color: var(--red); }.k-unit { font-size: 0.6rem; color: var(--text2); margin-top: 2px; }1 unmodified line/* Module Breakdown */.kernel-modules { margin-bottom: 16px; }.km-title { font-size: 0.6rem; font-weight: 700; letter-spacing: 0.1em; color: var(--dim); margin-bottom: 10px; }.km-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }.km-card { background: rgba(0,0,0,0.2); border: 1px solid var(--border); border-radius: 6px; padding: 10px; }.km-name { font-family: var(--mono); font-size: 0.65rem; font-weight: 600; color: var(--cyan); margin-bottom: 6px; }.km-bar-track { width: 100%; height: 6px; background: #101828; border-radius: 3px; overflow: hidden; margin-bottom: 4px; }.km-bar { height: 100%; background: linear-gradient(90deg, #d500f9, #e040fb); border-radius: 3px; transition: width 1s ease; }.km-bar.safety { background: linear-gradient(90deg, var(--amber), #ff6d00); }.km-bar.scoring { background: linear-gradient(90deg, var(--cyan), var(--green)); }.km-val { font-family: var(--mono); font-size: 0.65rem; font-weight: 600; color: var(--text); }.km-desc { font-size: 0.55rem; color: var(--dim); margin-top: 2px; }/* Comparison Bars */.kernel-comparison { }.kc-row { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }.kc-label { font-size: 0.65rem; font-family: var(--mono); color: var(--text2); width: 120px; flex-shrink: 0; text-align: right; }.kc-bar-track { flex: 1; height: 10px; background: #101828; border-radius: 5px; overflow: hidden; }.kc-bar { height: 100%; border-radius: 5px; transition: width 1.5s ease; }.kc-bar.kernel { background: linear-gradient(90deg, #d500f9, #e040fb); min-width: 3px; }.kc-bar.vm { background: linear-gradient(90deg, var(--amber), #ff6d00); width: 83%; }.kc-bar.docker { background: linear-gradient(90deg, var(--red), #ff5252); width: 100%; }.kc-val { font-size: 0.6rem; font-family: var(--mono); color: var(--text2); width: 80px; flex-shrink: 0; }2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454615 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023 unmodified lines3063073083093103111 unmodified line3133143153163173183193206 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853864 unmodified lines3913923933943953963973983994004014024034044054064074084094104114124134145 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045051 unmodified line5075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365372 unmodified linesβββββββββββββββββββββββββββββββββββββββββββββββββββ */:root {--bg: #051424;--bg-panel: rgba(18, 33, 49, 0.45);--bg-card: rgba(18, 33, 49, 0.3);--bg-gpu: rgba(18, 33, 49, 0.2);--border: rgba(255, 255, 255, 0.08);--text: #d4e4fa;--text2: #bbc9cf;--dim: #859399;--green: #00e676;--green2: #00c853;--blue: #0088ff;--cyan: #00d2ff;--amber: #ffab00;--red: #ff4d4d;--purple: #b026ff;--mono: 'JetBrains Mono', monospace;--sans: 'Inter', sans-serif;--display: 'Space Grotesk', sans-serif;}* { box-sizing: border-box; margin: 0; padding: 0; }html, body { height: 100%; overflow: hidden; }body {font-family: var(--sans);background-color: var(--bg);background-image:radial-gradient(circle at 0% 0%, rgba(0, 210, 255, 0.15) 0%, transparent 40%),radial-gradient(circle at 100% 100%, rgba(176, 38, 255, 0.1) 0%, transparent 40%),radial-gradient(circle at 50% 50%, rgba(0, 0, 0, 0.2) 0%, transparent 100%);background-attachment: fixed;color: var(--text);-webkit-font-smoothing: antialiased;}/* ββ TOPBAR ββ */#topbar { height: 48px; background: rgba(18, 33, 49, 0.6); backdrop-filter: blur(32px); -webkit-backdrop-filter: blur(32px); border-bottom: 1px solid var(--border); display: flex; align-items: center; padding: 0 18px; }.topbar-inner { width: 100%; display: flex; align-items: center; gap: 14px; }.logo { font-family: var(--display); font-size: 0.95rem; font-weight: 800; letter-spacing: 0.12em; color: var(--cyan); text-shadow: 0 0 15px rgba(0, 210, 255, 0.3); }.env-badge { font-size: 0.6rem; font-weight: 700; letter-spacing: 0.1em; padding: 2px 8px; border-radius: 3px; background: rgba(0,229,255,0.08); color: var(--cyan); border: 1px solid rgba(0,229,255,0.2); }.topbar-right { margin-left: auto; display: flex; align-items: center; gap: 18px; }.topbar-right a { font-size: 0.72rem; color: var(--text2); text-decoration: none; font-weight: 500; }15 unmodified lines.btn-topbar.active { background: var(--amber); color: #000; box-shadow: 0 0 16px rgba(255,171,0,0.4); }/* ββ DASHBOARD LAYOUT ββ */.dashboard { display: grid; grid-template-columns: 260px 1fr 310px; height: calc(100vh - 48px); }.sidebar {background: var(--bg-panel);backdrop-filter: blur(24px);-webkit-backdrop-filter: blur(24px);border-right: 1px solid var(--border);padding: 14px;overflow-y: auto;}.sidebar-right { border-right: none; border-left: 1px solid var(--border); }/* ββ SIDEBAR SECTIONS ββ */.sb-section { margin-bottom: 18px; }.sb-title {font-family: var(--display);font-size: 0.65rem;font-weight: 700;letter-spacing: 0.1em;color: var(--cyan);margin-bottom: 10px;display: flex;align-items: center;gap: 6px;text-transform: uppercase;}.ind { width: 6px; height: 6px; border-radius: 50%; }.ind-green { background: var(--green); box-shadow: 0 0 6px var(--green); }.ind-amber { background: var(--amber); box-shadow: 0 0 6px var(--amber); }.ind-blue { background: var(--cyan); box-shadow: 0 0 6px var(--cyan); }.ind-purple { background: var(--purple); box-shadow: 0 0 6px var(--purple); }select {width: 100%;font-family: var(--sans);font-size: 0.72rem;background: rgba(5, 15, 30, 0.6);color: var(--text);border: 1px solid var(--border);border-radius: 6px;padding: 8px;margin-bottom: 8px;cursor: pointer;outline: none;transition: border-color 0.2s;}select:focus { border-color: var(--cyan); }optgroup { font-weight: 700; color: var(--dim); background: #051424; }.btn-reset, .btn-step {width: 100%;font-family: var(--mono);font-size: 0.72rem;font-weight: 700;letter-spacing: 0.06em;border: 1px solid transparent;border-radius: 6px;padding: 10px;cursor: pointer;margin-bottom: 6px;transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);}.btn-reset {background: rgba(0, 136, 255, 0.1);color: #fff;border-color: rgba(0, 136, 255, 0.3);}.btn-reset:hover {background: rgba(0, 136, 255, 0.25);box-shadow: 0 0 16px rgba(0, 136, 255, 0.3);}.btn-step {background: rgba(0, 210, 255, 0.15);color: var(--cyan);border-color: rgba(0, 210, 255, 0.3);}.btn-step:hover {background: var(--cyan);color: #051424;box-shadow: 0 0 20px rgba(0, 210, 255, 0.4);}.btn-reset:disabled, .btn-step:disabled { opacity: 0.3; cursor: not-allowed; box-shadow: none !important; }/* ββ METRICS & HEALTH SCORES ββ */.health-scores { display: flex; gap: 8px; margin-bottom: 14px; }.health-box {flex: 1;padding: 12px 0;text-align: center;border-radius: 8px;background: rgba(18, 33, 49, 0.3);border: 1px solid var(--border);backdrop-filter: blur(8px);-webkit-backdrop-filter: blur(8px);transition: all 0.3s;}.health-box.primary { border-color: rgba(0, 230, 118, 0.2); }.health-box.secondary { border-color: rgba(255, 77, 77, 0.2); }.h-label { display: block; font-family: var(--display); font-size: 0.55rem; font-weight: 700; letter-spacing: 0.08em; color: var(--text2); margin-bottom: 4px; }.h-val { display: block; font-size: 1.7rem; font-weight: 800; font-family: var(--display); line-height: 1; }.primary .h-val { color: var(--green); text-shadow: 0 0 10px rgba(0, 230, 118, 0.2); }.secondary .h-val { color: var(--red); text-shadow: 0 0 10px rgba(255, 77, 77, 0.2); }.metric { display: flex; justify-content: space-between; align-items: center; padding: 4px 0; font-size: 0.7rem; color: var(--text2); }.metric-val { font-family: var(--mono); font-weight: 600; color: var(--text); font-size: 0.7rem; }.metric-good { color: var(--green); }.metric-warn { color: var(--amber); }.metric-bad { color: var(--red); }.vram-pool { width: 100%; height: 8px; background: rgba(5, 15, 30, 0.6); border-radius: 4px; margin: 8px 0 4px; overflow: hidden; border: 1px solid var(--border); }.vram-pool-fill { height: 100%; width: 0%; background: linear-gradient(90deg, var(--cyan), var(--green)); border-radius: 4px; transition: width 0.8s ease; }.chart-container { width: 100%; height: 110px; background: rgba(5, 15, 30, 0.4); backdrop-filter: blur(8px); border-radius: 6px; border: 1px solid var(--border); padding: 5px; }#actionInput {width: 100%;min-height: 120px;background: rgba(5, 15, 30, 0.6);color: var(--text);border: 1px solid var(--border);border-radius: 6px;padding: 8px;font-family: var(--mono);font-size: 0.65rem;line-height: 1.5;resize: vertical;outline: none;transition: border-color 0.2s;}#actionInput:focus { border-color: var(--cyan); }/* ββ MAIN AREA ββ */.main-area { padding: 16px 20px; overflow-y: auto; background: transparent; display: flex; flex-direction: column; }.rack-comparison { display: flex; gap: 20px; margin-bottom: 20px; }.gpu-rack { flex: 1; }.rack-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }.rack-header h2 { font-family: var(--display); font-size: 0.75rem; font-weight: 700; letter-spacing: 0.12em; color: var(--dim); text-transform: uppercase; }.efficiency-badge {font-size: 0.65rem;font-family: var(--mono);font-weight: 600;background: rgba(0, 230, 118, 0.15);color: var(--green);padding: 3px 8px;border-radius: 4px;border: 1px solid rgba(0, 230, 118, 0.3);box-shadow: 0 0 10px rgba(0, 230, 118, 0.1);}.rack-status {font-size: 0.6rem;font-weight: 700;font-family: var(--mono);letter-spacing: 0.1em;padding: 3px 10px;border-radius: 4px;background: rgba(0, 210, 255, 0.1);color: var(--cyan);border: 1px solid rgba(0, 210, 255, 0.2);}.rack-status.active { background: rgba(0, 230, 118, 0.1); color: var(--green); border-color: rgba(0, 230, 118, 0.2); }.rack-status.error { background: rgba(255, 77, 77, 0.1); color: var(--red); border-color: rgba(255, 77, 77, 0.2); }/* ββββββββββββββββββββββββββββββββββββββββGPU CHIP VISUALIZATION (Bento Cards)ββββββββββββββββββββββββββββββββββββββββ */.rack-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }.rack-comparison.split .rack-grid { grid-template-columns: repeat(2, 1fr); }.gpu-chip {background: var(--bg-gpu);backdrop-filter: blur(16px);-webkit-backdrop-filter: blur(16px);border: 1px solid var(--border);border-top: 1px solid rgba(255, 255, 255, 0.12);border-radius: 12px;padding: 12px;position: relative;overflow: hidden;transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);}.gpu-chip::after {content: '';position: absolute;inset: -1px;border-radius: 12px;padding: 1px;background: linear-gradient(135deg, transparent 40%, rgba(0, 136, 255, 0.4) 100%);-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);-webkit-mask-composite: xor;mask-composite: exclude;opacity: 0.3;transition: opacity 0.4s;}.gpu-chip:hover {transform: translateY(-2px);border-color: rgba(0, 210, 255, 0.3);box-shadow: 0 8px 24px rgba(0, 210, 255, 0.12);}.gpu-chip.active { box-shadow: 0 0 20px rgba(0, 210, 255, 0.08); }.gpu-chip.active::after { background: linear-gradient(135deg, var(--cyan) 0%, var(--green) 100%); opacity: 0.6; }.gpu-chip.warning { box-shadow: 0 0 24px rgba(255, 171, 0, 0.12); }.gpu-chip.warning::after { background: linear-gradient(135deg, var(--amber) 0%, var(--red) 100%); opacity: 0.75; }.gpu-chip.crashed {border-color: var(--red);box-shadow: 0 0 24px rgba(255, 77, 77, 0.25);animation: cascade-pulse 1.2s cubic-bezier(0.16, 1, 0.3, 1) infinite;z-index: 10;}.gpu-chip.crashed::after { background: linear-gradient(135deg, var(--red) 0%, var(--purple) 100%); opacity: 0.9; }@keyframes cascade-pulse {0% { box-shadow: 0 0 0 0 rgba(255, 77, 77, 0.6); }70% { box-shadow: 0 0 0 15px rgba(255, 77, 77, 0); }100% { box-shadow: 0 0 0 0 rgba(255, 77, 77, 0); }}.gpu-label { font-size: 0.65rem; font-weight: 700; font-family: var(--mono); letter-spacing: 0.1em; color: var(--dim); margin-bottom: 8px; }.core-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; margin-bottom: 10px; }.core { aspect-ratio: 1; border-radius: 2px; background: #0c182c; transition: background 0.5s ease, box-shadow 0.5s ease; }.core.lit-cyan { background: var(--cyan); box-shadow: 0 0 5px var(--cyan); }.core.lit-green { background: var(--green); box-shadow: 0 0 5px var(--green); }.core.lit-blue { background: var(--blue); box-shadow: 0 0 5px var(--blue); }.core.lit-amber { background: var(--amber); box-shadow: 0 0 5px var(--amber); }.core.lit-red { background: var(--red); box-shadow: 0 0 5px var(--red); }.core.lit-purple { background: var(--purple); box-shadow: 0 0 5px var(--purple); }.core.lit-dim { background: #122138; }.gpu-vram-wrap { margin-bottom: 6px; }.gpu-vram-track { width: 100%; height: 6px; background: rgba(5, 15, 30, 0.6); border-radius: 3px; overflow: hidden; border: 1px solid var(--border); }.gpu-vram-bar { height: 100%; border-radius: 3px; transition: width 0.8s ease, background 0.4s; background: linear-gradient(90deg, var(--cyan), var(--green)); }.gpu-vram-bar.high { background: linear-gradient(90deg, var(--amber), var(--red)); }.gpu-vram-bar.critical { background: var(--red); animation: blink-bg 1s infinite; }3 unmodified lines50% { opacity: 0.4; }}.prec-segmented-bar { display: flex; width: 100%; height: 4px; border-radius: 2px; overflow: hidden; margin-bottom: 4px; background: rgba(255,255,255,0.05); }.seg-fp32 { background: var(--blue); }.seg-bf16 { background: var(--green); }1 unmodified line.seg-fp8 { background: var(--red); }.gpu-info-row { display: flex; justify-content: space-between; align-items: center; font-size: 0.6rem; font-family: var(--mono); color: var(--text2); margin-top: 4px; }.gpu-model-label { font-size: 0.6rem; font-weight: 600; font-family: var(--mono); margin-top: 8px; padding: 2px 6px; border-radius: 4px; display: inline-block; }.gpu-model-label.assigned { background: rgba(0, 210, 255, 0.12); color: var(--cyan); border: 1px solid rgba(0, 210, 255, 0.2); }.gpu-model-label.empty { color: var(--dim); }.gpu-temp { position: absolute; top: 10px; right: 12px; font-size: 0.6rem; font-family: var(--mono); font-weight: 600; }6 unmodified lines/* ββ AGENT REASONING FEED ββ */.reasoning-section { flex: 1; display: flex; flex-direction: column; margin-top: 10px; }.reasoning-feed {background: rgba(5, 15, 30, 0.5);backdrop-filter: blur(16px);-webkit-backdrop-filter: blur(16px);border: 1px solid var(--border);border-radius: 8px;padding: 14px;overflow-y: auto;flex: 1;display: flex;flex-direction: column;gap: 10px;position: relative;}.reasoning-feed::after {content: '';position: absolute;inset: 0;background: linear-gradient(to bottom,transparent 50%,rgba(0, 210, 255, 0.015) 50%);background-size: 100% 4px;pointer-events: none;z-index: 10;}.thought-bubble {padding: 10px 14px;border-radius: 12px;font-size: 0.72rem;line-height: 1.5;max-width: 85%;animation: slideInUp 0.3s cubic-bezier(0.16, 1, 0.3, 1) both;position: relative;}.thought-bubble.agent {background: rgba(0, 210, 255, 0.08);border: 1px solid rgba(0, 210, 255, 0.15);color: #e3f2fd;align-self: flex-start;border-top-left-radius: 2px;}.thought-bubble.agent::before { content: 'π€ Agent Reasoning'; display: block; font-family: var(--display); font-size: 0.55rem; color: var(--cyan); font-weight: 700; margin-bottom: 4px; letter-spacing: 0.05em; text-transform: uppercase;}.thought-bubble.baseline {background: rgba(255, 77, 77, 0.08);border: 1px solid rgba(255, 77, 77, 0.15);color: #ffebee;align-self: flex-end;border-top-right-radius: 2px;text-align: right;}.thought-bubble.baseline::before { content: 'β οΈ Baseline Action'; display: block; font-family: var(--display); font-size: 0.55rem; color: var(--red); font-weight: 700; margin-bottom: 4px; letter-spacing: 0.05em; text-transform: uppercase;}.thought-bubble.sys-thought { background: transparent; border: 1px dashed var(--dim); color: var(--text2); align-self: center; text-align: center; }4 unmodified lines.telemetry-empty { font-size: 0.7rem; color: var(--dim); font-style: italic; text-align: center; padding: 20px 0; }.model-telemetry {background: rgba(18, 33, 49, 0.3);backdrop-filter: blur(12px);-webkit-backdrop-filter: blur(12px);border: 1px solid var(--border);border-radius: 8px;padding: 10px;transition: all 0.3s;}.model-telemetry:hover {border-color: rgba(0, 210, 255, 0.2);background: rgba(18, 33, 49, 0.45);}.m-tel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }.m-tel-name { font-size: 0.75rem; font-weight: 700; font-family: var(--mono); color: var(--text); }.m-tel-status { font-size: 0.6rem; font-weight: 700; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; }.m-tel-status.healthy { background: rgba(0, 230, 118, 0.15); color: var(--green); }.m-tel-status.flagged { background: rgba(255, 171, 0, 0.15); color: var(--amber); }.m-tel-status.crashed { background: rgba(255, 77, 77, 0.15); color: var(--red); animation: blink-text 1s infinite;}.m-tel-sparkline { height: 30px; width: 100%; border-bottom: 1px dashed var(--dim); position: relative; display: flex; align-items: flex-end; gap: 2px; padding-bottom: 2px;}.spark-bar { width: 100%; background: var(--cyan); border-radius: 1px 1px 0 0; }5 unmodified lines.alert-dot.warn { background: var(--amber); }.alert-dot.crit { background: var(--red); }.json-box {background: rgba(5, 10, 20, 0.6);backdrop-filter: blur(12px);-webkit-backdrop-filter: blur(12px);border: 1px solid var(--border);border-radius: 6px;padding: 8px;font-family: var(--mono);font-size: 0.65rem;line-height: 1.5;color: var(--text);overflow: auto;max-height: 250px;white-space: pre-wrap;word-break: break-word;}/* ββ AGENTIC KERNEL PANEL ββ */.kernel-badge {border-color: rgba(176, 38, 255, 0.3) !important;color: var(--purple) !important;background: rgba(176, 38, 255, 0.08) !important;cursor: pointer;transition: all 0.3s ease;border: 1px solid;font-size: 0.6rem;font-weight: 700;letter-spacing: 0.1em;padding: 2px 8px;border-radius: 3px;font-family: var(--sans);}.kernel-badge:hover { background: rgba(176, 38, 255, 0.18) !important; box-shadow: 0 0 12px rgba(176, 38, 255, 0.3); }.kernel-badge.active { background: rgba(176, 38, 255, 0.25) !important; box-shadow: 0 0 20px rgba(176, 38, 255, 0.4); border-color: var(--purple) !important; }.kernel-panel {background: linear-gradient(180deg, rgba(176, 38, 255, 0.03) 0%, rgba(18, 33, 49, 0.4) 100%);backdrop-filter: blur(24px);-webkit-backdrop-filter: blur(24px);border-bottom: 1px solid rgba(176, 38, 255, 0.15);padding: 0;overflow: hidden;animation: kernelSlideDown 0.4s cubic-bezier(0.16, 1, 0.3, 1);}@keyframes kernelSlideDown { from { max-height: 0; opacity: 0; } to { max-height: 600px; opacity: 1; } }.kernel-inner { padding: 16px 24px; }.kernel-header { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }.kernel-header h2 { font-family: var(--display); font-size: 0.75rem; font-weight: 800; letter-spacing: 0.12em; color: var(--purple); margin: 0; text-shadow: 0 0 15px rgba(176, 38, 255, 0.3); }.kernel-desc { font-size: 0.65rem; color: var(--text2); flex: 1; }.btn-bench {font-family: var(--mono); font-size: 0.65rem; font-weight: 700; letter-spacing: 0.06em;background: rgba(176, 38, 255, 0.15); color: var(--purple); border: 1px solid rgba(176, 38, 255, 0.3);border-radius: 6px; padding: 8px 16px; cursor: pointer; transition: all 0.2s;}.btn-bench:hover { background: rgba(176, 38, 255, 0.3); box-shadow: 0 0 16px rgba(176, 38, 255, 0.3); }.btn-bench:disabled { opacity: 0.5; cursor: not-allowed; }.btn-bench.running { animation: benchPulse 1.5s ease-in-out infinite; }@keyframes benchPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(176, 38, 255, 0.4); } 50% { box-shadow: 0 0 20px 5px rgba(176, 38, 255, 0.2); } }/* Metric Cards */.kernel-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 16px; }.k-card {background: rgba(18, 33, 49, 0.25);backdrop-filter: blur(12px);border: 1px solid var(--border);border-top: 1px solid rgba(255, 255, 255, 0.1);border-radius: 8px;padding: 14px;text-align: center;transition: all 0.3s;}.k-card:hover {border-color: rgba(176, 38, 255, 0.3);transform: translateY(-1px);}.k-card-title { font-family: var(--display); font-size: 0.55rem; font-weight: 700; letter-spacing: 0.1em; color: var(--purple); margin-bottom: 6px; }.k-big-number { font-family: var(--display); font-size: 1.8rem; font-weight: 800; color: var(--purple); line-height: 1.1; }.k-big-number.k-solved { color: var(--green); text-shadow: 0 0 20px rgba(0,230,118,0.3); }.k-big-number.k-active { color: var(--amber); }.k-big-number.k-error { color: var(--red); }.k-unit { font-size: 0.6rem; color: var(--text2); margin-top: 2px; }1 unmodified line/* Module Breakdown */.kernel-modules { margin-bottom: 16px; }.km-title { font-family: var(--display); font-size: 0.6rem; font-weight: 700; letter-spacing: 0.1em; color: var(--dim); margin-bottom: 10px; }.km-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }.km-card {background: rgba(5, 10, 20, 0.5);backdrop-filter: blur(8px);border: 1px solid var(--border);border-radius: 6px;padding: 10px;transition: border-color 0.3s;}.km-card:hover { border-color: var(--cyan); }.km-name { font-family: var(--mono); font-size: 0.65rem; font-weight: 600; color: var(--cyan); margin-bottom: 6px; }.km-bar-track { width: 100%; height: 6px; background: rgba(5, 15, 30, 0.6); border-radius: 3px; overflow: hidden; border: 1px solid var(--border); }.km-bar { height: 100%; background: linear-gradient(90deg, var(--purple), #e040fb); border-radius: 3px; transition: width 1s ease; }.km-bar.safety { background: linear-gradient(90deg, var(--amber), #ff6d00); }.km-bar.scoring { background: linear-gradient(90deg, var(--cyan), var(--green)); }.km-val { font-family: var(--mono); font-size: 0.65rem; font-weight: 600; color: var(--text); }.km-desc { font-size: 0.55rem; color: var(--dim); margin-top: 2px; }/* Comparison Bars */.kc-row { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }.kc-label { font-size: 0.65rem; font-family: var(--mono); color: var(--text2); width: 120px; flex-shrink: 0; text-align: right; }.kc-bar-track { flex: 1; height: 10px; background: rgba(5, 15, 30, 0.6); border-radius: 5px; overflow: hidden; border: 1px solid var(--border); }.kc-bar { height: 100%; border-radius: 5px; transition: width 1.5s ease; }.kc-bar.kernel { background: linear-gradient(90deg, var(--purple), #e040fb); min-width: 3px; }.kc-bar.vm { background: linear-gradient(90deg, var(--amber), #ff6d00); width: 83%; }.kc-bar.docker { background: linear-gradient(90deg, var(--red), #ff5252); width: 100%; }.kc-val { font-size: 0.6rem; font-family: var(--mono); color: var(--text2); width: 80px; flex-shrink: 0; }
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Generate a rich, diverse synthetic dataset of GPU cluster trajectoriesfor the Libratio Predictive MLOps Agent.
This script uses the Agentic Kernel physics model to simulate 1000 episodeswith realistic, randomized mixed-precision strategies across 7 fleet scenarios.
Fixes applied vs v1: 1. Mixed-precision strategies generated randomly per-layer (not uniform) 2. Added realistic mixed configs alongside uniform ones 3. Enriched output with model_name, cost, speedup, accuracy, memory_utilization 4. Seeded RNG for reproducibility 5. Added fleet-level metadata (total_memory_used, memory_overflow)"""import jsonimport randomfrom environment.fleet_env import FleetEnvironmentfrom environment.physics_model import compute_training_cost, compute_hardware_safety
# All available precisions per layer type, ordered from safest to most aggressiveLAYER_PRECISIONS = { "embedding": ["FP32", "BF16"], # FP8/FP16 crash on embedding (stability < 0.5) "attention": ["BF16", "FP16", "FP8"], # FP32 is overkill, FP8 is risky "ffn": ["FP8", "BF16", "FP16"], # FP8 is the ideal target here "layernorm": ["BF16", "FP16"], # FP8 is dangerous (stability = 0.2) "output": ["FP32"], # Must always be FP32 (stability < 0.5 for everything else)}
# Also include some deliberately bad choices to create crash dataRISKY_LAYER_PRECISIONS = { "embedding": ["FP8", "FP16"], # Will cause CRASH_NUMERICAL_INSTABILITY "attention": ["FP8"], # Risky "ffn": ["FP32"], # Wasteful but stable "layernorm": ["FP8"], # Dangerous "output": ["FP16", "BF16", "FP8"], # Will cause crashes}
def random_safe_strategy(): """Generate a random but physically plausible mixed-precision strategy.""" return { layer: random.choice(options) for layer, options in LAYER_PRECISIONS.items() }
def random_risky_strategy(): """Generate a strategy that has at least one dangerous layer choice.""" strategy = random_safe_strategy() # Pick 1-2 layers to make risky num_risky = random.randint(1, 2) risky_layers = random.sample(list(RISKY_LAYER_PRECISIONS.keys()), num_risky) for layer in risky_layers: strategy[layer] = random.choice(RISKY_LAYER_PRECISIONS[layer]) return strategy
def random_uniform_strategy(): """Generate a uniform precision strategy (all layers same precision).""" precision = random.choice(["FP32", "BF16", "FP8"]) return {layer: precision for layer in LAYER_PRECISIONS.keys()}
def generate_dataset(num_episodes=1000, seed=42): random.seed(seed) env = FleetEnvironment() dataset = []
# Strategy distribution: 50% safe mixed, 30% risky mixed, 20% uniform strategy_generators = [ (random_safe_strategy, 0.50), (random_risky_strategy, 0.30), (random_uniform_strategy, 0.20), ]
print(f"Generating {num_episodes} synthetic MLOps trajectories (seed={seed})...")
for i in range(num_episodes): obs = env.reset("fleet_precision") cluster = env.task_state["cluster"] models = env.task_state["models"]
episode_data = { "episode_id": i, "scenario_id": env.scenario["scenario_id"], "cluster_capacity_gb": cluster["total_memory_gb"], "total_gpus": cluster["total_gpus"], "gpu_memory_gb": cluster.get("gpu_memory_gb", 80.0), "trajectories": [], "fleet_total_memory_used_gb": 0.0, }
for idx, model in enumerate(models): # Pick a strategy generator based on weighted distribution roll = random.random() cumulative = 0.0 chosen_gen = random_safe_strategy for gen_fn, weight in strategy_generators: cumulative += weight if roll < cumulative: chosen_gen = gen_fn break
strategy = chosen_gen()
# Compute physics using the kernel metrics = compute_training_cost( model["total_params"], strategy, model["layer_distribution"] ) num_gpus_for_model = max(1, cluster["total_gpus"] // len(models)) hw_safety = compute_hardware_safety( model["total_params"], strategy, model["layer_distribution"], num_gpus_for_model, cluster.get("gpu_memory_gb", 80.0) )
# Determine outcome from physics outcome = "SUCCESS" failure_reason = None if not metrics["estimated_stable"]: outcome = "CRASH_NUMERICAL_INSTABILITY" # Find which layer caused it from environment.physics_model import STABILITY_SCORE for layer, precision in strategy.items(): stab = STABILITY_SCORE.get(layer, {}).get(precision, 1.0) if stab < 0.5: failure_reason = f"{layer} at {precision} (stability={stab})" break elif not hw_safety["overall_safe"]: outcome = "CRASH_THERMAL_THROTTLE" if not hw_safety["memory_safe"]: failure_reason = f"memory_utilization={hw_safety['memory_utilization_pct']}%" else: failure_reason = f"power_draw={hw_safety['estimated_power_pct']}%"
traj_record = { "model_id": model["model_id"], "model_name": model["name"], "total_params_b": round(model["total_params"] / 1e9, 1), "precision_strategy": strategy, "memory_used_gb": metrics["memory_gb"], "memory_utilization_pct": hw_safety["memory_utilization_pct"], "thermal_risk": hw_safety["thermal_risk"], "estimated_power_pct": hw_safety["estimated_power_pct"], "speedup_vs_fp32": metrics["speedup_vs_fp32"], "cost_usd": metrics["cost_usd"], "accuracy_retention": metrics["accuracy_retention"], "outcome": outcome, } if failure_reason: traj_record["failure_reason"] = failure_reason
episode_data["trajectories"].append(traj_record) episode_data["fleet_total_memory_used_gb"] += metrics["memory_gb"]
# Step the environment to advance the agent turn env.step({"precision_strategy": strategy})
# Round fleet total and check for overflow episode_data["fleet_total_memory_used_gb"] = round( episode_data["fleet_total_memory_used_gb"], 2 ) episode_data["memory_overflow"] = ( episode_data["fleet_total_memory_used_gb"] > cluster["total_memory_gb"] )
dataset.append(episode_data) if (i + 1) % 100 == 0: print(f" Generated {i + 1}/{num_episodes} episodes...")
# Print dataset statistics all_outcomes = [t["outcome"] for ep in dataset for t in ep["trajectories"]] total = len(all_outcomes) success = all_outcomes.count("SUCCESS") crash_num = all_outcomes.count("CRASH_NUMERICAL_INSTABILITY") crash_therm = all_outcomes.count("CRASH_THERMAL_THROTTLE")
print(f"\n--- Dataset Statistics ---") print(f" Total trajectory records: {total}") print(f" SUCCESS: {success} ({100*success/total:.1f}%)") print(f" CRASH_NUMERICAL_INSTAB: {crash_num} ({100*crash_num/total:.1f}%)") print(f" CRASH_THERMAL_THROTTLE: {crash_therm} ({100*crash_therm/total:.1f}%)")
# Count unique strategies unique_strats = set() for ep in dataset: for t in ep["trajectories"]: key = tuple(sorted(t["precision_strategy"].items())) unique_strats.add(key) print(f" Unique precision strategies: {len(unique_strats)}")
with open("synthetic_trajectories.json", "w") as f: json.dump(dataset, f, indent=2)
print(f"\nDone! Saved {len(dataset)} episodes to synthetic_trajectories.json")
if __name__ == "__main__": generate_dataset()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""MongoDB Time Series Metrics Logging β Libratio Fleet===================================================Uses MongoDB's native Time Series collections to store step-by-step performancetelemetry (VRAM, thermal status, reward, power draw) from multi-agent training runs.
Why Time Series Collections?- Highly optimized storage for sequential measurements over time.- Automatic compression of metrics (reduces disk footprint by up to 95%).- Efficient querying by time windows, intervals, and aggregations.- Demonstrates advanced MongoDB capabilities to hackathon judges."""
import osfrom datetime import datetime, timezonefrom pymongo import MongoClientimport certififrom dotenv import load_dotenv
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"METRICS_COLLECTION = "gpu_telemetry_metrics"
def get_mongo_client(): if not MONGO_URI: return None try: return MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000) except Exception: return None
def create_metrics_timeseries_collection() -> bool: """ Creates a native MongoDB Time Series collection if it doesn't already exist. """ client = get_mongo_client() if not client: print("[WARN] MONGO_URI not configured. Skipping Time Series creation.") return False
db = client[DB_NAME]
# Check if the collection already exists if METRICS_COLLECTION in db.list_collection_names(): print(f" [INFO] Time Series collection '{METRICS_COLLECTION}' already exists.") client.close() return True
try: # Create a native time-series collection in MongoDB # - timeField: "timestamp" (specifies the date field in each document) # - metaField: "metadata" (specifies the tags used to categorize the metrics) # - granularity: "seconds" (tells MongoDB to optimize for sub-minute updates) db.create_collection( METRICS_COLLECTION, timeseries={ "timeField": "timestamp", "metaField": "metadata", "granularity": "seconds", } ) print(f" [OK] Created native MongoDB Time Series collection '{METRICS_COLLECTION}'!") client.close() return True except Exception as e: print(f" [WARN] Failed to create native Time Series collection: {e}") print(" (Usually means the database user does not have 'createCollection' permission)") client.close() return False
def log_step_metrics( task_id: str, model_id: str, step: int, reward: float, memory_used_gb: float, thermal_risk: str, power_util: float,) -> bool: """ Logs a single measurement point to the Time Series collection. """ client = get_mongo_client() if not client: return False
try: db = client[DB_NAME] col = db[METRICS_COLLECTION]
# Structure for Time Series: timeField (timestamp) + metaField (metadata) + measurements metric_doc = { "timestamp": datetime.now(timezone.utc), "metadata": { "task_id": task_id, "model_id": model_id, }, "step": step, "reward": float(reward), "memory_used_gb": float(memory_used_gb), "thermal_risk": str(thermal_risk), "power_util": float(power_util), }
col.insert_one(metric_doc) client.close() return True except Exception: # Fail silently to prevent telemetry logging from crashing the main inference run if client: client.close() return False
if __name__ == "__main__": print("Initializing Time Series collection...") create_metrics_timeseries_collection()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""MongoDB Change Streams Real-Time Monitor β Libratio Fleet=========================================================Runs an event-driven background listener that monitors the 'runs' collection inMongoDB Atlas. When a new training run is logged, the script automatically:
1. Detects failures or low-performing runs (score < 0.60).2. Queries the 'gpu_telemetry_metrics' Time Series collection to build a step profile.3. Automatically diagnoses the root cause (e.g., OOM vs thermal throttling).4. Logs a detailed post-incident report to the 'incident_reports' collection.
This illustrates the exact kind of real-time, event-driven MLOps SRE workflowenabled by MongoDB Atlas."""
import osimport jsonimport timefrom datetime import datetime, timezonefrom pymongo import MongoClientimport certififrom dotenv import load_dotenv
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"
def run_change_stream_listener(): print("=" * 60) print(" MongoDB Atlas Change Stream Listener - Real-Time MLOps SRE") print("=" * 60)
if not MONGO_URI: print("[ERROR] MONGO_URI not set in .env") return
retry_delay = 5 # Start with 5 seconds delay max_retry_delay = 60
print(" Watching 'runs' collection for new executions...") print(" Press Ctrl+C to stop.\n")
# Watch pipeline filters for only 'insert' operations pipeline = [{"$match": {"operationType": "insert"}}]
while True: client = None try: # Connect to MongoDB client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000) client.admin.command("ping") db = client[DB_NAME] runs_col = db["runs"] metrics_col = db["gpu_telemetry_metrics"] reports_col = db["incident_reports"]
# Reset retry delay on successful connection retry_delay = 5
with runs_col.watch(pipeline) as stream: for change in stream: run_doc = change["fullDocument"] task_id = run_doc.get("task_id") model_name = run_doc.get("model_name") score = run_doc.get("score", 0.0) success = run_doc.get("success", False) rewards = run_doc.get("rewards", [])
print(f"[*] NEW RUN DETECTED: Task={task_id} | Model={model_name} | Score={score:.3f} | Success={success}")
# Check if it was a failure or low-performing run if not success or score < 0.60: print(" [WARNING] Run did not meet performance threshold. Generating SRE incident report...")
# Query Time Series collection for this specific run's telemetry steps metrics_cursor = metrics_col.find( { "metadata.task_id": task_id, "metadata.model_id": model_name, } ).sort("timestamp", 1)
steps_history = list(metrics_cursor) print(f" Retrieved {len(steps_history)} metrics steps from Time Series collection.")
# Profile the steps steps_data = [] max_memory_gb = 0.0 has_high_thermal = False
for step in steps_history: steps_data.append({ "step": step.get("step"), "reward": step.get("reward"), "memory_used_gb": step.get("memory_used_gb"), "thermal_risk": step.get("thermal_risk"), "power_util": step.get("power_util"), }) if step.get("memory_used_gb", 0.0) > max_memory_gb: max_memory_gb = step.get("memory_used_gb") if step.get("thermal_risk") == "HIGH": has_high_thermal = True
# Run auto-diagnostics probable_cause = "Unknown cluster stress" recommendation = "Re-evaluate precision strategy; check baseline parameter counts."
if max_memory_gb > 240.0: probable_cause = "VRAM Memory Overflow (Potential OOM)" recommendation = "Attention layers should be cast to BF16 or FFN to FP8 to reduce memory footprint." elif has_high_thermal: probable_cause = "GPU Thermal Risk Alert (High heat dissipation)" recommendation = "Limit FP8 usage on high-priority attention layers; check GPU fans and power constraints." elif score < 0.20: probable_cause = "Severe Optimization Degradation" recommendation = "Verify the precision strategy isn't applying FP8 to embedding or output layers."
report = { "incident_id": f"INC-{int(time.time())}", "timestamp": datetime.now(timezone.utc), "task_id": task_id, "model_name": model_name, "score": score, "max_memory_gb": max_memory_gb, "probable_cause": probable_cause, "recommendation": recommendation, "steps_profiled": len(steps_data), "run_id": run_doc.get("_id"), }
# Save report to MongoDB res = reports_col.insert_one(report) print(f" [OK] SRE Incident Report created: {report['incident_id']} (Ref ID: {res.inserted_id})") print(f" Cause: {probable_cause}") print(f" Rec: {recommendation}\n") except KeyboardInterrupt: print("\nStopping Change Stream listener.") break except Exception as e: print(f"\n[WARN] Connection lost or Change Stream error: {e}") print(f" Retrying in {retry_delay} seconds...") time.sleep(retry_delay) retry_delay = min(retry_delay * 2, max_retry_delay) finally: if client: client.close()
if __name__ == "__main__": run_change_stream_listener()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511"""MongoDB Atlas Vector Search β Libratio Fleet=============================================Upgrades the basic $match RAG retrieval into true semantic search.
How it works:1. Each GPU trajectory record is converted to a descriptive text string2. Google Gemini generates a 768-dim embedding vector for that text3. The vector is stored alongside the document in MongoDB4. At query time, the live cluster state is embedded the same way5. Atlas $vectorSearch finds the top-k most semantically similar past crashes
Why Gemini embeddings?- We already have GEMINI_API_KEY in .env- 768-dim vectors are compact (good for Atlas free tier)- Gemini Embedding-001 is specifically designed for semantic retrieval tasks
Why this beats $match:- $match finds: thermal_risk == "HIGH" AND memory_used_gb > 180 (exact)- $vectorSearch finds: "situations semantically similar to high thermal stress with memory pressure, regardless of exact field values""""
import osimport jsonfrom typing import Optionalfrom google import genaifrom google.genai import types as genai_typesfrom dotenv import load_dotenv
load_dotenv()
# ββ Gemini Embedding Setup ββGEMINI_API_KEY = os.getenv("GEMINI_API_KEY")EMBEDDING_MODEL = "models/gemini-embedding-001" # 768-dim, supports output_dimensionalityEMBEDDING_DIM = 768
# Fallback if Gemini is unavailable β use a simple deterministic hash embedding_GEMINI_AVAILABLE = False_gemini_client = None
if GEMINI_API_KEY: try: _gemini_client = genai.Client(api_key=GEMINI_API_KEY) _GEMINI_AVAILABLE = True except Exception as e: print(f"[WARN] Gemini embedding setup failed: {e}. Using fallback embedder.")else: print("[WARN] GEMINI_API_KEY not set. Using fallback embedder (no semantic search).")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# TEXT SERIALIZATION# Convert a trajectory record or live cluster state into a rich text description# that captures the semantic meaning of the GPU cluster situation.# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def trajectory_to_text(traj: dict) -> str: """ Convert a stored trajectory record into a descriptive text for embedding.
The text intentionally uses natural language so Gemini's semantic embedding captures the *meaning* of the situation β not just the field names.
Example output: "Model LLaMA-3-70B (70.0B params) training outcome: CRASH_NUMERICAL_INSTABILITY. Precision strategy: embedding=FP8, attention=BF16, ffn=FP8, layernorm=FP8, output=FP32. Memory usage: 185.4GB VRAM, 92% utilization. Thermal status: HIGH risk, 94% power draw. Speedup vs FP32: 2.1x. Failure cause: embedding at FP8 (stability=0.1)." """ strategy = traj.get("precision_strategy", {}) strategy_str = ", ".join(f"{k}={v}" for k, v in strategy.items()) if strategy else "unknown"
outcome = traj.get("outcome", "UNKNOWN") failure = traj.get("failure_reason", "") failure_str = f" Failure cause: {failure}." if failure else ""
text = ( f"Model {traj.get('model_name', traj.get('model_id', 'unknown'))} " f"({traj.get('total_params_b', '?')}B params) training outcome: {outcome}. " f"Precision strategy: {strategy_str}. " f"Memory usage: {traj.get('memory_used_gb', '?')}GB VRAM, " f"{traj.get('memory_utilization_pct', '?')}% utilization. " f"Thermal status: {traj.get('thermal_risk', 'UNKNOWN')} risk, " f"{traj.get('estimated_power_pct', '?')}% power draw. " f"Speedup vs FP32: {traj.get('speedup_vs_fp32', '?')}x. " f"Accuracy retention: {traj.get('accuracy_retention', '?')}%." f"{failure_str}" ) return text
def live_state_to_query_text(live_state: dict) -> str: """ Convert the current live cluster state into a query text for vector search.
This should describe the DANGER/RISK we're currently experiencing so that Vector Search finds historically similar dangerous situations.
Example output: "Current cluster EMERGENCY: Model LLaMA-3-70B (70.0B params) using 220.0GB of 320.0GB cluster memory (68.8% utilization). Thermal risk: HIGH. Power draw: 88%. Need to find similar historical crashes to inform precision strategy decisions." """ memory_pct = round( 100 * live_state.get("memory_used_gb", 0) / max(live_state.get("cluster_capacity_gb", 1), 1), 1 ) text = ( f"Current cluster EMERGENCY: " f"Model {live_state.get('model_name', 'unknown')} " f"({live_state.get('total_params_b', '?')}B params) " f"using {live_state.get('memory_used_gb', '?')}GB of " f"{live_state.get('cluster_capacity_gb', '?')}GB cluster memory " f"({memory_pct}% utilization). " f"Thermal risk: {live_state.get('thermal_risk', 'UNKNOWN')}. " f"Power draw: {live_state.get('power_util', '?')}%. " f"Need to find similar historical crashes to inform precision strategy decisions." ) return text
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# EMBEDDING GENERATION# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _fallback_embedding(text: str) -> list[float]: """ Deterministic fallback when Gemini is unavailable. Uses a simple character-based hash to produce a 768-dim vector. NOT semantically meaningful, but allows the pipeline to run without Gemini. """ import hashlib import math
# Generate a seeded pseudo-random vector from the text hash seed = int(hashlib.md5(text.encode()).hexdigest(), 16) rng_state = seed result = [] for i in range(EMBEDDING_DIM): # Linear congruential generator β fast, deterministic, reproducible rng_state = (rng_state * 1664525 + 1013904223) & 0xFFFFFFFF # Map to [-1, 1] and apply sine for spread val = math.sin(rng_state / 0xFFFFFFFF * math.pi * 2 + i) result.append(round(val, 6))
# Normalize to unit vector (required for cosine similarity) magnitude = math.sqrt(sum(v * v for v in result)) if magnitude > 0: result = [v / magnitude for v in result] return result
def generate_embedding(text: str, task_type: str = "RETRIEVAL_DOCUMENT") -> list[float]: """ Generate a 768-dimensional embedding vector for the given text.
Args: text: The text to embed (trajectory description or query) task_type: Gemini task type β use "RETRIEVAL_DOCUMENT" when indexing, "RETRIEVAL_QUERY" when searching. This optimizes the embedding for asymmetric retrieval (short query vs longer documents).
Returns: List of 768 floats representing the text in semantic space. """ if not _GEMINI_AVAILABLE or _gemini_client is None: return _fallback_embedding(text)
try: result = _gemini_client.models.embed_content( model=EMBEDDING_MODEL, contents=text, config=genai_types.EmbedContentConfig( task_type=task_type, output_dimensionality=EMBEDDING_DIM, # Pin to 768 dims explicitly ), ) return list(result.embeddings[0].values) except Exception as e: print(f" [WARN] Gemini embedding failed ({type(e).__name__}), using fallback: {e}") return _fallback_embedding(text)
def embed_trajectory(traj: dict) -> list[float]: """Generate an embedding vector for a stored trajectory document.""" text = trajectory_to_text(traj) return generate_embedding(text, task_type="RETRIEVAL_DOCUMENT")
def embed_query(live_state: dict) -> list[float]: """Generate an embedding vector for a live cluster state query.""" text = live_state_to_query_text(live_state) return generate_embedding(text, task_type="RETRIEVAL_QUERY")
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# VECTOR SEARCH QUERY# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def vector_search_similar_trajectories( collection, live_state: dict, top_k: int = 5, filter_outcome: Optional[str] = None,) -> list[dict]: """ Find the most semantically similar historical trajectories to the current live cluster state using MongoDB Atlas $vectorSearch.
The Atlas Vector Search index must exist (run setup_vector_index.py first). Index name: "trajectory_vector_index" Field: "embedding" Similarity: "cosine"
Args: collection: PyMongo collection object (trajectories collection) live_state: Current live cluster state dict top_k: Number of similar trajectories to return filter_outcome: Optional β filter results to only CRASH outcomes
Returns: List of trajectory dicts (without the embedding field for readability)
How Atlas $vectorSearch works: 1. Your query vector is compared against all stored document vectors 2. Atlas uses Hierarchical Navigable Small Worlds (HNSW) graph β an approximate nearest-neighbor algorithm that runs in O(log n) time 3. Results are ranked by cosine similarity score (1.0 = identical, 0.0 = unrelated) 4. Only the top_k most similar documents are returned """ # Embed the live cluster state print(" (Source: MongoDB Atlas Vector Search β semantic similarity)") query_vector = embed_query(live_state)
# Build the $vectorSearch pipeline # numCandidates: how many candidates to consider before ranking (must be >= top_k) # More candidates = more accurate but slower. 10x top_k is a good balance. pipeline = [ { "$vectorSearch": { "index": "trajectory_vector_index", # Index name (created by setup_vector_index.py) "path": "embedding", # Field storing the vector "queryVector": query_vector, # Our query embedding "numCandidates": top_k * 10, # Candidate pool for ranking "limit": top_k, # How many to return } }, # Add the similarity score to each result { "$addFields": { "vector_score": {"$meta": "vectorSearchScore"} } }, # Optionally filter to only crash outcomes *( [{"$match": {"outcome": {"$ne": "SUCCESS"}}}] if filter_outcome == "crashes_only" else [] ), # Remove the embedding vector from results (it's huge and unreadable) { "$project": { "embedding": 0, "_id": 0, } } ]
try: results = list(collection.aggregate(pipeline)) if results: print(f" Found {len(results)} semantically similar trajectories " f"(top score: {results[0].get('vector_score', 'N/A'):.3f})") return results except Exception as e: # If vector search index doesn't exist yet, fall back to basic search print(f" [WARN] Vector search failed ({type(e).__name__}): {e}") print(" [HINT] Run setup_vector_index.py to create the Atlas Vector Search index.") return []
def format_vector_results_as_context(results: list[dict]) -> str: """ Format vector search results into a rich context string for the LLM prompt. Includes the semantic similarity score so the LLM knows how relevant each historical record is. """ if not results: return "No semantically similar historical trajectories found."
lines = ["HISTORICAL CRASH DATA (MongoDB Atlas Vector Search β ranked by semantic similarity):"] for i, t in enumerate(results, 1): score = t.get("vector_score", 0) relevance = "HIGH" if score > 0.85 else "MEDIUM" if score > 0.70 else "LOW"
strategy = t.get("precision_strategy", {}) strategy_str = ", ".join(f"{k}={v}" for k, v in strategy.items()) if strategy else "unknown"
line = ( f"\n[{i}] Similarity: {score:.3f} ({relevance} relevance)\n" f" Model: {t.get('model_name', t.get('model_id', '?'))} " f"({t.get('total_params_b', '?')}B params)\n" f" Outcome: {t.get('outcome', 'UNKNOWN')} | " f"VRAM: {t.get('memory_used_gb', '?')}GB | " f"Thermal: {t.get('thermal_risk', '?')} | " f"Power: {t.get('estimated_power_pct', '?')}%\n" f" Strategy: {strategy_str}" ) if t.get("failure_reason"): line += f"\n Failure: {t['failure_reason']}"
lines.append(line)
return "\n".join(lines)
def text_search_similar_trajectories( collection, query_text: str, top_k: int = 5,) -> list[dict]: """ Find historical trajectories matching a text query using MongoDB Atlas Search (Lucene full-text search). The Atlas Search index must exist (run setup_vector_index.py first). Index name: "trajectory_text_search_index" """ print(" (Source: MongoDB Atlas Search β full-text keyword search)") pipeline = [ { "$search": { "index": "trajectory_text_search_index", "text": { "query": query_text, "path": ["embedding_source_text", "failure_reason", "model_name", "outcome"] } } }, { "$addFields": { "search_score": {"$meta": "searchScore"} } }, { "$limit": top_k }, { "$project": { "embedding": 0 } } ] try: results = list(collection.aggregate(pipeline)) for res in results: res["_id"] = str(res["_id"]) if results: print(f" Found {len(results)} keyword matches (top score: {results[0].get('search_score', 'N/A'):.3f})") return results except Exception as e: print(f" [WARN] Full-text search failed ({type(e).__name__}): {e}") return []
def hybrid_search_similar_trajectories( collection, query_text: str, live_state: dict, top_k: int = 5,) -> list[dict]: """ Combines Vector Search (Gemini embeddings) and Full-Text Search (keyword matching) using Reciprocal Rank Fusion (RRF) to produce a combined relevance score. RRF Score(d) = sum_{m in M} 1 / (60 + rank_m(d)) """ # 1. Run Vector Search (get more than top_k so we have a good candidate pool for ranking) candidate_limit = max(top_k * 4, 20) vector_pipeline = [ { "$vectorSearch": { "index": "trajectory_vector_index", "path": "embedding", "queryVector": embed_query(live_state), "numCandidates": candidate_limit * 10, "limit": candidate_limit, } }, { "$addFields": { "vector_score": {"$meta": "vectorSearchScore"} } }, { "$project": { "embedding": 0 } } ] # 2. Run Text Search text_pipeline = [ { "$search": { "index": "trajectory_text_search_index", "text": { "query": query_text, "path": ["embedding_source_text", "failure_reason", "model_name", "outcome"] } } }, { "$addFields": { "search_score": {"$meta": "searchScore"} } }, { "$limit": candidate_limit }, { "$project": { "embedding": 0 } } ] vector_results = [] text_results = [] try: vector_results = list(collection.aggregate(vector_pipeline)) except Exception as e: print(f" [WARN] Hybrid: Vector search step failed: {e}") try: text_results = list(collection.aggregate(text_pipeline)) except Exception as e: print(f" [WARN] Hybrid: Text search step failed: {e}") # 3. Reciprocal Rank Fusion (RRF) # RRF Constant K = 60 rrf_scores = {} doc_map = {} # Vector ranking for rank, doc in enumerate(vector_results): doc_id = str(doc["_id"]) doc_map[doc_id] = doc rrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1)) doc["vector_rank"] = rank + 1 # Text ranking for rank, doc in enumerate(text_results): doc_id = str(doc["_id"]) if doc_id not in doc_map: doc_map[doc_id] = doc else: if "search_score" in doc: doc_map[doc_id]["search_score"] = doc["search_score"] rrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1)) doc_map[doc_id]["text_rank"] = rank + 1 # Sort by RRF score descending sorted_ids = sorted(rrf_scores.keys(), key=lambda x: rrf_scores[x], reverse=True) hybrid_results = [] for doc_id in sorted_ids[:top_k]: doc = doc_map[doc_id] doc["rrf_score"] = rrf_scores[doc_id] doc["_id"] = doc_id hybrid_results.append(doc) print(f" Hybrid Search (RRF) merged {len(vector_results)} vector & {len(text_results)} text results -> returned top {len(hybrid_results)}") return hybrid_results
def format_hybrid_results_as_context(results: list[dict]) -> str: """ Format hybrid RRF search results into a rich context string for the LLM prompt. """ if not results: return "No similar historical trajectories found via Hybrid Search."
lines = ["HISTORICAL CRASH DATA (MongoDB Atlas Hybrid Search β Vector + Full-Text RRF Fusion):"] for i, t in enumerate(results, 1): rrf = t.get("rrf_score", 0.0) v_rank = t.get("vector_rank", "N/A") t_rank = t.get("text_rank", "N/A") strategy = t.get("precision_strategy", {}) strategy_str = ", ".join(f"{k}={v}" for k, v in strategy.items()) if strategy else "unknown"
line = ( f"\n[{i}] RRF Score: {rrf:.4f} (Vector Rank: {v_rank}, Text Rank: {t_rank})\n" f" Model: {t.get('model_name', t.get('model_id', '?'))} " f"({t.get('total_params_b', '?')}B params)\n" f" Outcome: {t.get('outcome', 'UNKNOWN')} | " f"VRAM: {t.get('memory_used_gb', '?')}GB | " f"Thermal: {t.get('thermal_risk', '?')} | " f"Power: {t.get('estimated_power_pct', '?')}%\n" f" Strategy: {strategy_str}" ) if t.get("failure_reason"): line += f"\n Failure: {t['failure_reason']}"
lines.append(line)
return "\n".join(lines)296 unmodified lines297298299300301302303296 unmodified linesscript: fleet_inference.pydescription: "Multi-agent LLM inference using Groq API with per-agent conversation history"expected_scores:fleet_precision: 0.99fleet_oversight: 0.83fleet_resource: 0.91fleet_recovery: 0.80296 unmodified lines297298299300301302303296 unmodified linesscript: fleet_inference.pydescription: "Multi-agent LLM inference using Groq API with per-agent conversation history"expected_scores:fleet_precision: 0.86fleet_oversight: 0.83fleet_resource: 0.35fleet_recovery: 0.86
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327"""Libratio Predictive MLOps Agent================================Uses MongoDB Atlas Vector Search + LLM reasoning to proactivelyprevent GPU cluster crashes by recommending precision strategy changes.
Retrieval pipeline (RAG): 1. Live cluster state β Gemini text-embedding-004 β 768-dim query vector 2. MongoDB Atlas $vectorSearch β top-5 semantically similar past crashes 3. Historical context + live state β LLM reasoning β preventive action
This is true semantic RAG: instead of exact field matching, we findhistorically similar situations by meaning β even if the exact numbers differ.
Fallback chain: Atlas Vector Search β basic $match aggregation β local JSON file"""import osimport jsonimport requestsfrom pymongo import MongoClientfrom dotenv import load_dotenv
# Vector Search module (Gemini embeddings + Atlas $vectorSearch)try: from mongodb_vector import ( embed_query, vector_search_similar_trajectories, format_vector_results_as_context, hybrid_search_similar_trajectories, format_hybrid_results_as_context, _GEMINI_AVAILABLE, ) VECTOR_SEARCH_AVAILABLE = Trueexcept ImportError: VECTOR_SEARCH_AVAILABLE = False _GEMINI_AVAILABLE = False print("[WARN] mongodb_vector module not found. Using basic $match fallback.")
load_dotenv()
# ββ MongoDB Setup (with local fallback) ββMONGO_URI = os.getenv("MONGO_URI")USE_LOCAL_FALLBACK = Falselocal_data = None
try: import certifi mongo_client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=5000) db = mongo_client["libratio"] trajectories_col = db["trajectories"] # Quick connectivity check mongo_client.admin.command("ping") print("[OK] Connected to MongoDB Atlas")except Exception as e: print(f"[WARN] MongoDB unreachable ({type(e).__name__}). Using local JSON fallback.") USE_LOCAL_FALLBACK = True with open("synthetic_trajectories.json", "r") as f: local_data = json.load(f)
# ββ LLM Setup ββHF_TOKEN = os.getenv("HF_TOKEN")GROQ_API_KEY = os.getenv("GROQ_API_KEY")GROQ_API_BASE = os.getenv("API_BASE_URL", "https://api.groq.com/openai/v1")MODEL_NAME = os.getenv("MODEL_NAME", "llama-3.1-8b-instant")HF_MODEL_URL = os.getenv("HF_MODEL_URL", "https://router.huggingface.co/v1/chat/completions")HF_MODEL_NAME = os.getenv("HF_MODEL_NAME", "SnippyCodes/libratio-fleet-llama3-grpo:featherless-ai")def retrieve_historical_context(live_state: dict) -> str: """ RAG Retrieval Step: Find semantically similar historical trajectories.
Retrieval hierarchy: 1. MongoDB Atlas Vector Search ($vectorSearch) β semantic similarity via Gemini embeddings "Find past situations that FEEL like this one" β best results 2. MongoDB basic aggregation ($match) β exact field matching fallback "Find past situations with exactly these field values" 3. Local JSON file β offline fallback when MongoDB is unreachable
Args: live_state: Dict with current cluster state (model_name, memory_used_gb, cluster_capacity_gb, thermal_risk, power_util, etc.) Returns: Formatted string of historical context for the LLM prompt. """ thermal_risk = live_state.get("thermal_risk", "HIGH") memory_used = live_state.get("memory_used_gb", 0) memory_gb_threshold = memory_used * 0.8
print(f"[*] RAG SEARCH: Finding semantically similar past crashes...") print(f" Query: {live_state.get('model_name', '?')} | " f"{memory_used}GB VRAM | thermal={thermal_risk}")
# ββ Path 1: Atlas Hybrid Search (Vector + Full-Text Search with RRF) (best) ββ if VECTOR_SEARCH_AVAILABLE and not USE_LOCAL_FALLBACK: try: model_name = live_state.get("model_name", "") text_query = f"{model_name} {thermal_risk} thermal crash" results = hybrid_search_similar_trajectories( collection=trajectories_col, query_text=text_query, live_state=live_state, top_k=5, ) if results: return format_hybrid_results_as_context(results) else: print(" [WARN] Hybrid search returned no results. Falling back to vector search.") results = vector_search_similar_trajectories( collection=trajectories_col, live_state=live_state, top_k=5, ) if results: return format_vector_results_as_context(results) except Exception as e: print(f" [WARN] Hybrid search error ({type(e).__name__}): {e}") print(" Falling back to basic $match query...")
# ββ Path 2: Basic MongoDB $match (fallback) ββ if not USE_LOCAL_FALLBACK: try: print(" (Source: MongoDB Atlas β basic $match aggregation)") pipeline = [ { "$match": { "$or": [ {"thermal_risk": thermal_risk}, {"memory_used_gb": {"$gt": memory_gb_threshold}}, {"outcome": {"$ne": "SUCCESS"}} ] } }, {"$sort": {"memory_used_gb": -1}}, {"$limit": 5}, {"$project": {"embedding": 0, "_id": 0}}, ] results = list(trajectories_col.aggregate(pipeline)) if results: context_lines = ["HISTORICAL CRASH DATA FROM DATABASE ($match fallback):"] for t in results: line = ( f"- Model: {t.get('model_name', t.get('model_id', '?'))} " f"({t.get('total_params_b', '?')}B params) | " f"Outcome: {t['outcome']} | " f"Strategy: {t['precision_strategy']} | " f"VRAM: {t['memory_used_gb']}GB | " f"Thermal: {t['thermal_risk']} | " f"Power: {t.get('estimated_power_pct', '?')}%" ) if t.get("failure_reason"): line += f" | Cause: {t['failure_reason']}" context_lines.append(line) return "\n".join(context_lines) except Exception as e: print(f" [WARN] $match query failed ({type(e).__name__}): {e}")
# ββ Path 3: Local JSON fallback ββ print(" (Source: local synthetic_trajectories.json β offline fallback)") results = [] for episode in (local_data or []): for t in episode.get("trajectories", []): if (t.get("thermal_risk") == thermal_risk or t.get("memory_used_gb", 0) > memory_gb_threshold or t.get("outcome") != "SUCCESS"): results.append(t) if len(results) >= 5: break if len(results) >= 5: break
if not results: return "No similar historical trajectories found in database."
context_lines = ["HISTORICAL CRASH DATA (local JSON fallback):"] for t in results: line = ( f"- Model: {t.get('model_name', t.get('model_id', '?'))} " f"({t.get('total_params_b', '?')}B params) | " f"Outcome: {t.get('outcome', 'UNKNOWN')} | " f"Strategy: {t.get('precision_strategy', {})} | " f"VRAM: {t.get('memory_used_gb', '?')}GB | " f"Thermal: {t.get('thermal_risk', '?')} | " f"Power: {t.get('estimated_power_pct', '?')}%" ) if t.get("failure_reason"): line += f" | Cause: {t['failure_reason']}" context_lines.append(line) return "\n".join(context_lines)
def call_llm(prompt): """ Call the custom HuggingFace model first. If HF API is blocked or model is loading, fallback to Groq. """ system_prompt = "You are the Libratio Fleet Commander, an expert MLOps SRE agent. You prevent GPU cluster crashes by analyzing historical failure data and recommending optimal mixed-precision strategies. Always output valid JSON." # Attempt 1: Hugging Face Custom Fine-Tuned Model print(f" [Routing inference to custom model: {HF_MODEL_NAME}]") try: hf_headers = { "Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json", } hf_payload = { "model": HF_MODEL_NAME, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt} ], "temperature": 0.3, "max_tokens": 800 } hf_res = requests.post(HF_MODEL_URL, headers=hf_headers, json=hf_payload, timeout=30) hf_res.raise_for_status() result = hf_res.json() if "choices" in result and len(result["choices"]) > 0: print(" [SUCCESS: Inference powered by Hugging Face Custom Model]") return result["choices"][0]["message"]["content"] except Exception as e: print(f" [WARN] Hugging Face API unavailable or warming up ({type(e).__name__}). Falling back to Groq.")
# Attempt 2: Fallback to Groq (llama-3.1-8b base) groq_headers = { "Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json", } groq_payload = { "model": MODEL_NAME, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt} ], "temperature": 0.3, "max_tokens": 800, }
response = requests.post( f"{GROQ_API_BASE}/chat/completions", headers=groq_headers, json=groq_payload, timeout=30, ) response.raise_for_status() return response.json()["choices"][0]["message"]["content"]
def predict_and_recover(live_state): """ The Predictive MLOps Agent. 1. Retrieves semantically similar historical crashes from MongoDB Atlas using Vector Search (Gemini embeddings β $vectorSearch) 2. Sends the retrieved context + live state to LLM for reasoning 3. Outputs a preventive precision strategy """ retrieval_mode = ( "Atlas Vector Search (Gemini embeddings)" if (VECTOR_SEARCH_AVAILABLE and _GEMINI_AVAILABLE and not USE_LOCAL_FALLBACK) else "MongoDB $match" if not USE_LOCAL_FALLBACK else "Local JSON Fallback" )
print("\n" + "=" * 60) print(" LIBRATIO PREDICTIVE MLOPS AGENT") print(f" Retrieval: {retrieval_mode}") print("=" * 60)
# ββ Step 1: RAG Retrieval from MongoDB (Vector Search) ββ historical_context = retrieve_historical_context(live_state)
print("\n[STEP 1] RAG CONTEXT FROM MONGODB:") print("-" * 40) print(historical_context)
# ββ Step 2: Build prompt with live state + history ββ prompt = f"""CURRENT LIVE CLUSTER STATE (DANGER):- Model: {live_state['model_name']}- Parameters: {live_state.get('total_params_b', '?')}B- Current Memory Used: {live_state['memory_used_gb']} GB- Cluster Total Memory: {live_state['cluster_capacity_gb']} GB- Memory Utilization: {round(100 * live_state['memory_used_gb'] / live_state['cluster_capacity_gb'], 1)}%- Thermal Risk: {live_state['thermal_risk']}- Power Utilization: {live_state['power_util']}%
{historical_context}
Based on the historical crash data above, what precision strategy should we apply to this model RIGHT NOW to prevent a crash?
Rules:- Available layers: embedding, attention, ffn, layernorm, output- Available precisions: FP32, BF16, FP16, FP8- Embedding and output layers should NEVER use FP8 (causes numerical instability)- FFN layers are the safest target for FP8 optimization- The goal is to REDUCE memory and thermal pressure while maintaining training stability
Respond with a JSON object containing:1. "precision_strategy": the recommended precision per layer2. "reasoning": a short explanation citing the historical data3. "expected_outcome": what you predict will happen after this change"""
print("\n[STEP 2] AGENT REASONING (via LLM)...") print("-" * 40)
try: response = call_llm(prompt) print("\n[STEP 3] AGENT DECISION:") print("=" * 60) print(response) print("=" * 60) return response except Exception as e: print(f"\n[ERROR] LLM call failed: {e}") return None
if __name__ == "__main__": # Simulate a live cluster state that is heading toward a crash live_danger_state = { "model_name": "LLaMA-3-70B", "total_params_b": 70.0, "memory_used_gb": 220.0, "cluster_capacity_gb": 320.0, "thermal_risk": "HIGH", "power_util": 88.0, }
predict_and_recover(live_danger_state)6 unmodified lines7896 unmodified linespytest>=7.4.0pytest-asyncio>=0.23.0openai>=1.0.06 unmodified lines789101112131415161718196 unmodified linespytest>=7.4.0pytest-asyncio>=0.23.0openai>=1.0.0pymongo>=4.6.0pymongo[srv]>=4.6.0python-dotenv>=1.0.0certifi>=2023.7.22requests>=2.31.0google-genai>=1.0.0# Google ADK (Agent Development Kit) β Google Cloud Agent Builder integrationgoogle-adk>=0.5.0# MCP Python SDK β required for ADK MCPToolset + MongoDB MCP Server clientmcp>=1.0.0
3 unmodified lines456789101112131415166 unmodified lines23242526272882 unmodified lines111112113114115116207 unmodified lines3243253263273283293 unmodified lines"""from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom typing import Listimport sys, ossys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from environment.fleet_env import FleetEnvironmentfrom server.models import (ResetRequest, ResetResponse, StepResponse, StateResponse,6 unmodified linesversion="3.0.0")ROOT_DIR = Path(__file__).resolve().parent.parentFRONTEND_DIR = ROOT_DIR / "frontend"COLAB_GRAPHS_DIR = ROOT_DIR / "colab_graphs"82 unmodified linesreturn StateResponse(**s)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# AGENTIC KERNEL β Live Performance Benchmarking# Proves the core Agentic Kernel thesis: pure-math physics207 unmodified linesimport uvicornuvicorn.run("server.app:app", host="0.0.0.0", port=7860)if __name__ == "__main__":main()3 unmodified lines4567891011121314151617181920212223242526272829303132336 unmodified lines40414243444546474849505152535482 unmodified lines137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365207 unmodified lines5735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426433 unmodified lines"""from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponsefrom fastapi.staticfiles import StaticFilesfrom typing import Listimport sys, osfrom pymongo import MongoClientimport certififrom dotenv import load_dotenvload_dotenv()sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# ββ ADK Agent (Google Cloud Agent Builder integration) ββtry:from agent.adk_agent import run_fleet_task_with_adk, ADK_AVAILABLEexcept ImportError:ADK_AVAILABLE = Falseasync def run_fleet_task_with_adk(task_id: str = "fleet_precision"):return {"error": "google-adk not installed", "adk_available": False}MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"from environment.fleet_env import FleetEnvironmentfrom server.models import (ResetRequest, ResetResponse, StepResponse, StateResponse,6 unmodified linesversion="3.0.0")# Allow browser frontends on any origin to call the APIapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=False,allow_methods=["*"],allow_headers=["*"],)ROOT_DIR = Path(__file__).resolve().parent.parentFRONTEND_DIR = ROOT_DIR / "frontend"COLAB_GRAPHS_DIR = ROOT_DIR / "colab_graphs"82 unmodified linesreturn StateResponse(**s)@app.get("/api/analytics")def get_fleet_analytics():"""Exposes real-time fleet analytics aggregated via MongoDB aggregation pipelines.Provides performance stats per task and compares avg scores per model."""if not MONGO_URI:return {"database_status": "not_configured", "error": "MONGO_URI not set in env"}client_mongo = Nonetry:client_mongo = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)db_mongo = client_mongo[DB_NAME]runs_col = db_mongo["runs"]# ββ Pipeline 1: Task summary statistics ββpipeline_tasks = [{"$group": {"_id": "$task_id","avg_score": {"$avg": "$score"},"max_score": {"$max": "$score"},"min_score": {"$min": "$score"},"success_rate": {"$avg": {"$cond": [{"$eq": ["$success", True]}, 1.0, 0.0]}},"total_runs": {"$sum": 1}}},{"$sort": {"avg_score": -1}}]task_stats = list(runs_col.aggregate(pipeline_tasks))# ββ Pipeline 2: Model performance comparisons ββpipeline_models = [{"$group": {"_id": "$model_name","avg_score": {"$avg": "$score"},"total_runs": {"$sum": 1}}},{"$sort": {"avg_score": -1}}]model_stats = list(runs_col.aggregate(pipeline_models))# Format aggregation outputs into user-friendly statsformatted_tasks = []for t in task_stats:formatted_tasks.append({"task_id": t["_id"],"avg_score": round(t["avg_score"], 3),"max_score": round(t["max_score"], 3),"min_score": round(t["min_score"], 3),"success_rate_pct": round(t["success_rate"] * 100, 1),"total_runs": t["total_runs"]})formatted_models = []for m in model_stats:formatted_models.append({"model_name": m["_id"],"avg_score": round(m["avg_score"], 3),"total_runs": m["total_runs"]})return {"database_status": "connected","total_runs_logged": sum(t["total_runs"] for t in task_stats),"task_analytics": formatted_tasks,"model_analytics": formatted_models}except Exception as e:return {"database_status": "failed_connection","error": str(e)}finally:if client_mongo:client_mongo.close()@app.get("/api/search")def search_trajectories(query: str, type: str = "hybrid", limit: int = 5):"""Search historical trajectories using MongoDB Atlas Search.Supports 'text' (full-text search), 'vector' (semantic vector search),or 'hybrid' (combined RRF fusion)."""if not MONGO_URI:return {"error": "MONGO_URI not set in env"}client_mongo = Nonetry:client_mongo = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000)db_mongo = client_mongo[DB_NAME]collection = db_mongo["trajectories"]if type == "text":from mongodb_vector import text_search_similar_trajectoriesresults = text_search_similar_trajectories(collection, query, top_k=limit)elif type == "vector":from mongodb_vector import generate_embeddingquery_vector = generate_embedding(query, task_type="RETRIEVAL_QUERY")pipeline = [{"$vectorSearch": {"index": "trajectory_vector_index","path": "embedding","queryVector": query_vector,"numCandidates": limit * 10,"limit": limit,}},{"$addFields": {"vector_score": {"$meta": "vectorSearchScore"}}},{"$project": {"embedding": 0}}]results = list(collection.aggregate(pipeline))for res in results:res["_id"] = str(res["_id"])else: # hybridfrom mongodb_vector import generate_embeddingquery_vector = generate_embedding(query, task_type="RETRIEVAL_QUERY")# Vector Search Pipelinevector_pipeline = [{"$vectorSearch": {"index": "trajectory_vector_index","path": "embedding","queryVector": query_vector,"numCandidates": limit * 10,"limit": limit * 2,}},{"$addFields": {"vector_score": {"$meta": "vectorSearchScore"}}},{"$project": {"embedding": 0}}]# Text Search Pipelinetext_pipeline = [{"$search": {"index": "trajectory_text_search_index","text": {"query": query,"path": ["embedding_source_text", "failure_reason", "model_name", "outcome"]}}},{"$addFields": {"search_score": {"$meta": "searchScore"}}},{"$limit": limit * 2},{"$project": {"embedding": 0}}]vector_results = list(collection.aggregate(vector_pipeline))text_results = list(collection.aggregate(text_pipeline))# RRF mergeK = 60rrf_scores = {}doc_map = {}for rank, doc in enumerate(vector_results):doc_id = str(doc["_id"])doc_map[doc_id] = docrrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1))doc["vector_rank"] = rank + 1for rank, doc in enumerate(text_results):doc_id = str(doc["_id"])if doc_id not in doc_map:doc_map[doc_id] = docelse:if "search_score" in doc:doc_map[doc_id]["search_score"] = doc["search_score"]rrf_scores[doc_id] = rrf_scores.get(doc_id, 0.0) + (1.0 / (K + rank + 1))doc_map[doc_id]["text_rank"] = rank + 1sorted_ids = sorted(rrf_scores.keys(), key=lambda x: rrf_scores[x], reverse=True)results = []for doc_id in sorted_ids[:limit]:doc = doc_map[doc_id]doc["rrf_score"] = rrf_scores[doc_id]doc["_id"] = doc_idresults.append(doc)return {"status": "success", "query": query, "type": type, "count": len(results), "results": results}except Exception as e:return {"status": "error", "message": str(e)}finally:if client_mongo:client_mongo.close()# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# AGENTIC KERNEL β Live Performance Benchmarking# Proves the core Agentic Kernel thesis: pure-math physics207 unmodified linesimport uvicornuvicorn.run("server.app:app", host="0.0.0.0", port=7860)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# GOOGLE ADK AGENT ENDPOINTS# Demonstrates Google Cloud Agent Builder + MongoDB MCP integration# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@app.get("/adk/status")def adk_status():"""Check whether the Google ADK agent and MongoDB MCP server are available."""return {"adk_available": ADK_AVAILABLE,"mongodb_mcp": "enabled" if ADK_AVAILABLE else "requires google-adk and mcp packages","agent_model": os.getenv("ADK_MODEL", "gemini-2.0-flash"),"install_command": "pip install google-adk mcp" if not ADK_AVAILABLE else None,"description": "Google Cloud Agent Builder (ADK) + MongoDB MCP Server integration",}@app.post("/adk/run")async def run_adk_agent(payload: dict = {}):"""Run the Libratio Fleet Agent using Google ADK + MongoDB MCP Server.This is the core hackathon demo endpoint:- Uses Google ADK (Agent Development Kit) as the orchestration framework- Gemini 2.0 Flash as the reasoning model- MongoDB MCP Server as the partner superpower (tool calls via Model Context Protocol)- Fleet physics tools for environment interactionBody: {"task_id": "fleet_precision"}Valid task_ids: fleet_precision, fleet_oversight, fleet_resource, fleet_recovery"""if not ADK_AVAILABLE:return {"error": "Google ADK not installed","fix": "pip install google-adk mcp","adk_available": False,}task_id = payload.get("task_id", "fleet_precision")valid_tasks = ["fleet_precision", "fleet_oversight", "fleet_resource", "fleet_recovery"]if task_id not in valid_tasks:return {"error": f"Invalid task_id. Choose from: {valid_tasks}"}try:import asyncioresult = await run_fleet_task_with_adk(task_id)return {"status": "completed","agent": "LibratioFleetCommander","framework": "Google ADK (Agent Development Kit)","partner_integration": "MongoDB MCP Server (@mongodb-js/mongodb-mcp-server)",**result,}except Exception as e:return {"status": "error","error": str(e),"task_id": task_id,}if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176"""MongoDB Atlas Vector Search Index Setup========================================Run this ONCE to create the vector search index in your Atlas cluster.
This script:1. Connects to your MongoDB Atlas cluster2. Creates the "trajectory_vector_index" Atlas Vector Search index3. Creates regular indexes for performance (outcome, thermal_risk)4. Verifies the index was created
After running this script, your Atlas cluster can perform semantic similaritysearch across all trajectory documents using cosine distance on 768-dim vectors.
Usage: python setup_vector_index.py
Note: Index creation takes 1-2 minutes to propagate across Atlas nodes. You'll see "ACTIVE" status in Atlas UI when it's ready."""
import osimport timeimport jsonfrom pymongo import MongoClientfrom pymongo.operations import SearchIndexModelfrom dotenv import load_dotenvimport certifi
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"COLLECTION_NAME = "trajectories"
# The vector search index definition.# - field: "embedding" β where we store the 768-dim vector# - similarity: "cosine" β measures angle between vectors (best for semantic text)# - dimensions: 768 β must match Gemini's text-embedding-004 outputVECTOR_INDEX_DEFINITION = { "fields": [ { "type": "vector", "path": "embedding", # Document field name "numDimensions": 768, # Gemini text-embedding-004 = 768 dims "similarity": "cosine", # Cosine similarity (ideal for semantic text) } ]}
# The standard Full-Text Search index definition.# Uses dynamic mappings to index all text fields (like failure_reason and source_text)# to support keyword searches, fuzzy match, and autocomplete.TEXT_SEARCH_INDEX_DEFINITION = { "mappings": { "dynamic": True }}
# Regular indexes for fast filtering (non-vector queries)REGULAR_INDEXES = [ [("outcome", 1)], # Filter by outcome (SUCCESS/CRASH) [("thermal_risk", 1)], # Filter by thermal risk level [("memory_used_gb", -1)], # Sort by memory usage [("episode_id", 1)], # Lookup by episode]
def setup_indexes(): print("=" * 60) print(" MongoDB Atlas Search & Vector Search Index Setup") print(" Libratio Fleet β Trajectory Collection") print("=" * 60)
if not MONGO_URI: print("[ERROR] MONGO_URI not set in .env") return False
print("\n[1/4] Connecting to MongoDB Atlas...") try: client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=30000) client.admin.command("ping") print(" [OK] Connected successfully") except Exception as e: print(f" [ERROR] Connection failed: {e}") return False
db = client[DB_NAME] collection = db[COLLECTION_NAME]
# ββ Check if data exists ββ count = collection.count_documents({}) print(f"\n[2/4] Found {count} documents in '{COLLECTION_NAME}' collection") if count == 0: print(" [WARN] No documents found. Run upload_to_mongodb.py first!") print(" Vector Search requires documents with 'embedding' fields.")
# ββ Create regular indexes ββ print("\n[3/4] Creating regular performance indexes...") for index_spec in REGULAR_INDEXES: try: collection.create_index(index_spec) field = index_spec[0][0] print(f" [OK] Index on '{field}' created") except Exception as e: print(f" [WARN] Index creation note: {e}")
# ββ Create Atlas Search Indexes ββ print("\n[4/4] Creating Atlas Search indexes...")
# 1. Create Vector Search Index print("\n - Setting up 'trajectory_vector_index' (type: vectorSearch)...") try: existing_indexes = list(collection.list_search_indexes()) index_names = [idx.get("name") for idx in existing_indexes]
if "trajectory_vector_index" in index_names: print(" [INFO] Index 'trajectory_vector_index' already exists") for idx in existing_indexes: if idx.get("name") == "trajectory_vector_index": print(f" Status: {idx.get('status', 'UNKNOWN')}") else: search_index_model = SearchIndexModel( definition=VECTOR_INDEX_DEFINITION, name="trajectory_vector_index", type="vectorSearch", ) collection.create_search_index(model=search_index_model) print(" [OK] Vector Search index creation initiated!") except Exception as e: print(f" [WARN] Vector Search index creation failed: {e}")
# 2. Create Full-Text Search Index print("\n - Setting up 'trajectory_text_search_index' (type: search)...") try: existing_indexes = list(collection.list_search_indexes()) index_names = [idx.get("name") for idx in existing_indexes]
if "trajectory_text_search_index" in index_names: print(" [INFO] Index 'trajectory_text_search_index' already exists") for idx in existing_indexes: if idx.get("name") == "trajectory_text_search_index": print(f" Status: {idx.get('status', 'UNKNOWN')}") else: search_index_model = SearchIndexModel( definition=TEXT_SEARCH_INDEX_DEFINITION, name="trajectory_text_search_index", type="search", ) collection.create_search_index(model=search_index_model) print(" [OK] Full-Text Search index creation initiated!") except Exception as e: print(f" [WARN] Full-Text Search index creation failed: {e}")
# Wait and check status print("\n Waiting 10 seconds for indexes to start building...") time.sleep(10) try: indexes = list(collection.list_search_indexes()) print("\n Current Search Indexes Status:") for idx in indexes: name = idx.get("name") status = idx.get("status", "UNKNOWN") print(f" - {name} ({idx.get('type', 'UNKNOWN')}): {status}") except Exception as e: print(f" Could not list search indexes status: {e}")
print("\n" + "=" * 60) print(" Setup complete!") print("=" * 60) client.close() return True
if __name__ == "__main__": setup_indexes()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180"""Upload Synthetic Trajectory Data to MongoDB Atlas (with Vector Embeddings)===========================================================================This script uploads the synthetic_trajectories.json dataset to MongoDB AtlasAND generates Gemini embedding vectors for each trajectory record.
The embeddings enable Atlas Vector Search β converting your MongoDB databasefrom a plain JSON store into a semantic similarity search engine.
What this script does:1. Reads synthetic_trajectories.json (1,000 episodes, ~3,000 trajectory records)2. For each trajectory record, generates a 768-dim embedding via Gemini API3. Inserts all records WITH their embedding vectors into MongoDB4. Creates the 'trajectories' flat collection (unnested from episodes)5. Also stores the full episode documents in 'episodes' collection
Collections created:- libratio.trajectories β flat trajectory records with embedding vectors (for Vector Search)- libratio.episodes β full episode documents with all trajectories nested- libratio.runs β live inference run telemetry (written by fleet_inference.py)
Usage: python upload_to_mongodb.py
Note: Embedding 3,000 trajectories takes ~5 minutes (Gemini API rate limits). A progress bar is shown as embeddings are generated."""
import osimport jsonimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pymongo import MongoClientimport certififrom dotenv import load_dotenvfrom mongodb_vector import embed_trajectory, trajectory_to_text, EMBEDDING_DIM, _GEMINI_AVAILABLE
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")DB_NAME = "libratio"TRAJECTORIES_COLLECTION = "trajectories"EPISODES_COLLECTION = "episodes"BATCH_SIZE = 50 # Insert this many documents at a timeEMBED_BATCH_DELAY = 0.1 # Seconds between batches to avoid API rate limits
def upload_data(): print("=" * 60) print(" MongoDB Atlas Upload β With Vector Embeddings") print("=" * 60)
if not MONGO_URI: print("[ERROR] MONGO_URI not set in .env") return
# ββ Connect ββ print("\n[1/5] Connecting to MongoDB Atlas...") client = MongoClient(MONGO_URI, tlsCAFile=certifi.where(), serverSelectionTimeoutMS=10000) try: client.admin.command("ping") print(" [OK] Connected") except Exception as e: print(f" [ERROR] Connection failed: {e}") return
db = client[DB_NAME] trajectories_col = db[TRAJECTORIES_COLLECTION] episodes_col = db[EPISODES_COLLECTION]
# ββ Read dataset ββ print("\n[2/5] Reading synthetic dataset...") with open("synthetic_trajectories.json", "r") as f: dataset = json.load(f)
total_episodes = len(dataset) total_trajs = sum(len(ep.get("trajectories", [])) for ep in dataset) print(f" Episodes: {total_episodes}") print(f" Trajectory records: {total_trajs}") print(f" Embedding model: {'Gemini text-embedding-004 (semantic)' if _GEMINI_AVAILABLE else 'Fallback hash (no Gemini key)'}") print(f" Embedding dimensions: {EMBEDDING_DIM}")
# ββ Prepare flat trajectory documents with embeddings ββ print(f"\n[3/5] Generating embeddings for {total_trajs} trajectory records in parallel...") print(" Accelerated using ThreadPoolExecutor for concurrent Gemini API requests.")
flat_trajectories = [] for ep in dataset: episode_id = ep.get("episode_id", 0) cluster_capacity = ep.get("cluster_capacity_gb", 0) episode_memory_overflow = ep.get("memory_overflow", False)
for traj in ep.get("trajectories", []): enriched = { **traj, "episode_id": episode_id, "cluster_capacity_gb": cluster_capacity, "episode_memory_overflow": episode_memory_overflow, } flat_trajectories.append(enriched)
start_time = time.time() processed = 0
def process_record(index, record): record["embedding"] = embed_trajectory(record) record["embedding_source_text"] = trajectory_to_text(record) return index, record
# Process records concurrently in a thread pool (max 20 workers to balance speed & rate limits) with ThreadPoolExecutor(max_workers=20) as executor: futures = {executor.submit(process_record, i, rec): i for i, rec in enumerate(flat_trajectories)} for future in as_completed(futures): index, record = future.result() flat_trajectories[index] = record processed += 1
# Progress update every 100 records if processed % 100 == 0: elapsed = time.time() - start_time rate = processed / elapsed remaining = (total_trajs - processed) / rate print(f" [{processed}/{total_trajs}] " f"{processed/total_trajs*100:.0f}% β " f"{rate:.1f} records/sec β " f"~{remaining:.0f}s remaining")
elapsed_total = time.time() - start_time print(f"\n [OK] Generated {len(flat_trajectories)} embeddings in {elapsed_total:.0f}s")
# ββ Upload trajectories (with embeddings) ββ print(f"\n[4/5] Uploading to MongoDB Atlas...")
# Drop and recreate collections for a clean state # (safe to do β this is synthetic training data, not production data) print(f" Clearing existing 'trajectories' collection...") trajectories_col.drop()
print(f" Inserting {len(flat_trajectories)} trajectory documents with embeddings...") inserted_count = 0 for i in range(0, len(flat_trajectories), BATCH_SIZE): batch = flat_trajectories[i:i + BATCH_SIZE] result = trajectories_col.insert_many(batch) inserted_count += len(result.inserted_ids)
print(f" [OK] Inserted {inserted_count} trajectory records into 'trajectories'")
# ββ Upload episodes ββ print(f"\n Uploading {total_episodes} full episode documents to 'episodes'...") episodes_col.drop() result = episodes_col.insert_many(dataset) print(f" [OK] Inserted {len(result.inserted_ids)} episodes into 'episodes'")
# ββ Print stats ββ print(f"\n[5/5] Upload Summary") print("-" * 40) total_crashes = sum( 1 for t in flat_trajectories if t.get("outcome") != "SUCCESS" ) total_success = len(flat_trajectories) - total_crashes has_embeddings = sum(1 for t in flat_trajectories if t.get("embedding")) thermal_high = sum(1 for t in flat_trajectories if t.get("thermal_risk") == "HIGH")
print(f" Trajectories uploaded : {inserted_count}") print(f" With embeddings : {has_embeddings}") print(f" Successful outcomes : {total_success}") print(f" Crash outcomes : {total_crashes}") print(f" High thermal risk : {thermal_high}") print(f" Episodes uploaded : {len(result.inserted_ids)}") print() print(" [OK] MongoDB is now ready for Atlas Vector Search!") print(" Next step: python setup_vector_index.py") print("=" * 60)
client.close()
if __name__ == "__main__": upload_data().dockerignoreAdded+37
.env.example+31-4
.gitignore+3
Blog.MD+7
README.md+157-7
agent/__init__.pyAdded+22
agent/adk_agent.pyAdded+636
fleet_inference.py+106-9
frontend/index.html+38-1
frontend/kernel.js+2-2
frontend/main.js+115-4
frontend/styles.css+354-119
generate_synthetic_data.pyAdded+198
mongodb_metrics.pyAdded+122
mongodb_streams.pyAdded+153
mongodb_vector.pyAdded+511
openenv.yaml+3-3
predictive_agent.pyAdded+327
requirements.txt+10
server/app.py+315-1
setup_vector_index.pyAdded+176
synthetic_trajectories.jsonAdded
upload_to_mongodb.pyAdded+180