model-deployment
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "model-deployment" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-67818cf9bb502198a64caa9bd6ff181a6ffab100fde97087d09c7b7ca1e6afd9. Verify the upstream source and version against https://skillhub.cn/skills/org-02qudk26/model-deployment before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Deploy trained machine learning models as production-ready services using REST APIs, containers, serverless functions, and orchestration platforms.
Introduction source: third_party · org-02qudk26 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: model-deployment
description: 使用 REST API、容器、无服务器函数和编排平台,将训练好的机器学习模型部署为生产就绪的服务。
license: MIT
metadata:
author: AI Agent Skills
version: 1.0.0模型部署
本技能让 AI Agent 将训练好的机器学习模型部署到生产环境。涵盖将模型打包为带 FastAPI 或 Flask 的服务 API、用 Docker 容器化、用 Kubernetes 编排,以及部署到无服务器平台。Agent 处理模型版本管理、健康检查、输入验证、日志记录和监控,以确保生产环境中可靠且可扩展的推理。
工作流
-
序列化并打包模型: 将训练好的模型导出为可移植格式,如 ONNX、TorchScript、SavedModel 或 joblib pickle。将模型产物与其预处理流水线和任何所需配置文件捆绑在一起,使推理自包含。
-
构建服务 API: 使用 FastAPI 或 Flask 创建 REST API,在启动时加载模型并暴露预测端点。包含健康检查端点、带输入验证(Pydantic 模型)的请求/响应模式、结构化日志记录,以及返回有意义 HTTP 状态码的错误处理。
-
用 Docker 容器化: 编写 Dockerfile,从固定的
requirements.txt安装依赖,复制模型产物和服务代码,并将入口点设为 API 服务器。使用多阶段构建以最小化镜像大小,并避免包含仅用于训练的依赖。 -
配置编排与扩缩容: 定义 Kubernetes Deployment 和 Service 清单(或你平台的等价物),包含资源请求/限制、指向健康检查端点的就绪和存活探针,以及基于 CPU、内存或请求延迟等自定义指标的 Horizontal Pod Autoscaler。
-
部署并验证: 将容器镜像推送到镜像仓库,应用 Kubernetes 清单或部署到无服务器平台,并对实时端点运行冒烟测试。验证对一组已知输入,响应与预期输出一致。
-
监控与迭代: 与 Prometheus 和 Grafana 等监控工具集成,跟踪请求延迟、错误率、吞吐量和模型特定指标(如预测分布漂移)。为异常设置告警,并使用蓝绿或金丝雀策略建立更新模型版本的重新部署工作流。
支持技术
- API 框架: FastAPI、Flask、TorchServe、TensorFlow Serving、Triton Inference Server
- 容器化: Docker、Podman
- 编排: Kubernetes、Docker Compose、AWS ECS、Google Cloud Run
- 无服务器: AWS Lambda、Google Cloud Functions、Azure Functions
- 监控: Prometheus、Grafana、Datadog、AWS CloudWatch
- 模型注册表: MLflow Model Registry、AWS SageMaker Model Registry、Weights & Biases
使用方式
为 Agent 提供训练好的模型产物、其依赖,以及目标部署环境(本地 Docker、Kubernetes 集群、无服务器)。Agent 将生成所有必要的服务代码、容器配置和部署清单,然后引导你完成部署过程。
示例
示例 1:用 FastAPI 部署模型
# app.py
import joblib
import numpy as np
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator
from contextlib import asynccontextmanager
from typing import List
model = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global model
model = joblib.load("model.pkl")
yield
app = FastAPI(title="ML Model API", version="1.0.0", lifespan=lifespan)
class PredictionRequest(BaseModel):
features: List[float]
@validator("features")
def validate_features(cls, v):
if len(v) != 4:
raise ValueError("Expected exactly 4 features")
return v
class PredictionResponse(BaseModel):
prediction: int
probability: List[float]
@app.get("/health")
def health_check():
return {"status": "healthy", "model_loaded": model is not None}
@app.post("/predict", response_model=PredictionResponse)
def predict(request: PredictionRequest):
try:
features = np.array(request.features).reshape(1, -1)
prediction = int(model.predict(features)[0])
probability = model.predict_proba(features)[0].tolist()
return PredictionResponse(prediction=prediction, probability=probability)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
示例 2:Docker + Kubernetes 部署
Dockerfile:
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin/uvicorn /usr/local/bin/uvicorn
COPY app.py model.pkl ./
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
k8s-deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: ml-model-api
spec:
replicas: 3
selector:
matchLabels:
app: ml-model-api
template:
metadata:
labels:
app: ml-model-api
spec:
containers:
- name: api
image: registry.example.com/ml-model-api:v1.0.0
ports:
- containerPort: 8000
resources:
requests: { cpu: "250m", memory: "512Mi" }
limits: { cpu: "1000m", memory: "1Gi" }
readinessProbe:
httpGet: { path: /health, port: 8000 }
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet: { path: /health, port: 8000 }
initialDelaySeconds: 15
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: ml-model-api
spec:
selector:
app: ml-model-api
ports:
- port: 80
targetPort: 8000
type: LoadBalancer
最佳实践
- 固定所有依赖版本于
requirements.txt,并使用确定性的 Docker 构建,以保证跨环境的可复现性。 - 将模型产物与代码分离,这样你可以在不重建整个容器镜像的情况下更新模型。使用带版本化路径的模型注册表或云存储。
- 使用 Pydantic 或 JSON Schema 实现输入验证,在畸形请求到达模型并产生令人困惑的错误之前将其拒绝。
- 在 Kubernetes 中使用就绪探针,防止流量到达尚未完成模型加载的 Pod——对大型模型而言加载可能需要相当长时间。
- 采用金丝雀部署来发布新模型版本——将少量流量路由到新版本,在全面推广前比较指标。
- 记录预测和输入(隐去 PII),以便在生产中调试、审计和检测数据漂移。
边缘情况
- 大模型文件(> 1 GB): 避免将它们烘焙进 Docker 镜像。改为在启动时从云存储(S3、GCS)下载或挂载持久卷。如果模型初始化耗时较长,使用懒加载。
- 无服务器上的冷启动延迟: 无服务器函数加载大模型可能需要 10–30 秒。通过预置并发(AWS Lambda)、最小实例(Cloud Run),或使用 ONNX Runtime 等优化格式来缓解。
- 推理时预处理不一致: 训练时使用的预处理流水线必须与推理时运行的完全一致。序列化整个流水线(例如使用 scikit-learn Pipeline + joblib),而非单独重新实现转换。
- 优雅关闭与在途请求: 处理 SIGTERM 信号,在关闭前完成在途请求的处理。配置 Kubernetes
terminationGracePeriodSeconds以留出足够时间让待处理请求完成。 - GPU 与 CPU 推理不匹配: 在 GPU 上训练的模型,如果部署到仅 CPU 环境可能会失败。加载时显式地将模型张量映射到 CPU(
torch.load(path, map_location="cpu")),并在部署前在目标硬件上测试推理。
Current listing version
1.0.0
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供机器学习模型部署的完整端到端解决方案,涵盖 API 构建、容器化、编排、监控等生产级能力
- 适用于广泛的实际应用场景,具有明确的实用价值
Highlights
- description 明确描述了使用 REST API、容器、无服务器函数和编排平台部署模型的核心功能
- 触发词精准完整,边界清晰,用户能准确理解 Skill 的用途
Highlights
- 文档结构清晰,包含工作流、支持技术、使用方式、示例、最佳实践和边缘情况
- 步骤划分明确,有端到端示例,frontmatter 完整,便于用户理解和执行
Highlights
- 提供了具体的代码示例、Dockerfile 和 Kubernetes 配置,工具来源明确,参数正确
- 覆盖了主要异常处理(如输入验证、错误处理、健康检查),并提到了监控和告警机制
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 100
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.