policyengine-modal-deployment
Deploying PolicyEngine backend APIs to Modal — workspace setup, authentication, deployment commands, environments, and troubleshooting
What this skill does
# PolicyEngine Modal deployment
How to deploy PolicyEngine backend APIs (custom Modal backends for dashboards and interactive tools) to Modal under the PolicyEngine organizational workspace.
**This skill applies only when a dashboard or tool uses the `custom-backend` data pattern.** If the project uses `api-v2-alpha` (stub data or direct API calls), no Modal deployment is needed.
## Workspace
PolicyEngine uses a shared Modal workspace called `policyengine`. All backend deployments MUST target this workspace — never a personal workspace.
### Environments
The `policyengine` workspace has three environments:
| Environment | Web suffix | URL pattern | Purpose |
|-------------|-----------|-------------|---------|
| `main` | _(empty)_ | `policyengine--<app>-<func>.modal.run` | Production |
| `staging` | `staging` | `policyengine-staging--<app>-<func>.modal.run` | Pre-production testing |
| `testing` | `testing` | `policyengine-testing--<app>-<func>.modal.run` | Development/CI |
Default to `main` for production deployments.
## Authentication
### Prerequisites
1. A Modal account linked to the PolicyEngine workspace (ask a workspace owner for an invite)
2. The Modal CLI installed: `pip install modal`
3. A token for the `policyengine` workspace stored in a local profile
### Setting up authentication
```bash
# Create a token for the policyengine workspace (opens browser)
modal token new --profile policyengine
# Activate the profile
modal profile activate policyengine
# Verify — must show "Workspace: policyengine"
modal token info
```
### Verifying authentication before deploy
**HUMAN GATE:** Before any deployment, verify the active workspace:
```bash
modal token info
modal profile list
```
Expected output from `modal profile list`:
```
┏━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓
┃ ┃ Profile ┃ Workspace ┃
┡━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩
│ • │ policyengine │ policyengine │
└───┴──────────────┴──────────────┘
```
The `•` indicates the active profile. If `policyengine` is not active or not present:
> **Authentication required.** Your Modal CLI is not configured for the `policyengine` workspace.
>
> Run:
> ```bash
> modal token new --profile policyengine
> modal profile activate policyengine
> ```
>
> If you don't have access to the PolicyEngine workspace, ask a workspace owner to invite you at https://modal.com/settings/policyengine
**Do NOT proceed with deployment until `modal token info` shows `Workspace: policyengine`.**
### Critical: environment variable override
Modal CLI respects `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` environment variables, which **override** the profile. If these are set (e.g., from a CI environment), the CLI will deploy to whatever workspace those tokens belong to — potentially a personal workspace.
**Always unset before deploying:**
```bash
unset MODAL_TOKEN_ID MODAL_TOKEN_SECRET
```
## App structure
### Naming convention
The Modal app name MUST match the dashboard/tool repo name in kebab-case:
```python
app = modal.App("my-dashboard-name")
```
This keeps the app name consistent with the GitHub repo and Vercel project.
### Image and dependencies
Build a container image with the required Python packages:
```python
image = (
modal.Image.debian_slim(python_version="3.12")
.pip_install(
"policyengine-us>=1.155.0", # Pin minimum version
"fastapi[standard]",
"numpy",
"pandas",
)
.env({"NUMEXPR_MAX_THREADS": "4"})
.add_local_dir("api", "/root/api") # Local source code
.add_local_file("config.yaml", "/root/config.yaml") # Config files
)
```
**Guidelines:**
- Use `debian_slim` with Python 3.12 or 3.13
- Pin minimum versions for `policyengine-us` / `policyengine-uk`
- Use `.add_local_dir()` / `.add_local_file()` for project source code
- Use `.env()` for non-secret environment variables
- Set memory and timeout on the function, not the image
### Web endpoint patterns
#### Simple endpoint (single function)
For tools with one calculation endpoint:
```python
@app.function(image=image, timeout=300, memory=2048)
@modal.web_endpoint(method="POST")
def calculate(data: dict) -> dict:
from policyengine_us import Simulation
# Build simulation from data, return results
return {"result": value}
```
URL: `https://policyengine--<app-name>-calculate.modal.run`
#### Full FastAPI app (multiple endpoints)
For dashboards with multiple API routes:
```python
@app.function(image=image, timeout=300, memory=2048)
@modal.concurrent(max_inputs=100)
@modal.asgi_app()
def fastapi_app():
from api.main import app as api
return api
```
URL: `https://policyengine--<app-name>-fastapi-app.modal.run`
#### Health check endpoint
Every Modal backend SHOULD include a health check:
```python
@app.function(image=image)
@modal.web_endpoint(method="GET")
def health():
return {"status": "ok"}
```
### Function configuration
| Parameter | Default | Recommended for PE | Purpose |
|-----------|---------|-------------------|---------|
| `timeout` | 60s | 300 | PolicyEngine simulations can take minutes |
| `memory` | 128MB | 2048 | PE models are memory-intensive |
| `@modal.concurrent(max_inputs=N)` | 1 | 100 | Handle concurrent requests without cold starts |
### Secrets
Store sensitive values as Modal Secrets (not in code or `.env` files):
```bash
# Create a secret
modal secret create my-secret API_KEY=abc123
# List secrets
modal secret list
```
Reference in code:
```python
@app.function(
image=image,
secrets=[modal.Secret.from_name("my-secret")],
)
def my_function():
import os
api_key = os.environ["API_KEY"] # Injected by Modal
```
Existing secrets in the `policyengine` workspace:
- `policyengine-logfire` — logging/observability
- `gcp-credentials` — Google Cloud access
- `huggingface-token` — HuggingFace model access
- `anthropic-api-key` — Anthropic API access
## Deployment
### Deploy command
```bash
# 1. Ensure correct workspace
unset MODAL_TOKEN_ID MODAL_TOKEN_SECRET
modal token info # Verify "Workspace: policyengine"
# 2. Deploy to production
modal deploy modal_app.py --env main
# 3. Deploy to staging (for testing)
modal deploy modal_app.py --env staging
```
**Flags:**
- `--env main` / `--env staging` / `--env testing` — target environment
- `--name TEXT` — override the deployment name (rarely needed)
- `--tag TEXT` — tag the deployment with a version string
- `--stream-logs` — stream container logs during deployment
### Verify deployment
```bash
# List deployed apps
modal app list --env main
# Health check
curl -s -w "\n%{http_code}" https://policyengine--DASHBOARD_NAME-health.modal.run
# Test the endpoint
curl -X POST https://policyengine--DASHBOARD_NAME-calculate.modal.run \
-H "Content-Type: application/json" \
-d '{"test": true}'
```
### Connecting to Vercel frontend
After Modal deployment, set the API URL as an environment variable in the Vercel project:
```bash
vercel env add NEXT_PUBLIC_API_URL production
# Enter: https://policyengine--DASHBOARD_NAME-calculate.modal.run
vercel --prod --force --yes --scope policy-engine
```
The `--force` flag is required to rebuild with the new environment variable.
### Redeployment
Redeploying an existing app is the same command — Modal handles zero-downtime transitions:
1. New containers build while old ones handle requests
2. New containers start accepting requests
3. Old containers finish in-flight requests then terminate
```bash
modal deploy modal_app.py --env main
```
### Stopping an app
**WARNING: This is destructive and irreversible.** A stopped app cannot be restarted; you must redeploy.
```bash
modal app stop <app-name>
```
## Monitoring
```bash
# View logs for a deployed app
modal app logs <app-name>
# List all apps and their status
modal app list --env main
```
App states:
- `deployed` — running and accepting requests
- `ephemeral` — temporary (from `modal serve`)
- `stopped` — permanently stopped
## Troubleshooting
| Issue | Cause | Fix Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.