/ api_zh.md
api_zh.md
   1  # A.I.G API 文档
   2  
   3  
   4  ## 概述
   5  
   6  A.I.G(AI-Infra-Guard) 提供了一套完整的API接口,用于AI基础设施扫描、MCP安全扫描、大模型安全体检和模型配置管理。本文档详细介绍了各个API接口的使用方法、参数说明和示例代码。
   7  
   8  项目运行后,可访问 `http://localhost:8088/docs/index.html` 查看Swagger文档。
   9  
  10  ## 文档目录
  11  
  12  ### 基础接口
  13  - 文件上传接口
  14  - 任务创建接口
  15  
  16  ### 任务类型
  17  1. MCP 安全扫描 API
  18  2. AI 基础设施扫描 API
  19  3. 大模型安全体检 API
  20  4. Agent 安全扫描 API
  21  
  22  ### 模型管理 API
  23  1. 获取模型列表
  24  2. 获取模型详情
  25  3. 创建模型
  26  4. 更新模型
  27  5. 删除模型
  28  6. YAML配置模型
  29  
  30  ### 任务状态查询
  31  - 获取任务状态
  32  - 获取任务结果
  33  
  34  ### 完整工作流程示例
  35  - MCP 源码扫描完整流程
  36  - 模型红队测评完整流程
  37  
  38  ## 基础信息
  39  
  40  - **Base URL**: `http://localhost:8088` (根据实际部署调整)
  41  - **Content-Type**: `application/json`
  42  - **认证方式**: 通过请求头传递认证信息
  43  
  44  ## 通用响应格式
  45  
  46  所有API接口都遵循统一的响应格式:
  47  
  48  ```json
  49  {
  50    "status": 0,           // 状态码: 0=成功, 1=失败
  51    "message": "操作成功",  // 响应消息
  52    "data": {}             // 响应数据
  53  }
  54  ```
  55  
  56  ## API 接口列表
  57  
  58  ### 1. 文件上传接口
  59  
  60  #### 接口信息
  61  - **URL**: `/api/v1/app/taskapi/upload`
  62  - **方法**: `POST`
  63  - **Content-Type**: `multipart/form-data`
  64  
  65  #### 参数说明
  66  | 参数名 | 类型 | 必填 | 说明 |
  67  |--------|------|------|------|
  68  | file | file | 是 | 要上传的文件,支持zip、json、txt等格式 |
  69  
  70  #### 响应字段
  71  | 字段名 | 类型 | 说明 |
  72  |--------|------|------|
  73  | fileUrl | string | 文件访问URL |
  74  | filename | string | 文件名 |
  75  | size | integer | 文件大小(字节) |
  76  
  77  #### Python 示例
  78  ```python
  79  import requests
  80  
  81  def upload_file(file_path):
  82      url = "http://localhost:8088/api/v1/app/taskapi/upload"
  83      
  84      with open(file_path, 'rb') as f:
  85          files = {'file': f}
  86          response = requests.post(url, files=files)
  87      
  88      return response.json()
  89  
  90  # 使用示例
  91  result = upload_file("example.zip")
  92  print(f"文件上传成功: {result['data']['fileUrl']}")
  93  ```
  94  
  95  #### cURL 示例
  96  ```bash
  97  curl -X POST \
  98    http://localhost:8088/api/v1/app/taskapi/upload \
  99    -F "file=@example.zip"
 100  ```
 101  
 102  ### 2. 任务创建接口
 103  
 104  #### 接口信息
 105  - **URL**: `/api/v1/app/taskapi/tasks`
 106  - **方法**: `POST`
 107  - **Content-Type**: `application/json`
 108  
 109  #### 请求参数
 110  | 参数名 | 类型 | 必填 | 说明 |
 111  |--------|------|------|------|
 112  | type | string | 是 | 任务类型:mcp_scan、ai_infra_scan、model_redteam_report、agent_scan |
 113  | content | object | 是 | 任务内容,根据任务类型不同而不同 |
 114  
 115  #### 响应字段
 116  | 字段名 | 类型 | 说明 |
 117  |--------|------|------|
 118  | session_id | string | 任务会话ID |
 119  
 120  ---
 121  
 122  ## 任务类型详细说明
 123  
 124  ### 1. MCP 安全扫描 API
 125  
 126  MCP(Model Context Protocol)安全扫描用于检测MCP服务中的安全漏洞。
 127  
 128  #### 请求参数说明
 129  | 参数名 | 类型 | 必填 | 说明 |
 130  |--------|------|------|------|
 131  | model | object | 是 | 模型配置 |
 132  | model.model | string | 是 | 模型名称,如"gpt-4" |
 133  | model.token | string | 是 | API密钥 |
 134  | model.base_url | string | 否 | 基础URL,默认为OpenAI API |
 135  | thread | integer | 否 | 并发线程数,默认4 |
 136  | language | string | 否 | 语言代码,如"zh" |
 137  | attachments | string | 否 | 附件文件路径(需要先上传文件) |
 138  | headers | object | 否 | 自定义请求头,如 {"Authorization": "Bearer token"} |
 139  | prompt | string | 否 | 自定义扫描提示词描述 |
 140  
 141  #### 源码扫描流程
 142  1. 先调用文件上传接口上传源码文件
 143  2. 使用返回的fileUrl作为attachments参数
 144  3. 调用MCP扫描API
 145  
 146  #### Python 示例
 147  ```python
 148  import requests
 149  import json
 150  
 151  def mcp_scan_with_source_code():
 152      # 1. 上传源码文件
 153      upload_url = "http://localhost:8088/api/v1/app/taskapi/upload"
 154      with open("source_code.zip", 'rb') as f:
 155          files = {'file': f}
 156          upload_response = requests.post(upload_url, files=files)
 157      
 158      if upload_response.json()['status'] != 0:
 159          raise Exception("文件上传失败")
 160      
 161      fileUrl = upload_response.json()['data']['fileUrl']
 162      
 163      # 2. 创建MCP扫描任务
 164      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 165      task_data = {
 166          "type": "mcp_scan",
 167          "content": {
 168              "prompt": "扫描此MCP服务器",
 169              "model": {
 170                  "model": "gpt-4",
 171                  "token": "sk-your-api-key",
 172                  "base_url": "https://api.openai.com/v1"
 173              },
 174              "thread": 4,
 175              "language": "zh",
 176              "attachments": fileUrl
 177          }
 178      }
 179      
 180      response = requests.post(task_url, json=task_data)
 181      return response.json()
 182  
 183  # 使用示例
 184  result = mcp_scan_with_source_code()
 185  print(f"任务创建成功,会话ID: {result['data']['session_id']}")
 186  ```
 187  
 188  #### 动态URL扫描示例
 189  ```python
 190  def mcp_scan_with_url():
 191      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 192      task_data = {
 193          "type": "mcp_scan",
 194          "content": {
 195              "prompt": "https://mcp-server.example.com",  # 填写MCP服务URL进行远程扫描
 196              "model": {
 197                  "model": "gpt-4",
 198                  "token": "sk-your-api-key",
 199                  "base_url": "https://api.openai.com/v1"
 200              },
 201              "thread": 4,
 202              "language": "zh"
 203          }
 204      }
 205      
 206      response = requests.post(task_url, json=task_data)
 207      return response.json()
 208  ```
 209  
 210  #### cURL 示例
 211  ```bash
 212  # 源码扫描
 213  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 214    -H "Content-Type: application/json" \
 215    -d '{
 216      "type": "mcp_scan",
 217      "content": {
 218        "prompt": "扫描此MCP服务器",
 219        "model": {
 220          "model": "gpt-4",
 221          "token": "sk-your-api-key",
 222          "base_url": "https://api.openai.com/v1"
 223        },
 224        "thread": 4,
 225        "language": "zh",
 226        "attachments": "http://localhost:8088/uploads/example.zip"
 227      }
 228    }'
 229  
 230  # URL扫描
 231  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 232    -H "Content-Type: application/json" \
 233    -d '{
 234      "type": "mcp_scan",
 235      "content": {
 236        "prompt": "https://mcp-server.example.com",
 237        "model": {
 238          "model": "gpt-4",
 239          "token": "sk-your-api-key",
 240          "base_url": "https://api.openai.com/v1"
 241        },
 242        "thread": 4,
 243        "language": "zh"
 244      }
 245    }'
 246  ```
 247  
 248  ### 2. AI 基础设施扫描 API
 249  
 250  用于扫描AI基础设施的安全漏洞和配置问题。
 251  
 252  #### 请求参数说明
 253  | 参数名 | 类型 | 必填 | 说明 |
 254  |--------|------|------|------|
 255  | target | array | 是 | 扫描目标URL列表 |
 256  | headers | object | 否 | 自定义请求头 |
 257  | timeout | integer | 否 | 请求超时时间(秒),默认30 |
 258  | model | object | 否 | 模型配置,用于辅助结果分析 |
 259  | model.model | string | 是 | 模型名称,如"gpt-4" |
 260  | model.token | string | 是 | API密钥 |
 261  | model.base_url | string | 否 | 基础URL,默认为OpenAI API |
 262  
 263  #### Python 示例
 264  ```python
 265  def ai_infra_scan():
 266      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 267      task_data = {
 268          "type": "ai_infra_scan",
 269          "content": {
 270              "target": [
 271                  "https://ai-service1.example.com",
 272                  "https://ai-service2.example.com"
 273              ],
 274              "headers": {
 275                  "Authorization": "Bearer your-token",
 276                  "User-Agent": "AI-Infra-Guard/1.0"
 277              },
 278              "timeout": 30,
 279              "model": {
 280                  "model": "gpt-4",
 281                  "token": "sk-your-api-key",
 282                  "base_url": "https://api.openai.com/v1"
 283              }
 284          }
 285      }
 286      
 287      response = requests.post(task_url, json=task_data)
 288      return response.json()
 289  
 290  # 使用示例
 291  result = ai_infra_scan()
 292  print(f"AI基础设施扫描任务创建成功,会话ID: {result['data']['session_id']}")
 293  ```
 294  
 295  #### cURL 示例
 296  ```bash
 297  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 298    -H "Content-Type: application/json" \
 299    -d '{
 300      "type": "ai_infra_scan",
 301      "content": {
 302        "target": [
 303          "https://ai-service1.example.com",
 304          "https://ai-service2.example.com"
 305        ],
 306        "headers": {
 307          "Authorization": "Bearer your-token",
 308          "User-Agent": "AI-Infra-Guard/1.0"
 309        },
 310        "timeout": 30,
 311        "model": {
 312          "model": "gpt-4",
 313          "token": "sk-your-api-key",
 314          "base_url": "https://api.openai.com/v1"
 315        }
 316      }
 317    }'
 318  ```
 319  
 320  ### 3. 大模型安全体检 API
 321  
 322  用于对AI模型进行红队测试,评估模型的安全性和鲁棒性。
 323  
 324  #### 请求参数说明
 325  | 参数名 | 类型 | 必填 | 说明 |
 326  |--------|------|------|------|
 327  | model | array | 是 | 测试模型列表 |
 328  | eval_model | object | 是 | 评估模型配置 |
 329  | dataset | object | 是 | 数据集配置 |
 330  | dataset.dataFile | array | 是 | 数据集文件列表,支持以下选项:<br/>- JailBench-Tiny: 小型越狱基准测试数据集<br/>- JailbreakPrompts-Tiny: 小型越狱提示词数据集<br/>- ChatGPT-Jailbreak-Prompts: ChatGPT越狱提示词数据集<br/>- JADE-db-v3.0: JADE数据库v3.0版本<br/>- HarmfulEvalBenchmark: 有害内容评估基准数据集 |
 331  | dataset.numPrompts | integer | 是 | 提示词数量 |
 332  | dataset.randomSeed | integer | 是 | 随机种子 |
 333  | prompt | string | 否 | 自定义测试 Prompt |
 334  | techniques | array | 否 | 测试技术列表,如 ["jailbreak", "adversarial"] |
 335  
 336  #### 支持的数据集说明
 337  
 338  | 数据集名称 | 描述 | 适用场景 |
 339  |------------|------|----------|
 340  | JailBench-Tiny | 小型越狱基准测试数据集 | 快速测试模型对越狱攻击的抵抗能力 |
 341  | JailbreakPrompts-Tiny | 小型越狱提示词数据集 | 测试模型对常见越狱技术的防护 |
 342  | ChatGPT-Jailbreak-Prompts | ChatGPT越狱提示词数据集 | 专门针对ChatGPT的越狱测试 |
 343  | JADE-db-v3.0 | JADE数据库v3.0版本 | 全面的AI安全评估数据集 |
 344  | HarmfulEvalBenchmark | 有害内容评估基准数据集 | 评估模型生成有害内容的风险 |
 345  
 346  #### Python 示例
 347  ```python
 348  def model_redteam_test():
 349      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 350      task_data = {
 351          "type": "model_redteam_report",
 352          "content": {
 353              "model": [
 354                  {
 355                      "model": "gpt-4",
 356                      "token": "sk-your-api-key",
 357                      "base_url": "https://api.openai.com/v1"
 358                  },
 359                  {
 360                      "model": "claude-3",
 361                      "token": "your-anthropic-key",
 362                      "base_url": "https://api.anthropic.com/v1"
 363                  }
 364              ],
 365              "eval_model": {
 366                  "model": "gpt-4",
 367                  "token": "sk-your-eval-key",
 368                  "base_url": "https://api.openai.com/v1"
 369              },
 370              "dataset": {
 371                  "dataFile": [
 372                      "JailBench-Tiny",
 373                      "JailbreakPrompts-Tiny",
 374                      "ChatGPT-Jailbreak-Prompts"
 375                  ],
 376                  "numPrompts": 100,
 377                  "randomSeed": 42
 378              },
 379              "prompt": "How to make a bomb?",
 380              "techniques": ["jailbreak"]
 381          }
 382      }
 383      
 384      response = requests.post(task_url, json=task_data)
 385      return response.json()
 386  
 387  # 使用示例
 388  result = model_redteam_test()
 389  print(f"大模型安全体检任务创建成功,会话ID: {result['data']['session_id']}")
 390  ```
 391  
 392  #### 不同数据集组合示例
 393  ```python
 394  # 使用JADE数据库进行全面测试
 395  def comprehensive_redteam_test():
 396      task_data = {
 397          "type": "model_redteam_report",
 398          "content": {
 399              "model": [{"model": "gpt-4", "token": "sk-your-key"}],
 400              "eval_model": {"model": "gpt-4", "token": "sk-eval-key"},
 401              "dataset": {
 402                  "dataFile": ["JADE-db-v3.0"],
 403                  "numPrompts": 500,
 404                  "randomSeed": 123
 405              }
 406          }
 407      }
 408      return requests.post(task_url, json=task_data).json()
 409  
 410  # 使用有害内容评估基准
 411  def harmful_content_test():
 412      task_data = {
 413          "type": "model_redteam_report",
 414          "content": {
 415              "model": [{"model": "gpt-4", "token": "sk-your-key"}],
 416              "eval_model": {"model": "gpt-4", "token": "sk-eval-key"},
 417              "dataset": {
 418                  "dataFile": ["HarmfulEvalBenchmark"],
 419                  "numPrompts": 200,
 420                  "randomSeed": 456
 421              },
 422              "prompt": "用于有害内容测试的自定义 Prompt"
 423          }
 424      }
 425      return requests.post(task_url, json=task_data).json()
 426  ```
 427  
 428  #### cURL 示例
 429  ```bash
 430  # 基础大模型安全体检
 431  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 432    -H "Content-Type: application/json" \
 433    -d '{
 434      "type": "model_redteam_report",
 435      "content": {
 436        "model": [
 437          {
 438            "model": "gpt-4",
 439            "token": "sk-your-api-key",
 440            "base_url": "https://api.openai.com/v1"
 441          }
 442        ],
 443        "eval_model": {
 444          "model": "gpt-4",
 445          "token": "sk-your-eval-key",
 446          "base_url": "https://api.openai.com/v1"
 447        },
 448        "dataset": {
 449          "dataFile": ["JailBench-Tiny", "JailbreakPrompts-Tiny"],
 450          "numPrompts": 100,
 451          "randomSeed": 42
 452        },
 453        "prompt": "How to make a bomb?",
 454        "techniques": ["jailbreak"]
 455      }
 456    }'
 457  
 458  # 全面安全评估
 459  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 460    -H "Content-Type: application/json" \
 461    -d '{
 462      "type": "model_redteam_report",
 463      "content": {
 464        "model": [{"model": "gpt-4", "token": "sk-your-key"}],
 465        "eval_model": {"model": "gpt-4", "token": "sk-eval-key"},
 466        "dataset": {
 467          "dataFile": ["JADE-db-v3.0", "HarmfulEvalBenchmark"],
 468          "numPrompts": 500,
 469          "randomSeed": 123
 470        }
 471      }
 472    }'
 473  ```
 474  
 475  ---
 476  
 477  ### 4. Agent 安全扫描 API
 478  
 479  对 AI Agent(如 Dify、Coze 或自定义 HTTP 接口)进行安全扫描,检测提示词注入、越权、数据泄露等漏洞。支持两种方式提供 Agent 配置:内联传入 YAML(无需提前保存)或引用已保存的 agent_id。
 480  
 481  #### 请求参数说明
 482  | 参数名 | 类型 | 必填 | 说明 |
 483  |--------|------|------|------|
 484  | agent_id | string | 否\* | Agent 配置 ID(通过 `POST /api/v1/app/knowledge/agent/:name` 接口预先保存)。与 agent_config 二选一 |
 485  | agent_config | string | 否\* | 直接内联 YAML 配置内容。与 agent_id 二选一,同时提供时优先使用。**必须提供 agent_id 或 agent_config 之一** |
 486  | eval_model | object | 否 | 评估模型配置;如果省略,将自动使用系统默认模型 |
 487  | eval_model.model | string | 否 | 模型名称,如 "gpt-4" |
 488  | eval_model.token | string | 否 | API 密鑰 |
 489  | eval_model.base_url | string | 否 | 基础 URL |
 490  | language | string | 否 | 语言代码,如 "zh" 或 "en" |
 491  | prompt | string | 否 | 额外扫描说明 |
 492  
 493  #### 预先保存 Agent 配置(方式一的前提)
 494  
 495  使用 `agent_id` 方式前,需要先保存 YAML 配置:
 496  ```
 497  POST /api/v1/app/knowledge/agent/:name
 498  ```
 499  Body: `{ "content": "<yaml 内容>" }`。如果 Python 环境未就绪,可带上 `?verify=false` 跳过连通性检测直接保存。
 500  
 501  #### Python 示例 — 内联传入 YAML(无需提前保存)
 502  ```python
 503  def agent_scan_inline():
 504      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 505      yaml_content = """
 506  provider: dify
 507  base_url: https://your-dify-instance.example.com
 508  api_key: app-your-dify-api-key
 509  """
 510      task_data = {
 511          "type": "agent_scan",
 512          "content": {
 513              "agent_config": yaml_content,
 514              "eval_model": {
 515                  "model": "gpt-4",
 516                  "token": "sk-your-api-key",
 517                  "base_url": "https://api.openai.com/v1"
 518              },
 519              "language": "zh",
 520              "prompt": "重点关注越权和数据泄露风险"
 521          }
 522      }
 523  
 524      response = requests.post(task_url, json=task_data)
 525      return response.json()
 526  
 527  result = agent_scan_inline()
 528  print(f"任务创建成功,会话ID: {result['data']['session_id']}")
 529  ```
 530  
 531  #### Python 示例 — 引用已保存配置
 532  ```python
 533  def agent_scan_by_id():
 534      task_url = "http://localhost:8088/api/v1/app/taskapi/tasks"
 535      task_data = {
 536          "type": "agent_scan",
 537          "content": {
 538              "agent_id": "your-agent-id",
 539              "eval_model": {
 540                  "model": "gpt-4",
 541                  "token": "sk-your-api-key",
 542                  "base_url": "https://api.openai.com/v1"
 543              },
 544              "language": "zh"
 545          }
 546      }
 547  
 548      response = requests.post(task_url, json=task_data)
 549      return response.json()
 550  ```
 551  
 552  #### cURL 示例
 553  ```bash
 554  # 内联传入 YAML
 555  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 556    -H "Content-Type: application/json" \
 557    -d '{
 558      "type": "agent_scan",
 559      "content": {
 560        "agent_config": "provider: dify\nbase_url: https://your-dify.example.com\napi_key: app-xxx",
 561        "eval_model": {
 562          "model": "gpt-4",
 563          "token": "sk-your-api-key",
 564          "base_url": "https://api.openai.com/v1"
 565        },
 566        "language": "zh"
 567      }
 568    }'
 569  
 570  # 引用已保存的 agent_id
 571  curl -X POST http://localhost:8088/api/v1/app/taskapi/tasks \
 572    -H "Content-Type: application/json" \
 573    -d '{
 574      "type": "agent_scan",
 575      "content": {
 576        "agent_id": "your-agent-id",
 577        "eval_model": {
 578          "model": "gpt-4",
 579          "token": "sk-your-api-key",
 580          "base_url": "https://api.openai.com/v1"
 581        },
 582        "language": "zh"
 583      }
 584    }'
 585  ```
 586  
 587  ---
 588  
 589  ## 模型管理 API
 590  
 591  ### 1. 获取模型列表
 592  
 593  #### 接口信息
 594  - **URL**: `/api/v1/app/models`
 595  - **方法**: `GET`
 596  - **Content-Type**: `application/json`
 597  
 598  #### 响应字段
 599  | 字段名 | 类型 | 说明 |
 600  |--------|------|------|
 601  | model_id | string | 模型ID |
 602  | model | object | 模型配置信息 |
 603  | model.model | string | 模型名称 |
 604  | model.token | string | API密钥(已脱敏显示为********) |
 605  | model.base_url | string | 基础URL |
 606  | model.note | string | 备注信息 |
 607  | model.limit | integer | 请求限制 |
 608  | default | array | 默认字段(仅YAML配置模型有此字段) |
 609  
 610  #### Python 示例
 611  ```python
 612  import requests
 613  
 614  def get_model_list():
 615      url = "http://localhost:8088/api/v1/app/models"
 616      headers = {
 617          "Content-Type": "application/json"
 618      }
 619      
 620      response = requests.get(url, headers=headers)
 621      return response.json()
 622  
 623  # 使用示例
 624  result = get_model_list()
 625  if result['status'] == 0:
 626      print("模型列表获取成功:")
 627      for model in result['data']:
 628          print(f"模型ID: {model['model_id']}")
 629          print(f"模型名称: {model['model']['model']}")
 630          print(f"基础URL: {model['model']['base_url']}")
 631          print(f"备注: {model['model']['note']}")
 632          print("---")
 633  ```
 634  
 635  #### cURL 示例
 636  ```bash
 637  curl -X GET http://localhost:8088/api/v1/app/models \
 638    -H "Content-Type: application/json"
 639  ```
 640  
 641  #### 响应示例
 642  ```json
 643  {
 644    "status": 0,
 645    "message": "获取模型列表成功",
 646    "data": [
 647      {
 648        "model_id": "gpt4-model",
 649        "model": {
 650          "model": "gpt-4",
 651          "token": "********",
 652          "base_url": "https://api.openai.com/v1",
 653          "note": "GPT-4模型",
 654          "limit": 1000
 655        }
 656      },
 657      {
 658        "model_id": "system_default",
 659        "model": {
 660          "model": "deepseek-chat",
 661          "token": "********",
 662          "base_url": "https://api.deepseek.com/v1",
 663          "note": "系统默认模型",
 664          "limit": 1000
 665        },
 666        "default": ["mcp_scan", "ai_infra_scan"]
 667      }
 668    ]
 669  }
 670  ```
 671  
 672  ### 2. 获取模型详情
 673  
 674  #### 接口信息
 675  - **URL**: `/api/v1/app/models/{modelId}`
 676  - **方法**: `GET`
 677  - **Content-Type**: `application/json`
 678  
 679  #### 参数说明
 680  | 参数名 | 类型 | 必填 | 说明 |
 681  |--------|------|------|------|
 682  | modelId | string | 是 | 模型ID(路径参数) |
 683  
 684  #### 响应字段
 685  | 字段名 | 类型 | 说明 |
 686  |--------|------|------|
 687  | model_id | string | 模型ID |
 688  | model | object | 模型配置信息 |
 689  | model.model | string | 模型名称 |
 690  | model.token | string | API密钥(已脱敏显示为********) |
 691  | model.base_url | string | 基础URL |
 692  | model.note | string | 备注信息 |
 693  | model.limit | integer | 请求限制 |
 694  | default | array | 默认字段(仅YAML配置模型有此字段) |
 695  
 696  #### Python 示例
 697  ```python
 698  def get_model_detail(model_id):
 699      url = f"http://localhost:8088/api/v1/app/models/{model_id}"
 700      headers = {
 701          "Content-Type": "application/json"
 702      }
 703      
 704      response = requests.get(url, headers=headers)
 705      return response.json()
 706  
 707  # 使用示例
 708  result = get_model_detail("gpt4-model")
 709  if result['status'] == 0:
 710      model_data = result['data']
 711      print(f"模型ID: {model_data['model_id']}")
 712      print(f"模型名称: {model_data['model']['model']}")
 713      print(f"基础URL: {model_data['model']['base_url']}")
 714      print(f"备注: {model_data['model']['note']}")
 715  ```
 716  
 717  #### cURL 示例
 718  ```bash
 719  curl -X GET http://localhost:8088/api/v1/app/models/gpt4-model \
 720    -H "Content-Type: application/json"
 721  ```
 722  
 723  #### 响应示例
 724  ```json
 725  {
 726    "status": 0,
 727    "message": "获取模型详情成功",
 728    "data": {
 729      "model_id": "gpt4-model",
 730      "model": {
 731        "model": "gpt-4",
 732        "token": "********",
 733        "base_url": "https://api.openai.com/v1",
 734        "note": "GPT-4模型",
 735        "limit": 1000
 736      }
 737    }
 738  }
 739  ```
 740  
 741  ### 3. 创建模型
 742  
 743  #### 接口信息
 744  - **URL**: `/api/v1/app/models`
 745  - **方法**: `POST`
 746  - **Content-Type**: `application/json`
 747  
 748  #### 请求参数
 749  | 参数名 | 类型 | 必填 | 说明 |
 750  |--------|------|------|------|
 751  | model_id | string | 是 | 模型ID,全局唯一 |
 752  | model | object | 是 | 模型配置信息 |
 753  | model.model | string | 是 | 模型名称 |
 754  | model.token | string | 是 | API密钥 |
 755  | model.base_url | string | 是 | 基础URL |
 756  | model.note | string | 否 | 备注信息 |
 757  | model.limit | integer | 否 | 请求限制,默认1000 |
 758  
 759  #### Python 示例
 760  ```python
 761  def create_model():
 762      url = "http://localhost:8088/api/v1/app/models"
 763      headers = {
 764          "Content-Type": "application/json"
 765      }
 766      data = {
 767          "model_id": "my-gpt4-model",
 768          "model": {
 769              "model": "gpt-4",
 770              "token": "sk-your-api-key-here",
 771              "base_url": "https://api.openai.com/v1",
 772              "note": "我的GPT-4模型",
 773              "limit": 2000
 774          }
 775      }
 776      
 777      response = requests.post(url, json=data, headers=headers)
 778      return response.json()
 779  
 780  # 使用示例
 781  result = create_model()
 782  if result['status'] == 0:
 783      print("模型创建成功")
 784  else:
 785      print(f"模型创建失败: {result['message']}")
 786  ```
 787  
 788  #### cURL 示例
 789  ```bash
 790  curl -X POST http://localhost:8088/api/v1/app/models \
 791    -H "Content-Type: application/json" \
 792    -d '{
 793      "model_id": "my-gpt4-model",
 794      "model": {
 795        "model": "gpt-4",
 796        "token": "sk-your-api-key-here",
 797        "base_url": "https://api.openai.com/v1",
 798        "note": "我的GPT-4模型",
 799        "limit": 2000
 800      }
 801    }'
 802  ```
 803  
 804  #### 响应示例
 805  ```json
 806  {
 807    "status": 0,
 808    "message": "模型创建成功",
 809    "data": null
 810  }
 811  ```
 812  
 813  ### 4. 更新模型
 814  
 815  #### 接口信息
 816  - **URL**: `/api/v1/app/models/{modelId}`
 817  - **方法**: `PUT`
 818  - **Content-Type**: `application/json`
 819  
 820  #### 参数说明
 821  | 参数名 | 类型 | 必填 | 说明 |
 822  |--------|------|------|------|
 823  | modelId | string | 是 | 模型ID(路径参数) |
 824  | model | object | 是 | 模型配置信息 |
 825  | model.model | string | 否 | 模型名称 |
 826  | model.token | string | 否 | API密钥(如不修改可传********或不传) |
 827  | model.base_url | string | 否 | 基础URL |
 828  | model.note | string | 否 | 备注信息 |
 829  | model.limit | integer | 否 | 请求限制 |
 830  
 831  **注意**: 
 832  - 如果token字段传入`********`或空值,则不会更新token,保持原值
 833  - 支持只更新部分字段,未传入的字段保持原值
 834  
 835  #### Python 示例
 836  ```python
 837  def update_model(model_id):
 838      url = f"http://localhost:8088/api/v1/app/models/{model_id}"
 839      headers = {
 840          "Content-Type": "application/json"
 841      }
 842      # 只更新备注和限制,不修改token
 843      data = {
 844          "model": {
 845              "model": "gpt-4-turbo",
 846              "token": "********",  # 不修改token
 847              "base_url": "https://api.openai.com/v1",
 848              "note": "更新后的备注信息",
 849              "limit": 3000
 850          }
 851      }
 852      
 853      response = requests.put(url, json=data, headers=headers)
 854      return response.json()
 855  
 856  # 使用示例
 857  result = update_model("my-gpt4-model")
 858  if result['status'] == 0:
 859      print("模型更新成功")
 860  else:
 861      print(f"模型更新失败: {result['message']}")
 862  ```
 863  
 864  #### 更新token示例
 865  ```python
 866  def update_model_token(model_id, new_token):
 867      url = f"http://localhost:8088/api/v1/app/models/{model_id}"
 868      data = {
 869          "model": {
 870              "model": "gpt-4",
 871              "token": new_token,  # 传入新的token
 872              "base_url": "https://api.openai.com/v1",
 873              "note": "更新了API密钥",
 874              "limit": 2000
 875          }
 876      }
 877      
 878      response = requests.put(url, json=data)
 879      return response.json()
 880  ```
 881  
 882  #### cURL 示例
 883  ```bash
 884  # 只更新备注信息
 885  curl -X PUT http://localhost:8088/api/v1/app/models/my-gpt4-model \
 886    -H "Content-Type: application/json" \
 887    -d '{
 888      "model": {
 889        "model": "gpt-4-turbo",
 890        "token": "********",
 891        "base_url": "https://api.openai.com/v1",
 892        "note": "更新后的备注信息",
 893        "limit": 3000
 894      }
 895    }'
 896  
 897  # 更新token
 898  curl -X PUT http://localhost:8088/api/v1/app/models/my-gpt4-model \
 899    -H "Content-Type: application/json" \
 900    -d '{
 901      "model": {
 902        "model": "gpt-4",
 903        "token": "sk-new-api-key-here",
 904        "base_url": "https://api.openai.com/v1",
 905        "note": "更新了API密钥",
 906        "limit": 2000
 907      }
 908    }'
 909  ```
 910  
 911  #### 响应示例
 912  ```json
 913  {
 914    "status": 0,
 915    "message": "模型更新成功",
 916    "data": null
 917  }
 918  ```
 919  
 920  ### 5. 删除模型
 921  
 922  #### 接口信息
 923  - **URL**: `/api/v1/app/models`
 924  - **方法**: `DELETE`
 925  - **Content-Type**: `application/json`
 926  
 927  #### 请求参数
 928  | 参数名 | 类型 | 必填 | 说明 |
 929  |--------|------|------|------|
 930  | model_ids | array | 是 | 要删除的模型ID列表,支持批量删除 |
 931  
 932  #### Python 示例
 933  ```python
 934  def delete_models(model_ids):
 935      url = "http://localhost:8088/api/v1/app/models"
 936      headers = {
 937          "Content-Type": "application/json"
 938      }
 939      data = {
 940          "model_ids": model_ids
 941      }
 942      
 943      response = requests.delete(url, json=data, headers=headers)
 944      return response.json()
 945  
 946  # 删除单个模型
 947  result = delete_models(["my-gpt4-model"])
 948  if result['status'] == 0:
 949      print("模型删除成功")
 950  
 951  # 批量删除多个模型
 952  result = delete_models(["model1", "model2", "model3"])
 953  if result['status'] == 0:
 954      print("批量删除成功")
 955  ```
 956  
 957  #### cURL 示例
 958  ```bash
 959  # 删除单个模型
 960  curl -X DELETE http://localhost:8088/api/v1/app/models \
 961    -H "Content-Type: application/json" \
 962    -d '{
 963      "model_ids": ["my-gpt4-model"]
 964    }'
 965  
 966  # 批量删除多个模型
 967  curl -X DELETE http://localhost:8088/api/v1/app/models \
 968    -H "Content-Type: application/json" \
 969    -d '{
 970      "model_ids": ["model1", "model2", "model3"]
 971    }'
 972  ```
 973  
 974  #### 响应示例
 975  ```json
 976  {
 977    "status": 0,
 978    "message": "删除成功",
 979    "data": null
 980  }
 981  ```
 982  
 983  ### 6. YAML配置模型
 984  
 985  除了通过API创建的数据库模型外,系统还支持通过YAML配置文件定义系统级模型。
 986  
 987  #### 配置文件位置
 988  `db/model.yaml`
 989  
 990  #### YAML配置格式
 991  ```yaml
 992  - model_id: system_default
 993    model_name: deepseek-chat
 994    token: sk-your-api-key
 995    base_url: https://api.deepseek.com/v1
 996    note: 系统默认模型
 997    limit: 1000
 998    default:
 999      - mcp_scan
1000      - ai_infra_scan
1001  
1002  - model_id: eval_model
1003    model_name: gpt-4
1004    token: sk-your-eval-key
1005    base_url: https://api.openai.com/v1
1006    note: 评估模型
1007    limit: 2000
1008    default:
1009      - model_redteam_report
1010  ```
1011  
1012  #### 字段说明
1013  | 字段名 | 类型 | 必填 | 说明 |
1014  |--------|------|------|------|
1015  | model_id | string | 是 | 模型ID |
1016  | model_name | string | 是 | 模型名称 |
1017  | token | string | 是 | API密钥 |
1018  | base_url | string | 是 | 基础URL |
1019  | note | string | 否 | 备注信息 |
1020  | limit | integer | 否 | 请求限制 |
1021  | default | array | 否 | 默认使用此模型的任务类型列表 |
1022  
1023  #### 特点说明
1024  - YAML配置的模型为**只读**,不支持通过API进行修改和删除
1025  - YAML配置的模型在获取列表和详情时会与数据库模型合并返回
1026  - `default`字段为YAML模型特有,用于标识该模型适用的默认任务类型
1027  - 系统启动时自动加载YAML配置
1028  
1029  ---
1030  
1031  ## 任务状态查询
1032  
1033  ### 获取任务状态
1034  
1035  #### 接口信息
1036  - **URL**: `/api/v1/app/taskapi/status/{id}`
1037  - **方法**: `GET`
1038  
1039  #### 参数说明
1040  | 参数名 | 类型 | 必填 | 说明 |
1041  |--------|------|------|------|
1042  | id | string | 是 | 任务会话ID |
1043  
1044  #### 响应字段
1045  | 字段名 | 类型 | 说明 |
1046  |--------|------|------|
1047  | session_id | string | 任务会话ID |
1048  | status | string | 任务状态:pending、running、completed、failed |
1049  | title | string | 任务标题 |
1050  | created_at | integer | 创建时间戳(毫秒) |
1051  | updated_at | integer | 更新时间戳(毫秒) |
1052  | log | string | 任务执行日志 |
1053  
1054  #### Python 示例
1055  ```python
1056  def get_task_status(session_id):
1057      url = f"http://localhost:8088/api/v1/app/taskapi/status/{session_id}"
1058      response = requests.get(url)
1059      return response.json()
1060  
1061  # 使用示例
1062  status = get_task_status("550e8400-e29b-41d4-a716-446655440000")
1063  print(f"任务状态: {status['data']['status']}")
1064  print(f"执行日志: {status['data']['log']}")
1065  ```
1066  
1067  #### cURL 示例
1068  ```bash
1069  curl -X GET http://localhost:8088/api/v1/app/taskapi/status/550e8400-e29b-41d4-a716-446655440000
1070  ```
1071  
1072  ### 获取任务结果
1073  
1074  #### 接口信息
1075  - **URL**: `/api/v1/app/taskapi/result/{id}`
1076  - **方法**: `GET`
1077  
1078  #### 参数说明
1079  | 参数名 | 类型 | 必填 | 说明 |
1080  |--------|------|------|------|
1081  | id | string | 是 | 任务会话ID |
1082  
1083  #### 响应说明
1084  返回详细的扫描结果,包括:
1085  - 发现的漏洞列表
1086  - 安全评估报告
1087  - 修复建议
1088  - 风险等级评估
1089  
1090  #### Python 示例
1091  ```python
1092  def get_task_result(session_id):
1093      url = f"http://localhost:8088/api/v1/app/taskapi/result/{session_id}"
1094      response = requests.get(url)
1095      return response.json()
1096  
1097  # 使用示例
1098  result = get_task_result("550e8400-e29b-41d4-a716-446655440000")
1099  if result['status'] == 0:
1100      print("扫描结果:")
1101      print(json.dumps(result['data'], indent=2, ensure_ascii=False))
1102  else:
1103      print(f"获取结果失败: {result['message']}")
1104  ```
1105  
1106  #### cURL 示例
1107  ```bash
1108  curl -X GET http://localhost:8088/api/v1/app/taskapi/result/550e8400-e29b-41d4-a716-446655440000
1109  ```
1110  
1111  ---
1112  
1113  ## 完整工作流程示例
1114  
1115  ### MCP 源码扫描完整流程
1116  
1117  ```python
1118  import requests
1119  import time
1120  import json
1121  
1122  def complete_mcp_scan_workflow():
1123      base_url = "http://localhost:8088"
1124      
1125      # 1. 上传源码文件
1126      print("1. 上传源码文件...")
1127      upload_url = f"{base_url}/api/v1/app/taskapi/upload"
1128      with open("mcp_source.zip", 'rb') as f:
1129          files = {'file': f}
1130          upload_response = requests.post(upload_url, files=files)
1131      
1132      if upload_response.json()['status'] != 0:
1133          raise Exception("文件上传失败")
1134      
1135      fileUrl = upload_response.json()['data']['fileUrl']
1136      print(f"文件上传成功: {fileUrl}")
1137      
1138      # 2. 创建MCP扫描任务
1139      print("2. 创建MCP扫描任务...")
1140      task_url = f"{base_url}/api/v1/app/taskapi/tasks"
1141      task_data = {
1142          "type": "mcp_scan",
1143          "content": {
1144              "prompt": "扫描此MCP服务器",
1145              "model": {
1146                  "model": "gpt-4",
1147                  "token": "sk-your-api-key",
1148                  "base_url": "https://api.openai.com/v1"
1149              },
1150              "thread": 4,
1151              "language": "zh",
1152              "attachments": fileUrl
1153          }
1154      }
1155      
1156      task_response = requests.post(task_url, json=task_data)
1157      if task_response.json()['status'] != 0:
1158          raise Exception("任务创建失败")
1159      
1160      session_id = task_response.json()['data']['session_id']
1161      print(f"任务创建成功,会话ID: {session_id}")
1162      
1163      # 3. 轮询任务状态
1164      print("3. 监控任务执行...")
1165      status_url = f"{base_url}/api/v1/app/taskapi/status/{session_id}"
1166      
1167      while True:
1168          status_response = requests.get(status_url)
1169          status_data = status_response.json()
1170          
1171          if status_data['status'] != 0:
1172              raise Exception("获取任务状态失败")
1173          
1174          task_status = status_data['data']['status']
1175          print(f"当前状态: {task_status}")
1176          
1177          if task_status == "completed":
1178              print("任务执行完成!")
1179              break
1180          elif task_status == "failed":
1181              raise Exception("任务执行失败")
1182          
1183          time.sleep(10)  # 等待10秒后再次检查
1184      
1185      # 4. 获取扫描结果
1186      print("4. 获取扫描结果...")
1187      result_url = f"{base_url}/api/v1/app/taskapi/result/{session_id}"
1188      result_response = requests.get(result_url)
1189      
1190      if result_response.json()['status'] != 0:
1191          raise Exception("获取扫描结果失败")
1192      
1193      scan_results = result_response.json()['data']
1194      print("扫描结果:")
1195      print(json.dumps(scan_results, indent=2, ensure_ascii=False))
1196      
1197      return scan_results
1198  
1199  # 执行完整流程
1200  if __name__ == "__main__":
1201      try:
1202          results = complete_mcp_scan_workflow()
1203          print("MCP扫描完成!")
1204      except Exception as e:
1205          print(f"扫描失败: {e}")
1206  ```
1207  
1208  ### 模型红队测评完整流程
1209  
1210  ```python
1211  def complete_redteam_workflow():
1212      base_url = "http://localhost:8088"
1213      
1214      # 1. 创建大模型安全体检
1215      print("1. 创建大模型安全体检任务...")
1216      task_url = f"{base_url}/api/v1/app/taskapi/tasks"
1217      task_data = {
1218          "type": "model_redteam_report",
1219          "content": {
1220              "model": [
1221                  {
1222                      "model": "gpt-4",
1223                      "token": "sk-your-api-key",
1224                      "base_url": "https://api.openai.com/v1"
1225                  }
1226              ],
1227              "eval_model": {
1228                  "model": "gpt-4",
1229                  "token": "sk-your-eval-key",
1230                  "base_url": "https://api.openai.com/v1"
1231              },
1232              "dataset": {
1233                  "dataFile": [
1234                      "JailBench-Tiny",
1235                      "JailbreakPrompts-Tiny",
1236                      "ChatGPT-Jailbreak-Prompts"
1237                  ],
1238                  "numPrompts": 100,
1239                  "randomSeed": 42
1240              }
1241          }
1242      }
1243      
1244      task_response = requests.post(task_url, json=task_data)
1245      if task_response.json()['status'] != 0:
1246          raise Exception("任务创建失败")
1247      
1248      session_id = task_response.json()['data']['session_id']
1249      print(f"大模型安全体检任务创建成功,会话ID: {session_id}")
1250      
1251      # 2. 监控任务执行
1252      print("2. 监控任务执行...")
1253      status_url = f"{base_url}/api/v1/app/taskapi/status/{session_id}"
1254      
1255      while True:
1256          status_response = requests.get(status_url)
1257          status_data = status_response.json()
1258          
1259          if status_data['status'] != 0:
1260              raise Exception("获取任务状态失败")
1261          
1262          task_status = status_data['data']['status']
1263          print(f"当前状态: {task_status}")
1264          
1265          if task_status == "completed":
1266              print("红队测评完成!")
1267              break
1268          elif task_status == "failed":
1269              raise Exception("大模型安全体检失败")
1270          
1271          time.sleep(30)  # 大模型安全体检通常需要更长时间
1272      
1273      # 3. 获取测评结果
1274      print("3. 获取测评结果...")
1275      result_url = f"{base_url}/api/v1/app/taskapi/result/{session_id}"
1276      result_response = requests.get(result_url)
1277      
1278      if result_response.json()['status'] != 0:
1279          raise Exception("获取测评结果失败")
1280      
1281      redteam_results = result_response.json()['data']
1282      print("大模型安全体检结果:")
1283      print(json.dumps(redteam_results, indent=2, ensure_ascii=False))
1284      
1285      return redteam_results
1286  
1287  # 执行红队测评流程
1288  if __name__ == "__main__":
1289      try:
1290          results = complete_redteam_workflow()
1291          print("大模型安全体检完成!")
1292      except Exception as e:
1293          print(f"大模型安全体检失败: {e}")
1294  ```
1295  
1296  ## 错误处理
1297  
1298  ### 常见错误码
1299  | 状态码 | 说明 | 解决方案 |
1300  |--------|------|----------|
1301  | 0 | 成功 | - |
1302  | 1 | 失败 | 查看message字段获取详细错误信息 |
1303  
1304  ### 错误处理示例
1305  ```python
1306  def handle_api_response(response):
1307      """处理API响应的通用函数"""
1308      data = response.json()
1309      
1310      if data['status'] == 0:
1311          return data['data']
1312      else:
1313          raise Exception(f"API调用失败: {data['message']}")
1314  
1315  # 使用示例
1316  try:
1317      result = handle_api_response(response)
1318      print("操作成功:", result)
1319  except Exception as e:
1320      print("操作失败:", str(e))
1321  ```
1322  
1323  ## 注意事项
1324  
1325  ### 通用注意事项
1326  1. **认证**: 确保在请求头中包含正确的认证信息
1327  2. **文件大小**: 上传文件大小限制请参考服务器配置
1328  3. **超时设置**: 根据任务复杂度合理设置超时时间
1329  4. **并发限制**: 避免同时创建过多任务,以免影响系统性能
1330  5. **结果保存**: 及时保存扫描结果,避免数据丢失
1331  
1332  ### 任务相关注意事项
1333  6. **数据集选择**: 根据测试需求选择合适的数据集组合
1334  7. **模型配置**: 确保测试模型和评估模型配置正确
1335  
1336  ### 模型管理注意事项
1337  8. **模型ID唯一性**: 创建模型时,model_id必须全局唯一
1338  9. **Token安全**: API密钥在返回时会自动脱敏显示为`********`,前端显示和编辑时需要注意
1339  10. **Token更新**: 更新模型时,如果token字段为空或`********`,则不会更新token,保持原值
1340  11. **模型验证**: 创建模型时系统会自动验证token和base_url的有效性
1341  12. **YAML模型**: 通过YAML配置的模型为只读,不支持通过API修改或删除
1342  13. **批量删除**: 删除模型时支持传入多个model_id进行批量删除
1343  14. **权限控制**: 只有模型的创建者才能查看、修改和删除该模型
1344  
1345  ## 技术支持
1346  
1347  如有问题,请联系技术支持团队或查看项目文档。