离散事件模拟服务器

一个基于插件的离散事件模拟服务器,支持MCP集成,使AI助手能够运行和分析模拟。

  • by bulentsoykan
  • Python
  • 本地部署
  • 8 星标
  • 更新于
在 GitHub 查看 bulentsoykan/Simulation-AI-Agent

使用说明

模拟AI代理

基于插件的离散事件仿真服务器,集成了MCP(模型上下文协议),使AI助手能够运行和分析仿真。

特性

  • 基于插件的仿真引擎:支持多种仿真类型的可扩展架构
  • 内置模拟:排队、制造、库存和物流
  • MCP集成:将模拟作为克劳德和其他人工智能助手的工具公开
  • JWT身份验证:通过用户/租户管理实现安全的API访问
  • 多租户支持:数据隔离的行级安全
  • 实时WebSocket更新:实时流式传输模拟事件
  • 分析和报告:综合统计和趋势分析
  • ML预测:用于结果预测的PyTorch神经网络
  • 普罗米修斯指标:监视API性能和模拟运行

快速开始

安装

# Clone and install
git clone https://github.com/bulentsoykan/Simulation-AI-Agent.git
cd Simulation-AI-Agent
pip install -r requirements.txt

运行服务器

# Terminal 1: Start FastAPI server (port 8000)
python server.py

# Terminal 2: Start MCP server (port 8001)
python mcp_server.py

API将于http://localhost:8000交互式文档位于http://localhost:8000/docs

模拟类型

排队(M/M/c队列)

使用多台服务器模拟客户到达、等待和服务。

curl -X POST http://localhost:8000/simulations/queueing/run \
  -H "Content-Type: application/json" \
  -d '{"params": {"n_servers": 3, "arrival_rate": 10, "service_time": 2, "sim_time": 480}}'

参数:

  • n_servers:并行服务站的数量(默认值:1)
  • arrival_rate:每个时间单位的客户到达率(默认值:5.0)
  • service_time:每位客户的平均服务时间(默认值:3.0)
  • sim_time:总模拟时间(默认值:1440)

韵律学:

  • total_customers, avg_wait_time, avg_system_time, max_wait_time, server_utilization

制造(生产线)

模型在带有缓冲区的生产站中工作。

curl -X POST http://localhost:8000/simulations/manufacturing/run \
  -H "Content-Type: application/json" \
  -d '{"params": {"stations": ["Cutting", "Assembly", "QC"], "processing_times": [2.0, 5.0, 1.5], "arrival_rate": 0.3}}'

参数:

  • stations:按顺序排列的生产站名称
  • processing_times:每个站的处理时间
  • buffer_sizes:每个车站前的缓冲容量
  • arrival_rate:原材料到货率

韵律学:

  • throughput, avg_cycle_time, wip, station_utilization, bottleneck_station

库存政策

带有再订购点和交付周期的模型库存。

curl -X POST http://localhost:8000/simulations/inventory/run \
  -H "Content-Type: application/json" \
  -d '{"params": {"reorder_point": 20, "order_up_to": 100, "demand_rate": 5.0, "lead_time": 5.0}}'

参数:

  • reorder_point:触发重新订购的库存水平
  • order_up_to:订购时的目标库存水平(S)
  • demand_rate:每单位时间的平均需求
  • lead_time:订单和交货之间的时间

韵律学:

  • total_demand, total_fulfilled, fill_rate, avg_inventory, stockout_count, total_cost

物流(车辆路线)

模型具有交付车辆路线的容量限制。

curl -X POST http://localhost:8000/simulations/logistics/run \
  -H "Content-Type: application/json" \
  -d '{"params": {"num_vehicles": 3, "vehicle_capacity": 100, "num_customers": 20}}'

参数:

  • num_vehicles:送货车辆数量
  • vehicle_capacity:每辆车的容量
  • num_customers:客户地点数量
  • service_time:为每位客户服务的时间

韵律学:

  • customers_served, customers_unserved, total_distance, vehicle_utilization, demand_fulfilled

API终点

模拟

端点 方法 描述
/simulations GET 列出所有可用的模拟类型
/simulations/{type}/schema GET 获取模拟的参数模式
/simulations/{type}/run POST 运行模拟
/simulate POST 运行排队模拟(传统)

认证

端点 方法 描述
/auth/register POST 注册新用户
/auth/login POST 登录并获取令牌
/auth/refresh POST 刷新访问令牌
/auth/me GET 获取当前用户信息

分析

端点 方法 描述
/analytics/simulation-summary GET 获取模拟运行统计信息
/analytics/trends GET 获取随时间变化的指标趋势

ML预测

端点 方法 描述
/predict/{sim_type} GET 预测模拟结果
/ml/train POST 列车预测模型(管理员)
/ml/model-info GET 获取模型信息

健康与监测

端点 方法 描述
/health GET 健康检查
/health/ready GET 准备状态检查(DB)
/metrics GET 普罗米修斯指标

MCP工具

当通过MCP连接时,可以使用以下工具:

  • list_simulations:列出所有可用的模拟类型
  • run_simulation(simulation_type, params):运行任何模拟类型
  • simulate(...):运行排队模拟(便利包装器)
  • get_workorder_details(workorder_number):获取工单跟踪信息
  • get_workorder_configuration(workorder_number):获取工单配置

Claude桌面集成

添加到您的Claude桌面配置(~/Library/Application Support/Claude/claude_desktop_config.json):

{
  "mcpServers": {
    "simulation": {
      "command": "npx",
      "args": ["mcp-remote", "http://localhost:8001/mcp"]
    }
  }
}

添加自定义模拟

通过扩展创建新的模拟 BaseSimulation:

from simulations.base import BaseSimulation
from simulations.registry import SimulationRegistry

@SimulationRegistry.register
class MySimulation(BaseSimulation):
    name = "my_simulation"
    description = "My custom simulation"

    def get_parameter_schema(self) -> dict:
        return {
            "type": "object",
            "properties": {
                "my_param": {"type": "number", "default": 1.0}
            }
        }

    def get_metrics_schema(self) -> dict:
        return {
            "type": "object",
            "properties": {
                "my_metric": {"type": "number"}
            }
        }

    def run(self, params: dict, callback=None) -> dict:
        validated = self.validate_params(params)
        # Run your simulation logic
        return {"my_metric": 42.0}

配置

环境变量(或 .env 文件):

变量 默认值 描述
DATABASE_URL sqlite:///./simulation.db 数据库连接字符串
JWT_SECRET_KEY (已生成) JWT签名密码
API_PORT 8000 FastAPI服务器端口
MCP_PORT 8001 MCP服务器端口
DEBUG false 启用调试模式

项目结构

simulation-ai-agent/
├── server.py              # FastAPI application
├── mcp_server.py          # MCP server
├── config.py              # Configuration settings
├── simulations/           # Simulation plugins
│   ├── base.py            # BaseSimulation class
│   ├── registry.py        # Plugin registry
│   ├── queueing.py        # M/M/c queue
│   ├── manufacturing.py   # Production line
│   ├── inventory.py       # Inventory management
│   └── logistics.py       # Vehicle routing
├── database/              # SQLAlchemy models
│   ├── connection.py      # DB session management
│   └── models.py          # ORM models
├── auth/                  # JWT authentication
│   ├── jwt_handler.py     # Token creation/validation
│   ├── dependencies.py    # FastAPI dependencies
│   └── schemas.py         # Pydantic schemas
├── analytics/             # Reporting
│   ├── aggregations.py    # Query aggregations
│   └── reports.py         # Report generation
├── ml/                    # Machine learning
│   ├── predictor.py       # PyTorch inference
│   └── trainer.py         # Model training
├── websocket/             # Real-time updates
│   └── manager.py         # Connection manager
└── monitoring/            # Prometheus metrics
    └── metrics.py         # Metric collectors

作者

Bulent 冷却器

许可证

麻省理工学院

项目概述

一个基于插件的MCP服务器,向AI助手展示离散事件模拟。特征:

  • 基于插件的仿真引擎(排队、制造、库存、物流)
  • 支持多租户的JWT身份验证
  • 实时WebSocket更新
  • 分析和基于机器学习的预测
  • 普罗米修斯监控

建筑

┌─────────────────┐    WS/HTTP   ┌─────────────────┐
│  MCP Clients    │ ◄──────────► │  mcp_server.py  │
└─────────────────┘    :8001     └────────┬────────┘
                                          │
┌─────────────────┐    WS/HTTP   ┌────────▼────────┐    ┌─────────────────┐
│  Web Clients    │ ◄──────────► │   server.py     │◄──►│  SQLite DB      │
└─────────────────┘    :8000     │   (FastAPI)     │    │  (SQLAlchemy)   │
                                 └────────┬────────┘    └─────────────────┘
                                          │
              ┌───────────────────────────┼───────────────────────────┐
              ▼                           ▼                           ▼
    ┌─────────────────┐         ┌─────────────────┐         ┌─────────────────┐
    │ simulations/    │         │  ml/            │         │  analytics/     │
    │  base.py        │         │  predictor.py   │         │  reports.py     │
    │  registry.py    │         │   (PyTorch)     │         │  aggregations.py│
    │  queueing.py    │         └─────────────────┘         └─────────────────┘
    │  manufacturing.py│
    │  inventory.py   │
    │  logistics.py   │
    └─────────────────┘

运行项目

# Install dependencies
pip install -r requirements.txt

# Terminal 1: FastAPI server (port 8000)
python server.py

# Terminal 2: MCP server (port 8001)
python mcp_server.py

关键组件

仿真插件系统(simulations/)

  • base.py: BaseSimulation 抽象类 run(), get_parameter_schema(), get_metrics_schema()
  • registry.py: SimulationRegistry 用于插件发现和实例化
  • 内置类型: queueing, manufacturing, inventory, logistics

身份验证(auth/)

  • 基于JWT的访问/刷新令牌
  • 多租户通过 tenant_id 在所有型号上
  • 依赖关系: get_current_user, get_current_tenant, require_role()

数据库(database/)

  • SQLAlchemy ORM与SQLite(可配置为PostgreSQL)
  • 模型: Tenant, User, SimulationRun, Workorder

ML预测(ml/)

  • 基于历史模拟数据训练的PyTorch神经网络
  • SimulationPredictor 为了推理, SimulationTrainer 用于培训

API终点

类别 端点 描述
模拟 GET /simulations 列出模拟类型
GET /simulations/{type}/schema 获取参数架构
POST /simulations/{type}/run 运行模拟
认证 POST /auth/register 注册用户
POST /auth/login 获取代币
GET /auth/me 当前用户
健康 GET /health 健康检查
GET /metrics 普罗米修斯指标

MCP工具

  • list_simulations():列出可用的模拟类型
  • run_simulation(simulation_type, params):运行任何模拟
  • simulate(...):运行排队模拟(传统)
  • get_workorder_details(workorder_number):获取工单信息
  • get_workorder_configuration(workorder_number):获取工单配置

添加新模拟

from simulations.base import BaseSimulation
from simulations.registry import SimulationRegistry

@SimulationRegistry.register
class MySimulation(BaseSimulation):
    name = "my_simulation"
    description = "Description here"

    def get_parameter_schema(self) -> dict:
        return {"type": "object", "properties": {...}}

    def get_metrics_schema(self) -> dict:
        return {"type": "object", "properties": {...}}

    def run(self, params: dict, callback=None) -> dict:
        validated = self.validate_params(params)
        # Simulation logic here
        return {"metric": value}

配置

从环境加载的设置或 .env:

  • DATABASE_URL:数据库连接(默认值: sqlite:///./simulation.db)
  • JWT_SECRET_KEY:JWT签名秘密
  • API_PORT / MCP_PORT:服务器端口(8000/8001)
  • DEBUG:启用调试模式