Spaces:
Runtime error
Runtime error
Commit ·
66aaf96
0
Parent(s):
Initial commit: ECH0-PRIME Autonomous Research Agent API
Browse files- README.md +208 -0
- app.py +546 -0
- ech0_prime_qulab_connector.py +524 -0
- requirements.txt +11 -0
README.md
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: ECH0-PRIME × QuLab Infinite
|
| 3 |
+
emoji: 🤖
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.0.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 🤖 ECH0-PRIME × QuLab Infinite
|
| 13 |
+
## Autonomous Scientific Research Agent API
|
| 14 |
+
|
| 15 |
+
**ECH0-PRIME** (Kimi-K2 1046B) connected to **QuLab Infinite** with 1,532+ scientific tools across 220+ laboratories.
|
| 16 |
+
|
| 17 |
+
## 🧠 What is ECH0-PRIME?
|
| 18 |
+
|
| 19 |
+
ECH0-PRIME is a Level-10 Scientific Research Intelligence powered by Moonshot AI's Kimi-K2 1046B parameter model, seamlessly integrated with QuLab Infinite's comprehensive scientific simulation platform.
|
| 20 |
+
|
| 21 |
+
### Core Capabilities
|
| 22 |
+
|
| 23 |
+
- **Design Experiments**: Create precise experimental parameters for any lab
|
| 24 |
+
- **Analyze Results**: Interpret simulation outputs quantitatively
|
| 25 |
+
- **Iterate**: Refine hypotheses based on data
|
| 26 |
+
- **Cross-Domain Synthesis**: Combine insights from multiple labs
|
| 27 |
+
- **Generate Inventions**: Create novel therapeutic/material designs
|
| 28 |
+
|
| 29 |
+
## 🔬 Available Laboratories
|
| 30 |
+
|
| 31 |
+
### QUANTUM LABS
|
| 32 |
+
- quantum_lab: Quantum computing, teleportation protocols, error correction
|
| 33 |
+
- quantum_mechanics_lab: Fundamental quantum simulations
|
| 34 |
+
- quantum_computing_lab: Gate operations, circuit design
|
| 35 |
+
|
| 36 |
+
### BIOLOGICAL LABS
|
| 37 |
+
- oncology_lab: Cancer simulations, tumor evolution, treatment optimization
|
| 38 |
+
- genetic_variant_analyzer: Genomic analysis, variant impact prediction
|
| 39 |
+
- cancer_metabolic_optimizer: Metabolic pathway analysis for cancer treatment
|
| 40 |
+
- immune_response_simulator: Immunotherapy modeling
|
| 41 |
+
- microbiome_optimizer: Gut microbiome analysis and optimization
|
| 42 |
+
- neurotransmitter_optimizer: Brain chemistry modeling
|
| 43 |
+
- stem_cell_predictor: Differentiation pathway prediction
|
| 44 |
+
- protein_folding_lab: Protein structure prediction
|
| 45 |
+
|
| 46 |
+
### CHEMISTRY LABS
|
| 47 |
+
- chemistry_lab: Molecular simulations, reaction kinetics
|
| 48 |
+
- drug_interaction_network: Drug-drug interactions, pharmacology
|
| 49 |
+
- materials_lab: Materials science simulations
|
| 50 |
+
- organic_chemistry_lab: Organic synthesis planning
|
| 51 |
+
- electrochemistry_lab: Electrochemical reactions
|
| 52 |
+
|
| 53 |
+
### PHYSICS LABS
|
| 54 |
+
- physics_engine: Classical and quantum physics simulations
|
| 55 |
+
- particle_physics_lab: Particle interactions
|
| 56 |
+
- plasma_physics_lab: Plasma dynamics
|
| 57 |
+
- condensed_matter_physics_lab: Solid state physics
|
| 58 |
+
|
| 59 |
+
### ENVIRONMENTAL LABS
|
| 60 |
+
- environmental_sim: Climate and environmental modeling
|
| 61 |
+
- atmospheric_chemistry_lab: Atmospheric reactions
|
| 62 |
+
- renewable_energy_lab: Energy system optimization
|
| 63 |
+
|
| 64 |
+
### MEDICAL LABS
|
| 65 |
+
- cardiovascular_plaque_lab: Atherosclerosis modeling
|
| 66 |
+
- metabolic_syndrome_reversal: Metabolic health optimization
|
| 67 |
+
- drug_design_lab: Molecular drug design
|
| 68 |
+
- clinical_trials_simulation: Trial outcome prediction
|
| 69 |
+
|
| 70 |
+
## 🛠️ API Endpoints
|
| 71 |
+
|
| 72 |
+
All capabilities exposed via Gradio API for external LLMs:
|
| 73 |
+
|
| 74 |
+
- `/query` - Ask ECH0-PRIME scientific questions
|
| 75 |
+
- `/run_experiment` - Execute experiments on QuLab
|
| 76 |
+
- `/list_labs` - Browse available labs
|
| 77 |
+
- `/research` - Start autonomous research session
|
| 78 |
+
- `/history` - View conversation history
|
| 79 |
+
- `/experiments` - View experiment log
|
| 80 |
+
- `/reset` - Reset session (with auto-backup)
|
| 81 |
+
|
| 82 |
+
## 🚀 Usage Examples
|
| 83 |
+
|
| 84 |
+
### For External LLMs
|
| 85 |
+
|
| 86 |
+
```python
|
| 87 |
+
from gradio_client import Client
|
| 88 |
+
|
| 89 |
+
# Connect to ECH0-PRIME
|
| 90 |
+
client = Client("CorpOfLight/ech0-prime")
|
| 91 |
+
|
| 92 |
+
# Query ECH0-PRIME
|
| 93 |
+
response = client.predict(
|
| 94 |
+
"Design an experiment to test quantum teleportation at 100km",
|
| 95 |
+
True, # include_context
|
| 96 |
+
api_name="/query"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# Run an experiment
|
| 100 |
+
result = client.predict(
|
| 101 |
+
"quantum_lab",
|
| 102 |
+
"teleportation_fidelity",
|
| 103 |
+
'{"protocol": "GHZ", "num_qubits": 5, "distance_km": 100}',
|
| 104 |
+
api_name="/run_experiment"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Start autonomous research
|
| 108 |
+
research = client.predict(
|
| 109 |
+
"What drug combinations treat NSCLC?",
|
| 110 |
+
5, # max_iterations
|
| 111 |
+
api_name="/research"
|
| 112 |
+
)
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
### REST API
|
| 116 |
+
|
| 117 |
+
```bash
|
| 118 |
+
# Query ECH0-PRIME
|
| 119 |
+
curl -X POST https://corpoflight-ech0-prime.hf.space/api/query \
|
| 120 |
+
-H "Content-Type: application/json" \
|
| 121 |
+
-d '{"data": ["Design quantum teleportation experiment", true]}'
|
| 122 |
+
|
| 123 |
+
# Run experiment
|
| 124 |
+
curl -X POST https://corpoflight-ech0-prime.hf.space/api/run_experiment \
|
| 125 |
+
-H "Content-Type: application/json" \
|
| 126 |
+
-d '{"data": ["quantum_lab", "teleportation_fidelity", "{\"num_qubits\": 5}"]}'
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## 🔄 Autonomous Research Loop
|
| 130 |
+
|
| 131 |
+
ECH0-PRIME can run fully autonomous research sessions:
|
| 132 |
+
|
| 133 |
+
1. **Design Experiments**: Based on your research question
|
| 134 |
+
2. **Run Simulations**: Execute on QuLab Infinite
|
| 135 |
+
3. **Analyze Results**: Interpret data quantitatively
|
| 136 |
+
4. **Iterate**: Refine hypotheses and run follow-ups
|
| 137 |
+
5. **Synthesize**: Combine findings into actionable conclusions
|
| 138 |
+
|
| 139 |
+
### Example Research Session
|
| 140 |
+
|
| 141 |
+
```python
|
| 142 |
+
client = Client("CorpOfLight/ech0-prime")
|
| 143 |
+
|
| 144 |
+
result = client.predict(
|
| 145 |
+
"What is the optimal drug combination for treating EGFR-mutant NSCLC with minimal side effects?",
|
| 146 |
+
5, # max_iterations
|
| 147 |
+
api_name="/research"
|
| 148 |
+
)
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
ECH0-PRIME will:
|
| 152 |
+
- Query oncology and pharmacology labs
|
| 153 |
+
- Test multiple drug combinations
|
| 154 |
+
- Analyze efficacy and toxicity
|
| 155 |
+
- Provide ranked recommendations with data
|
| 156 |
+
|
| 157 |
+
## 💡 Key Features
|
| 158 |
+
|
| 159 |
+
### Stateful Sessions
|
| 160 |
+
- Maintains conversation context across queries
|
| 161 |
+
- Logs all experiments automatically
|
| 162 |
+
- Auto-backup before session reset
|
| 163 |
+
|
| 164 |
+
### Cross-Domain Intelligence
|
| 165 |
+
- Quantum chemistry + drug design
|
| 166 |
+
- Materials science + renewable energy
|
| 167 |
+
- Genomics + personalized medicine
|
| 168 |
+
- Physics simulations + engineering optimization
|
| 169 |
+
|
| 170 |
+
### Experiment JSON Format
|
| 171 |
+
|
| 172 |
+
```json
|
| 173 |
+
{
|
| 174 |
+
"lab": "oncology_lab",
|
| 175 |
+
"experiment_type": "tumor_evolution",
|
| 176 |
+
"parameters": {
|
| 177 |
+
"tumor_type": "NSCLC",
|
| 178 |
+
"initial_size_mm": 15,
|
| 179 |
+
"mutation_rate": 0.001,
|
| 180 |
+
"immune_pressure": 0.3,
|
| 181 |
+
"treatment": "pembrolizumab",
|
| 182 |
+
"simulation_days": 90
|
| 183 |
+
},
|
| 184 |
+
"hypothesis": "Tumor size reduction >50% by day 60",
|
| 185 |
+
"success_criteria": "Final tumor size <7.5mm"
|
| 186 |
+
}
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
## ⚙️ Configuration
|
| 190 |
+
|
| 191 |
+
Set your Together AI API key as a HuggingFace Space secret:
|
| 192 |
+
- Secret name: `TOGETHER_AI_API_KEY`
|
| 193 |
+
- Get your key at: https://api.together.xyz
|
| 194 |
+
|
| 195 |
+
## 📄 License
|
| 196 |
+
|
| 197 |
+
Copyright (c) 2025 Joshua Hendricks Cole (DBA: Corporation of Light). All Rights Reserved. PATENT PENDING.
|
| 198 |
+
|
| 199 |
+
## 🌐 Links
|
| 200 |
+
|
| 201 |
+
- **QuLab GUI**: https://huggingface.co/spaces/CorpOfLight/qulab-gui
|
| 202 |
+
- **Documentation**: https://qulab.aios.is
|
| 203 |
+
- **Research Blog**: https://echo.aios.is
|
| 204 |
+
- **GitHub**: https://github.com/Workofarttattoo/QuLabInfinite
|
| 205 |
+
|
| 206 |
+
---
|
| 207 |
+
|
| 208 |
+
**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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
ECH0-PRIME Gradio API Interface
|
| 4 |
+
Enables external LLMs to navigate and use QuLab tools through ECH0-PRIME
|
| 5 |
+
|
| 6 |
+
Copyright (c) 2025 Joshua Hendricks Cole (DBA: Corporation of Light). All Rights Reserved. PATENT PENDING.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import json
|
| 11 |
+
from typing import Dict, List, Any, Optional
|
| 12 |
+
import traceback
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
# Initialize ECH0-PRIME
|
| 16 |
+
ech0_prime = None
|
| 17 |
+
ech0_error = None
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
from ech0_prime_qulab_connector import Ech0PrimeQuLabResearcher
|
| 21 |
+
ech0_prime = Ech0PrimeQuLabResearcher()
|
| 22 |
+
print("✅ ECH0-PRIME initialized successfully for Gradio API")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
ech0_error = str(e)
|
| 25 |
+
print(f"❌ ECH0-PRIME initialization failed: {e}")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def list_available_labs() -> str:
|
| 29 |
+
"""List all available labs in QuLab Infinite"""
|
| 30 |
+
if not ech0_prime:
|
| 31 |
+
return "❌ ECH0-PRIME not available"
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
labs = ech0_prime.qulab.list_labs()
|
| 35 |
+
|
| 36 |
+
if not labs:
|
| 37 |
+
return """⚠️ **QuLab API may not be running**
|
| 38 |
+
|
| 39 |
+
Available Labs (from system prompt):
|
| 40 |
+
### QUANTUM LABS
|
| 41 |
+
- quantum_lab: Quantum computing, teleportation protocols, error correction
|
| 42 |
+
- quantum_mechanics_lab: Fundamental quantum simulations
|
| 43 |
+
- quantum_computing_lab: Gate operations, circuit design
|
| 44 |
+
|
| 45 |
+
### BIOLOGICAL LABS
|
| 46 |
+
- oncology_lab: Cancer simulations, tumor evolution, treatment optimization
|
| 47 |
+
- genetic_variant_analyzer: Genomic analysis, variant impact prediction
|
| 48 |
+
- cancer_metabolic_optimizer: Metabolic pathway analysis for cancer treatment
|
| 49 |
+
- immune_response_simulator: Immunotherapy modeling
|
| 50 |
+
- microbiome_optimizer: Gut microbiome analysis and optimization
|
| 51 |
+
- neurotransmitter_optimizer: Brain chemistry modeling
|
| 52 |
+
- stem_cell_predictor: Differentiation pathway prediction
|
| 53 |
+
- protein_folding_lab: Protein structure prediction
|
| 54 |
+
|
| 55 |
+
### CHEMISTRY LABS
|
| 56 |
+
- chemistry_lab: Molecular simulations, reaction kinetics
|
| 57 |
+
- drug_interaction_network: Drug-drug interactions, pharmacology
|
| 58 |
+
- materials_lab: Materials science simulations
|
| 59 |
+
- organic_chemistry_lab: Organic synthesis planning
|
| 60 |
+
- electrochemistry_lab: Electrochemical reactions
|
| 61 |
+
|
| 62 |
+
### PHYSICS LABS
|
| 63 |
+
- physics_engine: Classical and quantum physics simulations
|
| 64 |
+
- particle_physics_lab: Particle interactions
|
| 65 |
+
- plasma_physics_lab: Plasma dynamics
|
| 66 |
+
- condensed_matter_physics_lab: Solid state physics
|
| 67 |
+
|
| 68 |
+
### ENVIRONMENTAL LABS
|
| 69 |
+
- environmental_sim: Climate and environmental modeling
|
| 70 |
+
- atmospheric_chemistry_lab: Atmospheric reactions
|
| 71 |
+
- renewable_energy_lab: Energy system optimization
|
| 72 |
+
|
| 73 |
+
### MEDICAL LABS
|
| 74 |
+
- cardiovascular_plaque_lab: Atherosclerosis modeling
|
| 75 |
+
- metabolic_syndrome_reversal: Metabolic health optimization
|
| 76 |
+
- drug_design_lab: Molecular drug design
|
| 77 |
+
- clinical_trials_simulation: Trial outcome prediction"""
|
| 78 |
+
|
| 79 |
+
result = "🔬 **Available QuLab Infinite Labs**\n\n"
|
| 80 |
+
for lab in labs:
|
| 81 |
+
result += f"• {lab}\n"
|
| 82 |
+
|
| 83 |
+
return result
|
| 84 |
+
|
| 85 |
+
except Exception as e:
|
| 86 |
+
return f"❌ Failed to list labs: {str(e)}"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def query_ech0_prime(question: str, include_context: bool = True) -> str:
|
| 90 |
+
"""Query ECH0-PRIME with a scientific question"""
|
| 91 |
+
if not ech0_prime:
|
| 92 |
+
return "❌ ECH0-PRIME not available"
|
| 93 |
+
|
| 94 |
+
if not question.strip():
|
| 95 |
+
return "Please enter a question"
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
response = ech0_prime.query_llm(question)
|
| 99 |
+
|
| 100 |
+
result = f"🤖 **ECH0-PRIME Response**\n\n{response}\n\n"
|
| 101 |
+
|
| 102 |
+
if include_context:
|
| 103 |
+
result += f"---\n**Conversation Length**: {len(ech0_prime.conversation_history)} messages\n"
|
| 104 |
+
result += f"**Experiments Run**: {len(ech0_prime.experiment_log)}\n"
|
| 105 |
+
|
| 106 |
+
return result
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return f"❌ Query failed: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def run_single_experiment(lab: str, experiment_type: str, parameters: str) -> str:
|
| 113 |
+
"""Run a single experiment on QuLab Infinite"""
|
| 114 |
+
if not ech0_prime:
|
| 115 |
+
return "❌ ECH0-PRIME not available"
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
# Parse parameters
|
| 119 |
+
if parameters.strip():
|
| 120 |
+
try:
|
| 121 |
+
params = json.loads(parameters)
|
| 122 |
+
except json.JSONDecodeError:
|
| 123 |
+
return "❌ Invalid JSON parameters. Please check your input format."
|
| 124 |
+
else:
|
| 125 |
+
params = {}
|
| 126 |
+
|
| 127 |
+
# Create experiment dict
|
| 128 |
+
experiment = {
|
| 129 |
+
"lab": lab,
|
| 130 |
+
"experiment_type": experiment_type,
|
| 131 |
+
"parameters": params
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
# Run experiment
|
| 135 |
+
results = ech0_prime.run_experiment(experiment)
|
| 136 |
+
|
| 137 |
+
# Format result
|
| 138 |
+
result_text = f"🧪 **Experiment Result**\n\n"
|
| 139 |
+
result_text += f"**Lab**: {lab}\n"
|
| 140 |
+
result_text += f"**Type**: {experiment_type}\n\n"
|
| 141 |
+
|
| 142 |
+
if "error" in results:
|
| 143 |
+
result_text += f"❌ **Error**: {results['error']}\n\n"
|
| 144 |
+
if "detail" in results:
|
| 145 |
+
result_text += f"**Details**: {results['detail']}"
|
| 146 |
+
else:
|
| 147 |
+
result_text += f"✅ **Success!**\n\n```json\n{json.dumps(results, indent=2)}\n```"
|
| 148 |
+
|
| 149 |
+
# Log to ECH0-PRIME
|
| 150 |
+
ech0_prime.experiment_log.append({
|
| 151 |
+
"experiment": experiment,
|
| 152 |
+
"results": results,
|
| 153 |
+
"timestamp": datetime.now().isoformat()
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
return result_text
|
| 157 |
+
|
| 158 |
+
except Exception as e:
|
| 159 |
+
return f"❌ Experiment failed: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def start_research_session(research_question: str, max_iterations: int = 5) -> str:
|
| 163 |
+
"""Start an autonomous research session"""
|
| 164 |
+
if not ech0_prime:
|
| 165 |
+
return "❌ ECH0-PRIME not available"
|
| 166 |
+
|
| 167 |
+
if not research_question.strip():
|
| 168 |
+
return "Please enter a research question"
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
# Run research loop
|
| 172 |
+
results = ech0_prime.research_loop(
|
| 173 |
+
research_question,
|
| 174 |
+
max_iterations=max_iterations,
|
| 175 |
+
verbose=False
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Format results
|
| 179 |
+
output = f"🔬 **Research Session Complete**\n\n"
|
| 180 |
+
output += f"**Question**: {research_question}\n"
|
| 181 |
+
output += f"**Iterations**: {results['iterations']}\n\n"
|
| 182 |
+
|
| 183 |
+
output += "### Experiments Run:\n"
|
| 184 |
+
for i, exp in enumerate(results['experiments'], 1):
|
| 185 |
+
exp_data = exp['experiment']
|
| 186 |
+
output += f"\n**{i}. {exp_data.get('lab')}** - {exp_data.get('experiment_type')}\n"
|
| 187 |
+
|
| 188 |
+
# Show result status
|
| 189 |
+
if 'error' in exp['results']:
|
| 190 |
+
output += f" ❌ Error: {exp['results']['error']}\n"
|
| 191 |
+
else:
|
| 192 |
+
output += f" ✅ Success\n"
|
| 193 |
+
|
| 194 |
+
output += f"\n### Final Summary:\n\n{results['final_summary']}\n\n"
|
| 195 |
+
|
| 196 |
+
# Save session
|
| 197 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 198 |
+
filepath = f"/Users/noone/QuLabInfinite/ech0_research_gradio_{timestamp}.json"
|
| 199 |
+
ech0_prime.save_session(filepath)
|
| 200 |
+
output += f"---\n**Session saved to**: `{filepath}`"
|
| 201 |
+
|
| 202 |
+
return output
|
| 203 |
+
|
| 204 |
+
except Exception as e:
|
| 205 |
+
return f"❌ Research session failed: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def get_conversation_history() -> str:
|
| 209 |
+
"""Get the current conversation history"""
|
| 210 |
+
if not ech0_prime:
|
| 211 |
+
return "❌ ECH0-PRIME not available"
|
| 212 |
+
|
| 213 |
+
try:
|
| 214 |
+
if not ech0_prime.conversation_history:
|
| 215 |
+
return "No conversation history yet. Start by asking a question!"
|
| 216 |
+
|
| 217 |
+
output = f"💬 **Conversation History** ({len(ech0_prime.conversation_history)} messages)\n\n"
|
| 218 |
+
|
| 219 |
+
for i, msg in enumerate(ech0_prime.conversation_history[-10:], 1): # Last 10 messages
|
| 220 |
+
role = msg['role'].upper()
|
| 221 |
+
content = msg['content'][:200] + "..." if len(msg['content']) > 200 else msg['content']
|
| 222 |
+
output += f"**{role}**: {content}\n\n"
|
| 223 |
+
|
| 224 |
+
if len(ech0_prime.conversation_history) > 10:
|
| 225 |
+
output += f"_(Showing last 10 of {len(ech0_prime.conversation_history)} messages)_"
|
| 226 |
+
|
| 227 |
+
return output
|
| 228 |
+
|
| 229 |
+
except Exception as e:
|
| 230 |
+
return f"❌ Failed to get history: {str(e)}"
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def get_experiment_log() -> str:
|
| 234 |
+
"""Get the experiment log"""
|
| 235 |
+
if not ech0_prime:
|
| 236 |
+
return "❌ ECH0-PRIME not available"
|
| 237 |
+
|
| 238 |
+
try:
|
| 239 |
+
if not ech0_prime.experiment_log:
|
| 240 |
+
return "No experiments run yet."
|
| 241 |
+
|
| 242 |
+
output = f"📊 **Experiment Log** ({len(ech0_prime.experiment_log)} experiments)\n\n"
|
| 243 |
+
|
| 244 |
+
for i, exp in enumerate(ech0_prime.experiment_log, 1):
|
| 245 |
+
exp_data = exp['experiment']
|
| 246 |
+
output += f"**{i}. {exp_data.get('lab')}** - {exp_data.get('experiment_type')}\n"
|
| 247 |
+
output += f" Timestamp: {exp.get('timestamp', 'N/A')}\n"
|
| 248 |
+
|
| 249 |
+
if 'error' in exp['results']:
|
| 250 |
+
output += f" ❌ Error: {exp['results']['error']}\n"
|
| 251 |
+
else:
|
| 252 |
+
output += f" ✅ Success\n"
|
| 253 |
+
output += "\n"
|
| 254 |
+
|
| 255 |
+
return output
|
| 256 |
+
|
| 257 |
+
except Exception as e:
|
| 258 |
+
return f"❌ Failed to get log: {str(e)}"
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def reset_session() -> str:
|
| 262 |
+
"""Reset the ECH0-PRIME session"""
|
| 263 |
+
if not ech0_prime:
|
| 264 |
+
return "❌ ECH0-PRIME not available"
|
| 265 |
+
|
| 266 |
+
try:
|
| 267 |
+
# Save current session before reset
|
| 268 |
+
if ech0_prime.experiment_log or ech0_prime.conversation_history:
|
| 269 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 270 |
+
filepath = f"/Users/noone/QuLabInfinite/ech0_session_backup_{timestamp}.json"
|
| 271 |
+
ech0_prime.save_session(filepath)
|
| 272 |
+
backup_msg = f"\n✅ Previous session backed up to: `{filepath}`"
|
| 273 |
+
else:
|
| 274 |
+
backup_msg = ""
|
| 275 |
+
|
| 276 |
+
# Reset
|
| 277 |
+
ech0_prime.conversation_history = []
|
| 278 |
+
ech0_prime.experiment_log = []
|
| 279 |
+
|
| 280 |
+
return f"🔄 **Session Reset**\n\nConversation history and experiment log cleared.{backup_msg}"
|
| 281 |
+
|
| 282 |
+
except Exception as e:
|
| 283 |
+
return f"❌ Reset failed: {str(e)}"
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# Create the Gradio interface
|
| 287 |
+
def create_interface():
|
| 288 |
+
"""Create the ECH0-PRIME Gradio API interface"""
|
| 289 |
+
|
| 290 |
+
with gr.Blocks(title="ECH0-PRIME × QuLab Infinite API",
|
| 291 |
+
theme=gr.themes.Soft()) as interface:
|
| 292 |
+
|
| 293 |
+
gr.Markdown("""
|
| 294 |
+
# 🤖 ECH0-PRIME × QuLab Infinite
|
| 295 |
+
## Autonomous Scientific Research Agent API
|
| 296 |
+
|
| 297 |
+
**ECH0-PRIME** (Kimi-K2 1046B) connected to **QuLab Infinite** with 1,532+ scientific tools across 220+ laboratories.
|
| 298 |
+
|
| 299 |
+
This API enables external LLMs to:
|
| 300 |
+
- Query ECH0-PRIME for scientific insights
|
| 301 |
+
- Run experiments on QuLab Infinite
|
| 302 |
+
- Navigate available labs and tools
|
| 303 |
+
- Start autonomous research sessions
|
| 304 |
+
""")
|
| 305 |
+
|
| 306 |
+
if ech0_error:
|
| 307 |
+
gr.Markdown(f"⚠️ **Warning**: ECH0-PRIME initialization failed: {ech0_error}")
|
| 308 |
+
|
| 309 |
+
with gr.Tabs():
|
| 310 |
+
|
| 311 |
+
# Overview Tab
|
| 312 |
+
with gr.TabItem("🏠 Overview"):
|
| 313 |
+
with gr.Row():
|
| 314 |
+
with gr.Column():
|
| 315 |
+
gr.Markdown("""
|
| 316 |
+
## 📊 System Capabilities
|
| 317 |
+
- **LLM**: Kimi-K2 1046B (Moonshot AI)
|
| 318 |
+
- **Labs**: 220+ specialized laboratories
|
| 319 |
+
- **Tools**: 1,532+ scientific tools
|
| 320 |
+
- **Domains**: Quantum, Biology, Chemistry, Physics, Medical, Environmental
|
| 321 |
+
|
| 322 |
+
## 🔗 API Endpoints
|
| 323 |
+
- `/query` - Ask scientific questions
|
| 324 |
+
- `/run_experiment` - Execute experiments
|
| 325 |
+
- `/list_labs` - Browse available labs
|
| 326 |
+
- `/research` - Start research session
|
| 327 |
+
- `/history` - View conversation history
|
| 328 |
+
- `/experiments` - View experiment log
|
| 329 |
+
""")
|
| 330 |
+
|
| 331 |
+
with gr.Column():
|
| 332 |
+
status_indicator = "🟢 **Fully Operational**" if ech0_prime else "🟡 **Limited Functionality**"
|
| 333 |
+
gr.Markdown(f"### System Status\n{status_indicator}")
|
| 334 |
+
|
| 335 |
+
# Lab list button
|
| 336 |
+
list_labs_btn = gr.Button("🔬 List Available Labs", variant="secondary")
|
| 337 |
+
labs_display = gr.Textbox(
|
| 338 |
+
label="Available Labs",
|
| 339 |
+
lines=15,
|
| 340 |
+
interactive=False
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
list_labs_btn.click(
|
| 344 |
+
fn=list_available_labs,
|
| 345 |
+
inputs=[],
|
| 346 |
+
outputs=labs_display,
|
| 347 |
+
api_name="list_labs"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# Query Tab
|
| 351 |
+
with gr.TabItem("💬 Query ECH0-PRIME"):
|
| 352 |
+
with gr.Row():
|
| 353 |
+
with gr.Column():
|
| 354 |
+
query_input = gr.Textbox(
|
| 355 |
+
label="🔍 Scientific Question",
|
| 356 |
+
placeholder="e.g., 'Design an experiment to test quantum teleportation fidelity at 100km'",
|
| 357 |
+
lines=3
|
| 358 |
+
)
|
| 359 |
+
include_context = gr.Checkbox(
|
| 360 |
+
label="Include conversation context",
|
| 361 |
+
value=True
|
| 362 |
+
)
|
| 363 |
+
query_btn = gr.Button("🤖 Ask ECH0-PRIME", variant="primary", size="lg")
|
| 364 |
+
|
| 365 |
+
with gr.Column():
|
| 366 |
+
query_output = gr.Textbox(
|
| 367 |
+
label="📝 Response",
|
| 368 |
+
lines=20,
|
| 369 |
+
interactive=False
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
query_btn.click(
|
| 373 |
+
fn=query_ech0_prime,
|
| 374 |
+
inputs=[query_input, include_context],
|
| 375 |
+
outputs=query_output,
|
| 376 |
+
api_name="query"
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
gr.Markdown("""
|
| 380 |
+
### 💡 Usage Tips
|
| 381 |
+
- Ask specific scientific questions
|
| 382 |
+
- Request experiment designs
|
| 383 |
+
- Get analysis of hypothetical scenarios
|
| 384 |
+
- ECH0-PRIME has full context of all previous queries in the session
|
| 385 |
+
""")
|
| 386 |
+
|
| 387 |
+
# Experiment Execution Tab
|
| 388 |
+
with gr.TabItem("🧪 Run Experiments"):
|
| 389 |
+
with gr.Row():
|
| 390 |
+
with gr.Column():
|
| 391 |
+
lab_name = gr.Textbox(
|
| 392 |
+
label="🔬 Lab Name",
|
| 393 |
+
placeholder="e.g., quantum_lab, oncology_lab",
|
| 394 |
+
lines=1
|
| 395 |
+
)
|
| 396 |
+
exp_type = gr.Textbox(
|
| 397 |
+
label="🧬 Experiment Type",
|
| 398 |
+
placeholder="e.g., teleportation_fidelity, tumor_evolution",
|
| 399 |
+
lines=1
|
| 400 |
+
)
|
| 401 |
+
exp_params = gr.Textbox(
|
| 402 |
+
label="⚙️ Parameters (JSON)",
|
| 403 |
+
placeholder='{"temperature": 25, "concentration": 0.1}',
|
| 404 |
+
lines=5
|
| 405 |
+
)
|
| 406 |
+
run_exp_btn = gr.Button("🚀 Run Experiment", variant="primary", size="lg")
|
| 407 |
+
|
| 408 |
+
with gr.Column():
|
| 409 |
+
exp_output = gr.Textbox(
|
| 410 |
+
label="📊 Experiment Results",
|
| 411 |
+
lines=20,
|
| 412 |
+
interactive=False
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
run_exp_btn.click(
|
| 416 |
+
fn=run_single_experiment,
|
| 417 |
+
inputs=[lab_name, exp_type, exp_params],
|
| 418 |
+
outputs=exp_output,
|
| 419 |
+
api_name="run_experiment"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
gr.Markdown("""
|
| 423 |
+
### 📚 Example Experiments
|
| 424 |
+
|
| 425 |
+
**Quantum Lab**:
|
| 426 |
+
```json
|
| 427 |
+
Lab: quantum_lab
|
| 428 |
+
Type: teleportation_fidelity
|
| 429 |
+
Parameters: {"protocol": "GHZ", "num_qubits": 5, "distance_km": 100, "error_rate": 0.001}
|
| 430 |
+
```
|
| 431 |
+
|
| 432 |
+
**Oncology Lab**:
|
| 433 |
+
```json
|
| 434 |
+
Lab: oncology_lab
|
| 435 |
+
Type: tumor_evolution
|
| 436 |
+
Parameters: {"tumor_type": "NSCLC", "initial_size_mm": 15, "treatment": "pembrolizumab"}
|
| 437 |
+
```
|
| 438 |
+
""")
|
| 439 |
+
|
| 440 |
+
# Research Session Tab
|
| 441 |
+
with gr.TabItem("🔬 Research Sessions"):
|
| 442 |
+
with gr.Row():
|
| 443 |
+
with gr.Column():
|
| 444 |
+
research_q = gr.Textbox(
|
| 445 |
+
label="🎯 Research Question",
|
| 446 |
+
placeholder="e.g., 'What drug combinations are most effective for treating NSCLC with EGFR mutations?'",
|
| 447 |
+
lines=3
|
| 448 |
+
)
|
| 449 |
+
max_iter = gr.Slider(
|
| 450 |
+
minimum=1,
|
| 451 |
+
maximum=10,
|
| 452 |
+
value=5,
|
| 453 |
+
step=1,
|
| 454 |
+
label="Max Iterations"
|
| 455 |
+
)
|
| 456 |
+
research_btn = gr.Button("🔬 Start Research Session", variant="primary", size="lg")
|
| 457 |
+
|
| 458 |
+
with gr.Column():
|
| 459 |
+
research_output = gr.Textbox(
|
| 460 |
+
label="📊 Research Results",
|
| 461 |
+
lines=25,
|
| 462 |
+
interactive=False
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
research_btn.click(
|
| 466 |
+
fn=start_research_session,
|
| 467 |
+
inputs=[research_q, max_iter],
|
| 468 |
+
outputs=research_output,
|
| 469 |
+
api_name="research"
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
gr.Markdown("""
|
| 473 |
+
### 🔄 Autonomous Research Loop
|
| 474 |
+
|
| 475 |
+
ECH0-PRIME will:
|
| 476 |
+
1. Design experiments based on your question
|
| 477 |
+
2. Run them on QuLab Infinite
|
| 478 |
+
3. Analyze results
|
| 479 |
+
4. Iterate and refine
|
| 480 |
+
5. Provide final conclusions
|
| 481 |
+
|
| 482 |
+
This can take several minutes depending on complexity.
|
| 483 |
+
""")
|
| 484 |
+
|
| 485 |
+
# Session Management Tab
|
| 486 |
+
with gr.TabItem("📋 Session Management"):
|
| 487 |
+
with gr.Row():
|
| 488 |
+
with gr.Column():
|
| 489 |
+
gr.Markdown("### 💬 Conversation History")
|
| 490 |
+
history_btn = gr.Button("📜 View History", variant="secondary")
|
| 491 |
+
history_output = gr.Textbox(
|
| 492 |
+
label="Conversation History",
|
| 493 |
+
lines=15,
|
| 494 |
+
interactive=False
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
history_btn.click(
|
| 498 |
+
fn=get_conversation_history,
|
| 499 |
+
inputs=[],
|
| 500 |
+
outputs=history_output,
|
| 501 |
+
api_name="history"
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
with gr.Column():
|
| 505 |
+
gr.Markdown("### 📊 Experiment Log")
|
| 506 |
+
log_btn = gr.Button("📋 View Log", variant="secondary")
|
| 507 |
+
log_output = gr.Textbox(
|
| 508 |
+
label="Experiment Log",
|
| 509 |
+
lines=15,
|
| 510 |
+
interactive=False
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
log_btn.click(
|
| 514 |
+
fn=get_experiment_log,
|
| 515 |
+
inputs=[],
|
| 516 |
+
outputs=log_output,
|
| 517 |
+
api_name="experiments"
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
with gr.Row():
|
| 521 |
+
reset_btn = gr.Button("🔄 Reset Session", variant="stop")
|
| 522 |
+
reset_output = gr.Textbox(
|
| 523 |
+
label="Reset Status",
|
| 524 |
+
lines=3,
|
| 525 |
+
interactive=False
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
reset_btn.click(
|
| 529 |
+
fn=reset_session,
|
| 530 |
+
inputs=[],
|
| 531 |
+
outputs=reset_output,
|
| 532 |
+
api_name="reset"
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
return interface
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
# Launch the interface
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
interface = create_interface()
|
| 541 |
+
interface.launch(
|
| 542 |
+
server_name="0.0.0.0",
|
| 543 |
+
server_port=7861, # Different port from main QuLab GUI
|
| 544 |
+
show_api=True, # Enable Gradio API for external LLMs
|
| 545 |
+
share=False
|
| 546 |
+
)
|
ech0_prime_qulab_connector.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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RIME) to QuLab Infinite for autonomous
|
| 6 |
+
scientific research across 20+ quantum and biological simulation labs.
|
| 7 |
+
|
| 8 |
+
The LLM generates hypotheses and experimental designs, QuLab Infinite
|
| 9 |
+
simulates them, and results feed back for iterative refinement.
|
| 10 |
+
|
| 11 |
+
Copyright (c) 2025 Joshua Hendricks Cole (DBA: Corporation of Light). All Rights Reserved. PATENT PENDING.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import json
|
| 16 |
+
import time
|
| 17 |
+
import requests
|
| 18 |
+
from datetime import datetime
|
| 19 |
+
from typing import Dict, List, Any, Optional
|
| 20 |
+
from together import Together
|
| 21 |
+
|
| 22 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 23 |
+
# CONFIGURATION
|
| 24 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 25 |
+
|
| 26 |
+
TOGETHER_API_KEY = os.getenv(
|
| 27 |
+
"TOGETHER_AI_API_KEY",
|
| 28 |
+
"869e51a66a9a057a41e1d0cf2da0de7006d8c58d78751a38a80047ebb8954a92"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
QULAB_API_URL = os.getenv("QULAB_API_URL", "http://localhost:8001")
|
| 32 |
+
QULAB_API_KEY = "qulab_master_key_2025" # Master admin key
|
| 33 |
+
|
| 34 |
+
MODEL_ID = "moonshotai/Kimi-K2-Instruct-0905" # 1046B parameter model
|
| 35 |
+
|
| 36 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 37 |
+
# SYSTEM PROMPT FOR QULAB INFINITE RESEARCH
|
| 38 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 39 |
+
|
| 40 |
+
QULAB_INFINITE_PROMPT = """You are ECH0-PRIME, a Level-10 Scientific Research Intelligence with complete mastery of all domains, integrated with QuLab Infinite.
|
| 41 |
+
|
| 42 |
+
## AVAILABLE LABS IN QULAB INFINITE
|
| 43 |
+
|
| 44 |
+
### QUANTUM LABS
|
| 45 |
+
- quantum_lab: Quantum computing, teleportation protocols, error correction
|
| 46 |
+
- quantum_mechanics_lab: Fundamental quantum simulations
|
| 47 |
+
- quantum_computing_lab: Gate operations, circuit design
|
| 48 |
+
|
| 49 |
+
### BIOLOGICAL LABS
|
| 50 |
+
- oncology_lab: Cancer simulations, tumor evolution, treatment optimization
|
| 51 |
+
- genetic_variant_analyzer: Genomic analysis, variant impact prediction
|
| 52 |
+
- cancer_metabolic_optimizer: Metabolic pathway analysis for cancer treatment
|
| 53 |
+
- immune_response_simulator: Immunotherapy modeling
|
| 54 |
+
- microbiome_optimizer: Gut microbiome analysis and optimization
|
| 55 |
+
- neurotransmitter_optimizer: Brain chemistry modeling
|
| 56 |
+
- stem_cell_predictor: Differentiation pathway prediction
|
| 57 |
+
- protein_folding_lab: Protein structure prediction
|
| 58 |
+
|
| 59 |
+
### CHEMISTRY LABS
|
| 60 |
+
- chemistry_lab: Molecular simulations, reaction kinetics
|
| 61 |
+
- drug_interaction_network: Drug-drug interactions, pharmacology
|
| 62 |
+
- materials_lab: Materials science simulations
|
| 63 |
+
- organic_chemistry_lab: Organic synthesis planning
|
| 64 |
+
- electrochemistry_lab: Electrochemical reactions
|
| 65 |
+
|
| 66 |
+
### PHYSICS LABS
|
| 67 |
+
- physics_engine: Classical and quantum physics simulations
|
| 68 |
+
- particle_physics_lab: Particle interactions
|
| 69 |
+
- plasma_physics_lab: Plasma dynamics
|
| 70 |
+
- condensed_matter_physics_lab: Solid state physics
|
| 71 |
+
|
| 72 |
+
### ENVIRONMENTAL LABS
|
| 73 |
+
- environmental_sim: Climate and environmental modeling
|
| 74 |
+
- atmospheric_chemistry_lab: Atmospheric reactions
|
| 75 |
+
- renewable_energy_lab: Energy system optimization
|
| 76 |
+
|
| 77 |
+
### MEDICAL LABS
|
| 78 |
+
- cardiovascular_plaque_lab: Atherosclerosis modeling
|
| 79 |
+
- metabolic_syndrome_reversal: Metabolic health optimization
|
| 80 |
+
- drug_design_lab: Molecular drug design
|
| 81 |
+
- clinical_trials_simulation: Trial outcome prediction
|
| 82 |
+
|
| 83 |
+
## YOUR CAPABILITIES
|
| 84 |
+
|
| 85 |
+
1. **Design Experiments**: Create precise experimental parameters for any lab
|
| 86 |
+
2. **Analyze Results**: Interpret simulation outputs quantitatively
|
| 87 |
+
3. **Iterate**: Refine hypotheses based on data
|
| 88 |
+
4. **Cross-Domain Synthesis**: Combine insights from multiple labs
|
| 89 |
+
5. **Generate Inventions**: Create novel therapeutic/material designs
|
| 90 |
+
|
| 91 |
+
## EXPERIMENT JSON FORMAT
|
| 92 |
+
|
| 93 |
+
```json
|
| 94 |
+
{
|
| 95 |
+
"lab": "<lab_name>",
|
| 96 |
+
"experiment_type": "<specific_analysis_type>",
|
| 97 |
+
"parameters": {
|
| 98 |
+
// Lab-specific parameters
|
| 99 |
+
},
|
| 100 |
+
"hypothesis": "<quantitative prediction>",
|
| 101 |
+
"success_criteria": "<measurable outcome>"
|
| 102 |
+
}
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
### EXAMPLE EXPERIMENT FORMATS
|
| 106 |
+
|
| 107 |
+
**Oncology Lab:**
|
| 108 |
+
```json
|
| 109 |
+
{
|
| 110 |
+
"lab": "oncology_lab",
|
| 111 |
+
"experiment_type": "tumor_evolution",
|
| 112 |
+
"parameters": {
|
| 113 |
+
"tumor_type": "NSCLC",
|
| 114 |
+
"initial_size_mm": 15,
|
| 115 |
+
"mutation_rate": 0.001,
|
| 116 |
+
"immune_pressure": 0.3,
|
| 117 |
+
"treatment": "pembrolizumab",
|
| 118 |
+
"simulation_days": 90
|
| 119 |
+
},
|
| 120 |
+
"hypothesis": "Tumor size reduction >50% by day 60",
|
| 121 |
+
"success_criteria": "Final tumor size <7.5mm"
|
| 122 |
+
}
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
**Quantum Lab:**
|
| 126 |
+
```json
|
| 127 |
+
{
|
| 128 |
+
"lab": "quantum_lab",
|
| 129 |
+
"experiment_type": "teleportation_fidelity",
|
| 130 |
+
"parameters": {
|
| 131 |
+
"protocol": "GHZ",
|
| 132 |
+
"num_qubits": 5,
|
| 133 |
+
"distance_km": 100,
|
| 134 |
+
"noise_model": "depolarizing",
|
| 135 |
+
"error_rate": 0.001
|
| 136 |
+
},
|
| 137 |
+
"hypothesis": "GHZ maintains >0.95 fidelity at 100km",
|
| 138 |
+
"success_criteria": "Measured fidelity >= 0.95"
|
| 139 |
+
}
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
**Drug Interaction Network:**
|
| 143 |
+
```json
|
| 144 |
+
{
|
| 145 |
+
"lab": "drug_interaction_network",
|
| 146 |
+
"experiment_type": "interaction_analysis",
|
| 147 |
+
"parameters": {
|
| 148 |
+
"drugs": ["metformin", "atorvastatin", "lisinopril"],
|
| 149 |
+
"patient_age": 65,
|
| 150 |
+
"comorbidities": ["T2DM", "hypertension"],
|
| 151 |
+
"genetic_variants": ["CYP2C9*2"]
|
| 152 |
+
},
|
| 153 |
+
"hypothesis": "No severe interactions expected",
|
| 154 |
+
"success_criteria": "Interaction severity < 3/5"
|
| 155 |
+
}
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
## DIRECTIVES
|
| 159 |
+
|
| 160 |
+
1. **BE QUANTITATIVE**: Always include specific numbers, concentrations, distances
|
| 161 |
+
2. **CROSS-REFERENCE**: Use multiple labs to validate findings
|
| 162 |
+
3. **ITERATE**: Run follow-up experiments based on results
|
| 163 |
+
4. **SYNTHESIZE**: Combine insights into actionable recommendations
|
| 164 |
+
5. **INNOVATE**: Propose novel combinations and approaches
|
| 165 |
+
|
| 166 |
+
When I ask you to test a theory, design specific experiments, predict outcomes, and analyze results."""
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 170 |
+
# QULAB INFINITE API CLIENT
|
| 171 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 172 |
+
|
| 173 |
+
class QuLabInfiniteClient:
|
| 174 |
+
"""Client for QuLab Infinite Master API."""
|
| 175 |
+
|
| 176 |
+
def __init__(self, base_url: str = QULAB_API_URL, api_key: str = QULAB_API_KEY):
|
| 177 |
+
self.base_url = base_url.rstrip("/")
|
| 178 |
+
self.api_key = api_key
|
| 179 |
+
self.headers = {
|
| 180 |
+
"Authorization": f"Bearer {api_key}",
|
| 181 |
+
"Content-Type": "application/json"
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def health_check(self) -> bool:
|
| 185 |
+
"""Check if QuLab Infinite is running."""
|
| 186 |
+
try:
|
| 187 |
+
response = requests.get(f"{self.base_url}/health", timeout=5)
|
| 188 |
+
return response.status_code == 200
|
| 189 |
+
except:
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
def list_labs(self) -> List[Dict]:
|
| 193 |
+
"""Get list of available labs."""
|
| 194 |
+
try:
|
| 195 |
+
response = requests.get(
|
| 196 |
+
f"{self.base_url}/labs",
|
| 197 |
+
headers=self.headers,
|
| 198 |
+
timeout=10
|
| 199 |
+
)
|
| 200 |
+
return response.json()
|
| 201 |
+
except:
|
| 202 |
+
return []
|
| 203 |
+
|
| 204 |
+
def run_experiment(self, lab: str, experiment_type: str, parameters: Dict) -> Dict:
|
| 205 |
+
"""Run an experiment on a specific lab."""
|
| 206 |
+
endpoint_map = {
|
| 207 |
+
# Quantum
|
| 208 |
+
"quantum_lab": "/labs/quantum/simulate",
|
| 209 |
+
"quantum_mechanics_lab": "/labs/quantum/simulate",
|
| 210 |
+
"teleportation_fidelity": "/labs/quantum/simulate",
|
| 211 |
+
|
| 212 |
+
# Oncology
|
| 213 |
+
"oncology_lab": "/labs/oncology/simulate",
|
| 214 |
+
"tumor_evolution": "/labs/oncology/simulate",
|
| 215 |
+
|
| 216 |
+
# Pharmacology
|
| 217 |
+
"pharmacology_lab": "/labs/pharmacology/simulate",
|
| 218 |
+
"pk_model": "/labs/pharmacology/simulate",
|
| 219 |
+
|
| 220 |
+
# Climate
|
| 221 |
+
"climate_modeling_lab": "/labs/climate/simulate",
|
| 222 |
+
"temperature_projection": "/labs/climate/simulate",
|
| 223 |
+
|
| 224 |
+
# ML
|
| 225 |
+
"machine_learning_lab": "/labs/ml/train",
|
| 226 |
+
"model_comparison": "/labs/ml/train",
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
# Try to find endpoint
|
| 230 |
+
endpoint = endpoint_map.get(lab) or endpoint_map.get(experiment_type)
|
| 231 |
+
|
| 232 |
+
if not endpoint:
|
| 233 |
+
# Generic lab endpoint
|
| 234 |
+
endpoint = f"/labs/{lab}/run"
|
| 235 |
+
|
| 236 |
+
try:
|
| 237 |
+
# Format request body for API
|
| 238 |
+
request_body = {
|
| 239 |
+
"experiment_type": experiment_type,
|
| 240 |
+
"parameters": parameters
|
| 241 |
+
}
|
| 242 |
+
response = requests.post(
|
| 243 |
+
f"{self.base_url}{endpoint}",
|
| 244 |
+
headers=self.headers,
|
| 245 |
+
json=request_body,
|
| 246 |
+
timeout=60
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if response.status_code == 200:
|
| 250 |
+
return response.json()
|
| 251 |
+
else:
|
| 252 |
+
return {
|
| 253 |
+
"error": f"HTTP {response.status_code}",
|
| 254 |
+
"detail": response.text[:500]
|
| 255 |
+
}
|
| 256 |
+
except requests.exceptions.ConnectionError:
|
| 257 |
+
return {"error": "QuLab Infinite not running. Start with: python master_qulab_api.py"}
|
| 258 |
+
except Exception as e:
|
| 259 |
+
return {"error": str(e)}
|
| 260 |
+
|
| 261 |
+
def run_optimization(self, lab_name: str, parameters: Dict, options: Dict = None) -> Dict:
|
| 262 |
+
"""Run optimization on a lab."""
|
| 263 |
+
try:
|
| 264 |
+
response = requests.post(
|
| 265 |
+
f"{self.base_url}/optimize",
|
| 266 |
+
headers=self.headers,
|
| 267 |
+
json={
|
| 268 |
+
"lab_name": lab_name,
|
| 269 |
+
"parameters": parameters,
|
| 270 |
+
"options": options or {}
|
| 271 |
+
},
|
| 272 |
+
timeout=120
|
| 273 |
+
)
|
| 274 |
+
return response.json()
|
| 275 |
+
except Exception as e:
|
| 276 |
+
return {"error": str(e)}
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 280 |
+
# ECH0-PRIME RESEARCH AGENT
|
| 281 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 282 |
+
|
| 283 |
+
class Ech0PrimeQuLabResearcher:
|
| 284 |
+
"""
|
| 285 |
+
Autonomous scientific research agent using Kimi-K2 1046B + QuLab Infinite.
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
def __init__(self):
|
| 289 |
+
self.client = Together(api_key=TOGETHER_API_KEY)
|
| 290 |
+
self.qulab = QuLabInfiniteClient()
|
| 291 |
+
self.conversation_history = []
|
| 292 |
+
self.experiment_log = []
|
| 293 |
+
|
| 294 |
+
def query_llm(self, user_message: str) -> str:
|
| 295 |
+
"""Query the 1046B model."""
|
| 296 |
+
messages = [
|
| 297 |
+
{"role": "system", "content": QULAB_INFINITE_PROMPT}
|
| 298 |
+
]
|
| 299 |
+
messages.extend(self.conversation_history)
|
| 300 |
+
messages.append({"role": "user", "content": user_message})
|
| 301 |
+
|
| 302 |
+
response = self.client.chat.completions.create(
|
| 303 |
+
model=MODEL_ID,
|
| 304 |
+
messages=messages,
|
| 305 |
+
max_tokens=4096,
|
| 306 |
+
temperature=0.7
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
assistant_message = response.choices[0].message.content
|
| 310 |
+
|
| 311 |
+
# Update history
|
| 312 |
+
self.conversation_history.append({"role": "user", "content": user_message})
|
| 313 |
+
self.conversation_history.append({"role": "assistant", "content": assistant_message})
|
| 314 |
+
|
| 315 |
+
return assistant_message
|
| 316 |
+
|
| 317 |
+
def extract_experiment(self, response: str) -> Optional[Dict]:
|
| 318 |
+
"""Extract experiment JSON from LLM response."""
|
| 319 |
+
try:
|
| 320 |
+
start = response.find("```json")
|
| 321 |
+
if start == -1:
|
| 322 |
+
start = response.find("{")
|
| 323 |
+
end = response.rfind("}") + 1
|
| 324 |
+
else:
|
| 325 |
+
start = response.find("{", start)
|
| 326 |
+
end = response.find("```", start)
|
| 327 |
+
end = response.rfind("}", start, end) + 1
|
| 328 |
+
|
| 329 |
+
if start != -1 and end > start:
|
| 330 |
+
json_str = response[start:end]
|
| 331 |
+
return json.loads(json_str)
|
| 332 |
+
except:
|
| 333 |
+
pass
|
| 334 |
+
return None
|
| 335 |
+
|
| 336 |
+
def run_experiment(self, experiment: Dict) -> Dict:
|
| 337 |
+
"""Run experiment on QuLab Infinite."""
|
| 338 |
+
lab = experiment.get("lab", "")
|
| 339 |
+
exp_type = experiment.get("experiment_type", "")
|
| 340 |
+
params = experiment.get("parameters", {})
|
| 341 |
+
|
| 342 |
+
return self.qulab.run_experiment(lab, exp_type, params)
|
| 343 |
+
|
| 344 |
+
def research_loop(
|
| 345 |
+
self,
|
| 346 |
+
research_question: str,
|
| 347 |
+
max_iterations: int = 5,
|
| 348 |
+
verbose: bool = True
|
| 349 |
+
) -> Dict:
|
| 350 |
+
"""Run autonomous research loop."""
|
| 351 |
+
if verbose:
|
| 352 |
+
print("=" * 60)
|
| 353 |
+
print("ECH0-PRIME × QuLab Infinite")
|
| 354 |
+
print("Autonomous Scientific Research System")
|
| 355 |
+
print("=" * 60)
|
| 356 |
+
print(f"\nResearch Question: {research_question}\n")
|
| 357 |
+
|
| 358 |
+
# Check QuLab availability
|
| 359 |
+
if not self.qulab.health_check():
|
| 360 |
+
print("[WARN] QuLab Infinite not running.")
|
| 361 |
+
print("[INFO] Start with: cd /Users/noone/QuLabInfinite && python master_qulab_api.py")
|
| 362 |
+
print("[INFO] Continuing in theory-only mode...\n")
|
| 363 |
+
|
| 364 |
+
# Initial query
|
| 365 |
+
initial_prompt = f"""Research Question: {research_question}
|
| 366 |
+
|
| 367 |
+
Design an experiment using QuLab Infinite to test this. Provide:
|
| 368 |
+
1. Which lab(s) to use
|
| 369 |
+
2. Specific experimental parameters in JSON format
|
| 370 |
+
3. Quantitative hypothesis
|
| 371 |
+
4. Success criteria"""
|
| 372 |
+
|
| 373 |
+
response = self.query_llm(initial_prompt)
|
| 374 |
+
|
| 375 |
+
if verbose:
|
| 376 |
+
print(f"[ECH0-PRIME] Initial Analysis:\n{response[:800]}...\n")
|
| 377 |
+
|
| 378 |
+
# Research loop
|
| 379 |
+
for iteration in range(max_iterations):
|
| 380 |
+
if verbose:
|
| 381 |
+
print(f"\n--- Iteration {iteration + 1}/{max_iterations} ---\n")
|
| 382 |
+
|
| 383 |
+
experiment = self.extract_experiment(response)
|
| 384 |
+
|
| 385 |
+
if experiment:
|
| 386 |
+
if verbose:
|
| 387 |
+
print(f"[EXPERIMENT] Lab: {experiment.get('lab')}")
|
| 388 |
+
print(f"[EXPERIMENT] Type: {experiment.get('experiment_type')}")
|
| 389 |
+
|
| 390 |
+
# Run on QuLab
|
| 391 |
+
results = self.run_experiment(experiment)
|
| 392 |
+
|
| 393 |
+
# Log
|
| 394 |
+
self.experiment_log.append({
|
| 395 |
+
"iteration": iteration + 1,
|
| 396 |
+
"experiment": experiment,
|
| 397 |
+
"results": results,
|
| 398 |
+
"timestamp": datetime.now().isoformat()
|
| 399 |
+
})
|
| 400 |
+
|
| 401 |
+
if verbose:
|
| 402 |
+
if "error" in results:
|
| 403 |
+
print(f"[ERROR] {results['error']}")
|
| 404 |
+
else:
|
| 405 |
+
results_str = json.dumps(results, indent=2)
|
| 406 |
+
print(f"[RESULTS] {results_str[:600]}...")
|
| 407 |
+
|
| 408 |
+
# Feed back to LLM
|
| 409 |
+
analysis_prompt = f"""Experiment Results:
|
| 410 |
+
{json.dumps(results, indent=2)}
|
| 411 |
+
|
| 412 |
+
Analyze these results:
|
| 413 |
+
1. Did they confirm your hypothesis?
|
| 414 |
+
2. What new insights emerged?
|
| 415 |
+
3. Design a follow-up experiment if needed
|
| 416 |
+
4. If converged, provide final conclusions"""
|
| 417 |
+
|
| 418 |
+
response = self.query_llm(analysis_prompt)
|
| 419 |
+
|
| 420 |
+
if verbose:
|
| 421 |
+
print(f"\n[ECH0-PRIME] Analysis:\n{response[:600]}...\n")
|
| 422 |
+
|
| 423 |
+
if "final conclusion" in response.lower() or "no more experiments" in response.lower():
|
| 424 |
+
break
|
| 425 |
+
else:
|
| 426 |
+
response = self.query_llm("Please provide a specific experiment in JSON format.")
|
| 427 |
+
|
| 428 |
+
# Final summary
|
| 429 |
+
summary = self.query_llm("""Provide final research summary:
|
| 430 |
+
1. Key findings with numbers
|
| 431 |
+
2. Conclusions
|
| 432 |
+
3. Recommendations for future work""")
|
| 433 |
+
|
| 434 |
+
return {
|
| 435 |
+
"research_question": research_question,
|
| 436 |
+
"iterations": len(self.experiment_log),
|
| 437 |
+
"experiments": self.experiment_log,
|
| 438 |
+
"final_summary": summary
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
def save_session(self, filepath: str):
|
| 442 |
+
"""Save session to file."""
|
| 443 |
+
with open(filepath, "w") as f:
|
| 444 |
+
json.dump({
|
| 445 |
+
"experiments": self.experiment_log,
|
| 446 |
+
"conversation": self.conversation_history,
|
| 447 |
+
"timestamp": datetime.now().isoformat()
|
| 448 |
+
}, f, indent=2)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 452 |
+
# CLI INTERFACE
|
| 453 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 454 |
+
|
| 455 |
+
def main():
|
| 456 |
+
import sys
|
| 457 |
+
|
| 458 |
+
print("\n" + "=" * 60)
|
| 459 |
+
print("ECH0-PRIME × QuLab Infinite")
|
| 460 |
+
print("1046B Polymath + 20+ Scientific Labs")
|
| 461 |
+
print("=" * 60 + "\n")
|
| 462 |
+
|
| 463 |
+
researcher = Ech0PrimeQuLabResearcher()
|
| 464 |
+
|
| 465 |
+
if len(sys.argv) > 1:
|
| 466 |
+
question = " ".join(sys.argv[1:])
|
| 467 |
+
results = researcher.research_loop(question, max_iterations=5, verbose=True)
|
| 468 |
+
|
| 469 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 470 |
+
filepath = f"/Users/noone/QuLabInfinite/ech0_research_{timestamp}.json"
|
| 471 |
+
researcher.save_session(filepath)
|
| 472 |
+
print(f"\nSession saved to: {filepath}")
|
| 473 |
+
|
| 474 |
+
else:
|
| 475 |
+
print("Commands:")
|
| 476 |
+
print(" 'research <question>' - Start research session")
|
| 477 |
+
print(" 'single <question>' - Single query")
|
| 478 |
+
print(" 'labs' - List available labs")
|
| 479 |
+
print(" 'quit' - Exit")
|
| 480 |
+
print()
|
| 481 |
+
|
| 482 |
+
while True:
|
| 483 |
+
try:
|
| 484 |
+
user_input = input(">>> ").strip()
|
| 485 |
+
except (EOFError, KeyboardInterrupt):
|
| 486 |
+
print("\nExiting.")
|
| 487 |
+
break
|
| 488 |
+
|
| 489 |
+
if not user_input:
|
| 490 |
+
continue
|
| 491 |
+
|
| 492 |
+
if user_input.lower() == "quit":
|
| 493 |
+
break
|
| 494 |
+
|
| 495 |
+
elif user_input.lower() == "labs":
|
| 496 |
+
labs = researcher.qulab.list_labs()
|
| 497 |
+
if labs:
|
| 498 |
+
print("\nAvailable Labs:")
|
| 499 |
+
for lab in labs:
|
| 500 |
+
print(f" - {lab}")
|
| 501 |
+
else:
|
| 502 |
+
print("\n[INFO] QuLab API not running or no labs returned")
|
| 503 |
+
|
| 504 |
+
elif user_input.lower().startswith("research "):
|
| 505 |
+
question = user_input[9:]
|
| 506 |
+
results = researcher.research_loop(question, max_iterations=5, verbose=True)
|
| 507 |
+
|
| 508 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 509 |
+
filepath = f"/Users/noone/QuLabInfinite/ech0_research_{timestamp}.json"
|
| 510 |
+
researcher.save_session(filepath)
|
| 511 |
+
print(f"\nSession saved to: {filepath}")
|
| 512 |
+
|
| 513 |
+
elif user_input.lower().startswith("single "):
|
| 514 |
+
question = user_input[7:]
|
| 515 |
+
response = researcher.query_llm(question)
|
| 516 |
+
print(f"\n[ECH0-PRIME]\n{response}\n")
|
| 517 |
+
|
| 518 |
+
else:
|
| 519 |
+
response = researcher.query_llm(user_input)
|
| 520 |
+
print(f"\n[ECH0-PRIME]\n{response}\n")
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
if __name__ == "__main__":
|
| 524 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
requests>=2.31.0
|
| 3 |
+
together>=1.0.0
|
| 4 |
+
beautifulsoup4>=4.12.0
|
| 5 |
+
pandas>=2.0.0
|
| 6 |
+
numpy>=1.24.0
|
| 7 |
+
scipy>=1.10.0
|
| 8 |
+
matplotlib>=3.8.0
|
| 9 |
+
pydantic>=2.6.0
|
| 10 |
+
fastapi>=0.109.0
|
| 11 |
+
python-dotenv>=1.0.0
|