ModelInfo

类 ModelInfo 在 core/model_registry.py: 模型信息 | 方法: to_dict

class ModelInfo:
    """模型信息"""
    id: str                    # 模型唯一ID
    name: str                  # 显示名称
    provider: ModelProvider    # 提供商
    model_type: ModelType      # 模型类型
    model_id: str             # API模型ID
    description: str          # 描述
    context_length: int        # 上下文长度
    parameters: str           # 参数量
    pricing: Dict[str, Any]   # 定价信息
    capabilities: List[str]    # 能力列表
    rate_limits: Dict[str, int]  # 速率限制
    is_free: bool             # 是否免费
    reliability: float = 1.0  # 可靠性评分(0-1)
    latency_avg: float = 0.0  # 平均延迟(ms)
    usage_count: int = 0      # 使用次数
    last_used: Optional[float] = None  # 最后使用时间

    def to_dict(self) -> Dict:
        return asdict(self)


ModelRegistry

类 ModelRegistry 在 core/model_registry.py: 模型注册表管理器 | 方法: __init__, load_builtin_models, add_model, remove_model, get_model, get, list_models, get_models_by_capability, recommend_model, update_model_stats, get_provider_stats, export_config, import_config, save_to_file, load_from_file

class ModelRegistry:
    """模型注册表管理器"""

    def __init__(self):
        self.models: Dict[str, ModelInfo] = {}
        self.provider_configs: Dict[str, Dict] = {}
        self.load_builtin_models()

    def load_builtin_models(self):
        """加载内置模型配置"""

        # NVIDIA NIM 模型 (已验证可用)
        nim_models = [
            # === 已验证可用 (2025-05测试) ===
            ModelInfo(
                id="nim_nemotron_3_super",
                name="Nemotron-3 Super 120B",
                provider=ModelProvider.NVIDIA_NIM,
                model_type=ModelType.TOOL_USE,
                model_id="nvidia/nemotron-3-super-120b-a12b",
                description="Nemotron-3 Super 120B MoE, 1M上下文, 工具调用强",
                context_length=1000000, parameters="120B MoE",
                pricing={"cost": 0}, capabilities=["tool_use", "reasoning", "planning", "long_context"],
                rate_limits={"rpm": 40, "tpm": 10000}, is_free=True, reliability=0.85, latency_avg=7000
            ),
            ModelInfo(
                id="nim_llama4_maverick",
                name="Llama-4 Maverick 17B",
                provider=ModelProvider.NVIDIA_NIM,
                model_type=ModelType.CHAT,
                model_id="meta/llama-4-maverick-17b-128e-instruct",
                description="Llama-4 Maverick 17B MoE, 快速对话",
                context_length=131000, parameters="17B MoE",
                pricing={"cost": 0}, capabilities=["chat", "fast_response", "instruction_following"],
                rate_limits={"rpm": 40, "tpm": 10000}, is_free=True, reliability=0.85, latency_avg=660
            ),
            ModelInfo(
                id="nim_llama33_70b",
                name="Llama-3.3 70B Instruct",
                provider=ModelProvider.NVIDIA_NIM,
                model_type=ModelType.CHAT,
                model_id="meta/llama-3.3-70b-instruct",
                description="Llama-3.3 70B, 稳定对话",
                context_length=128000, parameters="70B",
                pricing={"cost": 0}, ca


方法 ModelRegistry.load_builtin_models():
        """加载内置模型配置"""

        # NVIDIA NIM 模型 (已验证可用)
        nim_models = [

def load_builtin_models(self):
        """加载内置模型配置"""

        # NVIDIA NIM 模型 (已验证可用)
        nim_models = [
            # === 已验证可用 (2025-05测试) ===
            ModelInfo(
                id="nim_nemotron_3_super",
                name="Nemotron-3 Super 120B",
                provider=ModelProvider.NVIDIA_NIM,
                model_type=ModelType.TOOL_USE,
                model_id="nvidia/nemotron-3-super-120b-a12b",
                description="Nemotron-3 Super 120B MoE, 1M上下文, 工具调用强",
                context_length=1000000, parameters="120B MoE",
                pricing={"cost": 0}, capabilities=["tool_use", "reasoning", "planning", "long_context"],
                rate_limits={"rpm": 40, "tpm": 10000}, is_free=True, reliability=0.85, latency_avg=7000
            ),
            ModelInfo(
                id="nim_llama4_maverick",
                name="Llama-4 Maverick 17B",
                provider=ModelProvider.NVIDIA_NIM,
                model_type=ModelType.CHAT,
                model_id="meta/llama-4


方法 ModelRegistry.add_model():
        """添加新模型"""
        self.models[model.id] = model
        print(f"[模型注册表] 添加模型: {model.name

def add_model(self):
        """添加新模型"""
        self.models[model.id] = model
        print(f"[模型注册表] 添加模型: {model.name} ({model.id})")


方法 ModelRegistry.remove_model():
        """移除模型"""
        if model_id in self.models:
            del self.models[model_id]

def remove_model(self):
        """移除模型"""
        if model_id in self.models:
            del self.models[model_id]
            print(f"[模型注册表] 移除模型: {model_id}")


方法 ModelRegistry.update_model_stats():
        """更新模型使用统计"""
        if model_id in self.models:
            model = self.models[model_id

def update_model_stats(self):
        """更新模型使用统计"""
        if model_id in self.models:
            model = self.models[model_id]
            model.usage_count += 1
            model.last_used = time.time()

            # 更新平均延迟
            if model.latency_avg == 0:
                model.latency_avg = latency
            else:
                model.latency_avg = model.latency_avg * 0.9 + latency * 0.1

            # 更新可靠性
            if success:
                model.reliability = min(1.0, model.reliability * 0.95 + 0.05)
            else:
                model.reliability = max(0.1, model.reliability * 0.9 - 0.1)

            print(f"[模型注册表] 更新统计: {model.name} 延迟={latency}ms 成功={success}")


方法 ModelRegistry.import_config():
        """导入配置"""
        self.models.clear()
        for model_id, model_data in config.get("mode

def import_config(self):
        """导入配置"""
        self.models.clear()
        for model_id, model_data in config.get("models", {}).items():
            model = ModelInfo(**model_data)
            self.models[model_id] = model

        self.provider_configs = config.get("provider_configs", {})


方法 ModelRegistry.save_to_file():
        """保存配置到文件"""
        config = self.export_config()
        with open(filepath, 'w', encodi

def save_to_file(self):
        """保存配置到文件"""
        config = self.export_config()
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=2)


方法 ModelRegistry.load_from_file():
        """从文件加载配置"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:

def load_from_file(self):
        """从文件加载配置"""
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                config = json.load(f)
            self.import_config(config)
            print(f"[模型注册表] 从 {filepath} 加载了 {len(self.models)} 个模型")
        except Exception as e:
            print(f"[模型注册表] 加载配置失败: {e}")

# 全局模型注册表实例
model_registry = ModelRegistry()


函数 init_default_models(registry: ModelRegistry = None) 在 core/model_registry.py: 初始化默认模型（已由ModelRegistry.__init__自动加载）

def init_default_models(registry: ModelRegistry = None):
    """初始化默认模型（已由ModelRegistry.__init__自动加载）"""
    # 内置模型在load_builtin_models中已自动加载
    # 此函数保留为外部调用接口
    pass

if __name__ == "__main__":
    # 测试模型注册表
    registry = ModelRegistry()

    print("=== 虫群模型注册表 ===\n")

    # 列出所有免费模型
    free_models = registry.list_models(only_free=True)
    print(f"免费模型总数: {len(free_models)}")
    for model in free_models[:5]:  # 显示前5个
        print(f"  - {model.name} ({model.provider.value})")
        print(f"    能力: {', '.join(model.capabilities[:3])}")
        print(f"    延迟: {model.latency_avg}ms 可靠性: {model.reliability}")
        print()

    # 推荐模型
    recommended = registry.recommend_model("coding", max_latency=1500)
    if recommended:
        print(f"推荐编码模型: {recommended.name}")
        print(f"  延迟: {recommended.latency_avg}ms 可靠性: {recommended.reliability}")
        print(f"  上下文: {recommended.context_length}")

    # 提供商统计
    provider_stats = registry.get_provider_stats()
    print("\n=== 提供商统计 ===")
    for provider, stats in provider_stats.items():
        print(f"{provider}: {stats['total_models']}模型, {stats['free_models']}免费, "
              f"平均延迟{stats['avg_latency']:.0f}ms, 总使用{stats['total_usage']}次")


文件 core/seed_model.py: 虫群v7 — 种子模型(Seed Model)
统一基座: 同一个种子，喂不同的数据长成不同的模型

设计思路:
- 虫皇模型是种子，只要喂养不同的素材，就可以长成不同的模型
- 体量大了就是虫巢/脑虫，体量小了就是个人端使用的虫后
- 功能模块是每层系统都有的
- 核心方法 grow(): 从种子生长为特定领域的模型 | 定义: class SeedModel, def __init__, def grow, def _train, def _simulated_train, def _validate_data, def _save_state, def _load_state, def get_info, def get_growth_log

#!/usr/bin/env python3
"""
虫群v7 — 种子模型(Seed Model)
统一基座: 同一个种子，喂不同的数据长成不同的模型

设计思路:
- 虫皇模型是种子，只要喂养不同的素材，就可以长成不同的模型
- 体量大了就是虫巢/脑虫，体量小了就是个人端使用的虫后
- 功能模块是每层系统都有的
- 核心方法 grow(): 从种子生长为特定领域的模型
"""

import json
import logging
import os
import time
from datetime import datetime
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

# ============================================================
# 种子模型配置
# ============================================================

SEED_CONFIGS


SeedModel

类 SeedModel 在 core/seed_model.py: 种子模型 — 虫群统一基座

    核心概念:
    1. 种子 = 初始化参数 + 训练框架
    2. grow(数据) = 训练 → 输出特定领域的模型
    3. 同一粒种子，喂物理数据长成物理老师，喂代码数据长成编程助手
    4. 体量由配置决定: drone < queen < cerebrate < hive

    当前实现: 元数据管理 + 训练调度 | 方法: __init__, grow, _train, _simulated_train, _validate_data, _save_state, _load_state, get_info, get_growth_log, list_seeds

class SeedModel:
    """
    种子模型 — 虫群统一基座

    核心概念:
    1. 种子 = 初始化参数 + 训练框架
    2. grow(数据) = 训练 → 输出特定领域的模型
    3. 同一粒种子，喂物理数据长成物理老师，喂代码数据长成编程助手
    4. 体量由配置决定: drone < queen < cerebrate < hive

    当前实现: 元数据管理 + 训练调度
    未来: 接入实际训练管线
    """

    SEEDS_DIR = "/home/admin/swarm/training/seeds"

    def __init__(self, seed_name: str = "default", role: str = "queen"):
        self.seed_name = seed_name
        self.role = role  # drone/queen/cerebrate/hive
        self.config = SEED_CONFIGS.get(role, SEED_CONFIGS["queen"])

        # 种子状态
        self.created_at = datetime.now().isoformat()
        self.growth_history: List[Dict] = []
        self.current_gen = 0  # 当前代数
        self.total_data_fed = 0  # 已喂养数据量(条)

        # 模型路径
        self.seed_dir = os.path.join(self.SEEDS_DIR, seed_name)
        self.model_path = ""
        self.is_grown = False

    # ============================================================
    # 核心方法: grow — 从种子生长为模型
    # ============================================================

    def grow(self, data_path: str, epochs: int = 2,
             learning_rate: float = 3e-4,
             description: str = "") -> Dict:
        """
        喂养数据让种子生长

        Args:
            data_path: 训练数据路径(JSON)
            epochs: 训练轮数
            learning_rate: 学习率
            description: 本次生长描述
        Returns:
            生长结果dict
        """
        start_time = time.time()

        # 验证数据
        data_info = self._validate_data(data_path)
        if not data_info["valid"]:
            return {"success": False, "error": data_info["error"]}

        # 记录生长事件
        self.current_gen += 1
        self.total_data_fed += data_info["count"]

        growth_event = {
            "gen": self.current_gen,
            "timestamp": datetime.now().isoformat(),
            "data_path": data_path,
            "data_count": data_info["count"],
            "epochs": epochs,
            "learning_rate":


文件 core/data_collector.py: 虫群v7.1 — 数据采集器
自动化收集、清洗、整理训练数据

数据来源:
  1. 对话数据: 用户日常交互产生的高质量对话
  2. 公开数据集: HuggingFace/GitHub上的中文训练数据
  3. 网络爬取: 按需爬取特定领域数据(需合规)
  4. 项目过程: 开发过程数据(日志、文档)作为验证

设计原则:
  - 质量优先: 低质量数据宁可不要
  - 自动去重: 相似内容 | 定义: class DataCollector, def __init__, def _load_data, def _load_hashes, def _save, def collect_from_chat, def collect_from_conversation, def collect_from_file, def list_public_datasets, def download_dataset

hashlib json logging os time datetime typing

#!/usr/bin/env python3
"""
虫群v7.1 — 数据采集器
自动化收集、清洗、整理训练数据

数据来源:
  1. 对话数据: 用户日常交互产生的高质量对话
  2. 公开数据集: HuggingFace/GitHub上的中文训练数据
  3. 网络爬取: 按需爬取特定领域数据(需合规)
  4. 项目过程: 开发过程数据(日志、文档)作为验证

设计原则:
  - 质量优先: 低质量数据宁可不要
  - 自动去重: 相似内容自动合并
  - 格式统一: 输出标准训练格式
  - 持续积累: 数据库式管理，不丢失
"""

import hashlib
import json
import logging
import os
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

# 数据质量评分阈值
QUALITY_CONFIG = {
    "min_leng


DataCollector

类 DataCollector 在 core/data_collector.py: 数据采集器 — 训练数据的自动积累

    使用方式:
      dc = DataCollector("my_queen")
      dc.collect_from_chat("你好", "你好！有什么可以帮你？")
      dc.collect_from_file("data.json") | 方法: __init__, _load_data, _load_hashes, _save, collect_from_chat, collect_from_conversation, collect_from_file, list_public_datasets, download_dataset, _quality_score, quality_filter, _hash_content, get_stats, export_training_data

class DataCollector:
    """
    数据采集器 — 训练数据的自动积累

    使用方式:
      dc = DataCollector("my_queen")
      dc.collect_from_chat("你好", "你好！有什么可以帮你？")
      dc.collect_from_file("data.json")
    """

    def __init__(self, model_name: str,
                 base_dir: str = "/home/admin/swarm/training/seeds"):
        self.model_name = model_name
        self.data_dir = os.path.join(base_dir, model_name, "data")
        self._data_file = os.path.join(self.data_dir, "collected_data.json")
        self._dedup_file = os.path.join(self.data_dir, "dedup_hashes.json")

        # 加载已有数据
        self._data: List[Dict] = self._load_data()
        self._hashes: set = self._load_hashes()

    def _load_data(self) -> List[Dict]:
        """加载已收集数据"""
        if os.path.exists(self._data_file):
            with open(self._data_file, "r") as f:
                return json.load(f)
        return []

    def _load_hashes(self) -> set:
        """加载去重哈希集"""
        if os.path.exists(self._dedup_file):
            with open(self._dedup_file, "r") as f:
                return set(json.load(f))
        return set()

    def _save(self):
        """保存数据"""
        os.makedirs(self.data_dir, exist_ok=True)
        with open(self._data_file, "w") as f:
            json.dump(self._data, f, indent=2, ensure_ascii=False)
        with open(self._dedup_file, "w") as f:
            json.dump(list(self._hashes), f)

    # ============================================================
    # 对话采集
    # ============================================================

    def collect_from_chat(self, user_msg: str, ai_msg: str,
                          metadata: Dict = None) -> bool:
        """
        从对话中采集一条训练数据

        Args:
            user_msg: 用户消息
            ai_msg: AI回复
            metadata: 附加信息(模型、延迟等)
        Returns:
            是否成功采集(通过质量过滤)
        """
        # 质量检查
        score = self._quality_score(user_msg, ai_msg)
        if score < QUALITY_CONFIG["min_quality_score"]:
            logger.debug


config.py

文件 core/config.py: 虫群 Swarm 统一配置加载器 | 定义: def get_config, def get_api_key, def get_model_path, def get_cloud_model, def get_swarm_config, def reload_config

"""虫群 Swarm 统一配置加载器"""
import os
import yaml
from pathlib import Path

# 项目根目录（core的上一级）
PROJECT_ROOT = Path(__file__).parent.parent

_config = None

def get_config() -> dict:
    """获取全局配置，首次调用时从config.yaml加载"""
    global _config
    if _config is None:
        config_path = PROJECT_ROOT / "config.yaml"
        if config_path.exists():
            with open(config_path, "r", encoding="utf-8") as f:
                _config = yaml.safe_load(f)
        else:
            _config = {}
    return _c


函数 reload_config() 在 core/config.py: 重新加载配置

def reload_config():
    """重新加载配置"""
    global _config
    _config = None
    return get_config()


文件 core/queen_agent.py: 虫群v7 — 虫后(Queen)个人端智能体
个人模型系统核心：元模型调度 + 记忆模型 + 任务模型树

架构:
  用户输入 → 元模型(分析/拆分/路由) → 任务模型/记忆模型/虫巢大模型 → 聚合 → 返回

虫后是每个用户的专属AI系统，所有交互的统一入口。 | 定义: class QueenAgent, def __init__, def chat, def chat_detailed, def _execute_route, def _execute_local_drone, def _execute_memory, def _execute_cloud, def _execute_moa, def _call_cloud

#!/usr/bin/env python3
"""
虫群v7 — 虫后(Queen)个人端智能体
个人模型系统核心：元模型调度 + 记忆模型 + 任务模型树

架构:
  用户输入 → 元模型(分析/拆分/路由) → 任务模型/记忆模型/虫巢大模型 → 聚合 → 返回

虫后是每个用户的专属AI系统，所有交互的统一入口。
"""

import logging
import time
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Any

from core.types import (
    SwarmRole, DroneType, ModelLocation, TaskPriority,
    DroneInfo, QueenInfo, SwarmTask, SwarmStatus,
)
from core.meta_model import MetaModel
from core.memory_model import MemoryModel, Memo


QueenAgent

类 QueenAgent 在 core/queen_agent.py: 虫后智能体 — 个人端核心

    三大组件:
    1. 元模型(MetaModel): 意图分析 → 任务拆分 → 路由决策
    2. 记忆模型(MemoryModel): 参数化个人记忆，模型即数据库
    3. 任务模型树(TaskTree): 知识树结构的按需加载任务模型群 | 方法: __init__, chat, chat_detailed, _execute_route, _execute_local_drone, _execute_memory, _execute_cloud, _execute_moa, _call_cloud, _load_config_for_api, new_conversation, get_history, get_status, get_info

class QueenAgent:
    """
    虫后智能体 — 个人端核心

    三大组件:
    1. 元模型(MetaModel): 意图分析 → 任务拆分 → 路由决策
    2. 记忆模型(MemoryModel): 参数化个人记忆，模型即数据库
    3. 任务模型树(TaskTree): 知识树结构的按需加载任务模型群
    """

    def __init__(self, user_id: str = "default", queen_name: str = ""):
        # 虫后身份
        self.queen_id = f"queen_{user_id}_{uuid.uuid4().hex[:6]}"
        self.user_id = user_id
        self.queen_name = queen_name or f"虫后-{user_id}"

        # 会话状态
        self.conversation_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self._session_history: List[Dict] = []

        # 模型注册表（兼容v6）
        self.registry = get_registry()
        init_default_models()

        # === 三大核心组件 ===
        # 1. 元模型 — 任务分析与路由
        self.meta = MetaModel(user_id=user_id)

        # 2. 记忆矩阵 — 参数化个人记忆(含任务分叉)
        self.memory_matrix = MemoryMatrix(user_id)
        self.memory = self.memory_matrix.current  # 当前活跃记忆

        # 3. 任务模型树 — 按需加载的任务模型群
        self.task_tree = TaskTree(user_id=user_id)

        # === 自动训练 + 数据采集 ===
        self.trainer = AutoTrainer(user_id, role="queen")
        self.collector = DataCollector(user_id)

        # === 推理后端 ===
        self.local_backend = get_local_backend()
        self.cloud_backend = get_glm_backend()

        # === API推理管理器（支持NIM） ===
        from core.api_inference import APIInferenceManager
        # 尝试从config.yaml读取NIM API Key
        cfg = self._load_config_for_api()
        if cfg:
            import os
            if cfg.get("nim_api_key"):
                os.environ["NIM_API_KEY"] = cfg["nim_api_key"]
            if cfg.get("glm_api_key"):
                os.environ["GLM_API_KEY"] = cfg["glm_api_key"]
        self.api_manager = APIInferenceManager.from_env()

        logger.info(f"API推理管理器: {len(self.api_manager.adapters)}提供商, {len(self.api_manager.models)}模型")

        # === MOA引擎（兼容v6，用于多模型聚合） ===
        self.moa = MOAEngine(self.registry)

        # 虫后信息


RoyalAgent

虫皇智能体 — v7兼容层，内部使用QueenAgent

类 RoyalAgent 在 core/queen_agent.py: 虫皇智能体 — v7兼容层，内部使用QueenAgent | 方法: __init__

class RoyalAgent:
    """虫皇智能体 — v7兼容层，内部使用QueenAgent"""

    def __init__(self):
        super().__init__(user_id="default", queen_name="虫皇")


文件 core/inference_service.py: 虫群v8 — 推理服务适配器

让SwarmNode对外提供真实的参数化记忆模型推理服务
聚合协议的临时服务器通过此适配器调度各节点的模型 | 定义: class InferenceService, def __init__, def infer, def store_and_learn, def get_stats, class DistributedInferenceBridge, def __init__, def register_service, def unregister_service, def dispatch_inference

#!/usr/bin/env python3
"""
虫群v8 — 推理服务适配器

让SwarmNode对外提供真实的参数化记忆模型推理服务
聚合协议的临时服务器通过此适配器调度各节点的模型
"""

import time
import hashlib
from typing import Dict, List, Optional

from core.parametric_memory import ParametricMemoryModel
from core.aggregation_protocol.types import NodeInfo

class InferenceService:
    """
    推理服务 — 包装参数化记忆模型，提供标准化推理接口

    每个SwarmNode运行一个InferenceService
    对外暴露：infer(query) → {response, confidence, latency_ms}
    """

    def __init__(self, memory_model: Param


InferenceService

类 InferenceService 在 core/inference_service.py: 推理服务 — 包装参数化记忆模型，提供标准化推理接口

    每个SwarmNode运行一个InferenceService
    对外暴露：infer(query) → {response, confidence, latency_ms} | 方法: __init__, infer, store_and_learn, get_stats

class InferenceService:
    """
    推理服务 — 包装参数化记忆模型，提供标准化推理接口

    每个SwarmNode运行一个InferenceService
    对外暴露：infer(query) → {response, confidence, latency_ms}
    """

    def __init__(self, memory_model: ParametricMemoryModel, node_id: str):
        self.memory = memory_model
        self.node_id = node_id
        self._request_count = 0
        self._total_latency_ms = 0.0

    def infer(self, query: str, max_tokens: int = 64,
              temperature: float = 0.3) -> Dict:
        """
        推理入口 — 从参数化记忆模型生成回答

        这就是"模型即数据库"的核心体现：
        不查数据库，直接从模型参数生成个性化回答
        """
        start = time.time()
        self._request_count += 1

        try:
            result = self.memory.recall(
                query, max_tokens=max_tokens, temperature=temperature
            )
            latency = (time.time() - start) * 1000
            self._total_latency_ms += latency

            return {
                "node_id": self.node_id,
                "response": result.get("response", ""),
                "confidence": result.get("confidence", 0.0),
                "source": result.get("source", "parametric"),
                "latency_ms": latency,
                "success": True,
                "error": "",
            }
        except Exception as e:
            latency = (time.time() - start) * 1000
            return {
                "node_id": self.node_id,
                "response": "",
                "confidence": 0.0,
                "source": "error",
                "latency_ms": latency,
                "success": False,
                "error": str(e),
            }

    def store_and_learn(self, user_input: str, ai_response: str,
                        memory_type: str = "chat",
                        importance: float = 0.5) -> Dict:
        """
        存储记忆并触发学习

        即时写入模式：存完即学，1-3步更新
        """
        start = time.time()
        mid = self.memory.store(
            user_input, ai_response,
            memory


DistributedInferenceBridge

类 DistributedInferenceBridge 在 core/inference_service.py: 分布式推理桥 — 聚合协议与推理服务之间的桥梁

    核心流程：
    1. 聚合协议组建临时服务器
    2. 桥接器将任务分发给各节点的InferenceService
    3. 收集结果，按策略聚合
    4. 返回最终结果

    这让聚合协议能调度真实的参数化记忆模型 | 方法: __init__, register_service, unregister_service, dispatch_inference, _aggregate, _is_similar, get_all_stats

class DistributedInferenceBridge:
    """
    分布式推理桥 — 聚合协议与推理服务之间的桥梁

    核心流程：
    1. 聚合协议组建临时服务器
    2. 桥接器将任务分发给各节点的InferenceService
    3. 收集结果，按策略聚合
    4. 返回最终结果

    这让聚合协议能调度真实的参数化记忆模型
    """

    def __init__(self):
        # node_id -> InferenceService
        self._services: Dict[str, InferenceService] = {}

    def register_service(self, node_id: str, service: InferenceService):
        """注册节点的推理服务"""
        self._services[node_id] = service

    def unregister_service(self, node_id: str):
        """注销节点的推理服务"""
        self._services.pop(node_id, None)

    def dispatch_inference(self, query: str, node_ids: List[str],
                           max_tokens: int = 64,
                           temperature: float = 0.3) -> Dict:
        """
        分发推理到多个节点

        1. 向所有指定节点发送推理请求
        2. 收集结果
        3. 聚合（置信度优先 + 内容互补）
        """
        results = []

        for nid in node_ids:
            service = self._services.get(nid)
            if not service:
                results.append({
                    "node_id": nid,
                    "response": "",
                    "confidence": 0.0,
                    "success": False,
                    "error": "服务不可用",
                })
                continue

            result = service.infer(query, max_tokens=max_tokens,
                                   temperature=temperature)
            results.append(result)

        # 聚合
        return self._aggregate(query, results)

    def _aggregate(self, query: str, results: List[Dict]) -> Dict:
        """
        聚合多节点推理结果

        策略：
        1. 过滤失败结果
        2. 按置信度排序
        3. 取最高置信度的作为主回答
        4. 其他结果作为备选
        5. 如果多个结果内容相似，提升置信度
        """
        successful = [r for r in results if r.get("success") and r.get("response")]

        if not successful:
            return {
                "response": "",
                "confidence": 0.0,
                "source": "distributed",


方法 DistributedInferenceBridge.register_service():
        """注册节点的推理服务"""
        self._services[node_id] = service

def register_service(self):
        """注册节点的推理服务"""
        self._services[node_id] = service


方法 DistributedInferenceBridge.unregister_service():
        """注销节点的推理服务"""
        self._services.pop(node_id, None)

def unregister_service(self):
        """注销节点的推理服务"""
        self._services.pop(node_id, None)


文件 core/performance_monitor.py: 虫群智能体系统 — 性能监控模块
请求统计、模型延迟、成功率追踪、告警规则 | 定义: class
class, class PerformanceMonitor, def __new__, def __init__, def record, def get_model_summary, def get_all_summaries, def get_recent_metrics, def get_hourly_stats, def get_daily_stats

json logging os threading time collections dataclasses datetime typing

#!/usr/bin/env python3
"""
虫群智能体系统 — 性能监控模块
请求统计、模型延迟、成功率追踪、告警规则
"""

import json
import logging
import os
import threading
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, List, Optional

logger = logging.getLogger(__name__)

# 默认存储路径
DEFAULT_METRICS_PATH = "/home/admin/swarm/data/metrics.json"

@dataclass
class RequestMetric:
    """单次请求指标"""
    request_id: str
    query: str


RequestMetric

类 RequestMetric 在 core/performance_monitor.py: 单次请求指标 | 方法:

class RequestMetric:
    """单次请求指标"""
    request_id: str
    query: str
    model_id: str
    latency_ms: float
    confidence: float
    success: bool
    timestamp: float = field(default_factory=time.time)
    error: str = ""


PerformanceMonitor

性能监控器 — 线程安全的请求指标收集和分析

类 PerformanceMonitor 在 core/performance_monitor.py: 性能监控器 — 线程安全的请求指标收集和分析 | 方法: __new__, __init__, record, get_model_summary, get_all_summaries, get_recent_metrics, get_hourly_stats, get_daily_stats, _window_stats, add_alert_rule, on_alert, _check_alerts, save, load, get_report

class PerformanceMonitor:
    """性能监控器 — 线程安全的请求指标收集和分析"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._initialized = False
            return cls._instance

    def __init__(self):
        if self._initialized:
            return
        self._initialized = True

        # 指标存储（最近N条）
        self._max_history = 1000
        self._metrics: deque = deque(maxlen=self._max_history)

        # 按模型汇总
        self._model_stats: Dict[str, dict] = defaultdict(lambda: {
            "total": 0, "success": 0, "fail": 0,
            "total_latency_ms": 0.0, "total_confidence": 0.0,
            "min_latency_ms": float("inf"), "max_latency_ms": 0.0,
        })

        # 时间窗口统计（最近1小时/24小时）
        self._hourly: Dict[str, deque] = defaultdict(lambda: deque(maxlen=3600))
        self._daily: Dict[str, deque] = defaultdict(lambda: deque(maxlen=86400))

        # 告警规则
        self._alerts: List[dict] = []
        self._alert_callbacks = []

        # 持久化路径
        self._metrics_path = DEFAULT_METRICS_PATH

        # 请求计数器
        self._request_counter = 0

    # ============================================================
    # 记录
    # ============================================================

    def record(self, model_id: str, latency_ms: float,
               confidence: float, success: bool,
               query: str = "", error: str = "") -> str:
        """
        记录一次请求指标，返回request_id
        """
        self._request_counter += 1
        request_id = f"req_{self._request_counter:06d}"

        metric = RequestMetric(
            request_id=request_id,
            query=query[:100],  # 只存前100字
            model_id=model_id,
            latency_ms=latency_ms,
            confidence=confidence,
            success=success,
            error=error[:200],
        )

        with self._lock:
            self._metrics.append(metri


方法 PerformanceMonitor.add_alert_rule():
        """添加告警规则"""
        self._alerts.append({
            "name": name,
            "model_id"

def add_alert_rule(self):
        """添加告警规则"""
        self._alerts.append({
            "name": name,
            "model_id": model_id,
            "min_latency_ms": min_latency_ms,
            "max_success_rate": max_success_rate,
            "min_confidence": min_confidence,
        })


方法 PerformanceMonitor.on_alert():
        """注册告警回调"""
        self._alert_callbacks.append(callback)

def on_alert(self):
        """注册告警回调"""
        self._alert_callbacks.append(callback)


save

方法 PerformanceMonitor.save():
        """保存指标到文件"""
        path = path or self._metrics_path
        os.makedirs(os.path.dirname

def save(self):
        """保存指标到文件"""
        path = path or self._metrics_path
        os.makedirs(os.path.dirname(path), exist_ok=True)
        data = {
            "request_counter": self._request_counter,
            "model_stats": dict(self._model_stats),
            "saved_at": datetime.now().isoformat(),
        }
        with open(path, "w") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)


load

方法 PerformanceMonitor.load():
        """从文件加载指标"""
        path = path or self._metrics_path
        if not os.path.exists(path)

def load(self):
        """从文件加载指标"""
        path = path or self._metrics_path
        if not os.path.exists(path):
            return
        try:
            with open(path) as f:
                data = json.load(f)
            self._request_counter = data.get("request_counter", 0)
            for mid, stats in data.get("model_stats", {}).items():
                self._model_stats[mid] = stats
            logger.info(f"性能指标已加载: {path}")
        except Exception as e:
            logger.warning(f"加载性能指标失败: {e}")

    # ============================================================
    # 报告
    # ============================================================


文件 core/unified_gateway.py: 虫群统一推理网关 Unified Inference Gateway
- 统一管理所有推理后端
- 自动路由 + 降级策略
- 支持本地/NIM/Modal/HF/香港中继 | 定义: class InferenceStrategy, class
class, def infer, def health_check, class
class, class UnifiedInferenceGateway, def __init__, def register, def unregister, def list_backends

#!/usr/bin/env python3
"""
虫群统一推理网关 Unified Inference Gateway
- 统一管理所有推理后端
- 自动路由 + 降级策略
- 支持本地/NIM/Modal/HF/香港中继
"""

import logging
from typing import Dict, List, Optional, Callable
from dataclasses import dataclass, field
from enum import Enum
import time

logger = logging.getLogger(__name__)

class InferenceStrategy(Enum):
    """推理策略"""
    AUTO = "auto"           # 自动选择最佳后端
    FAST = "fast"           # 最快响应
    QUALITY = "quality"     # 最高质量
    LOCAL_FIRST = "local"  # 本地优先
    CLOUD_FI


InferenceStrategy

类 InferenceStrategy 在 core/unified_gateway.py: 推理策略 | 方法:

class InferenceStrategy:
    """推理策略"""
    AUTO = "auto"           # 自动选择最佳后端
    FAST = "fast"           # 最快响应
    QUALITY = "quality"     # 最高质量
    LOCAL_FIRST = "local"  # 本地优先
    CLOUD_FIRST = "cloud"  # 云端优先

@dataclass


InferenceBackend

类 InferenceBackend 在 core/unified_gateway.py: 推理后端基类 | 方法: infer, health_check

class InferenceBackend:
    """推理后端基类"""
    name: str
    backend_type: str       # local/nim/modal/hf/proxy
    priority: int = 50      # 优先级（0-100）
    latency_ms: float = 0   # 上次延迟
    available: bool = True
    cost_per_1k: float = 0  # 每千token成本

    # 后端实例（由子类提供）
    instance: any = None

    def infer(self, query: str, **kwargs) -> 'InferenceResult':
        """推理接口，由子类实现"""
        raise NotImplementedError

    def health_check(self) -> bool:
        """健康检查"""
        raise NotImplementedError

@dataclass


InferenceResult

类 InferenceResult 在 core/unified_gateway.py: 推理结果 | 方法:

class InferenceResult:
    """推理结果"""
    success: bool
    answer: str = ""
    model: str = ""
    latency_ms: float = 0
    backend: str = ""
    error: str = ""
    cost: float = 0


UnifiedInferenceGateway

类 UnifiedInferenceGateway 在 core/unified_gateway.py: 统一推理网关

    用法:
        gateway = UnifiedInferenceGateway()
        gateway.register("nim", nim_backend, priority=80)
        gateway.register("local", local_backend, priority=30)

        | 方法: __init__, register, unregister, list_backends, get_backend, infer, _select_backend, _try_backend, _on_success, health_check, get_stats, reset_stats

class UnifiedInferenceGateway:
    """
    统一推理网关

    用法:
        gateway = UnifiedInferenceGateway()
        gateway.register("nim", nim_backend, priority=80)
        gateway.register("local", local_backend, priority=30)

        # 自动路由
        result = gateway.infer("你好")

        # 指定后端
        result = gateway.infer("你好", backend="nim")

        # 快速模式
        result = gateway.infer("你好", strategy="fast")
    """

    def __init__(self):
        self._backends: Dict[str, InferenceBackend] = {}
        self._default_strategy = InferenceStrategy.AUTO

        # 降级链：按顺序尝试
        self._fallback_chain: List[str] = []

        # 统计
        self._stats = {
            "total_requests": 0,
            "successful": 0,
            "failed": 0,
            "by_backend": {},
        }

    def register(self, name: str, backend: InferenceBackend,
                 priority: int = 50, fallback_after: List[str] = None):
        """
        注册推理后端

        Args:
            name: 后端名称
            backend: 后端实例
            priority: 优先级(0-100)
            fallback_after: 降级链（该后端失败后尝试的后端）
        """
        backend.priority = priority
        backend.name = name
        self._backends[name] = backend

        # 更新降级链
        if fallback_after:
            self._fallback_chain = fallback_after
        elif name not in self._fallback_chain:
            self._fallback_chain.append(name)

        logger.info(f"注册推理后端: {name} (优先级={priority}, 类型={backend.backend_type})")

    def unregister(self, name: str):
        """注销后端"""
        if name in self._backends:
            del self._backends[name]
            self._fallback_chain = [b for b in self._fallback_chain if b != name]
            logger.info(f"注销推理后端: {name}")

    def list_backends(self) -> List[Dict]:
        """列出所有后端"""
        result = []
        for name, backend in self._backends.items():
            result.append({
                "name": name,


register

方法 UnifiedInferenceGateway.register():
        """
        注册推理后端

        Args:
            name: 后端名称
            backend: 后端实例

def register(self):
        """
        注册推理后端

        Args:
            name: 后端名称
            backend: 后端实例
            priority: 优先级(0-100)
            fallback_after: 降级链（该后端失败后尝试的后端）
        """
        backend.priority = priority
        backend.name = name
        self._backends[name] = backend

        # 更新降级链
        if fallback_after:
            self._fallback_chain = fallback_after
        elif name not in self._fallback_chain:
            self._fallback_chain.append(name)

        logger.info(f"注册推理后端: {name} (优先级={priority}, 类型={backend.backend_type})")


unregister

方法 UnifiedInferenceGateway.unregister():
        """注销后端"""
        if name in self._backends:
            del self._backends[name]

def unregister(self):
        """注销后端"""
        if name in self._backends:
            del self._backends[name]
            self._fallback_chain = [b for b in self._fallback_chain if b != name]
            logger.info(f"注销推理后端: {name}")


方法 UnifiedInferenceGateway.reset_stats():
        """重置统计"""
        self._stats = {
            "total_requests": 0,
            "successful


文件 core/logging_config.py: 虫群智能体系统 — 结构化日志配置
统一日志格式、分级、轮转 | 定义: class ColoredFormatter, def format, def setup_logging, def get_logger

logging logging.handlers os sys datetime

#!/usr/bin/env python3
"""
虫群智能体系统 — 结构化日志配置
统一日志格式、分级、轮转
"""

import logging
import logging.handlers
import os
import sys
from datetime import datetime

LOG_DIR = "/home/admin/swarm/logs"
LOG_FORMAT = "%(asctime)s | %(levelname)-5s | %(name)-20s | %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

class ColoredFormatter(logging.Formatter):
    """终端彩色日志格式器"""

    COLORS = {
        logging.DEBUG: "\033[36m",     # 青色
        logging.INFO: "\033[32m",      # 绿色
        logging.WARNING: "\033[33m


ColoredFormatter

类 ColoredFormatter 在 core/logging_config.py: 终端彩色日志格式器 | 方法: format

class ColoredFormatter:
    """终端彩色日志格式器"""

    COLORS = {
        logging.DEBUG: "\033[36m",     # 青色
        logging.INFO: "\033[32m",      # 绿色
        logging.WARNING: "\033[33m",   # 黄色
        logging.ERROR: "\033[31m",     # 红色
        logging.CRITICAL: "\033[35m",  # 紫色
    }
    RESET = "\033[0m"

    def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


format

方法 ColoredFormatter.format():
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.lev

def format(self):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


函数 format(self, record) 在 core/logging_config.py:

def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        record.levelname = f"{color}{record.levelname}{self.RESET}"
        return super().format(record)


函数 setup_logging(level: str = "INFO", log_file: str = None) 在 core/logging_config.py: 配置虫群智能体日志系统

    参数:
        level: 日志级别 (DEBUG/INFO/WARNING/ERROR)
        log_file: 日志文件名（可选）

def setup_logging(level: str = "INFO", log_file: str = None):
    """
    配置虫群智能体日志系统

    参数:
        level: 日志级别 (DEBUG/INFO/WARNING/ERROR)
        log_file: 日志文件名（可选）
    """
    log_level = getattr(logging, level.upper(), logging.INFO)

    # 创建日志目录
    os.makedirs(LOG_DIR, exist_ok=True)

    # 根日志器
    root_logger = logging.getLogger("swarm")
    root_logger.setLevel(log_level)

    # 清除已有处理器
    root_logger.handlers.clear()

    # 1. 终端输出（彩色）
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(log_level)
    console_formatter = ColoredFormatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    console_handler.setFormatter(console_formatter)
    root_logger.addHandler(console_handler)

    # 2. 文件输出（按天轮转）
    if log_file is None:
        log_file = f"swarm_{datetime.now().strftime('%Y%m%d')}.log"
    file_path = os.path.join(LOG_DIR, log_file)

    file_handler = logging.handlers.TimedRotatingFileHandler(
        file_path,
        when="midnight",     # 每天轮转
        interval=1,
        backupCount=7,       # 保留7天
        encoding="utf-8",
    )
    file_handler.setLevel(log_level)
    file_formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    file_handler.setFormatter(file_formatter)
    root_logger.addHandler(file_handler)

    # 3. 错误日志单独文件
    error_path = os.path.join(LOG_DIR, "swarm_error.log")
    error_handler = logging.handlers.RotatingFileHandler(
        error_path,
        maxBytes=5*1024*1024,  # 5MB
        backupCount=3,
        encoding="utf-8",
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(file_formatter)
    root_logger.addHandler(error_handler)

    # 降低第三方库日志级别
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("flask").setLevel(logging.WARNING)
    logging.getLogger("werkzeug").setLevel(logging.WARNING)

    root_logger.info(f"日志系统初始化: 级别={level}, 文件={file_path}")
    return root_logger


types.py

文件 core/types.py: 虫群v6 — 统一类型定义

虫族生态体系：
  虫皇(Overmind)  — 最高控制中心，全局调度
  虫巢(Hive)      — 中央大模型集群，云端推理
  脑虫(Cerebrate) — 区域路由节点，任务分发
  虫后(Queen)     — 个人模型系统，用户专属
  子虫(Drone)     — 功能模型，按需启动 | 定义: class SwarmRole, class DroneType, class ModelLocation, class TaskPriority, class SwarmStatus, class
class, def to_dict, class
class, def to_dict, class
class

#!/usr/bin/env python3
"""
虫群v6 — 统一类型定义

虫族生态体系：
  虫皇(Overmind)  — 最高控制中心，全局调度
  虫巢(Hive)      — 中央大模型集群，云端推理
  脑虫(Cerebrate) — 区域路由节点，任务分发
  虫后(Queen)     — 个人模型系统，用户专属
  子虫(Drone)     — 功能模型，按需启动
"""

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Any
from datetime import datetime

# ============================================================
# 虫族角色枚举
# ============================================================

class SwarmRole(Enum


SwarmRole

类 SwarmRole 在 core/types.py: 虫族角色层级 | 方法:

class SwarmRole:
    """虫族角色层级"""
    OVERMIND = "overmind"     # 虫皇 — 最高决策
    HIVE = "hive"             # 虫巢 — 中央模型集群
    CEREBRATE = "cerebrate"   # 脑虫 — 区域路由
    QUEEN = "queen"           # 虫后 — 个人模型系统
    DRONE = "drone"           # 子虫 — 功能模型


DroneType

类 DroneType 在 core/types.py: 子虫类型 — 功能分类 | 方法:

class DroneType:
    """子虫类型 — 功能分类"""
    INTENT = "intent"           # 意图识别
    MEMORY = "memory"           # 记忆模型
    CHAT = "chat"               # 对话模型
    REASONING = "reasoning"     # 推理模型
    TRANSLATION = "translation" # 翻译模型
    CODING = "coding"           # 编程模型
    KNOWLEDGE = "knowledge"     # 知识模型
    CREATIVE = "creative"       # 创意模型
    CUSTOM = "custom"           # 自定义模型


ModelLocation

类 ModelLocation 在 core/types.py: 模型部署位置 | 方法:

class ModelLocation:
    """模型部署位置"""
    LOCAL = "local"       # 本地CPU/GPU
    CLOUD = "cloud"       # 云端API
    REMOTE = "remote"     # 远程虫后（其他用户）


TaskPriority

类 TaskPriority 在 core/types.py: 任务优先级 | 方法:

class TaskPriority:
    """任务优先级"""
    CRITICAL = 0   # 虫皇指令
    HIGH = 1       # 复杂推理
    NORMAL = 2     # 日常任务
    LOW = 3        # 后台学习


SwarmStatus

类 SwarmStatus 在 core/types.py: 虫群节点状态 | 方法:


DroneInfo

子虫信息 — 最小功能单元

类 DroneInfo 在 core/types.py: 子虫信息 — 最小功能单元 | 方法: to_dict

class DroneInfo:
    """子虫信息 — 最小功能单元"""
    drone_id: str                    # 唯一标识: queen_id.domain.name
    name: str                        # 显示名称
    drone_type: DroneType            # 功能类型
    location: ModelLocation          # 部署位置
    params_M: float = 0.0            # 参数量(M)
    status: SwarmStatus = SwarmStatus.IDLE
    confidence: float = 0.5          # 默认置信度
    avg_latency_ms: float = 0.0      # 平均延迟
    parent_queen: str = ""           # 所属虫后ID
    knowledge_domain: str = ""       # 知识领域（如"力学"、"编程"）
    tags: List[str] = field(default_factory=list)
    endpoint: str = ""               # API端点（远程子虫）
    last_active: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "drone_id": self.drone_id,
            "name": self.name,
            "drone_type": self.drone_type.value,
            "location": self.location.value,
            "params_M": self.params_M,
            "status": self.status.value,
            "confidence": self.confidence,
            "avg_latency_ms": self.avg_latency_ms,
            "parent_queen": self.parent_queen,
            "knowledge_domain": self.knowledge_domain,
            "tags": self.tags,
        }

@dataclass


QueenInfo

虫后信息 — 个人模型系统

类 QueenInfo 在 core/types.py: 虫后信息 — 个人模型系统 | 方法: to_dict

class QueenInfo:
    """虫后信息 — 个人模型系统"""
    queen_id: str                    # 用户唯一标识
    name: str                        # 用户名
    status: SwarmStatus = SwarmStatus.IDLE
    drones: List[str] = field(default_factory=list)  # 子虫ID列表
    memory_drone: str = ""           # 记忆子虫ID
    meta_model: str = ""             # 元模型（意图识别）子虫ID
    knowledge_tree: Dict = field(default_factory=dict)  # 知识树结构
    total_params_M: float = 0.0      # 总参数量
    created_at: datetime = field(default_factory=datetime.now)
    last_active: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "queen_id": self.queen_id,
            "name": self.name,
            "status": self.status.value,
            "drone_count": len(self.drones),
            "memory_drone": self.memory_drone,
            "meta_model": self.meta_model,
            "total_params_M": self.total_params_M,
        }

@dataclass


CerebrateInfo

脑虫信息 — 区域路由节点

类 CerebrateInfo 在 core/types.py: 脑虫信息 — 区域路由节点 | 方法: to_dict

class CerebrateInfo:
    """脑虫信息 — 区域路由节点"""
    cerebrate_id: str                # 节点ID
    name: str                        # 区域名称
    domain: str = ""                 # 负责领域
    status: SwarmStatus = SwarmStatus.ACTIVE
    queens: List[str] = field(default_factory=list)  # 管辖虫后列表
    hive_endpoint: str = ""          # 上连虫巢端点
    routing_table: Dict = field(default_factory=dict)  # 路由表
    capacity: int = 100              # 最大并发
    current_load: int = 0            # 当前负载

    def to_dict(self) -> Dict:
        return {
            "cerebrate_id": self.cerebrate_id,
            "name": self.name,
            "domain": self.domain,
            "status": self.status.value,
            "queen_count": len(self.queens),
            "capacity": self.capacity,
            "current_load": self.current_load,
        }

@dataclass


HiveModelInfo

虫巢模型信息 — 中央大模型

类 HiveModelInfo 在 core/types.py: 虫巢模型信息 — 中央大模型 | 方法: to_dict

class HiveModelInfo:
    """虫巢模型信息 — 中央大模型"""
    model_id: str                    # 模型标识
    name: str                        # 显示名称
    endpoint: str = ""               # API端点
    api_key: str = ""                # API密钥
    max_tokens: int = 4096
    avg_latency_ms: float = 0.0
    status: SwarmStatus = SwarmStatus.ACTIVE
    capabilities: List[str] = field(default_factory=list)  # 能力标签

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "name": self.name,
            "endpoint": self.endpoint,
            "status": self.status.value,
            "capabilities": self.capabilities,
            "avg_latency_ms": self.avg_latency_ms,
        }

@dataclass


SwarmTask

虫群任务 — 最小调度单元

类 SwarmTask 在 core/types.py: 虫群任务 — 最小调度单元 | 方法: to_dict

class SwarmTask:
    """虫群任务 — 最小调度单元"""
    task_id: str
    query: str                             # 原始查询
    user_id: str                           # 用户ID
    priority: TaskPriority = TaskPriority.NORMAL
    complexity: float = 0.0                # 复杂度 0~1
    subtasks: List[str] = field(default_factory=list)  # 子任务ID
    assigned_drones: List[str] = field(default_factory=list)
    results: Dict[str, Any] = field(default_factory=dict)  # drone_id -> result
    status: str = "pending"                # pending/running/done/failed
    created_at: datetime = field(default_factory=datetime.now)
    completed_at: Optional[datetime] = None

    def to_dict(self) -> Dict:
        return {
            "task_id": self.task_id,
            "query": self.query,
            "user_id": self.user_id,
            "priority": self.priority.value,
            "complexity": self.complexity,
            "assigned_drones": self.assigned_drones,
            "status": self.status,
        }

@dataclass


SwarmMessage

虫群通信消息 — 节点间传递

类 SwarmMessage 在 core/types.py: 虫群通信消息 — 节点间传递 | 方法: to_dict

class SwarmMessage:
    """虫群通信消息 — 节点间传递"""
    msg_id: str
    sender: str                      # 发送者ID
    receiver: str                    # 接收者ID
    msg_type: str                    # 消息类型: route/result/discover/sync
    payload: Dict = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)
    ttl: int = 10                    # 跳数限制（防环路）

    def to_dict(self) -> Dict:
        return {
            "msg_id": self.msg_id,
            "sender": self.sender,
            "receiver": self.receiver,
            "msg_type": self.msg_type,
            "timestamp": self.timestamp.isoformat(),
        }

# ============================================================
# v7新增: 元模型分析结果
# ============================================================

@dataclass


SubTask

子任务 — 任务拆分后的最小执行单元

类 SubTask 在 core/types.py: 子任务 — 任务拆分后的最小执行单元 | 方法: to_dict

class SubTask:
    """子任务 — 任务拆分后的最小执行单元"""
    subtask_id: str
    description: str                     # 子任务描述
    drone_type: DroneType = DroneType.CHAT  # 需要的子虫类型
    knowledge_domain: str = ""           # 知识领域
    priority: TaskPriority = TaskPriority.NORMAL
    assigned_model: str = ""             # 分配的模型ID
    status: str = "pending"              # pending/running/done/failed

    def to_dict(self) -> Dict:
        return {
            "subtask_id": self.subtask_id,
            "description": self.description,
            "drone_type": self.drone_type.value,
            "knowledge_domain": self.knowledge_domain,
            "priority": self.priority.value,
            "assigned_model": self.assigned_model,
            "status": self.status,
        }

@dataclass


TaskAnalysis

元模型分析结果 — 意图识别+任务拆分+路由决策

类 TaskAnalysis 在 core/types.py: 元模型分析结果 — 意图识别+任务拆分+路由决策 | 方法: to_dict

class TaskAnalysis:
    """元模型分析结果 — 意图识别+任务拆分+路由决策"""
    query: str                            # 原始查询
    intent: str                           # 意图: chat/query/code/reasoning/memory/compute/multi
    complexity: float = 0.0               # 复杂度 0~1
    route: str = "cloud_hive"             # 路由: local_drone/memory/cloud_hive/multi_model/remote_queen
    assigned_model: str = ""              # 主模型ID
    subtasks: List[SubTask] = field(default_factory=list)
    confidence: float = 0.5               # 分析置信度
    requires_memory: bool = False         # 是否需要记忆检索
    knowledge_domains: List[str] = field(default_factory=list)  # 涉及的知识领域
    reasoning_chain: List[str] = field(default_factory=list)    # 推理链（调试用）

    def to_dict(self) -> Dict:
        return {
            "query": self.query,
            "intent": self.intent,
            "complexity": self.complexity,
            "route": self.route,
            "assigned_model": self.assigned_model,
            "subtask_count": len(self.subtasks),
            "confidence": self.confidence,
            "requires_memory": self.requires_memory,
            "knowledge_domains": self.knowledge_domains,
        }

# ============================================================
# v6兼容: 模型管理相关类型
# ============================================================


ModelType

类 ModelType 在 core/types.py: 模型类型 | 方法:

class ModelType:
    """模型类型"""
    LOCAL = "local"       # 本地模型
    API = "api"           # API模型
    REMOTE = "remote"     # 远程模型


ModelStatus

类 ModelStatus 在 core/types.py: 模型状态 | 方法:

class ModelStatus:
    """模型状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    ERROR = "error"
    LOADING = "loading"


AggregationMethod

类 AggregationMethod 在 core/types.py: 聚合策略 | 方法:

class AggregationMethod:
    """聚合策略"""
    CONFIDENCE = "confidence"     # 置信度优先
    VOTING = "voting"             # 投票法
    WEIGHTED = "weighted"         # 加权平均
    SEQUENTIAL = "sequential"     # 顺序精炼
    ADAPTIVE = "adaptive"         # 自适应


MemoryCategory

类 MemoryCategory 在 core/types.py: 记忆类别 | 方法:

class MemoryCategory:
    """记忆类别"""
    GREETING = "greeting"          # 问候
    PERSONAL = "personal"          # 个人信息
    GENERAL = "general"            # 通用对话
    INFORMATION = "information"    # 信息/事实
    TASK = "task"                  # 任务相关
    CREATION = "creation"          # 创作内容
    CONVERSATION = "conversation"  # 对话记忆
    FACT = "fact"                  # 事实记忆
    PROCEDURE = "procedure"        # 过程记忆
    PREFERENCE = "preference"      # 偏好记忆
    EMOTION = "emotion"            # 情感记忆

@dataclass


ModelInfo

类 ModelInfo 在 core/types.py: 模型信息 | 方法: is_local, is_api, to_dict

class ModelInfo:
    """模型信息"""
    model_id: str
    name: str
    model_type: ModelType = ModelType.LOCAL
    description: str = ""
    endpoint: str = ""
    api_key: str = ""
    default_confidence: float = 0.5
    max_tokens: int = 1024
    priority: int = 5
    tags: List[str] = field(default_factory=list)
    status: ModelStatus = ModelStatus.ACTIVE

    @property
    def is_local(self) -> bool:
        return self.model_type == ModelType.LOCAL

    @property
    def is_api(self) -> bool:
        return self.model_type == ModelType.API

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "name": self.name,
            "model_type": self.model_type.value,
            "description": self.description,
            "default_confidence": self.default_confidence,
            "priority": self.priority,
            "tags": self.tags,
            "status": self.status.value,
        }

@dataclass


PerformanceStats

类 PerformanceStats 在 core/types.py: 模型性能统计 | 方法: success_rate, avg_latency_ms, avg_confidence, record, to_dict

class PerformanceStats:
    """模型性能统计"""
    model_id: str
    total_requests: int = 0
    successful_requests: int = 0
    total_latency_ms: float = 0.0
    total_confidence: float = 0.0

    @property
    def success_rate(self) -> float:
        return self.successful_requests / max(self.total_requests, 1)

    @property
    def avg_latency_ms(self) -> float:
        return self.total_latency_ms / max(self.total_requests, 1)

    @property
    def avg_confidence(self) -> float:
        return self.total_confidence / max(self.total_requests, 1)

    def record(self, latency_ms: float, confidence: float, success: bool):
        self.total_requests += 1
        if success:
            self.successful_requests += 1
        self.total_latency_ms += latency_ms
        self.total_confidence += confidence

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "total_requests": self.total_requests,
            "success_rate": round(self.success_rate, 3),
            "avg_latency_ms": round(self.avg_latency_ms, 1),
            "avg_confidence": round(self.avg_confidence, 3),
        }

# ============================================================
# v6兼容: 聚合与记忆类型
# ============================================================

@dataclass


record

方法 PerformanceStats.record():
        self.total_requests += 1
        if success:
            self.successful_requests += 1

def record(self):
        self.total_requests += 1
        if success:
            self.successful_requests += 1
        self.total_latency_ms += latency_ms
        self.total_confidence += confidence


ModelResult

类 ModelResult 在 core/types.py: 单个模型处理结果 | 方法: to_dict

class ModelResult:
    """单个模型处理结果"""
    model_id: str
    response: str = ""
    success: bool = False
    confidence: float = 0.0
    latency_ms: float = 0.0
    error: str = ""
    metadata: Dict = field(default_factory=dict)

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "success": self.success,
            "confidence": self.confidence,
            "latency_ms": round(self.latency_ms, 1),
        }

@dataclass


AggregationResult

类 AggregationResult 在 core/types.py: 多模型聚合结果 | 方法: to_dict

class AggregationResult:
    """多模型聚合结果"""
    final_response: str = ""
    method: AggregationMethod = AggregationMethod.CONFIDENCE
    model_results: List[ModelResult] = field(default_factory=list)
    total_latency_ms: float = 0.0
    models_used: int = 0
    confidence: float = 0.0

    def to_dict(self) -> Dict:
        return {
            "final_response": self.final_response[:100],
            "method": self.method.value,
            "models_used": self.models_used,
            "confidence": self.confidence,
            "total_latency_ms": round(self.total_latency_ms, 1),
        }

@dataclass


MemoryRecord

类 MemoryRecord 在 core/types.py: 记忆记录 | 方法: to_dict

class MemoryRecord:
    """记忆记录"""
    record_id: str = ""
    content: str = ""
    category: MemoryCategory = MemoryCategory.CONVERSATION
    importance: float = 0.5
    timestamp: datetime = field(default_factory=datetime.now)
    tags: List[str] = field(default_factory=list)

    def to_dict(self) -> Dict:
        return {
            "record_id": self.record_id,
            "content": self.content[:50],
            "category": self.category.value,
            "importance": self.importance,
        }

@dataclass


TaskContext

类 TaskContext 在 core/types.py: 任务上下文 | 方法:

class TaskContext:
    """任务上下文"""
    task_id: str = ""
    query: str = ""
    user_id: str = "default"
    complexity: float = 0.0
    history: List[Dict] = field(default_factory=list)
    metadata: Dict = field(default_factory=dict)


ComplexityLevel

类 ComplexityLevel 在 core/types.py: 复杂度等级 | 方法:

class ComplexityLevel:
    """复杂度等级"""
    SIMPLE = "simple"         # < 0.2
    NORMAL = "normal"         # 0.2-0.5
    COMPLEX = "complex"       # 0.5-0.8
    CRITICAL = "critical"     # > 0.8


record

函数 record(self, latency_ms: float, confidence: float, success: bool) 在 core/types.py:

def record(self, latency_ms: float, confidence: float, success: bool):
        self.total_requests += 1
        if success:
            self.successful_requests += 1
        self.total_latency_ms += latency_ms
        self.total_confidence += confidence

    def to_dict(self) -> Dict:
        return {
            "model_id": self.model_id,
            "total_requests": self.total_requests,
            "success_rate": round(self.success_rate, 3),
            "avg_latency_ms": round(self.avg_latency_ms, 1),
            "avg_confidence": round(self.avg_confidence, 3),
        }

# ============================================================
# v6兼容: 聚合与记忆类型
# ============================================================

@dataclass


文件 core/intent_memory_db.py: 意图记忆存储层 - SQLite实现 | 定义: class
class, def __post_init__, class
class, class
class, def __post_init__, class IntentMemoryDB, def __init__, def _init_db, def save_intent_pattern, def get_intent_patterns

sqlite3 json datetime typing dataclasses

"""
意图记忆存储层 - SQLite实现
"""

import sqlite3
import json
from datetime import datetime
from typing import Optional, Dict, List, Any
from dataclasses import dataclass, asdict

DB_PATH = "/home/admin/swarm/data/intent_memory.db"

@dataclass
class IntentPattern:
    """单次完整意图记录"""
    id: str
    user_id: str
    original_input: str
    extracted_intent: str
    entities_json: str = "{}"
    filled_params_json: str = "{}"
    success_score: float = 0.5
    usage_count: int = 1
    last_used: str =


IntentPattern

类 IntentPattern 在 core/intent_memory_db.py: 单次完整意图记录 | 方法: __post_init__

class IntentPattern:
    """单次完整意图记录"""
    id: str
    user_id: str
    original_input: str
    extracted_intent: str
    entities_json: str = "{}"
    filled_params_json: str = "{}"
    success_score: float = 0.5
    usage_count: int = 1
    last_used: str = None
    source: str = "explicit"
    created_at: str = None

    def __post_init__(self):
        if not self.created_at:
            self.created_at = datetime.now().isoformat()
        if not self.last_used:
            self.last_used = self.created_at

@dataclass


AbbreviationMap

类 AbbreviationMap 在 core/intent_memory_db.py: 缩写映射 | 方法:

class AbbreviationMap:
    """缩写映射"""
    id: int = None
    user_id: str = ""
    shortcut: str = ""
    expanded_intent: str = ""
    confidence: float = 0.5
    match_conditions_json: str = "{}"

@dataclass


UserPreferences

类 UserPreferences 在 core/intent_memory_db.py: 用户偏好 | 方法: __post_init__

class UserPreferences:
    """用户偏好"""
    user_id: str
    default_format: str = "markdown"
    language_style: str = "简洁"
    time_preference: str = ""
    task_granularity: str = "碎片处理"
    notification_style: str = "即时"
    updated_at: str = None

    def __post_init__(self):
        if not self.updated_at:
            self.updated_at = datetime.now().isoformat()


IntentMemoryDB

类 IntentMemoryDB 在 core/intent_memory_db.py: 意图记忆数据库 | 方法: __init__, _init_db, save_intent_pattern, get_intent_patterns, find_similar_intent, save_abbreviation, get_abbreviation, save_preferences, get_preferences, save_correction, get_recent_corrections, update_context, get_active_context

class IntentMemoryDB:
    """意图记忆数据库"""

    def __init__(self, db_path: str = DB_PATH):
        self.db_path = db_path
        self._init_db()

    def _init_db(self):
        """初始化数据库表"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()

        # 意图模式表
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS intent_patterns (
                id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                original_input TEXT NOT NULL,
                extracted_intent TEXT NOT NULL,
                entities_json TEXT DEFAULT '{}',
                filled_params_json TEXT DEFAULT '{}',
                success_score REAL DEFAULT 0.5,
                usage_count INTEGER DEFAULT 1,
                last_used TIMESTAMP,
                source TEXT DEFAULT 'explicit',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)

        # 缩写映射表
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS abbreviation_map (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id TEXT NOT NULL,
                shortcut TEXT NOT NULL,
                expanded_intent TEXT NOT NULL,
                confidence REAL DEFAULT 0.5,
                match_conditions_json TEXT DEFAULT '{}',
                UNIQUE(user_id, shortcut)
            )
        """)

        # 用户偏好表
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS user_preferences (
                user_id TEXT PRIMARY KEY,
                default_format TEXT DEFAULT 'markdown',
                language_style TEXT DEFAULT '简洁',
                time_preference TEXT DEFAULT '',
                task_granularity TEXT DEFAULT '碎片处理',
                notification_style TEXT DEFAULT '即时',
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)

        # 纠错记录表
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS corrections (
                id INTE


文件 core/swarm_agent.py: 虫群智能体引擎 — 主控模型拆分任务 + MOA调度 + 结果汇总 | 定义: class SwarmAgent, def __init__, def set_controller, def _call_controller, def _parse_subtasks, def chat, def test

os json time asyncio typing dataclasses core.model_adapter core.task_dispatcher

#!/usr/bin/env python3
"""
虫群智能体引擎 — 主控模型拆分任务 + MOA调度 + 结果汇总
"""

import os
import json
import time
import asyncio
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field

from core.model_adapter import ZhipuAdapter, NvidiaNimAdapter, CallResult
from core.task_dispatcher import (
    TaskDispatcher, TaskPlan, SubTask, TaskType, TaskStatus,
    TASK_TO_CAPABILITY, TASK_PREFERRED_PROVIDER
)

# 主控拆分提示词
DECOMPOSE_PROMPT = """你是一个任务拆分专家。将用户的请求拆分成1-3个独立的子任务。

规则：
1. 每个子任


SwarmAgent

虫群智能体 — 主控拆分+调度+汇总

类 SwarmAgent 在 core/swarm_agent.py: 虫群智能体 — 主控拆分+调度+汇总 | 方法: __init__, set_controller, _call_controller, _parse_subtasks, chat, test

class SwarmAgent:
    """虫群智能体 — 主控拆分+调度+汇总"""

    def __init__(self, controller_adapter=None, controller_model: str = ""):
        """
        controller_adapter: 主控模型适配器（用户自选的付费主模型）
        controller_model: 主控模型名称
        """
        self.dispatcher = TaskDispatcher()
        self.controller = controller_adapter
        self.controller_model = controller_model
        self.history: List[Dict] = []

    def set_controller(self, adapter, model: str):
        """设置主控模型（付费模型）"""
        self.controller = adapter
        self.controller_model = model

    async def _call_controller(self, prompt: str, max_tokens: int = 500) -> str:
        """调用主控模型"""
        if not self.controller:
            # 无主控模型，用智谱免费模型做拆分/汇总
            adapter = self.dispatcher.adapters.get("zhipu")
            if adapter:
                r = await adapter.call(
                    [{"role": "user", "content": prompt}],
                    model="glm-4-flash-250414",
                    max_tokens=max_tokens,
                    temperature=0.3
                )
                return r.text if not r.error else ""
            return ""

        r = await self.controller.call(
            [{"role": "user", "content": prompt}],
            model=self.controller_model,
            max_tokens=max_tokens,
            temperature=0.3
        )
        return r.text if not r.error else ""

    def _parse_subtasks(self, text: str) -> List[SubTask]:
        """从主控回复中解析子任务"""
        # 尝试提取JSON
        try:
            # 找到JSON块
            start = text.find("{")
            end = text.rfind("}") + 1
            if start >= 0 and end > start:
                data = json.loads(text[start:end])
                subtasks = []
                for item in data.get("subtasks", []):
                    task_type_str = item.get("type", "chat")
                    try:
                        task_type = TaskType(task_type_str)
                    except ValueError:
                        task_type = Ta


方法 SwarmAgent.set_controller():
        """设置主控模型（付费模型）"""
        self.controller = adapter
        self.controller_model = model

def set_controller(self):
        """设置主控模型（付费模型）"""
        self.controller = adapter
        self.controller_model = model

    async def _call_controller(self, prompt: str, max_tokens: int = 500) -> str:
        """调用主控模型"""
        if not self.controller:
            # 无主控模型，用智谱免费模型做拆分/汇总
            adapter = self.dispatcher.adapters.get("zhipu")
            if adapter:
                r = await adapter.call(
                    [{"role": "user", "content": prompt}],
                    model="glm-4-flash-250414",
                    max_tokens=max_tokens,
                    temperature=0.3
                )
                return r.text if not r.error else ""
            return ""

        r = await self.controller.call(
            [{"role": "user", "content": prompt}],
            model=self.controller_model,
            max_tokens=max_tokens,
            temperature=0.3
        )
        return r.text if not r.error else ""


test

方法 SwarmAgent.test():
        os.environ["GLM_API_KEY"] = "a357dd87003f45fa8070381675d64c4e.JLzEDqn5vXYkYlpF"
        os.

def test(self):
        os.environ["GLM_API_KEY"] = "a357dd87003f45fa8070381675d64c4e.JLzEDqn5vXYkYlpF"
        os.environ["NVIDIA_KEY"] = "nvapi-[REDACTED]_eBR6V0gmvpLUIxGBkMPXqn6OI8x"

        print("=== 虫群智能体测试 ===\n")

        agent = SwarmAgent()

        # 简单问题（不拆分）
        r1 = await agent.chat("你好，今天天气怎么样？")
        print(f"简单问题: {r1['reply'][:80]}")
        print(f"  子任务: {len(r1['subtasks'])}个 | 总耗时: {r1['total_ms']}ms")
        print()

        # 复杂问题（拆分）
        r2 = await agent.chat("解释什么是API，并给一个Python调用API的代码示例")
        print(f"复杂问题: {r2['reply'][:100]}")
        print(f"  子任务: {len(r2['subtasks'])}个 | 总耗时: {r2['total_ms']}ms")
        for s in r2['subtasks']:
            print(f"    {s['id']} [{s['type']}] → {s['model'][:30]} ({s['latency_ms']}ms)")

        print(f"\n✅ 智能体测试完成")

    asyncio.run(test())


文件 core/config_center.py: 虫群智能体系统 — 统一配置中心
集中管理所有配置：模型、路由、技能、API密钥等
支持环境变量覆盖 + 热加载 + 校验 | 定义: class ConfigCenter, def __new__, def load, def save, def hot_reload, def get, def set, def get_section, def get_all, def apply_env_overrides

json logging os threading time copy typing

#!/usr/bin/env python3
"""
虫群智能体系统 — 统一配置中心
集中管理所有配置：模型、路由、技能、API密钥等
支持环境变量覆盖 + 热加载 + 校验
"""

import json
import logging
import os
import threading
import time
from copy import deepcopy
from typing import Any, Dict, List, Optional

logger = logging.getLogger(__name__)

# 默认配置文件路径
DEFAULT_CONFIG_PATH = "/home/admin/swarm/config.json"

# ============================================================
# 默认配置模板
# ============================================================

DEFAULT_CONFIG = {
    "ver


ConfigCenter

统一配置中心 — 单例模式

类 ConfigCenter 在 core/config_center.py: 统一配置中心 — 单例模式 | 方法: __new__, load, save, hot_reload, get, set, get_section, get_all, apply_env_overrides, validate, get_api_keys, get_status, _deep_merge, _try_convert

class ConfigCenter:
    """统一配置中心 — 单例模式"""

    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._config = deepcopy(DEFAULT_CONFIG)
                cls._instance._loaded = False
                cls._instance._last_mtime = 0
            return cls._instance

    # ----------------------------------------------------------
    # 加载 / 保存
    # ----------------------------------------------------------

    def load(self, path: str = None) -> bool:
        """从JSON文件加载配置，合并到默认配置上"""
        path = path or DEFAULT_CONFIG_PATH
        if not os.path.exists(path):
            logger.info(f"配置文件不存在，使用默认配置: {path}")
            self._loaded = True
            return True

        try:
            with open(path, "r", encoding="utf-8") as f:
                user_config = json.load(f)

            # 深度合并：用户配置覆盖默认配置
            self._config = self._deep_merge(deepcopy(DEFAULT_CONFIG), user_config)
            self._last_mtime = os.path.getmtime(path)
            self._loaded = True
            logger.info(f"配置加载成功: {path}")
            return True
        except Exception as e:
            logger.warning(f"配置加载失败: {e}，使用默认配置")
            self._loaded = True
            return False

    def save(self, path: str = None) -> bool:
        """保存当前配置到JSON文件"""
        path = path or DEFAULT_CONFIG_PATH
        try:
            os.makedirs(os.path.dirname(path), exist_ok=True)
            with open(path, "w", encoding="utf-8") as f:
                json.dump(self._config, f, ensure_ascii=False, indent=2)
            logger.info(f"配置保存成功: {path}")
            return True
        except Exception as e:
            logger.error(f"配置保存失败: {e}")
            return False

    def hot_reload(self, path: str = None) -> bool:
        """热加载：文件修改时间变化时重新加载"""
        path = path or DEFAULT_CONFIG_PATH
        if not os.path.exists(path):


文件 core/swarm_types.py: 虫群v7 — 核心类型系统扩展

在v6类型基础上新增v7概念的类型定义：

v7新增概念：
  种子模型 SeedModel  — 同一架构不同喂养数据长成不同角色
  元模型 MetaModel    — 个人端核心调度，分析→拆分→路由
  记忆模型 MemoryModel — 参数化记忆，不存原文存参数
  任务模型树 TaskTree  — 知识树结构，像备课一样按需加载
  虫后 Qu | 定义: class SeedStage, class TaskDomain, class MemoryType, class MetaTaskState, class
class, def to_dict, class
class, def to_dict, class
class, def to_dict

dataclasses datetime enum typing core.types

#!/usr/bin/env python3
"""
虫群v7 — 核心类型系统扩展

在v6类型基础上新增v7概念的类型定义：

v7新增概念：
  种子模型 SeedModel  — 同一架构不同喂养数据长成不同角色
  元模型 MetaModel    — 个人端核心调度，分析→拆分→路由
  记忆模型 MemoryModel — 参数化记忆，不存原文存参数
  任务模型树 TaskTree  — 知识树结构，像备课一样按需加载
  虫后 QueenAgent     — 个人端完整系统(元模型+记忆+任务树)
  虫巢 HiveCluster    — 中央大模型集群
  虫皇 OvermindAgent  — 生态治理者

依赖: core.types 中的 SwarmRole, TaskPriority, SwarmStatus, HiveModelInfo 等基础类型
"""

from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from


SeedStage

种子模型成长阶段 — 从种子到可入虫巢

类 SeedStage 在 core/swarm_types.py: 种子模型成长阶段 — 从种子到可入虫巢 | 方法:

class SeedStage:
    """种子模型成长阶段 — 从种子到可入虫巢"""
    SEED = "seed"              # 种子 — 初始状态
    SPROUT = "sprout"          # 萌芽 — 开始喂养
    GROWTH = "growth"          # 成长 — 持续训练
    MATURE = "mature"          # 成熟 — 可用
    HIVE_READY = "hive_ready"  # 可入虫巢 — 可部署到虫巢


TaskDomain

任务领域分类 — 覆盖个人端主要场景

类 TaskDomain 在 core/swarm_types.py: 任务领域分类 — 覆盖个人端主要场景 | 方法:

class TaskDomain:
    """任务领域分类 — 覆盖个人端主要场景"""
    WORK = "work"              # 工作
    STUDY = "study"            # 学习
    LIFE = "life"              # 生活
    CREATIVE = "creative"      # 创作
    SOCIAL = "social"          # 社交
    CUSTOM = "custom"          # 自定义


MemoryType

记忆类型 — 参数化记忆体系

类 MemoryType 在 core/swarm_types.py: 记忆类型 — 参数化记忆体系 | 方法:

class MemoryType:
    """记忆类型 — 参数化记忆体系"""
    PARAMETRIC = "parametric"  # 参数化 — 编码为模型参数
    EPISODIC = "episodic"      # 片段 — 具体事件记忆
    SEMANTIC = "semantic"      # 语义 — 知识概念记忆


MetaTaskState

元模型任务状态 — 分析→拆分→路由→执行→聚合

类 MetaTaskState 在 core/swarm_types.py: 元模型任务状态 — 分析→拆分→路由→执行→聚合 | 方法:

class MetaTaskState:
    """元模型任务状态 — 分析→拆分→路由→执行→聚合"""
    ANALYZING = "analyzing"      # 分析中
    DECOMPOSING = "decomposing"  # 拆分中
    ROUTING = "routing"          # 路由中
    EXECUTING = "executing"      # 执行中
    AGGREGATING = "aggregating"  # 聚合中
    COMPLETED = "completed"      # 完成

# ============================================================
# v7 核心数据结构
# ============================================================

@dataclass


SeedInfo

类 SeedInfo 在 core/swarm_types.py: 种子模型信息 — 同一架构不同喂养数据长成不同角色

    种子是v7的核心概念：一个基础架构的模型种子，通过喂养不同数据，
    逐步成长为不同角色的子虫。就像同一颗种子，浇水施肥不同，长成不同的树。 | 方法: to_dict

class SeedInfo:
    """种子模型信息 — 同一架构不同喂养数据长成不同角色

    种子是v7的核心概念：一个基础架构的模型种子，通过喂养不同数据，
    逐步成长为不同角色的子虫。就像同一颗种子，浇水施肥不同，长成不同的树。
    """
    seed_id: str                           # 种子唯一标识
    name: str                              # 种子名称
    stage: SeedStage                       # 当前成长阶段
    base_arch: str                         # 基础架构(如"llama3", "qwen2")
    params_M: float                        # 参数量(M)
    feeding_data: str                      # 喂养数据来源
    fed_tokens: int                        # 已喂养token数
    evolved_from: str                      # 从哪个种子进化而来
    role: SwarmRole                        # 最终角色
    accuracy: float                        # 当前精度
    status: SwarmStatus                    # 当前状态

    def to_dict(self) -> Dict:
        return {
            "seed_id": self.seed_id,
            "name": self.name,
            "stage": self.stage.value,
            "base_arch": self.base_arch,
            "params_M": self.params_M,
            "feeding_data": self.feeding_data,
            "fed_tokens": self.fed_tokens,
            "evolved_from": self.evolved_from,
            "role": self.role.value,
            "accuracy": self.accuracy,
            "status": self.status.value,
        }

@dataclass


MetaTask

类 MetaTask 在 core/swarm_types.py: 元模型任务分解单元 — 分析→拆分→路由→执行→聚合

    元模型收到用户查询后，将任务分解为多个子任务，
    路由到不同子虫执行，最后聚合结果。 | 方法: to_dict

class MetaTask:
    """元模型任务分解单元 — 分析→拆分→路由→执行→聚合

    元模型收到用户查询后，将任务分解为多个子任务，
    路由到不同子虫执行，最后聚合结果。
    """
    task_id: str                           # 任务唯一标识
    parent_task_id: Optional[str]          # 父任务ID(顶层任务为None)
    query: str                             # 原始查询
    subtasks: List[str]                    # 子任务ID列表
    domain: TaskDomain                     # 任务领域
    complexity: float                      # 复杂度 0~1
    priority: TaskPriority                 # 优先级
    assigned_drone: str                    # 分配的子虫ID
    state: MetaTaskState                   # 当前状态
    result: str                            # 结果
    confidence: float                      # 置信度

    def to_dict(self) -> Dict:
        return {
            "task_id": self.task_id,
            "parent_task_id": self.parent_task_id,
            "query": self.query,
            "subtasks": self.subtasks,
            "domain": self.domain.value,
            "complexity": self.complexity,
            "priority": self.priority.value,
            "assigned_drone": self.assigned_drone,
            "state": self.state.value,
            "result": self.result,
            "confidence": self.confidence,
        }

@dataclass


MemoryEntry

类 MemoryEntry 在 core/swarm_types.py: 记忆条目 — 参数化记忆体系

    不存原文存参数：频繁访问的记忆编码为模型参数，
    不频繁的保留为片段/语义记忆，按需检索。 | 方法: to_dict

class MemoryEntry:
    """记忆条目 — 参数化记忆体系

    不存原文存参数：频繁访问的记忆编码为模型参数，
    不频繁的保留为片段/语义记忆，按需检索。
    """
    entry_id: str                          # 条目唯一标识
    user_id: str                           # 用户ID
    memory_type: MemoryType                # 记忆类型
    content: str                           # 内容摘要
    embedding: Optional[List[float]]       # 向量嵌入
    frequency: int = 1                     # 访问频率
    last_accessed: datetime = field(default_factory=datetime.now)  # 最后访问时间
    encoded_in_model: bool = False         # 是否已编码为参数

    def to_dict(self) -> Dict:
        return {
            "entry_id": self.entry_id,
            "user_id": self.user_id,
            "memory_type": self.memory_type.value,
            "content": self.content,
            "embedding": self.embedding,
            "frequency": self.frequency,
            "last_accessed": self.last_accessed.isoformat(),
            "encoded_in_model": self.encoded_in_model,
        }

@dataclass


TaskTreeNode

类 TaskTreeNode 在 core/swarm_types.py: 任务模型树节点 — 像高中物理知识树

    知识按树结构组织，像备课一样按需加载：
    学习/物理/力学 → 只激活力学相关的子虫
    学习/物理/电磁 → 切换到电磁相关子虫

    同一架构的种子，在不同知识节点上喂养不同数据，
    形成不同领域的专家子虫。 | 方法: to_dict

class TaskTreeNode:
    """任务模型树节点 — 像高中物理知识树

    知识按树结构组织，像备课一样按需加载：
    学习/物理/力学 → 只激活力学相关的子虫
    学习/物理/电磁 → 切换到电磁相关子虫

    同一架构的种子，在不同知识节点上喂养不同数据，
    形成不同领域的专家子虫。
    """
    node_id: str                           # 节点唯一标识
    name: str                              # 节点名称
    domain: TaskDomain                     # 所属领域
    parent_id: Optional[str]               # 父节点ID
    children: List[str]                    # 子节点ID列表
    drone_id: str                          # 对应的子虫ID
    knowledge_path: str                    # 知识路径(如"学习/物理/力学")
    params_M: float = 0.0                  # 参数量(M)
    is_active: bool = False                # 是否激活

    def to_dict(self) -> Dict:
        return {
            "node_id": self.node_id,
            "name": self.name,
            "domain": self.domain.value,
            "parent_id": self.parent_id,
            "children": self.children,
            "drone_id": self.drone_id,
            "is_active": self.is_active,
            "knowledge_path": self.knowledge_path,
            "params_M": self.params_M,
        }

@dataclass


QueenConfig

类 QueenConfig 在 core/swarm_types.py: 虫后个人配置 — 个人端完整系统

    虫后 = 元模型 + 记忆模型 + 任务树
    元模型负责分析和调度，记忆模型存储用户偏好，
    任务树按需加载知识领域的子虫。 | 方法: to_dict

class QueenConfig:
    """虫后个人配置 — 个人端完整系统

    虫后 = 元模型 + 记忆模型 + 任务树
    元模型负责分析和调度，记忆模型存储用户偏好，
    任务树按需加载知识领域的子虫。
    """
    queen_id: str                          # 虫后唯一标识(即用户ID)
    user_name: str                         # 用户名
    meta_model_id: str                     # 元模型ID
    memory_model_id: str                   # 记忆模型ID
    task_tree_root: str                    # 任务树根节点ID
    active_drones: List[str]               # 当前活跃子虫列表
    max_concurrent: int = 3                # 最大并发子虫数
    auto_evolve: bool = True               # 是否自动进化种子

    def to_dict(self) -> Dict:
        return {
            "queen_id": self.queen_id,
            "user_name": self.user_name,
            "meta_model_id": self.meta_model_id,
            "memory_model_id": self.memory_model_id,
            "task_tree_root": self.task_tree_root,
            "active_drones": self.active_drones,
            "max_concurrent": self.max_concurrent,
            "auto_evolve": self.auto_evolve,
        }

@dataclass


HiveClusterConfig

类 HiveClusterConfig 在 core/swarm_types.py: 虫巢集群配置 — 中央大模型集群

    虫巢是中央大模型的集群，为所有虫后提供推理能力。
    支持多种负载均衡策略，按能力匹配最适合的模型。 | 方法: to_dict

class HiveClusterConfig:
    """虫巢集群配置 — 中央大模型集群

    虫巢是中央大模型的集群，为所有虫后提供推理能力。
    支持多种负载均衡策略，按能力匹配最适合的模型。
    """
    cluster_id: str                        # 集群唯一标识
    name: str                              # 集群名称
    models: List[HiveModelInfo]            # 模型列表
    total_capacity: int                    # 总容量
    current_load: int                      # 当前负载
    load_balance_strategy: str = "round_robin"  # 负载均衡策略: round_robin/least_loaded/capability_match

    def to_dict(self) -> Dict:
        return {
            "cluster_id": self.cluster_id,
            "name": self.name,
            "models": [m.to_dict() for m in self.models],
            "total_capacity": self.total_capacity,
            "current_load": self.current_load,
            "load_balance_strategy": self.load_balance_strategy,
        }


文件 core/gateway_backends.py: 统一网关后端实现
- NIM后端
- Modal后端
- 本地后端
- HF Spaces后端 | 定义: class NIMBackend, def __init__, def _load_from_config, def _get_manager, def infer, def health_check, class ModalBackend, def __init__, def _get_backend, def infer

#!/usr/bin/env python3
"""
统一网关后端实现
- NIM后端
- Modal后端
- 本地后端
- HF Spaces后端
"""

import os
import logging
from typing import Dict, Optional
from core.unified_gateway import InferenceBackend, InferenceResult
from core.api_inference import APIInferenceManager

logger = logging.getLogger(__name__)

# ============================================================
# NIM后端
# ============================================================

class NIMBackend(InferenceBackend):
    """NIM API后端"""

    def


NIMBackend

类 NIMBackend 在 core/gateway_backends.py: NIM API后端 | 方法: __init__, _load_from_config, _get_manager, infer, health_check

class NIMBackend:
    """NIM API后端"""

    def __init__(self, api_key: str = None):
        super().__init__(name="nim", backend_type="nim", priority=80)
        # 优先使用传入的key，其次环境变量，最后config.yaml
        self.api_key = api_key or os.getenv("NIM_API_KEY", "")
        if not self.api_key:
            self.api_key = self._load_from_config()
        self._manager: Optional[APIInferenceManager] = None

    def _load_from_config(self) -> str:
        """从config.yaml加载NIM API Key"""
        try:
            import yaml
            from pathlib import Path
            config_path = Path(__file__).parent.parent / "config.yaml"
            if config_path.exists():
                with open(config_path, "r", encoding="utf-8") as f:
                    cfg = yaml.safe_load(f)
                    return cfg.get("api_keys", {}).get("nim_api_key", "")
        except Exception as e:
            logger.warning(f"加载config.yaml失败: {e}")
        return ""

    def _get_manager(self) -> APIInferenceManager:
        if self._manager is None:
            # 手动创建manager并添加NIM provider
            from core.api_inference import APIInferenceManager, APIModelConfig

            mgr = APIInferenceManager()
            if self.api_key:
                mgr.add_provider("nim", self.api_key)
                # 注册NIM模型
                mgr.register_model(APIModelConfig(
                    provider="nim",
                    model_name="meta/llama-4-maverick-17b-128e-instruct",
                    api_key=self.api_key,
                    base_url="",
                    priority=90,
                    free=True
                ))
                mgr.register_model(APIModelConfig(
                    provider="nim",
                    model_name="meta/llama-3.1-8b-instruct",
                    api_key=self.api_key,
                    base_url="",
                    priority=80,
                    free=True
                ))
            self._manager = mgr
        return self._manager


ModalBackend

类 ModalBackend 在 core/gateway_backends.py: Modal云端后端 | 方法: __init__, _get_backend, infer, health_check

class ModalBackend:
    """Modal云端后端"""

    def __init__(self, endpoint: str = None):
        super().__init__(name="modal", backend_type="modal", priority=60)
        self.endpoint = endpoint or os.getenv("MODAL_ENDPOINT", "")
        self._backend = None

    def _get_backend(self):
        if self._backend is None:
            try:
                from core.modal_glm import ModalGLMBackend
                self._backend = ModalGLMBackend()
            except Exception as e:
                logger.warning(f"Modal后端初始化失败: {e}")
        return self._backend

    def infer(self, query: str, **kwargs) -> InferenceResult:
        """调用Modal GLM"""
        try:
            backend = self._get_backend()
            if not backend:
                return InferenceResult(success=False, error="Modal后端未初始化")

            max_tokens = kwargs.get("max_tokens", 512)
            result = backend.chat(
                messages=[{"role": "user", "content": query}],
                max_tokens=max_tokens,
            )

            if result.get("success"):
                return InferenceResult(
                    success=True,
                    answer=result.get("response", ""),
                    model="glm-5.1",
                    latency_ms=result.get("latency_ms", 0),
                )
            else:
                return InferenceResult(
                    success=False,
                    error=result.get("error", "Modal调用失败"),
                )
        except Exception as e:
            logger.warning(f"Modal后端调用异常: {e}")
            return InferenceResult(success=False, error=str(e))

    def health_check(self) -> bool:
        """健康检查"""
        try:
            return self._get_backend() is not None
        except:
            return False

# ============================================================
# 本地后端
# ============================================================


LocalBackend

类 LocalBackend 在 core/gateway_backends.py: 本地模型后端 | 方法: __init__, _get_backend, infer, health_check

class LocalBackend:
    """本地模型后端"""

    def __init__(self, models_dir: str = "/home/admin/swarm/training/models"):
        super().__init__(name="local", backend_type="local", priority=30)
        self.models_dir = models_dir
        self._backend = None

    def _get_backend(self):
        if self._backend is None:
            try:
                from core.local_inference import LocalModelBackend
                self._backend = LocalModelBackend(self.models_dir)
            except Exception as e:
                logger.warning(f"本地后端初始化失败: {e}")
        return self._backend

    def infer(self, query: str, **kwargs) -> InferenceResult:
        """调用本地模型"""
        try:
            backend = self._get_backend()
            if not backend:
                return InferenceResult(success=False, error="本地后端未初始化")

            # 选择模型
            model_id = kwargs.get("model", "small")
            available = backend.list_available()

            if model_id not in available:
                # 降级到可用的
                for fallback in ["medium", "small", "tiny"]:
                    if fallback in available:
                        model_id = fallback
                        break
                else:
                    return InferenceResult(success=False, error="无可用本地模型")

            result = backend.infer(model_id, query)

            if result.get("success"):
                return InferenceResult(
                    success=True,
                    answer=result.get("response", ""),
                    model=model_id,
                    latency_ms=result.get("latency_ms", 0),
                    cost=0,  # 本地免费
                )
            else:
                return InferenceResult(
                    success=False,
                    error=result.get("error", "本地模型调用失败"),
                )
        except Exception as e:
            logger.warning(f"本地后端调用异常: {e}")
            return InferenceResult(success=False, e


HFSpacesBackend

类 HFSpacesBackend 在 core/gateway_backends.py: HuggingFace Spaces后端 | 方法: __init__, _get_session, infer, health_check

class HFSpacesBackend:
    """HuggingFace Spaces后端"""

    def __init__(self, space_url: str = None, api_key: str = None):
        super().__init__(name="hf", backend_type="hf", priority=70)
        self.space_url = space_url or os.getenv("HF_SPACE_URL", "")
        self.api_key = api_key or os.getenv("HF_TOKEN", "")
        self._session = None

    def _get_session(self):
        if self._session is None:
            try:
                import requests
                self._session = requests.Session()
                if self.api_key:
                    self._session.headers["Authorization"] = f"Bearer {self.api_key}"
            except ImportError:
                logger.warning("requests库未安装")
        return self._session

    def infer(self, query: str, **kwargs) -> InferenceResult:
        """调用HF Spaces API"""
        if not self.space_url:
            return InferenceResult(success=False, error="未配置HF Space URL")

        try:
            import requests
            import json

            session = self._get_session() or requests
            max_tokens = kwargs.get("max_tokens", 512)

            # 调用HF Space
            url = f"{self.space_url.rstrip('/')}/infer"
            payload = {
                "inputs": query,
                "parameters": {
                    "max_new_tokens": max_tokens,
                    "temperature": kwargs.get("temperature", 0.7),
                }
            }

            response = session.post(url, json=payload, timeout=30)

            if response.status_code == 200:
                data = response.json()
                # 兼容不同返回格式
                if isinstance(data, list) and len(data) > 0:
                    answer = data[0].get("generated_text", "")
                elif isinstance(data, dict):
                    answer = data.get("generated_text", "") or data.get("text", "")
                else:
                    answer = str(data)


ProxyBackend

类 ProxyBackend 在 core/gateway_backends.py: 香港服务器中继后端 | 方法: __init__, infer, health_check

class ProxyBackend:
    """香港服务器中继后端"""

    def __init__(self, server_url: str = None, api_key: str = None):
        super().__init__(name="proxy", backend_type="proxy", priority=50)
        self.server_url = server_url or os.getenv("PROXY_SERVER_URL", "")
        self.api_key = api_key or os.getenv("PROXY_API_KEY", "")

    def infer(self, query: str, **kwargs) -> InferenceResult:
        """通过香港中继调用"""
        if not self.server_url:
            return InferenceResult(success=False, error="未配置中继服务器")

        try:
            import requests

            max_tokens = kwargs.get("max_tokens", 512)
            url = f"{self.server_url.rstrip('/')}/api/chat"

            headers = {"Content-Type": "application/json"}
            if self.api_key:
                headers["Authorization"] = f"Bearer {self.api_key}"

            payload = {
                "message": query,
                "max_tokens": max_tokens,
            }

            response = requests.post(url, json=payload, headers=headers, timeout=30)

            if response.status_code == 200:
                data = response.json()
                return InferenceResult(
                    success=True,
                    answer=data.get("response", ""),
                    model=data.get("model", "proxy"),
                    latency_ms=response.elapsed.total_seconds() * 1000,
                )
            else:
                return InferenceResult(
                    success=False,
                    error=f"中继服务器返回{response.status_code}",
                )
        except Exception as e:
            logger.warning(f"中继后端调用异常: {e}")
            return InferenceResult(success=False, error=str(e))

    def health_check(self) -> bool:
        """健康检查"""
        if not self.server_url:
            return False
        try:
            import requests
            response = requests.get(f"{self.server_url}/health", timeout=5)
            return


文件 core/memory_model.py: 虫群v7 — 记忆模型(Memory Model)
参数化个人记忆系统：将交互记录编码为可检索的结构

设计思路：
- 传统方案：对话存数据库，检索靠关键词匹配
- 虫群方案：记忆以向量索引+时序结构存储，检索更精准
- 未来方向：将记忆编码为模型参数（模型即数据库）
- 当前实现：轻量级向量索引 + 时序衰减 + 关键词增强 | 定义: class MemoryEntry, def __init__, def _extract_keywords, def to_dict, class MemoryModel, def __init__, def retrieve_context, def retrieve, def store_interaction, def _evict

hashlib json logging math os re time datetime typing

#!/usr/bin/env python3
"""
虫群v7 — 记忆模型(Memory Model)
参数化个人记忆系统：将交互记录编码为可检索的结构

设计思路：
- 传统方案：对话存数据库，检索靠关键词匹配
- 虫群方案：记忆以向量索引+时序结构存储，检索更精准
- 未来方向：将记忆编码为模型参数（模型即数据库）
- 当前实现：轻量级向量索引 + 时序衰减 + 关键词增强
"""

import hashlib
import json
import logging
import math
import os
import re
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple

logger = logging.getLogger(__name__)

# ============================================================
# 记忆条目
# ============================


MemoryEntry

类 MemoryEntry 在 core/memory_model.py: 单条记忆 | 方法: __init__, _extract_keywords, to_dict

class MemoryEntry:
    """单条记忆"""

    def __init__(self, user_message: str, ai_response: str,
                 intent: str = "", route: str = "",
                 timestamp: str = ""):
        self.entry_id = hashlib.md5(
            f"{user_message}{ai_response}{time.time()}".encode()
        ).hexdigest()[:12]
        self.user_message = user_message
        self.ai_response = ai_response
        self.intent = intent
        self.route = route
        self.timestamp = timestamp or datetime.now().isoformat()
        self.created_at = time.time()

        # 关键词提取（简易版，替代分词）
        self.keywords = self._extract_keywords(user_message)

        # 访问计数（用于衰减/强化）
        self.access_count = 0
        self.last_access = self.created_at

    def _extract_keywords(self, text: str) -> List[str]:
        """简易中文关键词提取：去停用词 + 长词优先"""
        # 去标点
        cleaned = re.sub(r'[，。！？、；：""''（）\s]', ' ', text)
        # 按空格和常见分隔符切分
        words = re.split(r'[\s,.\-!?;:]+', cleaned)
        # 过滤短词
        keywords = [w for w in words if len(w) >= 2]
        return keywords[:20]  # 最多20个

    def to_dict(self) -> Dict:
        return {
            "entry_id": self.entry_id,
            "user_message": self.user_message[:100],
            "ai_response": self.ai_response[:100],
            "intent": self.intent,
            "keywords": self.keywords[:5],
            "timestamp": self.timestamp,
            "access_count": self.access_count,
        }

# ============================================================
# 记忆模型核心
# ============================================================


MemoryModel

类 MemoryModel 在 core/memory_model.py: 记忆模型 — 参数化个人记忆

    特性:
    1. retrieve_context(): 获取上下文摘要（给元模型用）
    2. retrieve(): 精确检索记忆条目
    3. store_interaction(): 存储新交互
    4. 时间衰减: 越早的记忆权重越低
    5. 关键词增强: 匹配关键词越多权重越高 | 方法: __init__, retrieve_context, retrieve, store_interaction, _evict, evict_score, _rebuild_index, _load, _save, get_stats, encode_realtime, _update_memory_params, _extract_concepts, _micro_finetune, fork_for_task, merge_from, get_unlimited_context, get_param_stats

class MemoryModel:
    """
    记忆模型 — 参数化个人记忆

    特性:
    1. retrieve_context(): 获取上下文摘要（给元模型用）
    2. retrieve(): 精确检索记忆条目
    3. store_interaction(): 存储新交互
    4. 时间衰减: 越早的记忆权重越低
    5. 关键词增强: 匹配关键词越多权重越高
    """

    # 记忆存储路径
    DATA_DIR = "/home/admin/swarm/data/memory"
    MAX_ENTRIES = 5000          # 最大记忆条数
    DECAY_HALF_LIFE = 86400 * 7  # 衰减半衰期: 7天

    def __init__(self, user_id: str = "default"):
        self.user_id = user_id
        self._entries: List[MemoryEntry] = []
        self._keyword_index: Dict[str, List[str]] = {}  # keyword -> [entry_ids]
        self._intent_index: Dict[str, List[str]] = {}    # intent -> [entry_ids]
        self._loaded = False

        # 统计
        self._store_count = 0
        self._retrieve_count = 0
        self._hit_count = 0

        # 延迟加载
        self._load()

    # ============================================================
    # 核心接口
    # ============================================================

    def retrieve_context(self, message: str) -> str:
        """
        获取与当前消息相关的记忆上下文文本
        返回格式: "之前你问过XXX，我回答了YYY"
        """
        self._retrieve_count += 1

        entries = self.retrieve(message, top_k=3)
        if not entries:
            return ""

        self._hit_count += 1
        parts = []
        for e in entries:
            msg = e.get("user_message", "") if isinstance(e, dict) else e.user_message
            resp = e.get("ai_response", "") if isinstance(e, dict) else e.ai_response
            parts.append(f"之前你问过「{msg[:50]}」，回答是「{resp[:50]}」")

        return "；".join(parts)

    def retrieve(self, query: str, top_k: int = 5) -> List[Dict]:
        """
        检索相关记忆条目

        算法: 关键词匹配 + 时间衰减 + 访问频次
        """
        self._retrieve_count += 1

        if not self._entries:
            return []

        # 提取查询关键词
        query_words = set()
        cleaned = re.sub(r'[，。！？、；：""''（）\s]', ' ', query)
        for w


方法 MemoryModel.encode_realtime():
        """
        实时训练: 每次交互都更新记忆参数

        实现策略:
        - 维护一个微型训练缓冲区(最近N条交互)

def encode_realtime(self):
        """
        实时训练: 每次交互都更新记忆参数

        实现策略:
        - 维护一个微型训练缓冲区(最近N条交互)
        - 当缓冲区满时触发微调(模拟)
        - 关键: 高频记忆权重增大，低频记忆权重衰减
        """
        # 先正常存储
        entry_id = self.store_interaction(message, result, analysis)

        # 更新记忆强度参数
        self._update_memory_params(message, result)

        # 检查是否需要触发微调
        if self._store_count % 20 == 0:
            self._micro_finetune()

        return entry_id


方法 MemoryModel.merge_from():
        """
        合并另一个记忆模型(从分叉回归)

        用法: 课上积累的物理记忆，课后合并回主记忆
        """
        me

def merge_from(self):
        """
        合并另一个记忆模型(从分叉回归)

        用法: 课上积累的物理记忆，课后合并回主记忆
        """
        merged = 0
        for entry in other._entries:
            # 检查是否已存在
            existing_ids = {e.entry_id for e in self._entries}
            if entry.entry_id not in existing_ids:
                self._entries.append(entry)
                for kw in entry.keywords:
                    if kw not in self._keyword_index:
                        self._keyword_index[kw] = []
                    self._keyword_index[kw].append(entry.entry_id)
                merged += 1

        # 合并参数
        if hasattr(other, '_param_dict') and hasattr(self, '_param_dict'):
            for k, v in other._param_dict.items():
                if k in self._param_dict:
                    self._param_dict[k] = max(self._param_dict[k], v)
                else:
                    self._param_dict[k] = v

        self._save()
        logger.info(f"记忆合并: +{merged}条新记忆")