MBE API 完整参考文档

版本: v2.1 | 更新: 2026-02-12 | Base URL: https://mbe.hi-maker.com


目录


1. 概述

基础信息

属性
Base URL(生产) https://mbe.hi-maker.com
Base URL(开发) http://localhost:8001
协议 HTTPS(生产强制)
数据格式 JSON(Content-Type: application/json
字符编码 UTF-8
API 版本 v1

通用响应格式

成功

{
  "success": true,
  "data": { "..." },
  "message": "操作成功"
}

失败

{
  "success": false,
  "error": "error_code",
  "message": "人类可读的错误描述",
  "detail": "详细信息(仅开发环境)"
}

2. 认证与鉴权

2.1 API Key 认证(推荐)

适用于 2B 客户的服务端调用。API Key 以 mbe_sk_ 为前缀。

四种传递方式(任选其一):

# 方式 1: Bearer Token(推荐)
Authorization: Bearer mbe_sk_xxxxxxxxxxxxxxxxxxxx

# 方式 2: 直接传递
Authorization: mbe_sk_xxxxxxxxxxxxxxxxxxxx

# 方式 3: 自定义 Header
X-API-Key: mbe_sk_xxxxxxxxxxxxxxxxxxxx

# 方式 4: Query 参数(不推荐,日志中可能暴露)
GET /api/v1/client/me?api_key=mbe_sk_xxxxxxxxxxxxxxxxxxxx

获取方式

  1. 访问 开发者门户 → 控制台 → API 密钥
  2. 或通过 API 创建:POST /api/v1/client/keys

安全特性

  • 支持 IP 白名单(allowed_ips
  • 支持按 Key 设置权限范围(permissions
  • 支持设置过期时间

2.2 JWT Token 认证

适用于已登录的终端用户。

Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

通过 POST /api/v1/users/login 获取。

2.3 Device ID 认证

适用于匿名客户端。

X-Device-ID: unique_device_identifier

3. 对话 API(核心)

3.1 专家问答

向专家提问并获取回答。

POST /mcp/analyze

请求体

字段 类型 必填 说明
user_input string 用户问题
device_id string 设备/会话 ID
user_id string 用户 ID
preferred_expert string 指定专家 ID
fast_mode boolean 快速模式(跳过 Self-Critique,默认 false)
ultra_fast boolean 极速模式(跳过 LLM,直接返回检索结果)

请求示例

curl -X POST https://mbe.hi-maker.com/mcp/analyze \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "user_input": "合同违约的法律后果是什么?",
    "device_id": "my-app-001"
  }'

响应

{
  "success": true,
  "expert": "民事法律专家",
  "expert_id": "dynamic_legal_001",
  "answer": "合同违约的法律后果主要包括:1. 继续履行...",
  "sources": [
    {"name": "民法典第577条", "confidence": 0.95, "snippet": "..."}
  ],
  "confidence": 0.92,
  "metadata": {
    "routing_time_ms": 45,
    "answer_time_ms": 1200,
    "self_critique_passed": true
  }
}

3.2 WebSocket 实时对话

ws://mbe.hi-maker.com/ws?device_id={device_id}

消息格式

// 发送
{"type": "chat", "content": "你好", "user_id": "user123"}

// 接收
{"type": "response", "expert": "...", "answer": "...", "confidence": 0.9}

3.3 MCP 协议(Cursor/Claude Desktop)

{
  "mcpServers": {
    "mbe": {
      "url": "https://mbe.hi-maker.com/mcp/sse",
      "headers": {"Authorization": "Bearer mbe_sk_xxxx"}
    }
  }
}

4. 知识库 API

4.1 创建知识库

POST /admin/knowledge/create
字段 类型 必填 说明
name string 知识库名称
description string 描述
language string 语言(auto/zh/en,默认 auto)

响应

{"success": true, "kb_id": "kb_abc123", "message": "知识库创建成功"}

4.2 上传文档

POST /admin/knowledge/upload/{kb_id}
Content-Type: multipart/form-data
字段 类型 必填 说明
file file PDF/TXT/MD/DOCX 文件
use_ocr boolean 是否使用 OCR(扫描件)
use_moe boolean 是否使用 MoE 分块(默认 true)

安全说明:上传时自动执行 Prompt 注入扫描(L1 KB 间接注入检测)。

4.3 导入网页

POST /admin/knowledge/import-url/{kb_id}
字段 类型 必填 说明
url string 网页 URL

4.4 搜索知识库

POST /admin/knowledge/search/{kb_id}
字段 类型 必填 说明
query string 搜索查询
top_k integer 返回结果数(默认 5)

4.5 获取知识库信息

GET /admin/knowledge/{kb_id}

4.6 删除知识库

DELETE /admin/knowledge/{kb_id}

5. 专家管理 API

5.1 发布专家

将知识库转为可提问的专家。

POST /admin/knowledge/expert/publish
字段 类型 必填 说明
kb_id string 知识库 ID
name string 专家名称
system_prompt string 系统提示(角色定义)

说明:发布时自动执行可靠性门禁检查(一级门禁)。

5.2 专家池

GET /expert-pool/available

返回当前用户可用的所有专家列表。

5.3 专家试用

POST /expert-pool/{expert_id}/try
字段 类型 必填 说明
query string 问题

6. 评估 API

6.1 专家质量评估

POST /api/evaluation/expert
字段 类型 必填 说明
kb_id string 知识库 ID
expert_id string 专家 ID
num_tests integer 测试用例数(默认 20)

6.2 可靠性门禁

POST /api/evaluation/gate/{expert_id}

响应

{
  "expert_id": "dynamic_legal_001",
  "gate_level": 1,
  "passed": true,
  "reliability_passed": true,
  "capability_passed": true,
  "overall_score": 92.5,
  "details": {
    "citation_pass_rate": 1.0,
    "hallucination_pass_rate": 1.0,
    "refusal_pass_rate": 0.97,
    "faithfulness_pass_rate": 0.96
  }
}

6.3 净分数评估

POST /api/evaluation/net-score
字段 类型 必填 说明
expert_id string 专家 ID
test_cases array [{question, answer, reference}]

响应

{
  "success": true,
  "data": {
    "net_score": 0.65,
    "correct_rate": 0.75,
    "incorrect_rate": 0.10,
    "uncertain_rate": 0.15,
    "calibration_score": 0.60,
    "hallucination_rate": 0.05
  },
  "interpretation": {
    "net_score_level": "良好",
    "net_score_description": "专家回答总体可靠,少量错误",
    "calibration_description": "专家在不确定时有时会编造答案(需改进)",
    "hallucination_warning": "幻觉率 5% ✅ 正常"
  }
}

6.4 净分数单条评估

POST /api/evaluation/net-score/single
字段 类型 必填 说明
question string 问题
answer string 回答
reference string 参考答案

6.5 评估历史

GET /api/evaluation/history/{expert_id}

6.6 评估趋势

GET /api/evaluation/trend/{expert_id}

7. Benchmark API

7.1 运行 Benchmark

POST /api/evaluation/benchmark/run
字段 类型 必填 说明
dimensions array 维度列表(null=全部 6 个)
num_trials integer 试验次数(1-10,默认 1)
concurrency integer 并发数(1-10,默认 3)

可选维度

维度 ID 说明
expert_matching 专家匹配准确率
kb_qa_quality 知识库问答质量(含净分数)
routing_efficiency 路由效率与延迟
hope_personalization HOPE 个性化效果
self_critique_effectiveness Self-Critique 15 模块有效性
e2e_task_completion 端到端任务完成率

请求示例

curl -X POST https://mbe.hi-maker.com/api/evaluation/benchmark/run \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "dimensions": ["kb_qa_quality", "self_critique_effectiveness"],
    "num_trials": 3
  }'

响应

{
  "success": true,
  "data": {
    "report_id": "bench_20260211_191800",
    "overall_score": 0.8234,
    "overall_pass_rate": 0.8500,
    "total_cases": 13,
    "num_trials": 3,
    "dimensions": {
      "kb_qa_quality": {
        "mean_score": 0.8400,
        "ci_95": [0.7800, 0.9000],
        "pass_rate": 0.8000,
        "avg_latency_ms": 1250.0,
        "by_difficulty": {"easy": 0.95, "medium": 0.80, "hard": 0.65}
      },
      "self_critique_effectiveness": {
        "mean_score": 0.8750,
        "ci_95": [0.8200, 0.9300],
        "pass_rate": 0.8750
      }
    }
  }
}

7.2 列出 Benchmark 维度

GET /api/evaluation/benchmark/dimensions

8. 知识库维护 API(Admin)

前缀:/api/ops/kb,需 Admin 认证。提供知识库的导出、备份、清洗、质量扫描能力。

8.1 导出单个知识库

POST /api/ops/kb/export/{kb_id}

导出指定知识库的元数据 + 所有 chunks 为 JSON 文件。

响应

{
  "success": true,
  "result": {
    "kb_id": "kb_law_001",
    "kb_name": "法律知识库",
    "export_path": "/exports/knowledge/kb_law_001.json",
    "chunk_count": 256,
    "file_size_bytes": 524288,
    "duration_ms": 150
  }
}

8.2 批量导出

POST /api/ops/kb/export-all

导出所有知识库,每个知识库一个 JSON 文件,统一放在时间戳目录下。

8.3 完整备份

POST /api/ops/kb/backup

备份整个 knowledge_bases/ 目录(快照),自动保留最近 7 份。

8.4 列出历史备份

GET /api/ops/kb/backups

返回所有备份的名称、路径、创建时间、大小。

8.5 清洗知识库

POST /api/ops/kb/cleanup/{kb_id}
字段 类型 必填 说明
dry_run boolean 仅预览不执行(默认 false)

清洗项:去重(MD5)、移除空/极短 chunk、格式修正(统一换行符、多余空行)。

8.6 批量清洗

POST /api/ops/kb/cleanup-all

参数同 8.5。

8.7 质量扫描

GET /api/ops/kb/quality-scan

检查所有知识库的健康状态:状态异常、空知识库、缺失文件、缺失向量索引。

响应

{
  "scan_id": "scan_20260212_034500",
  "total_kbs": 12,
  "healthy": 10,
  "warnings": 1,
  "critical": 1,
  "details": ["..."],
  "duration_ms": 320
}

9. 知识图谱 API(Admin)

前缀:/api/graph,需 Admin 认证。封装统一知识图谱(NetworkX)的查询与分析能力。

9.1 图谱统计

GET /api/graph/stats

返回节点/边数量、类型分布、连通分量数、密度。

9.2 健康检查

GET /api/graph/health

检测孤立节点、前置依赖环、无效边类型。

9.3 节点列表

GET /api/graph/nodes?node_type=expert&limit=100&offset=0
参数 类型 说明
node_type string 过滤类型:expert, domain, keyword, topic, user, knowledge_point, session
limit int 返回数量(1-1000,默认 100)
offset int 偏移量

9.4 节点详情

GET /api/graph/node/{node_id}

返回节点数据、出边、入边、出/入度。

9.5 多跳查询

POST /api/graph/query/multi-hop
字段 类型 必填 说明
start_node string 起始节点 ID
max_hops int 最大跳数(1-5,默认 2)
edge_types array 边类型过滤
target_node_type string 目标节点类型过滤
min_weight float 最小权重阈值

9.6 PageRank 排序

GET /api/graph/query/pagerank?node_type=expert&top_k=20

9.7 影响分析

GET /api/graph/query/impact/{node_id}

计算移除指定节点后受影响的下游节点,按类型分组。

9.8 连通分量

GET /api/graph/components

发现孤立的子图,用于检测图谱完整性。

9.9 导出图谱

POST /api/graph/export

导出全部节点和边为 JSON。


10. 运维 Agent API(Admin)

前缀:/api/ops,需 Admin 认证。提供运维命令执行、代码运行、Benchmark 自动化能力。

10.1 执行命令

POST /api/ops/execute

白名单验证 + 审计的 shell 命令执行。

10.2 运行代码

POST /api/ops/run-code
字段 类型 说明
code string 代码内容
language string python / javascript / typescript / shell
timeout int 超时秒数(默认 30)
operator string 操作人(审计用)

10.3 运行测试

POST /api/ops/run-test
字段 类型 说明
test_path string pytest 路径
markers string pytest 标记过滤

10.4 Benchmark 自动化运行

POST /api/ops/benchmark/run

10.5 Benchmark 环境检查

GET /api/ops/benchmark/health

10.6 Benchmark 历史

GET /api/ops/benchmark/history

10.7 Benchmark 趋势

GET /api/ops/benchmark/trend

10.8 保存基线

POST /api/ops/benchmark/baseline

11. 2B 客户自助 API

前缀:/api/v1/client,需 API Key 认证。

11.1 客户信息

GET /api/v1/client/me

响应

{
  "client_id": "cli_001",
  "name": "Acme Corp",
  "email": "dev@acme.com",
  "status": "active",
  "plan": "professional",
  "created_at": "2026-01-15T00:00:00Z"
}

11.2 使用量统计

GET /api/v1/client/usage?period=month
参数 类型 说明
period string day / week / month / all

11.3 每日用量

GET /api/v1/client/usage/daily?days=30

11.4 API Key 管理

# 列出 Keys
GET /api/v1/client/keys

# 创建 Key
POST /api/v1/client/keys
Body: {"name": "Production Key", "permissions": ["read", "write"], "allowed_ips": ["1.2.3.4"]}

# 吊销 Key
DELETE /api/v1/client/keys/{key_id}

# 禁用 Key
PUT /api/v1/client/keys/{key_id}/disable

11.5 账单

# 账单列表
GET /api/v1/client/bills?status=unpaid&limit=20

# 账单详情
GET /api/v1/client/bills/{bill_id}

11.6 套餐定价

GET /api/v1/client/pricing

(无需认证)

11.7 服务状态

GET /api/v1/client/status

12. HOPE 偏好 API

9.1 获取用户偏好

GET /api/v1/users/{user_id}/preferences

9.2 更新偏好

PUT /api/v1/users/{user_id}/preferences
字段 类型 说明
style string 回答风格(concise/detailed/professional)
language string 偏好语言
expertise_level string 专业水平(beginner/intermediate/expert)

13. Webhook 事件

配置 Webhook

POST /api/webhook/register
字段 类型 说明
url string 回调 URL
events array 订阅事件类型
secret string 签名密钥

支持事件

事件 触发时机
expert.published 专家发布上线
expert.quarantined 专家被隔离
evaluation.completed 评估完成
kb.updated 知识库更新
gate.failed 门禁检查未通过

14. 错误处理

HTTP 状态码

状态码 说明
200 成功
400 请求参数错误
401 未认证
403 权限不足 / Prompt 注入拦截
404 资源不存在
413 请求体过大(> 50MB)
429 请求过于频繁
500 服务器内部错误

错误码

错误码 说明
invalid_api_key API Key 无效或已过期
rate_limit_exceeded 超过请求频率限制
kb_not_found 知识库不存在
expert_not_found 专家不存在
expert_quarantined 专家已被隔离
gate_check_failed 可靠性门禁未通过
prompt_injection_detected 检测到 Prompt 注入
file_too_large 文件超过大小限制
insufficient_quota 配额不足

Prompt 注入拦截响应

当安全系统检测到 Prompt 注入时返回 403:

{
  "error": "prompt_injection_detected",
  "message": "您的请求包含疑似注入指令,已被安全系统拦截。如有疑问请联系管理员。",
  "risk_level": "high"
}

15. 限流策略

计划 速率限制 并发限制
免费 10 次/分钟 2
标准 60 次/分钟 5
专业 300 次/分钟 20
企业 自定义 自定义

超限时返回 429,响应头包含:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1707667200
Retry-After: 45

附录:SDK 示例

Python

import requests

class MBEClient:
    """MBE Python SDK 简易封装"""

    def __init__(self, api_key: str, base_url: str = "https://mbe.hi-maker.com"):
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        }

    def ask(self, question: str, expert_id: str = None, fast_mode: bool = False) -> dict:
        """向专家提问"""
        payload = {"user_input": question, "device_id": "sdk-python"}
        if expert_id:
            payload["preferred_expert"] = expert_id
        if fast_mode:
            payload["fast_mode"] = True
        resp = requests.post(f"{self.base_url}/mcp/analyze", headers=self.headers, json=payload)
        resp.raise_for_status()
        return resp.json()

    def create_kb(self, name: str, description: str = "") -> dict:
        """创建知识库"""
        resp = requests.post(f"{self.base_url}/admin/knowledge/create",
                             headers=self.headers, json={"name": name, "description": description})
        resp.raise_for_status()
        return resp.json()

    def upload_file(self, kb_id: str, filepath: str) -> dict:
        """上传文件到知识库"""
        with open(filepath, "rb") as f:
            resp = requests.post(f"{self.base_url}/admin/knowledge/upload/{kb_id}",
                                 headers={"Authorization": self.headers["Authorization"]},
                                 files={"file": f})
        resp.raise_for_status()
        return resp.json()

    def evaluate_net_score(self, expert_id: str, test_cases: list) -> dict:
        """净分数评估"""
        resp = requests.post(f"{self.base_url}/api/evaluation/net-score",
                             headers=self.headers,
                             json={"expert_id": expert_id, "test_cases": test_cases})
        resp.raise_for_status()
        return resp.json()

    def run_benchmark(self, dimensions: list = None, num_trials: int = 1) -> dict:
        """运行 Benchmark"""
        resp = requests.post(f"{self.base_url}/api/evaluation/benchmark/run",
                             headers=self.headers,
                             json={"dimensions": dimensions, "num_trials": num_trials})
        resp.raise_for_status()
        return resp.json()


# 使用示例
client = MBEClient("mbe_sk_your_api_key_here")

# 1. 创建专家
kb = client.create_kb("产品手册", "XX 产品使用说明")
client.upload_file(kb["kb_id"], "manual.pdf")

# 2. 提问
answer = client.ask("这个产品支持哪些操作系统?")
print(f"专家: {answer['expert']}")
print(f"回答: {answer['answer']}")

# 3. 评估
score = client.evaluate_net_score("my_expert", [
    {"question": "支持Windows吗?", "answer": "是的", "reference": "支持 Windows/Mac/Linux"},
])
print(f"净分数: {score['data']['net_score']}")

TypeScript / JavaScript

class MBEClient {
  private baseUrl: string;
  private headers: Record<string, string>;

  constructor(apiKey: string, baseUrl = "https://mbe.hi-maker.com") {
    this.baseUrl = baseUrl;
    this.headers = {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    };
  }

  async ask(question: string, options?: { expertId?: string; fastMode?: boolean }) {
    const body: any = { user_input: question, device_id: "sdk-ts" };
    if (options?.expertId) body.preferred_expert = options.expertId;
    if (options?.fastMode) body.fast_mode = true;

    const resp = await fetch(`${this.baseUrl}/mcp/analyze`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(body),
    });
    return resp.json();
  }

  async createKB(name: string, description = "") {
    const resp = await fetch(`${this.baseUrl}/admin/knowledge/create`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ name, description }),
    });
    return resp.json();
  }

  async evaluateNetScore(expertId: string, testCases: Array<{ question: string; answer: string; reference?: string }>) {
    const resp = await fetch(`${this.baseUrl}/api/evaluation/net-score`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ expert_id: expertId, test_cases: testCases }),
    });
    return resp.json();
  }

  async runBenchmark(dimensions?: string[], numTrials = 1) {
    const resp = await fetch(`${this.baseUrl}/api/evaluation/benchmark/run`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify({ dimensions, num_trials: numTrials }),
    });
    return resp.json();
  }
}

// 使用示例
const client = new MBEClient("mbe_sk_your_api_key_here");

const answer = await client.ask("什么是合同违约?");
console.log(`专家: ${answer.expert}`);
console.log(`回答: ${answer.answer}`);

cURL 速查

# 对话
curl -X POST https://mbe.hi-maker.com/mcp/analyze \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{"user_input": "什么是合同违约?", "device_id": "curl-test"}'

# 创建知识库
curl -X POST https://mbe.hi-maker.com/admin/knowledge/create \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{"name": "测试知识库"}'

# 上传文件
curl -X POST https://mbe.hi-maker.com/admin/knowledge/upload/kb_xxx \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -F "file=@document.pdf"

# 净分数评估
curl -X POST https://mbe.hi-maker.com/api/evaluation/net-score \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{"expert_id": "my_expert", "test_cases": [{"question": "Q", "answer": "A", "reference": "R"}]}'

# Benchmark
curl -X POST https://mbe.hi-maker.com/api/evaluation/benchmark/run \
  -H "Authorization: Bearer mbe_sk_xxxx" \
  -H "Content-Type: application/json" \
  -d '{"num_trials": 3}'

# 客户信息
curl https://mbe.hi-maker.com/api/v1/client/me \
  -H "Authorization: Bearer mbe_sk_xxxx"


14. 应用市场 API (Admin)

14.1 发布应用

POST /api/apps/publish

请求体

{
  "name": "my-app",
  "display_name": "我的应用",
  "description": "一个基于 MBE 的 AI 应用",
  "category": "tech",
  "tags": ["ai", "chatbot"],
  "developer_id": "dev_xxx",
  "pricing_model": "free",
  "mbe_features": ["api", "sdk"]
}

14.2 提交审核

POST /api/apps/{app_id}/submit

14.3 审核应用

POST /api/apps/{app_id}/review

请求体

{
  "action": "approve",
  "reviewer": "admin",
  "comment": "符合要求"
}

14.4 应用列表 / 搜索

GET /api/apps/list?category=tech&sort_by=newest&limit=20
GET /api/apps/search?q=chatbot
GET /api/apps/categories
GET /api/apps/{app_id}

14.5 安装/卸载

POST   /api/apps/{app_id}/install?user_id=u1
DELETE /api/apps/{app_id}/install?user_id=u1
GET    /api/apps/installed?user_id=u1
GET    /api/apps/my?developer_id=dev1

15. 一键部署 API (Admin)

15.1 获取部署目标

GET /api/deploy/targets

响应:Docker 本地 / Cloudflare Pages / Vercel / 本地开发

15.2 创建部署

POST /api/deploy/create

请求体

{
  "app_name": "my-app",
  "target": "docker",
  "source_path": "/app/src",
  "port": 3000,
  "env_vars": {"NODE_ENV": "production"}
}

15.3 部署状态 / 历史 / 回滚

GET  /api/deploy/status/{deploy_id}
GET  /api/deploy/history?app_id=xxx
POST /api/deploy/rollback/{deploy_id}

16. 收益分成 API (Admin)

16.1 记录收益(内部调用)

POST /api/revenue/record

请求体

{
  "developer_id": "dev1",
  "app_id": "app1",
  "app_name": "Test App",
  "amount": 100.0
}

分成比例:开发者 70% / 平台 30%

16.2 开发者收益

GET /api/revenue/developer/{id}/summary
GET /api/revenue/developer/{id}/apps
GET /api/revenue/developer/{id}/trend?days=30

16.3 结算

POST /api/revenue/settlement/request
GET  /api/revenue/settlement/history

最低结算金额 ¥100。

16.4 平台概览

GET /api/revenue/platform/summary

📬 API 问题反馈:开发者反馈

📖 OpenAPI 文档:https://mbe.hi-maker.com/docs(Swagger UI)/ https://mbe.hi-maker.com/redoc(ReDoc)