Atomgit-Ascend/MiniCPM-V-4_5
模型介绍
文件和版本
Pull Requests
讨论
分析

MiniCPM-V 4.5 NPU 适配版 API 服务

本项目提供基于华为昇腾 910B NPU 的 MiniCPM-V 4.5 模型推理服务,兼容 OpenAI API 格式。

目录结构

.
├── deploy_minicpm_npu.sh             # 一键部署脚本
├── MiniCPM-V-4_5/
│   ├── Dockerfile                    # NPU 适配镜像构建文件
│   ├── api/
│   │   └── main.py                   # FastAPI 服务入口
│   └── requirements.txt              # Python 依赖

快速开始

1. 环境准备

确保服务器已安装:

  • Docker
  • 华为昇腾驱动 (NPU driver)
  • 确保 npu-smi info 能正常输出

2. 部署

运行以下命令:

chmod +x deploy_minicpm_npu.sh
./deploy_minicpm_npu.sh

该脚本会自动:

  1. 构建适配 NPU 的 Docker 镜像(基于 CANN 8.2 + PyTorch 2.1.0)
  2. 启动容器并挂载 NPU 设备
  3. 启动 API 服务(端口 8000)

API 接口

接口地址

POST http://localhost:8000/v1/chat/completions

请求参数

参数类型必需说明
modelstring是模型名称,固定为 MiniCPM-V-4_5
messagesarray是消息列表
streamboolean否是否流式输出,默认 false
max_tokensinteger否最大生成 token 数,默认 1024
temperaturefloat否温度参数,默认 0.7
top_pfloat否Top-p 采样,默认 0.8

消息格式

消息内容 content 支持以下类型:

类型说明
text文本内容
image_url图片(支持 URL 或 Base64)
video_url视频(支持 URL 或 Base64)

调用示例

1. 纯文本对话

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniCPM-V-4_5",
    "messages": [
      {"role": "user", "content": "你好,介绍一下你自己"}
    ],
    "max_tokens": 512
  }'

2. 图片理解 - URL 方式

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniCPM-V-4_5",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}},
          {"type": "text", "text": "描述这张图片的内容"}
        ]
      }
    ]
  }'

3. 图片理解 - Base64 方式

# 将图片转为 Base64
IMAGE_BASE64=$(base64 -i image.jpg | tr -d '\n')

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"MiniCPM-V-4_5\",
    \"messages\": [
      {
        \"role\": \"user\",
        \"content\": [
          {\"type\": \"image_url\", \"image_url\": {\"url\": \"data:image/jpeg;base64,${IMAGE_BASE64}\"}},
          {\"type\": \"text\", \"text\": \"图片里有什么?\"}
        ]
      }
    ]
  }"

4. 视频理解 - URL 方式

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniCPM-V-4_5",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}},
          {"type": "text", "text": "描述这个视频的内容"}
        ]
      }
    ]
  }'

5. 视频理解 - Base64 方式

# 将视频转为 Base64
VIDEO_BASE64=$(base64 -i video.mp4 | tr -d '\n')

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"MiniCPM-V-4_5\",
    \"messages\": [
      {
        \"role\": \"user\",
        \"content\": [
          {\"type\": \"video_url\", \"video_url\": {\"url\": \"data:video/mp4;base64,${VIDEO_BASE64}\"}},
          {\"type\": \"text\", \"text\": \"视频里发生了什么?\"}
        ]
      }
    ]
  }"

6. 流式输出

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniCPM-V-4_5",
    "messages": [
      {"role": "user", "content": "讲一个故事"}
    ],
    "stream": true
  }'

7. 多轮对话

curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MiniCPM-V-4_5",
    "messages": [
      {"role": "user", "content": "1+1等于多少?"},
      {"role": "assistant", "content": "1+1等于2。"},
      {"role": "user", "content": "那再加上3呢?"}
    ]
  }'

Python 调用示例

import requests
import base64

API_URL = "http://localhost:8000/v1/chat/completions"

# 文本对话
def chat(message: str):
    response = requests.post(API_URL, json={
        "model": "MiniCPM-V-4_5",
        "messages": [{"role": "user", "content": message}]
    })
    return response.json()["choices"][0]["message"]["content"]

# 图片理解
def analyze_image(image_path: str, question: str):
    with open(image_path, "rb") as f:
        image_base64 = base64.b64encode(f.read()).decode()
    
    response = requests.post(API_URL, json={
        "model": "MiniCPM-V-4_5",
        "messages": [{
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}},
                {"type": "text", "text": question}
            ]
        }]
    })
    return response.json()["choices"][0]["message"]["content"]

# 视频理解
def analyze_video(video_path: str, question: str):
    with open(video_path, "rb") as f:
        video_base64 = base64.b64encode(f.read()).decode()
    
    response = requests.post(API_URL, json={
        "model": "MiniCPM-V-4_5",
        "messages": [{
            "role": "user",
            "content": [
                {"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{video_base64}"}},
                {"type": "text", "text": question}
            ]
        }]
    })
    return response.json()["choices"][0]["message"]["content"]

# 使用示例
print(chat("你好"))
print(analyze_image("test.jpg", "描述这张图片"))
print(analyze_video("test.mp4", "视频里发生了什么?"))

健康检查

curl http://localhost:8000/health

返回:

{"status": "healthy", "model_loaded": true}

响应格式

{
  "id": "chatcmpl-1234567890",
  "object": "chat.completion",
  "created": 1234567890,
  "model": "MiniCPM-V-4_5",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "模型的回复内容..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": -1,
    "completion_tokens": -1,
    "total_tokens": -1
  }
}

视频处理说明

  • 视频会自动提取最多 16 帧 作为图片输入模型
  • 使用 PyAV 在内存中处理视频,无需临时文件
  • 支持常见视频格式:MP4, AVI, MOV, WebM 等

NPU 适配说明

  • 基础镜像: quay.io/ascend/cann:8.2.rc1.alpha002-910b-openeuler22.03-py3.10
  • PyTorch: torch==2.1.0, torch_npu==2.1.0
  • 默认使用 NPU 2:可在 deploy_minicpm_npu.sh 中修改 NPU_ID 变量

常见问题

NPU 不可用

检查设备是否正确挂载:

docker exec -it minicpm-v-api npu-smi info

模型加载失败

确保模型路径正确,或设置 MODEL_PATH 环境变量指向模型目录。