modal – skill Lập trình cho agent AI
Modal là nền tảng đám mây serverless để chạy Python theo yêu cầu, bao gồm GPU theo yêu cầu. Dùng khi triển khai hoặc phục vụ mô hình AI/ML, chạy tác vụ tăng tốc GPU (huấn luyện, tinh chỉnh, suy luận), phục vụ web endpoint, lên lịch batch job, hoặc mở rộng mã Python lên container đám mây với Modal SDK.
Cài skill modal bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/modal-04f4e.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /modal – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/modal-04f4e.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $modal – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/modal-04f4e.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /modal – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/modal-04f4e.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /modal – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Modal
Overview
Modal is a cloud platform for running Python code serverlessly, with a focus on AI/ML workloads. Key capabilities:
- GPU compute on demand (including H100, H200, B200 and B300)
- Serverless functions with autoscaling from zero to thousands of containers
- Custom container images built entirely in Python code
- Persistent storage via Volumes for model weights and datasets
- Web endpoints for serving models and APIs
- Scheduled jobs via cron or fixed intervals
- Container reuse and warm pools to reduce cold starts (model loading still takes time)
Modal Apps and Images are defined in Python; existing Dockerfiles are also supported.
When to Use This Skill
Use this skill when:
- Deploy or serve AI/ML models in the cloud
- Run GPU-accelerated computations (training, inference, fine-tuning)
- Create serverless web APIs or endpoints
- Scale batch processing jobs in parallel
- Schedule recurring tasks (data pipelines, retraining, scraping)
- Need persistent cloud storage for model weights or datasets
- Want to run code in custom container environments
- Build job queues or async task processing systems
Installation and Authentication
Install
uv pip install "modal==1.6.0"Reviewed against SDK 1.6.0 and current [release notes](https://modal.com/docs/sdk/py/releases).
Local SDK construction and selected handlers were tested; remote builds, deployments,
GPU inference and cloud limits were not executed. Snippets using model/data placeholders
or third-party workloads are illustrative and require their stated dependencies.
Authenticate
Prefer existing credentials before creating new ones. Only the two Modal-specific
variables below are relevant — do not read, load, or expose any other environment
variables or .env file contents:
1. Reuse an existing Modal profile, or check whether both MODAL_TOKEN_ID and MODAL_TOKEN_SECRET are set; report presence only.
2. If not, look up only those two keys in a local .env file (ignore all other entries) and load them if appropriate for the workflow.
3. Only fall back to interactive modal setup if no usable profile or token pair exists. The SDK supports profiles in .modal.toml; environment tokens are optional when a profile authenticates.
modal setupThis opens a browser for authentication. For CI/CD or headless environments, use environment variables:
export MODAL_TOKEN_ID=<your-token-id>
export MODAL_TOKEN_SECRET=<your-token-secret>If neither an existing profile nor a token pair is available, create credentials at https://modal.com/settings
Check [current pricing](https://modal.com/pricing) and workspace quotas before sizing a run. GPU use requires a payment method even when credits remain.
Reference: See references/getting-started.md for detailed setup and first app walkthrough.
Core Concepts
App and Functions
A Modal App groups related functions. Functions decorated with @app.function() run remotely in the cloud:
import modal
app = modal.App("my-app")
@app.function()
def square(x):
return x ** 2
@app.local_entrypoint()
def main():
# .remote() runs in the cloud
print(square.remote(42))Run with modal run script.py. Deploy with modal deploy script.py.
Reference: See references/functions.md for lifecycle hooks, classes, .map(), .spawn(), and more.
Container Images
Modal builds container images from Python code. The recommended package installer is uv:
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("torch==2.12.0", "transformers==5.9.0", "accelerate==1.13.0")
.apt_install("git")
)
@app.function(image=image, gpu="L40S")
def inference(prompt):
from transformers import pipeline
pipe = pipeline("text-generation", model="openai-community/gpt2", device=0)
return pipe(prompt)Key image methods:
.uv_pip_install()— Install Python packages with uv (recommended).pip_install()— Install with pip (fallback).apt_install()— Install system packages.run_commands()— Run shell commands during build.run_function()— Run Python during build (e.g., download model weights).add_local_python_source()— Add local modules.env()— Set environment variables
Reference: See references/images.md for Dockerfiles, micromamba, caching, GPU build steps.
GPU Compute
Request GPUs via the gpu parameter:
@app.function(gpu="H100")
def train_model():
import torch
device = torch.device("cuda")
# GPU training code here
# Multiple GPUs
@app.function(gpu="H100:4")
def distributed_training():
...
# GPU fallback chain
@app.function(gpu=["H100", "A100-80GB", "A100-40GB"])
def flexible_inference():
...Available GPU strings include T4, L4, A10, L40S, A100, A100-40GB, A100-80GB, RTX-PRO-6000, H100, H200, B200, B200+ and B300.
- GPUs are always specified as strings (e.g.
gpu="H100",gpu="H100:4"). The oldmodal.gpu.*objects are deprecated as of v0.73.31. - Up to 8 GPUs per container (except A10: up to 4)
- L40S is recommended for inference (cost/performance balance, 48 GB VRAM)
- H100/A100 can be auto-upgraded to H200/A100-80GB at no extra cost; explicit A100-40GB selects 40 GB
- Use
gpu="H100!"to prevent auto-upgrade - B300 and B200+ require CUDA 13.1+ compatibility; RTX-PRO-6000 has 96 GB VRAM
Reference: See references/gpu.md for GPU selection guidance and multi-GPU training.
Volumes (Persistent Storage)
Volumes provide distributed, persistent file storage:
vol = modal.Volume.from_name("model-weights", create_if_missing=True)
@app.function(volumes={"/data": vol})
def save_model():
import torch
model = train_model() # Application-defined training code
# Write to the mounted path
with open("/data/model.pt", "wb") as f:
torch.save(model.state_dict(), f)
vol.commit()
@app.function(volumes={"/data": vol})
def load_model():
import torch
vol.reload()
model = MyModel() # Application-defined architecture
model.load_state_dict(torch.load("/data/model.pt", weights_only=True))- Optimized for write-once, read-many workloads (model weights, datasets)
- CLI access:
modal volume ls,modal volume put,modal volume get - Background auto-commits every few seconds
- For a producer/consumer handoff, close output files and explicitly
vol.commit()
before signaling completion; an already mounted consumer must close its open
volume handles and vol.reload() before reading the new state. A successful
function return or background commit timer is not a freshness check. Give
concurrent runs distinct output paths. See the [commit/reload contract](https://modal.com/docs/guide/volumes).
- Mount read-only or limit to a subdirectory with
vol.with_mount_options(read_only=True, sub_path="subset")
Reference: See references/volumes.md for v2 volumes, concurrent writes, and best practices.
Secrets
Securely pass credentials to functions:
@app.function(secrets=[modal.Secret.from_name("my-api-keys")])
def call_api():
import os
api_key = os.environ["API_KEY"]
# Use the keyCreate secrets via CLI: modal secret create my-api-keys API_KEY=sk-xxx
Or from a .env file: modal.Secret.from_dotenv()
Reference: See references/secrets.md for dashboard setup, multiple secrets, and templates.
Web Endpoints
Serve models and APIs as web endpoints:
web_image = modal.Image.debian_slim().uv_pip_install("fastapi[standard]==0.136.3")
@app.function(image=web_image)
@modal.fastapi_endpoint()
def predict(text: str):
return {"result": model.predict(text)}modal serve script.py— Development with hot reload and temporary URLmodal deploy script.py— Production deployment with permanent URL- Supports FastAPI, ASGI (Starlette, FastHTML), WSGI (Flask, Django), WebSockets
- Request bodies up to 4 GiB, unlimited response size
Reference: See references/web-endpoints.md for ASGI/WSGI apps, streaming, auth, and WebSockets.
Scheduled Jobs
Run functions on a schedule:
@app.function(schedule=modal.Cron("0 9 * * *")) # Daily at 9 AM UTC
def daily_pipeline():
# ETL, retraining, scraping, etc.
...
@app.function(schedule=modal.Period(hours=6))
def periodic_check():
...Deploy with modal deploy script.py to activate the schedule.
modal.Cron("...")— Standard cron syntax, stable across deploysmodal.Period(hours=N)— Fixed interval, resets on redeploy- Monitor runs in the Modal dashboard
Reference: See references/scheduled-jobs.md for cron syntax and management.
Scaling and Concurrency
Modal autoscales containers automatically. Configure limits:
@app.function(
max_containers=100, # Upper limit
min_containers=2, # Keep warm for low latency
buffer_containers=5, # Reserve capacity
scaledown… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- azure-eventhub-rust – SDK Azure Event Hubs cho Rust. Dùng để gửi và nhận sự kiện, nhập dữ liệu streaming.
- cpo-review – /c-level-agents:cpo-review [plan] — Chất vấn theo JTBD về lộ trình sản phẩm, tín hiệu…
- ncats-arax – Truy vấn API production ARAX của NCATS Translator để lấy quan hệ đồ thị tri thức sinh…
- azure-identity-rust – SDK Azure Identity cho xác thực Rust. Dùng cho DeveloperToolsCredential…
- azure-keyvault-certificates-rust – SDK Azure Key Vault Certificates cho Rust. Dùng để tạo, nhập và quản lý chứng chỉ.
- azure-keyvault-keys-rust – SDK Azure Key Vault Keys cho Rust. Dùng để tạo, quản lý và sử dụng khóa mật mã. Từ khóa…
- azure-keyvault-secrets-rust – SDK Azure Key Vault Secrets cho Rust. Dùng để lưu và lấy secret, mật khẩu và API key. Từ…
- azure-messaging-webpubsub-java – Xây dựng ứng dụng web thời gian thực với Azure Web PubSub SDK cho Java. Dùng khi triển…