递归语言模型代理

MCP-RLM是一个开源实现的递归语言模型架构,通过程序分解和递归查询使大型语言模型能够处理远超其上下文窗口限制的文档。

  • by MuhammadIndar
  • Python
  • 本地部署
  • 11 星标
  • 更新于
在 GitHub 查看 MuhammadIndar/MCP-RLM

使用说明

MCP-RLM

递归语言模型代理

大型语言模型的无限上下文推理

特性 • 安装 • 配置 • 用法 • 建筑



📋 概述

MCP-RLM 是 递归语言模型(RLMs) 麻省理工学院CSAIL的研究人员介绍的架构(Zhang等人,2025)。它使LLM能够通过编程分解和递归查询来处理远远超出其上下文窗口限制的文档。

挑战

传统LLM方法 MCP-RLM方法
❌ 仅限于4K-128K令牌上下文窗口 ✅ 无缝处理超过1000万个代币
❌ 上下文退化(“中间丢失”) ✅ 通过分块分析保持准确性
❌ 长文档很贵(15/100万美元代币) ✅ 具有成本效益(3/10万美元代币,节省80%)
❌ 单程处理瓶颈 ✅ 并行递归分解

✨ 特性

核心能力

  • 无限上下文处理 -处理带有数百万代币的文档
  • 多提供商支持 -OpenRouter、OpenAI、Anthropic、Ollama
  • 成本优化 -两层架构可将成本降低70-80%
  • 高精度 -孤立块分析可防止幻觉

技术亮点

  • MCP协议集成 -适用于克劳德桌面、光标等。
  • 灵活的供应商系统 -混合搭配LLM提供商
  • Python REPL引擎 -查询规划的动态代码生成
  • 免费套餐可用 -使用OpenRouter的免费型号

🏗 建筑

MCP-RLM采用 双层代理系统 将战略规划与执行分开:

graph TB
    subgraph Input
        A[User Query]
        B[Large Document<br/>10M+ tokens]
    end
    
    subgraph "Root Agent (Planner)"
        C[Analyze Metadata]
        D[Generate Strategy]
        E[Write Python Code]
    end
    
    subgraph "Execution Layer"
        F[Python REPL]
        G[Chunk Manager]
    end
    
    subgraph "Sub Agents (Workers)"
        H1[Worker 1]
        H2[Worker 2]
        H3[Worker N]
    end
    
    subgraph Output
        I[Aggregated Results]
        J[Final Answer]
    end
    
    A --> C
    B --> C
    C --> D
    D --> E
    E --> F
    F --> G
    G --> H1
    G --> H2
    G --> H3
    H1 --> I
    H2 --> I
    H3 --> I
    I --> J
    
    style A fill:#e3f2fd
    style B fill:#e3f2fd
    style C fill:#fff9c4
    style D fill:#fff9c4
    style E fill:#fff9c4
    style F fill:#f3e5f5
    style G fill:#f3e5f5
    style H1 fill:#e8f5e9
    style H2 fill:#e8f5e9
    style H3 fill:#e8f5e9
    style I fill:#fce4ec
    style J fill:#fce4ec

代理角色

代理 责任 特征 模型建议
根代理 战略规划和代码生成 •仅查看元数据
•生成Python策略
•每次查询调用5-10次
•克劳德3.5十四行诗
•GPT-4o
•西北风大
子代理 块级数据提取 •读取小段
•提取特定信息
•拨打100-1000+次
•GPT-4o-mini
•克劳德·海库
•Qwen 2.5(免费)

🚀 安装

先决条件

# Required
- Python 3.10 or higher
- pip package manager

# API Keys (choose at least one)
- OpenRouter API key (recommended for free tier)
- OpenAI API key
- Anthropic API key
- Ollama (for local deployment)

快速开始

# Clone the repository
git clone https://github.com/MuhammadIndar/MCP-RLM.git
cd MCP-RLM

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Linux/macOS:
source venv/bin/activate
# On Windows:
venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Configure environment
cp .env.EXAMPLE .env
# Edit .env with your API keys

# Start the server
python server.py

预期产量:

MCP RLM Server Started...
Listening on stdio...

⚙ 配置

1.环境设置

复制示例环境文件:

cp .env.EXAMPLE .env

编辑 .env 使用您的凭据:

# OpenRouter (Recommended - includes free tier)
OPENROUTER_API_KEY=sk-or-v1-xxxxx

# OpenAI Official
OPENAI_API_KEY=sk-proj-xxxxx

# Anthropic Official  
ANTHROPIC_API_KEY=sk-ant-xxxxx

# Ollama Local (optional, set to 'dummy' if not used)
OLLAMA_API_KEY=dummy

2.提供商配置

这 config.yaml 文件定义了可用的LLM提供程序:

providers:
  openrouter:
    type: "openai_compatible"
    base_url: "https://openrouter.ai/api/v1"
    api_key_env: "OPENROUTER_API_KEY"
  
  ollama_local:
    type: "openai_compatible"
    base_url: "http://localhost:11434/v1"
    api_key_env: "OLLAMA_API_KEY"
  
  openai_official:
    type: "openai_compatible"
    base_url: "https://api.openai.com/v1"
    api_key_env: "OPENAI_API_KEY"
  
  anthropic_official:
    type: "anthropic"
    api_key_env: "ANTHROPIC_API_KEY"

3.代理配置

配置为每个代理供电的模型:

agents:
  root:
    provider_ref: "openrouter"
    model: "anthropic/claude-3.5-sonnet"
    temperature: 0.0
    max_tokens: 4096
  
  sub:
    provider_ref: "openrouter"
    model: "qwen/qwen-2.5-vl-7b-instruct:free"
    temperature: 0.0
    max_tokens: 1000

system:
  max_loops: 5  # Maximum refinement iterations

推荐配置

Use Case Root Agent Sub Agent Provider Cost
Free Tier mistral-small-3.1:free qwen-2.5-vl-7b:free OpenRouter $0
Best Performance claude-3.5-sonnet gpt-4o-mini Mixed $$
Cost Optimized gpt-4o gpt-4o-mini OpenAI $
Privacy First claude-3.5-sonnet llama-3.1-8b Anthropic + Ollama $$
Fully Local llama-3.1-70b llama-3.1-8b Ollama $0

💻 MCP客户端集成

支持的客户

MCP-RLM可与任何兼容MCP的客户端集成:

客户端 平台 用例
克劳德桌面 桌面应用程序 通用人工智能助手
光标 IDE 代码分析和开发
反重力 IDE 人工智能驱动的开发

配置说明

Claude Desktop

1.查找配置文件

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • 窗户: %APPDATA%\Claude\claude_desktop_config.json

2.添加服务器配置

{
  "mcpServers": {
    "rlm-researcher": {
      "command": "/absolute/path/to/MCP-RLM/venv/bin/python",
      "args": ["/absolute/path/to/MCP-RLM/server.py"]
    }
  }
}

3.重新启动克劳德桌面

这 analyze_massive_document 工具现在将可用。

示例用法:

Use the analyze_massive_document tool to read /path/to/large_log.txt 
and find all ERROR entries from the last 24 hours
Cursor IDE

1.打开MCP设置

  • 导航至 设置 → 特性 → 主控程序

2.添加新服务器

  • 点击 +添加新的MCP服务器
  • 填写配置:
字段 值
姓名 RLM-Researcher
类型 stdio
指挥部 /absolute/path/to/MCP-RLM/venv/bin/python
Args ["/absolute/path/to/MCP-RLM/server.py"]

3.保存并验证

  • 绿色指示灯=已连接✅
  • 红色指示灯=配置错误❌
Antigravity IDE

选项A:通过用户界面

  1. 点击 ... 代理面板中的菜单
  2. 选择 管理MCP服务器
  3. 使用与Cursor相同的配置添加服务器

选项B:手动配置

编辑 ~/.gemini/antigravity/mcp_config.json:

{
  "mcpServers": {
    "rlm-researcher": {
      "command": "/absolute/path/to/MCP-RLM/venv/bin/python",
      "args": ["/absolute/path/to/MCP-RLM/server.py"],
      "enabled": true
    }
  }
}

📖 用法

可用工具

analyze_massive_document(file_path: str, query: str)

使用递归分解分析大型文档。

参数:

  • file_path (string):文档的绝对路径
  • query (string):关于文档的自然语言查询

退货: 分析结果为文本

查询示例

# Log Analysis
"Analyze /var/log/nginx/access.log and identify the top 10 IP addresses 
 making requests, along with their request patterns"

# Codebase Security Audit
"Scan the entire /src directory and find all instances where user input 
 is directly used in SQL queries without sanitization"

# Research Paper Synthesis
"Read all PDF files in /papers/machine-learning/ and summarize 
 the common evaluation metrics used across studies"

# Configuration Validation
"Parse /etc/config/*.yaml files and verify that all required 
 security parameters are present and properly configured"

性能指标

基于OpenRouter免费层模型的测试:

文档大小 子代理呼叫 处理时间 成本(免费层)
10K代币 ~10 10秒 0.00美元
10万个代币 ~100 1分钟 0.00美元
1M代币 ~500 5分钟 0.00美元
1000万代币 ~2000 20分钟 0.00美元

注意:时间因型号速度和网络延迟而异


📁 项目结构

MCP-RLM/
├── assets/
│   └── RLM.png              # Architecture diagram
│
├── .env.EXAMPLE             # Environment variables template
├── .gitignore               # Git ignore patterns
├── LICENSE                  # MIT License
├── README.md                # This documentation
├── config.yaml              # Provider & agent configuration
├── requirements.txt         # Python dependencies
│
├── server.py                # MCP server entry point
├── rlm_engine.py            # Core RLM recursive logic
├── llm_factory.py           # Multi-provider LLM abstraction
└── prompts.py               # System prompts for agents

核心组件

文件 目的
server.py 使用FastMCP实现MCP服务器
rlm_engine.py 使用Python REPL的递归执行引擎
llm_factory.py OpenAI/Anthropic/Ollama的统一接口
prompts.py 根代理策略的系统提示
config.yaml 提供程序和代理配置

🔬 研究基金会

该实施基于来自 MIT CSAIL 的:

递归语言模型
Alex L.Zhang、Tim Kraska、Omar Khattab
麻省理工学院计算机科学与人工智能实验室,2025年
📄 arXiv:2512.24601

关键贡献

概念 描述
程序分解 将长提示视为可通过代码访问的外部数据库
递归自查询 将复杂的查询分解为可管理的子问题
两层技术模型 将战略规划与执行分开,以提高成本效益
无限缩放 处理比上下文窗口大几个数量级的文档

性能提升

根据该论文,RLM实现了:

  • 准确率94% 大海捞针任务(标准LLM为23%)
  • 成本降低79% 与加载完整上下文相比
  • 线性缩放 使用文档大小而不是二次型

🤝 贡献

欢迎投稿!以下是您可以提供帮助的方式:

  1. 分叉存储库
  2. 创建要素分支 (git checkout -b feature/amazing-feature)
  3. 提交您的更改 (git commit -m 'Add amazing feature')
  4. 推到分支 (git push origin feature/amazing-feature)
  5. 打开拉取请求

开发设置

# Install development dependencies
pip install -r requirements.txt

# Run linting
flake8 *.py

# Run type checking
mypy *.py

📄 许可证

该项目根据 MIT许可证 -看看 许可证 文件以获取详细信息。

MIT License - Copyright (c) 2025 MCP-RLM Contributors

致谢

  • MIT CSAIL 的 -RLM的原创性研究及其理论基础
  • Anthropic -模型上下文协议规范和Claude模型
  • 开放路由 -免费访问多个LLM提供商
  • 奥拉玛 -本地LLM部署基础架构

📞 支持


如果你觉得这个项目有用,请考虑给它一个⭐