AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Modal is a serverless cloud platform designed to run Python code on demand. It simplifies cloud infrastructure by allowing developers to define container environments, GPU resources, and persistent storage directly within Python code. Modal handles autoscaling, container management, and web endpoint deployment, making it suitable for AI/ML inference, batch processing, and scheduled tasks.
What it does
- Provides on-demand GPU compute for training, fine-tuning, and inference.
- Enables serverless execution of Python functions with automatic scaling.
- Allows definition of custom container images using Python.
- Supports persistent storage via Volumes for datasets and model weights.
- Facilitates deployment of web APIs and endpoints.
- Manages scheduled jobs and recurring data pipelines.
When to use it
- When you need to deploy AI/ML models as scalable web services.
- When running GPU-intensive computations that require on-demand hardware.
- When you need to scale batch processing tasks in parallel.
- When you want to manage cloud infrastructure using only Python code.
- When you need persistent storage for large model weights or datasets.
Advantages
- Seamless transition from local development to cloud execution.
- Automatic autoscaling from zero to thousands of containers.
- Flexible GPU selection including H100, A100, and L40S.
- Stateful workloads supported via lifecycle hooks in classes.
- Integrated support for persistent volumes and secrets management.
Usage examples
- “How do I define a simple function to run on Modal?”
- You define an app using modal.App, decorate your function with @app.function(), and execute it remotely using .remote().
- “How can I request an H100 GPU for my inference task?”
- Add the gpu parameter to your function decorator: @app.function(gpu='H100').
- “How do I deploy a FastAPI app on Modal?”
- Use the @modal.fastapi_endpoint() decorator on a function within your Modal app to expose it as a web endpoint.
- “How do I run a job every day at 9 AM?”
- Use the schedule parameter with modal.Cron('0 9 * * *') in your function decorator.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/k-dense-ai/modal/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip modal.zip -d .agents/skills
Documentation by K-Dense Inc.
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. 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:
Reuse an existing Modal profile, or check whether both
MODAL_TOKEN_IDandMODAL_TOKEN_SECRETare set; report presence only.If not, look up only those two keys in a local
.envfile (ignore all other entries) and load them if appropriate for the workflow.Only fall back to interactive
modal setupif 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 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-upgradeB300 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 getBackground 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 andvol.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.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 URLSupports 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 redeployMonitor 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_window=300, # Idle seconds before shutdown
)
def process(data):
...Process inputs in parallel with .map():
results = list(process.map([item1, item2, item3, ...]))Enable concurrent request handling per container with @modal.concurrent. Set
target_inputs (the autoscaler's per-container target) below max_inputs (the hard
cap) to keep headroom while scaling up:
@app.function()
@modal.concurrent(max_inputs=10, target_inputs=8)
async def handle_request(req):
...Reconfigure a deployed Function or Cls at invocation time without redeploying using
Function.with_options() / Function.with_concurrency() / Function.with_batching()
(and Cls.with_options()):
Model = modal.Cls.from_name("my-app", "Model")
fast = Model.with_options(gpu="H200", max_containers=20)
fast().generate.remote(prompt)Reference: See references/scaling.md for .map(), .starmap(), .spawn(), and limits.
Resource Configuration
@app.function(
cpu=4.0, # Physical cores (not vCPUs)
memory=16384, # MiB
ephemeral_disk=51200, # MiB (up to 3 TiB)
timeout=3600, # Seconds
)
def heavy_computation():
...Defaults: 0.125 CPU cores, 128 MiB memory. Billed on max(request, usage).
Use cpu=(request, limit) and memory=(request, limit) for explicit limits.
Reference: See references/resources.md for limits and billing details.
Classes with Lifecycle Hooks
For stateful workloads (e.g., loading a model once and serving many requests):
@app.cls(gpu="L40S", image=image)
class Predictor:
@modal.enter()
def load_model(self):
self.model = load_heavy_model() # Runs once on container start
@modal.method()
def predict(self, text: str):
return self.model(text)
@modal.exit()
def cleanup(self):
... # Runs on container shutdownCall with: Predictor().predict.remote("hello")
Sandboxes
For running untrusted or dynamically generated code (for example, AI-agent output or a code interpreter), use a modal.Sandbox — an isolated container you create and control programmatically rather than a decorated Function:
app = modal.App.lookup("sandbox-demo", create_if_missing=True)
# Isolated container; restrict egress for untrusted workloads
sb = modal.Sandbox.create(
app=app,
image=modal.Image.debian_slim(),
block_network=True,
timeout=60,
)
try:
sb.filesystem.write_text("print(2 ** 10)\n", "/tmp/job.py")
proc = sb.exec("python", "/tmp/job.py")
output = proc.stdout.read()
proc.wait()
if proc.returncode != 0:
raise RuntimeError("Sandbox command failed")
print(output)
finally:
sb.terminate(wait=True)Run commands inside the sandbox with its
execmethod (e.g. runpython /tmp/job.py) and read stdout from the returned process handle — seereferences/api_reference.mdRestrict connectivity with
outbound_cidr_allowlist=[...]/inbound_cidr_allowlist=[...]SDK 1.6
Sandbox.create()blocks until scheduled; creation can raiseResourceExhaustedErrorsb.snapshot_filesystem()returns an Image with a default 30-day TTL, not permanent storageIdeal for code interpreters, agent tool execution, and per-user isolation
Common Workflow Patterns
GPU Model Inference Service
import modal
app = modal.App("llm-service")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("vllm==0.21.0", "fastapi[standard]==0.136.3")
)
@app.cls(gpu="H100", image=image, max_containers=1)
class LLMService:
@modal.enter()
def load(self):
from vllm import LLM
self.llm = LLM(model="Qwen/Qwen3-8B", max_model_len=4096)
@modal.fastapi_endpoint(method="POST", requires_proxy_auth=True)
def generate(self, body: dict):
from vllm import SamplingParams
params = SamplingParams(max_tokens=256)
outputs = self.llm.generate([body["prompt"]], sampling_params=params)
return {"text": outputs[0].outputs[0].text}Batch Processing Pipeline
Use .map() over independent inputs, unique output paths per run/chunk, and an
explicit Volume commit before returning. See the complete illustrative batch
pattern in references/examples.md.
Scheduled Data Pipeline
app = modal.App("etl-pipeline")
@app.function(
schedule=modal.Cron("0 */6 * * *"), # Every 6 hours
secrets=[modal.Secret.from_name("db-credentials")],
)
def etl_job():
import os
db_url = os.environ["DATABASE_URL"]
# Extract, transform, load
...CLI Reference
| Command | Description |
|---|---|
modal setup | Authenticate with Modal |
modal run script.py | Run a script's local entrypoint |
modal serve script.py | Dev server with hot reload |
modal deploy script.py | Deploy to production |
modal volume ls <name> | List files in a volume |
modal volume put <name> <file> | Upload file to volume |
modal volume get <name> <file> | Download file from volume |
modal secret create <name> K=V | Create a secret |
modal secret list | List secrets |
modal app list | List deployed apps |
modal app stop <name> | Stop a deployed app |
Security Notes
Credentials: Reuse an existing profile or the two
MODAL_TOKEN_*values for SDK authentication. Read only workload-specific keys when explicitly needed for that workload; never dump environments or forward platform tokens to containers.Subprocess / custom servers: Some patterns here (multi-GPU training launchers,
@modal.web_serverapps) callsubprocess.run/subprocess.Popenor shell commands during builds. Keep argument lists fixed and hardcoded. Never construct subprocess or shell arguments from unsanitized user input — pass untrusted values as data (files, env vars, stdin), not as command arguments.Untrusted code: Run user- or model-generated code inside a
modal.Sandbox(see above), not a regular Function, and restrict network access with CIDR allowlists.
Reference Files
Detailed documentation for each topic:
references/getting-started.md— Installation, authentication, first appreferences/functions.md— Functions, classes, lifecycle hooks, remote executionreferences/images.md— Container images, package installation, cachingreferences/gpu.md— GPU types, selection, multi-GPU, trainingreferences/volumes.md— Persistent storage, file management, v2 volumesreferences/secrets.md— Credentials, environment variables, dotenvreferences/web-endpoints.md— FastAPI, ASGI/WSGI, streaming, auth, WebSocketsreferences/scheduled-jobs.md— Cron, periodic schedules, managementreferences/scaling.md— Autoscaling, concurrency, .map(), limitsreferences/resources.md— CPU, memory, disk, timeout configurationreferences/examples.md— Common use cases and patternsreferences/api_reference.md— Key API classes and methods
Read these files when detailed information is needed beyond this overview.
Citing Scientific Agent Skills
This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:
Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065
Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
latest arXiv version, so never append a version suffix such as v1. When network access is
available, fetch https://arxiv.org/abs/2609.00065 (or
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
the author list, year, and version from that record. If the record lists a journal reference
or publisher DOI, cite the published version instead.
Files
- ATTRIBUTION.mdAdded by AutoGineer1003 B
- LICENSEAdded by AutoGineer10.0 KiB
- SKILL.md17.6 KiB
- references/api_reference.md8.5 KiB
- references/examples.md10.3 KiB
- references/functions.md8.3 KiB
- references/getting-started.md4.7 KiB
- references/gpu.md6.5 KiB
- references/images.md7.3 KiB
- references/resources.md3.2 KiB
- references/scaling.md6.5 KiB
- references/scheduled-jobs.md4.3 KiB
- references/secrets.md3.9 KiB
- references/volumes.md6.8 KiB
- references/web-endpoints.md8.2 KiB
references/examples.md
Modal Common Examples
Reviewed against Modal 1.6.0. These are illustrative cloud workload templates:
SDK registration and selected local handlers were checked, but container builds,
GPU jobs, weights and database writes were not executed. Package pins are examples,
not a validated combined environment. Resolve a lockfile per workload and record the
model revision, hardware, seeds and input provenance before a scientific run.
External helpers such as transform() are application-defined.
LLM Inference Service (vLLM)
import modal
app = modal.App("vllm-service")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("vllm==0.21.0", "fastapi[standard]==0.136.3")
)
@app.cls(gpu="H100", image=image, max_containers=1)
class LLMService:
@modal.enter()
def load(self):
from vllm import LLM
self.llm = LLM(model="Qwen/Qwen3-8B", max_model_len=4096)
@modal.method()
def generate(self, prompt: str, max_tokens: int = 512) -> str:
from vllm import SamplingParams
params = SamplingParams(max_tokens=max_tokens, temperature=0.7)
outputs = self.llm.generate([prompt], sampling_params=params)
return outputs[0].outputs[0].text
@modal.fastapi_endpoint(method="POST", requires_proxy_auth=True)
def api(self, request: dict):
text = self.generate.local(request["prompt"], request.get("max_tokens", 512))
return {"text": text}vLLM LLM.generate uses
SamplingParams; max_tokens is not a generate() keyword. This template accepts
a preformatted completion prompt. Apply the model's chat template for chat messages.
Use your Proxy Token to call the endpoint. A 70B BF16 model does not fit one H100;
GPU capacity must include weights and KV cache, not just parameter count.
Image Generation (Flux)
import modal
app = modal.App("image-gen")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install(
"diffusers==0.38.0",
"torch==2.12.0",
"transformers==5.9.0",
"accelerate==1.13.0",
)
)
vol = modal.Volume.from_name("flux-weights", create_if_missing=True)
@app.cls(gpu="L40S", image=image, volumes={"/models": vol})
class ImageGenerator:
@modal.enter()
def load(self):
import torch
from diffusers import FluxPipeline
self.pipe = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-schnell",
torch_dtype=torch.bfloat16,
cache_dir="/models",
).to("cuda")
vol.commit()
@modal.method()
def generate(self, prompt: str) -> bytes:
image = self.pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
import io
buf = io.BytesIO()
image.save(buf, format="PNG")
return buf.getvalue()Speech Transcription (Whisper)
The audio path must exist inside the container. Upload it to the named Volume first; passing a local laptop path does not transfer audio.
import modal
app = modal.App("transcription")
image = (
modal.Image.debian_slim(python_version="3.11")
.apt_install("ffmpeg")
.uv_pip_install("openai-whisper==20250625", "torch==2.12.0")
)
audio_vol = modal.Volume.from_name("audio-data", create_if_missing=True)
@app.cls(gpu="T4", image=image, volumes={"/audio": audio_vol})
class Transcriber:
@modal.enter()
def load(self):
import whisper
self.model = whisper.load_model("large-v3")
@modal.method()
def transcribe(self, audio_path: str) -> dict:
audio_vol.reload()
return self.model.transcribe(audio_path)Batch Data Processing
import modal
app = modal.App("batch-processor")
image = modal.Image.debian_slim().uv_pip_install("pandas", "pyarrow")
vol = modal.Volume.from_name("batch-data", create_if_missing=True)
@app.function(image=image, volumes={"/data": vol}, cpu=4.0, memory=8192)
def process_chunk(chunk_id: int) -> dict:
import pandas as pd
from pathlib import Path
from uuid import uuid4
vol.reload()
df = pd.read_parquet(f"/data/input/chunk_{chunk_id:04d}.parquet")
result = df.groupby("category").agg({"value": ["sum", "mean", "count"]})
output_dir = Path("/data/output") / uuid4().hex
output_dir.mkdir(parents=True)
output = output_dir / f"result_{chunk_id:04d}.parquet"
result.to_parquet(output)
vol.commit()
return {"chunk_id": chunk_id, "rows": len(df), "output": str(output)}
@app.local_entrypoint()
def main():
chunk_ids = list(range(500))
results = list(process_chunk.map(chunk_ids))
total = sum(r["rows"] for r in results)
print(f"Processed {total} total rows across {len(results)} chunks")Web Scraping at Scale
import modal
app = modal.App("scraper")
image = modal.Image.debian_slim().uv_pip_install("httpx", "beautifulsoup4")
@app.function(image=image, retries=3, timeout=60)
def scrape_url(url: str) -> dict:
import httpx
from bs4 import BeautifulSoup
response = httpx.get(url, follow_redirects=True, timeout=30)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
return {
"url": url,
"title": soup.title.string if soup.title else None,
"text": soup.get_text()[:5000],
}
@app.local_entrypoint()
def main():
urls = ["https://example.com", "https://example.org"] # Your URL list
results = list(scrape_url.map(urls))
for r in results:
print(f"{r['url']}: {r['title']}")Protein Structure Prediction
import modal
app = modal.App("protein-folding")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("chai-lab")
)
vol = modal.Volume.from_name("protein-data", create_if_missing=True)
@app.function(gpu="A100-80GB", image=image, volumes={"/data": vol}, timeout=3600)
def fold_protein(sequence: str) -> list[str]:
from pathlib import Path
from uuid import uuid4
from chai_lab.chai1 import run_inference
if not sequence or any(c not in "ACDEFGHIKLMNPQRSTVWY" for c in sequence):
raise ValueError("Provide one non-empty canonical protein sequence")
run_dir = Path("/data/runs") / uuid4().hex
run_dir.mkdir(parents=True)
fasta = run_dir / "input.fasta"
fasta.write_text(f">protein|name=target\n{sequence}\n")
candidates = run_inference(
fasta_file=fasta,
output_dir=run_dir / "predictions",
use_msa_server=False,
use_templates_server=False,
seed=42,
device="cuda:0",
)
vol.commit()
return [str(path) for path in candidates.cif_paths]The Chai API
accepts Path objects and returns StructureCandidates, not an output filename.
Server-based MSA/template search is disabled here; enabling it sends sequence data
to another service. Predicted structures and confidence scores require scientific
validation; they are not experimental evidence.
Scheduled ETL Pipeline
import modal
app = modal.App("etl")
image = modal.Image.debian_slim().uv_pip_install("pandas", "sqlalchemy", "psycopg2-binary")
@app.function(
image=image,
schedule=modal.Cron("0 3 * * *"), # 3 AM UTC daily
secrets=[modal.Secret.from_name("database-creds")],
timeout=7200,
)
def daily_etl():
import os
import pandas as pd
from sqlalchemy import create_engine
source = create_engine(os.environ["SOURCE_DB"])
dest = create_engine(os.environ["DEST_DB"])
df = pd.read_sql("SELECT * FROM events WHERE date = CURRENT_DATE - 1", source)
df = transform(df)
# Illustrative append: add a date/run key and transactional upsert in production
# so redeploys, retries or manual reruns cannot duplicate observations.
df.to_sql("daily_summary", dest, if_exists="append", index=False)
print(f"Loaded {len(df)} rows")FastAPI with GPU Model
import modal
app = modal.App("api-with-gpu")
image = (
modal.Image.debian_slim(python_version="3.11")
.uv_pip_install("fastapi[standard]==0.136.3", "sentence-transformers==5.5.1", "torch==2.12.0")
)
@app.cls(gpu="L40S", image=image, min_containers=1)
class EmbeddingService:
@modal.enter()
def load(self):
from sentence_transformers import SentenceTransformer
self.model = SentenceTransformer("all-MiniLM-L6-v2", device="cuda")
@modal.asgi_app(requires_proxy_auth=True)
def serve(self):
from fastapi import FastAPI
api = FastAPI()
@api.post("/embed")
def embed(request: dict):
embeddings = self.model.encode(request["texts"])
return {"embeddings": embeddings.tolist()}
@api.get("/health")
async def health():
return {"status": "ok"}
return apiDocument OCR Job Queue
import modal
app = modal.App("ocr-queue")
image = modal.Image.debian_slim().uv_pip_install("pytesseract", "Pillow").apt_install("tesseract-ocr")
vol = modal.Volume.from_name("ocr-data", create_if_missing=True)
@app.function(image=image, volumes={"/data": vol})
def ocr_page(image_path: str) -> str:
import pytesseract
from PIL import Image
vol.reload()
with Image.open(image_path) as img:
return pytesseract.image_to_string(img)
@app.function(volumes={"/data": vol})
def process_document(doc_id: str):
import os
from uuid import uuid4
if not doc_id or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for c in doc_id):
raise ValueError("Invalid document ID")
vol.reload()
pages = sorted(os.listdir(f"/data/docs/{doc_id}/"))
paths = [f"/data/docs/{doc_id}/{p}" for p in pages]
texts = list(ocr_page.map(paths))
full_text = "\n\n".join(texts)
os.makedirs("/data/results", exist_ok=True)
output = f"/data/results/{doc_id}-{uuid4().hex}.txt"
with open(output, "w") as f:
f.write(full_text)
vol.commit()
return {"doc_id": doc_id, "pages": len(texts), "output": output}Additional upstream contracts reviewed: FLUX, Whisper, Sentence Transformers. For pretrained weights, verify licensing/access and pin revisions; the GPU examples remain unexecuted and do not establish numerical reproducibility or performance.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs network access, Needs an API key, Needs Python
The author says: Requires Python 3.10-3.14 and modal 1.6.0. Cloud execution needs a Modal account, authentication and network access; GPU use needs a payment method. Workload dependencies belong in their container Images.
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- K-Dense Inc.
- Publisher
- K-Dense (Community)
- Source
- K-Dense-AI/scientific-agent-skills · skills/modal · commit a25cf9e
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (written by AutoGineer)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download modal.zip