Skip to main content
Glama
README.md
<div align="center">

<img src="assets/banner.svg" alt="HerbAgent Banner" width="100%"/>

<br/><br/>

[![CI](https://github.com/hwfengcs/HerbAgent/actions/workflows/ci.yml/badge.svg)](https://github.com/hwfengcs/HerbAgent/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/License-Apache%202.0-0f766e.svg)](LICENSE)
[![Python](https://img.shields.io/badge/Python-3.10%2B-3776ab.svg)](https://www.python.org/)
[![FastAPI](https://img.shields.io/badge/FastAPI-SSE%20Streaming-009688.svg)](https://fastapi.tiangolo.com/)
[![MCP](https://img.shields.io/badge/MCP-2024--11--05%20Ready-4338ca.svg)](docs/tools_and_mcp.md)
[![PRs Welcome](https://img.shields.io/badge/PRs-Welcome-brightgreen.svg)](CONTRIBUTING.md)

**English** | [简体中文](README_ZH.md)

*An open-source **Multi-Agent AI Co-Scientist** for multi-target polypharmacology & drug mechanism-of-action discovery.*
<br/>
*Given any multi-herb formulation, medicinal herb, or bioactive compound, **HerbAgent** runs a **Generate–Debate–Evolve** multi-agent engine with **Dempster–Shafer belief fusion**, **Bradley–Terry / RRF + Submodular MMR ranking**, **Personalized PageRank synergy scoring**, and **deterministic citation auditing** to synthesize verifiable 4-hop causal pathways (`Drug → Active Compound → Human Target → Disease`).*

[Quick Start](#-quick-start) · [Innovations](#-algorithmic--engineering-innovations) · [Live Studio](#-web-studio-showcase) · [Architecture](#-architecture) · [MCP Server](#-native-mcp-integration) · [Benchmarks](#-benchmarks) · [Roadmap](#-roadmap)

</div>

---

## ✨ Why HerbAgent?

Complex multi-component therapeutics (botanical drugs, polyherbal formulas, natural product libraries) operate through **multi-compound → multi-target → multi-pathway** synergy that breaks single-target drug discovery pipelines — and causes standalone LLMs to hallucinate unverified molecular pathways (**only 4.1% KG verifiability for Pure LLM**).

**HerbAgent** solves this with a specialized **7-Agent Generate–Debate–Evolve** architecture inspired by AI Co-Scientist workflows, backed by **17 domain tools** and an **in-memory 94,951-edge knowledge graph** (zero external DB setup required):

| Capability | What HerbAgent Delivers |
|---|---|
| **7-Agent Generate–Debate–Evolve** | `Planner` · `Similarity` · `Generation` · `Ranking` · `Reflection` · `Evolution` · `Meta-Review` collaborating via a shared **Blackboard** & live SSE event bus (up to 2 refinement rounds). |
| **17 Scientific Tools** | **9 KG tools** (multi-hop beam search, entity linking, verification), **6 Bioinformatics tools** (KEGG/GO enrichment in Python/R, STRING v12 PPI, UniProt, ADMET drug-likeness, PubChem SEA fingerprints, AlphaFold DB), **2 Literature tools** (Europe PMC co-occurrence, PubMed). |
| **Zero-Shot Generalization** | Handles drugs **absent from the KG** via formula decomposition with Jun-Chen-Zuo-Shi weighting, constituent inference, and **PubChem CACTVS Tanimoto ≥ 0.85** structural similarity target transfer (SEA). |
| **Native MCP Server** | Run `herbagent mcp` to expose all 17 pharmacology tools + end-to-end MoA reasoning directly inside **Claude Desktop, Cursor, OpenCode**, or any MCP-compatible agent host. |
| **Provider-Agnostic LLM Layer** | Works out-of-the-box with **DeepSeek, OpenAI, Qwen, OpenRouter, vLLM, and Ollama**, featuring **Adaptive Reasoning-Effort Routing** (`fast` / `standard` / `slow`) for optimal cost/accuracy trade-offs. |
| **Interactive Web Studio** | Minimalist real-time workspace with live collaboration trace, live hypothesis pool, Sankey pathway flows, animated architecture replay, comparative benchmarks, and interactive KG exploration. |

---

## 🧠 Algorithmic & Engineering Innovations

Unlike prompt-chaining wrappers, **HerbAgent** implements formal probabilistic, graph-theoretic, and systems-engineering foundations (`herbagent/algorithms/` & `herbagent/engine/`):

| Module | Algorithm / Architecture | What Problem It Solves |
|---|---|---|
| `algorithms/repurposing.py` | **Reverse Disease-Centric Drug Repurposing** | Screens all 504 botanical drugs & 14,315 compounds against any target disease via hypergeometric target enrichment (BH FDR) & multi-compound convergence — sub-second, **zero API key required**. |
| `algorithms/combination_synergy.py` | **Network Separation Synergy ($s_{AB}$)** | Implements the Menche–Cheng network proximity metric $s_{AB} = \langle d_{AB} \rangle - (\langle d_{AA}\rangle + \langle d_{BB}\rangle)/2$ on the human PPI graph to classify complementary synergy vs. overlapping potentiation. |
| `algorithms/belief_fusion.py` | **Dempster–Shafer Multi-Modal Belief Fusion** | Maps KG tiers, PubMed co-occurrence, KEGG enrichment, STRING PPI, and peer review into `(belief, disbelief, uncertainty)` mass triples combined via Dempster's rule with explicit inter-modality conflict coefficient $K$. |
| `algorithms/tournament.py` | **Bradley–Terry MLE + RRF + Submodular MMR** | Solves latent tournament ratings via Minorization–Maximization, fuses heterogeneous scales via Reciprocal Rank Fusion, and selects Top-$K$ pathways maximizing $\lambda \cdot \text{Rel}(h) - (1-\lambda)\max_{s\in S}\text{Sim}(h,s)$ to prevent hub-compound collapse. |
| `algorithms/network_synergy.py` | **Personalized PageRank (PPR) & Multi-Component Synergy Index (MCSI)** | Models tripartite `Compound → Target → Disease` subgraphs to quantify global topological centrality and Shannon-entropy-weighted multi-compound convergence. |
| `algorithms/grounding.py` | **Deterministic Claim Auditor & Inline Citation Binder** | Programmatically verifies every generated pathway explanation against verified entities & PMIDs, flags hallucinated citations, and binds structured `[KG:...]` / `[PMID:...]` / `[KEGG:...]` provenance badges. |
| `engine/dag.py` & `observability.py` | **Observable Stage Runner, Circuit Breaker & Prometheus `/metrics`** | Per-stage fault isolation and latency telemetry (`ExecutionReport`), sliding-failure circuit breaking, Pydantic v2 contracts, `X-Request-ID` tracing, synchronous `/api/analyze/sync` & SSE `/api/analyze`, and Prometheus metrics exposition. |

---

## 🖥️ Web Studio Showcase

<table>
  <tr>
    <td width="50%">
      <img src="assets/ui_discovery.png" alt="Reverse Repurposing & Combination Synergy Lab"/>
      <p align="center"><b>Zero-API-Key Discovery Lab</b> — Sub-second reverse disease repurposing (BH FDR) &amp; Menche–Cheng <i>s<sub>AB</sub></i> combination synergy</p>
    </td>
    <td width="50%">
      <img src="assets/ui_demo_huoxiang.png" alt="Live Multi-Agent Trace & Sankey"/>
      <p align="center"><b>Zero-Shot Formula Discovery</b> — Real-time agent collaboration trace, formula decomposition &amp; Sankey flow</p>
    </td>
  </tr>
  <tr>
    <td width="50%">
      <img src="assets/ui_architecture.png" alt="Animated Multi-Agent Architecture"/>
      <p align="center"><b>Live Architecture &amp; Replay</b> — Interactive 7-agent circular workflow with animated tool-call particle trails</p>
    </td>
    <td width="50%">
      <img src="assets/ui_evaluation.png" alt="Comparative Benchmark Dashboard"/>
      <p align="center"><b>Open Benchmark Dashboard</b> — Side-by-side MAS vs. ReAct vs. KG vs. LLM metrics, ablations &amp; LLM-Judge</p>
    </td>
  </tr>
  <tr>
    <td width="50%">
      <img src="assets/ui_graph.png" alt="Interactive Knowledge Graph Explorer"/>
      <p align="center"><b>Interactive Knowledge Atlas</b> — 504 herbs, 14,315 compounds, 4,968 targets &amp; 1,416 diseases with multi-hop expansion</p>
    </td>
    <td width="50%">
      <img src="assets/ui_dataset.png" alt="Stratified 4-Hop Benchmark Dataset"/>
      <p align="center"><b>500-Pathway Benchmark Browser</b> — Stratified across 20 pharmacological categories &amp; 13 disease systems (xlsx/jsonl)</p>
    </td>
  </tr>
</table>

---

## 🏗️ Architecture

<p align="center">
  <img src="assets/architecture.svg" alt="HerbAgent Architecture" width="100%"/>
</p>

1. **Planner** parses natural-language queries, performs multi-lingual entity linking (CN/EN/Latin/Pinyin/Gene Symbols/Aliases), recalls domain exemplars, and routes reasoning effort (`fast` / `standard` / `slow`).
2. **Similarity** activates for **unseen drugs**, inferring formula compositions or active constituents and transferring targets via **PubChem CACTVS fingerprint similarity (SEA, Tanimoto ≥ 0.85)**, plus deduplicating redundant hypotheses (`Tanimoto ≥ 0.90`).
3. **Generation** runs deterministic **KG Beam Search with backtracking pruning**, scoring thousands of candidate 4-hop chains with a **13-feature logistic-regression ranker** calibrated on 322,856 training candidates + LLM pharmacological priors.
4. **Reflection ↔ Evolution Loop** verifies Top-14 hypotheses against **KEGG/GO enrichment, STRING v12 PPI networks, and Europe PMC/PubMed co-occurrence**, critiques each path (`keep` / `revise` / `reject`), and performs targeted weak-hop mutation with elitist selection.
5. **Ranking & Meta-Review** fuse multi-source evidence with single-call **listwise tournament reranking** and synthesize a faithful Top-8 report with PMID citations, confidence calibration, and explicit limitations.

See [docs/architecture.md](docs/architecture.md) for algorithmic details.

---

## 🚀 Quick Start

### Option 1: Local Python Install (30 seconds)

```bash
git clone https://github.com/hwfengcs/HerbAgent.git
cd HerbAgent

python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Configure your LLM API key (DeepSeek / OpenAI / Qwen / OpenRouter / Ollama)
cp .env.example .env

# Launch Web Studio at http://127.0.0.1:8000
herbagent serve

# Or launch in Offline Mode (no API key needed to explore KG, benchmarks & 8 real-run demos!)
herbagent serve --offline
```

### Option 2: Docker Compose

```bash
cp .env.example .env
docker compose up --build
# Open http://127.0.0.1:8000 (API docs at /docs)
```

### Option 3: Python SDK & CLI

```python
from herbagent import MultiAgentSystem

mas = MultiAgentSystem()
result = mas.run("What is the mechanism of action of Huoxiang Zhengqi Pills?")

for p in result["answer"]["paths"]:
    print(f"[{p['rank']}] {p['drug']} → {p['ingredient']['name']} → {p['target']['symbol']} → {p['disease']['name']}")
    print("    ", p["explanation"])
```

```bash
# Zero-API-Key instant discovery CLI commands (sub-second, local KG)
herbagent repurpose "糖尿病" --top-k 10
herbagent synergy "人参" "丹参"

# Full multi-agent LLM mechanism analysis
herbagent analyze "丹参发挥药效的物质基础和作用靶点是什么?" --thinking auto

# Inspect KG & model info
herbagent info

# Run full offline test suite (31 unit, algorithm, discovery, API & MCP tests)
pytest -v
```

---

## 🔌 Native MCP Integration

Plug **HerbAgent**'s 17 pharmacology tools & multi-agent MoA discovery engine directly into **Claude Desktop**, **Cursor**, or **OpenCode** via the **Model Context Protocol (MCP)**:

```json
{
  "mcpServers": {
    "herbagent": {
      "command": "herbagent",
      "args": ["mcp"],
      "env": {
        "LLM_API_KEY": "sk-your-api-key",
        "LLM_BASE_URL": "https://api.deepseek.com",
        "LLM_MODEL": "deepseek-chat"
      }
    }
  }
}
```

Exposes **20 MCP tools** (`search_entity`, `find_mechanism_paths`, `verify_path`, `enrichment_analysis`, `ppi_network`, `similar_compounds`, `protein_structure`, `literature_cooccurrence`, `pubmed_search`, `analyze_mechanism`, `repurpose_for_disease`, `analyze_pair_synergy`, etc.) and **2 MCP resources** (`herbagent://kg/stats`, `herbagent://architecture`). See [docs/tools_and_mcp.md](docs/tools_and_mcp.md).

---

## 📊 Benchmarks

Evaluated on our standardized, drug-disjoint 4-hop polypharmacology benchmark (**500 sampled reference pathways across 220 drugs**: 179 seen herbs, 39 masked unseen herbs, 2 multi-herb formulas). All systems output Top-8 pathways per drug using the identical LLM backbone and 17-tool registry:

| System | Ref-Precision@8 | Path-Hit@8 | MRR@8 | Compound Hit@8 | Target Hit@8 | Disease Hit@8 | KG Verifiability | Avg Latency | Cost / Drug |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| **HerbAgent (MAS)** | **71.56%** | **4.80%** | **0.0172** | **46.80%** | **36.20%** | **32.80%** | **89.09%** | 52.2s | $0.0137 |
| ReAct (Single Agent) | 49.39% | 1.20% | 0.0037 | 36.20% | 21.60% | 18.80% | 85.91% | 25.4s | $0.0086 |
| KG-Heuristic (No LLM) | 57.33% | 2.60% | 0.0057 | 32.20% | 18.40% | 20.00% | 82.27% | 0.1s | $0.0000 |
| Pure LLM (No Tools) | 2.78% | 0.00% | 0.0000 | 18.00% | 11.00% | 6.80% | 4.09% | 25.4s | $0.0055 |

### Key Ablation Findings (61-Drug Stratified Subset)

- **Full HerbAgent**: `71.40%` Ref-Precision@8
- **w/o Reflection & Evolution**: `54.10%` (**−17.3 pp**) — multi-round critique & targeted mutation is the largest performance driver
- **w/o Literature Verification**: `56.97%` (**−14.4 pp**) — Europe PMC/PubMed co-occurrence grounding dramatically reduces false positives
- **All-Fast Mode**: `71.72%` in `16.6s` (**3.1× faster** with a modest dip in KG verifiability on unseen drugs)

> **Scientific Transparency**: Reference pools are weakly supervised via KG topology and literature co-occurrence and are *not* clinical efficacy ground truth. In blind LLM-as-a-Judge evaluation (60 drugs), ReAct scored higher on narrative fluency (`4.30/5` vs `3.94/5`) while HerbAgent led Ref-Precision@8 by **+22.17 pp**. Full tables, scenario splits, and error analysis are documented in [docs/benchmarks.md](docs/benchmarks.md).

---

## 📁 Project Structure

```text
HerbAgent/
├── herbagent/                 # Core Python package
│   ├── algorithms/            # DST belief fusion, Bradley-Terry/RRF/MMR, PPR synergy & citation auditor
│   ├── engine/                # Observable DAG telemetry, circuit breaker, Prometheus metrics & Pydantic v2
│   ├── agents/                # 7 specialized agents, Blackboard state, prompts & scoring
│   ├── kg/                    # In-memory polypharmacology KG, masked views & entity linker
│   ├── tools/                 # 17 KG, Bioinformatics & Literature tools + SQLite HTTP cache
│   ├── baselines/             # ReAct single-agent, Pure LLM, and KG-Heuristic baselines
│   ├── server/                # FastAPI SSE streaming server & KG Explorer API
│   ├── mcp_server.py          # Native Model Context Protocol (MCP) JSON-RPC 2.0 server
│   ├── orchestrator.py        # Generate–Debate–Evolve Supervisor workflow
│   ├── llm.py                 # Multi-provider OpenAI-compatible client & reasoning router
│   └── cli.py                 # Unified CLI (serve / analyze / mcp / info)
├── frontend/                  # Zero-build minimalist Web Studio (HTML/CSS/ES Modules + ECharts)
├── data/                      # Pre-built KG Parquet tables, 500-pathway benchmark & 8 demos
├── experiments/results/       # Benchmark metrics, ablations & LLM-as-a-Judge summaries
├── scripts/                   # Deterministic end-to-end KG build, ranker training & eval scripts
├── tests/                     # Fully offline pytest suite (core, FastAPI & MCP)
└── docs/                      # Architecture, tools/MCP, benchmarks & data pipeline guides
```

---

## 🗺️ Roadmap

- [x] **v0.2** — 7-agent Generate–Debate–Evolve engine, 17 KG/Bio/Lit tools, multi-provider LLM router, native MCP server, Docker & CI, interactive Web Studio
- [x] **v0.3** — Dempster–Shafer multi-modal belief fusion, Bradley–Terry MLE + RRF + Submodular MMR selection, Personalized PageRank network synergy (`MCSI`), deterministic claim auditor & inline citation binding, DAG stage telemetry & Prometheus `/metrics`
- [x] **v0.4** — Bi-directional **Discovery Lab** (zero-API-key reverse disease repurposing with BH FDR + Menche–Cheng $s_{AB}$ network combination synergy) across Web Studio, REST API, CLI & 20 MCP tools
- [ ] **v0.5** — Structure-based 3D validation plugin (AutoDock Vina / DiffDock / Boltz-2 binding affinity scoring directly on AlphaFold pockets) & directional modulation polarity (activation vs. inhibition)
- [ ] **v0.6** — Single-cell & transcriptomic perturbation grounding (LINCS L1000 / CMap) + trajectory-level RL optimization

---

## 📜 Citation & License

Released under the [Apache 2.0 License](LICENSE). If HerbAgent accelerates your research, please consider giving us a ⭐ and citing:

```bibtex
@software{herbagent2026,
  title  = {HerbAgent: Multi-Agent AI Co-Scientist for Polypharmacology and Mechanism-of-Action Discovery},
  author = {HerbAgent Contributors},
  year   = {2026},
  url    = {https://github.com/hwfengcs/HerbAgent}
}
```

> **Disclaimer**: HerbAgent is intended strictly for computational pharmacology research and hypothesis generation. Outputs do not constitute medical advice, clinical diagnosis, or prescribing guidance.