Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/just-cameron/comind. Comind, the cognitive layer for the web. comind.stream/docs/getting-started
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601import modalimport sysimport os
# Create our Modal applicationapp = modal.App("comind-vllm-inference")
# Set up the container image with vLLM and necessary packagesvllm_image = ( modal.Image.debian_slim(python_version="3.12") .pip_install( "vllm==0.7.2", "huggingface_hub[hf_transfer]==0.26.2", "flashinfer-python==0.2.0.post2", # pinning, very unstable extra_index_url="https://flashinfer.ai/whl/cu124/torch2.5", ) .env({"HF_HUB_ENABLE_HF_TRANSFER": "1"}) # faster model transfers)
# Enable vLLM's V1 engine for better performancevllm_image = vllm_image.env({"VLLM_USE_V1": "1"})
# Set up persistent volumes to cache models between runshf_cache_vol = modal.Volume.from_name("huggingface-cache", create_if_missing=True)vllm_cache_vol = modal.Volume.from_name("vllm-cache", create_if_missing=True)
# Configuration options (can be modified as needed)MINUTES = 60 # secondsVLLM_PORT = 8000API_KEY = "comind-api-key" # Default API key
# Try to use a secret if it exists, but make it optionaltry: # Try to use an existing secret api_key_secret = modal.Secret.from_name("comind-api-key") print("Using existing API key secret") has_secret = Trueexcept: # If it doesn't exist, we'll just use a default API key print("No 'comind-api-key' secret found. Using default API key.") print("To create a secret, visit: https://modal.com/secrets/create?secret_name=comind-api-key") has_secret = False
# Add these configuration variables for cold start optimizationMIN_CONTAINERS = 1 # Keep at least one container warm at all timesBUFFER_CONTAINERS = 1 # Provision one extra container when function is active
# Define available modelsMODELS = { "phi4": { "name": "microsoft/Phi-4", "revision": None, # Use latest "gpu": "A10G:1", # Adjust based on model size and budget }, "hermes-8b": { "name": "NousResearch/Hermes-3-Llama-3.1-8B", "revision": None, "gpu": "A10G:1", # 8B model should fit in one A10G }, "hermes-3b": { "name": "NousResearch/Hermes-3-Llama-3.2-3B", "revision": None, "gpu": "T4:1", # 3B model can run on a T4 }, "phi3-mini": { "name": "microsoft/Phi-3-mini-4k-instruct", "revision": None, "gpu": "A10G:1", # Smaller model can run on cheaper ? }, "tiny-llama": { "name": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "revision": None, "gpu": "T4:1", # Very small model }, "qwen3-0.6b": { "name": "RedHatAI/Qwen3-0.6B-FP8_dynamic", "revision": None, "gpu": "T4:1", # Ultra-small model, can run on T4 }, "embeddings": { "name": "mixedbread-ai/mxbai-embed-xsmall-v1", "revision": None, "gpu": "T4:1", # Embeddings can run on T4 },}
# Get the default model (for backward compatibility)DEFAULT_MODEL = "phi4"
# Define a function to get optional secrets listdef get_optional_secrets(): """Return a list with the API key secret if it exists, otherwise an empty list.""" if has_secret: return [api_key_secret] return []
# Define a function to get the API key valuedef get_api_key(): """Get the API key from the environment or default.""" import os # Modal automatically injects secret values as environment variables # We'll try to get it from environment, but fall back to our default return os.environ.get("api_key", API_KEY)
# Define each model function separately instead of dynamically generating them@app.function( image=vllm_image, gpu=MODELS["phi4"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_phi4(): """Serves Microsoft Phi-4 with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["phi4"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["hermes-8b"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_hermes_8b(): """Serves NousResearch Hermes-3-Llama-3.1-8B with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["hermes-8b"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["hermes-3b"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_hermes_3b(): """Serves NousResearch Hermes-3-Llama-3.2-3B with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["hermes-3b"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", "--dtype", "half", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["phi3-mini"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_phi3_mini(): """Serves Microsoft Phi-3-mini with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["phi3-mini"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", "--dtype", "half", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["tiny-llama"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_tiny_llama(): """Serves TinyLlama model with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["tiny-llama"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", "--dtype", "half", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["qwen3-0.6b"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def serve_qwen3_0_6b(): """Serves RedHatAI Qwen3-0.6B with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["qwen3-0.6b"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", "--dtype", "half", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
@app.function( image=vllm_image, gpu=MODELS["embeddings"]["gpu"], volumes={ "/root/.cache/huggingface": hf_cache_vol, "/root/.cache/vllm": vllm_cache_vol, }, secrets=get_optional_secrets(), min_containers=MIN_CONTAINERS, buffer_containers=BUFFER_CONTAINERS, scaledown_window=10 * MINUTES,)@modal.concurrent(max_inputs=100)@modal.web_server(port=VLLM_PORT, startup_timeout=5 * MINUTES)def embeddings(): """Serves the embeddings model with OpenAI-compatible API endpoints.""" import subprocess model_name = MODELS["embeddings"]["name"] cmd = [ "vllm", "serve", "--uvicorn-log-level=info", model_name, "--host", "0.0.0.0", "--port", str(VLLM_PORT), "--api-key", get_api_key(), "--guided-decoding-backend", "outlines", "--trust-remote-code", "--dtype", "half", ] print(f"Starting vLLM server for {model_name} with command: {' '.join(cmd)}") subprocess.Popen(" ".join(cmd), shell=True)
# Simple utility functions for the CLI
def create_secret_cli(): """Create the comind-api-key secret in Modal.""" print("🔑 Creating 'comind-api-key' secret...") # Ask for the API key value api_key = input("Enter the API key value (press Enter to use 'comind-api-key' as default): ").strip() if not api_key: api_key = "comind-api-key" # Create the secret try: modal.Secret.from_dict({"api_key": api_key}, name="comind-api-key") print("✅ Secret created successfully!") print(f"Your API key is: {api_key}") return True except Exception as e: print(f"❌ Error creating secret: {e}") print("Try creating it manually on the Modal website:") print("https://modal.com/secrets/create?secret_name=comind-api-key") return False
def deploy_and_warm_cli(): """Deploy the app and immediately keep containers warm.""" print("🚀 Deploying Modal inference server...") # First, check if the API key secret exists try: modal.Secret.from_name("comind-api-key") print("✓ API key secret found") except: print("⚠️ No 'comind-api-key' secret found.") print("You can create one now, or continue without it (a default key will be used).") create_now = input("Create secret now? (y/n): ").lower().strip() == 'y' if create_now: create_secret_cli() # Ask which models to deploy and warm print("\nAvailable models:") for idx, (model_key, model_info) in enumerate(MODELS.items(), 1): print(f" {idx}. {model_key} - {model_info['name']} ({model_info['gpu']})") selected = input("Enter model numbers to deploy (comma-separated, or 'all'): ").strip() if selected.lower() == 'all': models_to_deploy = list(MODELS.keys()) else: try: indices = [int(idx.strip()) - 1 for idx in selected.split(',')] models_to_deploy = [list(MODELS.keys())[i] for i in indices if 0 <= i < len(MODELS)] except: print("Invalid selection. Deploying default model only.") models_to_deploy = [DEFAULT_MODEL] print(f"\nDeploying models: {', '.join(models_to_deploy)}") app.deploy() print("\n✅ Deployment complete!") print("\n🔥 Warming up containers (this reduces cold start time)...") import time time.sleep(2) # Give Modal a moment to register the deployment # Only warm the models that were selected for model_key in models_to_deploy: if model_key == "phi4": serve_phi4.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "hermes-8b": serve_hermes_8b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "hermes-3b": serve_hermes_3b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "phi3-mini": serve_phi3_mini.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "tiny-llama": serve_tiny_llama.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "qwen3-0.6b": serve_qwen3_0_6b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "embeddings": embeddings.keep_warm(1) print(f" ✓ Warming {model_key}") print("\n🎉 Your Modal inference server is ready!") print("\nℹ️ You can access your endpoints at:") # Get your Modal workspace name modal_config_file = os.path.expanduser("~/.modal/config.toml") workspace = "your-workspace" # Default fallback if os.path.exists(modal_config_file): try: with open(modal_config_file, "r") as f: for line in f: if "workspace_name" in line: workspace = line.split("=")[1].strip().strip('"') break except Exception: pass # Only show deployed model endpoints for model_key in models_to_deploy: if model_key == "phi4": print(f" - Phi-4: https://{workspace}--comind-vllm-inference-serve-phi4.modal.run/v1") elif model_key == "hermes-8b": print(f" - Hermes-8B: https://{workspace}--comind-vllm-inference-serve-hermes-8b.modal.run/v1") elif model_key == "hermes-3b": print(f" - Hermes-3B: https://{workspace}--comind-vllm-inference-serve-hermes-3b.modal.run/v1") elif model_key == "phi3-mini": print(f" - Phi-3-mini: https://{workspace}--comind-vllm-inference-serve-phi3-mini.modal.run/v1") elif model_key == "tiny-llama": print(f" - TinyLlama: https://{workspace}--comind-vllm-inference-serve-tiny-llama.modal.run/v1") elif model_key == "qwen3-0.6b": print(f" - Qwen3-0.6B: https://{workspace}--comind-vllm-inference-serve-qwen3-0-6b.modal.run/v1") elif model_key == "embeddings": print(f" - Embeddings: https://{workspace}--comind-vllm-inference-embeddings.modal.run/v1") # Get the API key from our function api_key = get_api_key() print(f"\n💡 Use API key '{api_key}' for authentication")
def warm_containers_cli(): """Just warm up the containers without deploying.""" print("🔥 Warming up containers...") # Ask which models to warm print("\nAvailable models:") for idx, (model_key, model_info) in enumerate(MODELS.items(), 1): print(f" {idx}. {model_key} - {model_info['name']} ({model_info['gpu']})") selected = input("Enter model numbers to warm up (comma-separated, or 'all'): ").strip() if selected.lower() == 'all': models_to_warm = list(MODELS.keys()) else: try: indices = [int(idx.strip()) - 1 for idx in selected.split(',')] models_to_warm = [list(MODELS.keys())[i] for i in indices if 0 <= i < len(MODELS)] except: print("Invalid selection. Warming default model only.") models_to_warm = [DEFAULT_MODEL] print(f"\nWarming models: {', '.join(models_to_warm)}") # Only warm the models that were selected for model_key in models_to_warm: if model_key == "phi4": serve_phi4.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "hermes-8b": serve_hermes_8b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "hermes-3b": serve_hermes_3b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "phi3-mini": serve_phi3_mini.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "tiny-llama": serve_tiny_llama.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "qwen3-0.6b": serve_qwen3_0_6b.keep_warm(1) print(f" ✓ Warming {model_key}") elif model_key == "embeddings": embeddings.keep_warm(1) print(f" ✓ Warming {model_key}") print("✅ Containers are warming up!") print(" This reduces cold start time for your next requests.")
def check_status_cli(): """Check the status of your Modal app.""" try: import subprocess result = subprocess.run( ["modal", "app", "show", "comind-vllm-inference"], capture_output=True, text=True ) print(result.stdout) except Exception as e: print(f"❌ Error checking status: {e}") print("Make sure you have the Modal CLI installed and configured.")
@app.local_entrypoint()def main(): """ Main entrypoint for the script. Handles CLI commands. Usage: modal run modal_inference.py deploy # Deploy and keep containers warm modal run modal_inference.py warm # Just warm up existing containers modal run modal_inference.py status # Check the status of the app modal run modal_inference.py create-secret # Create the API key secret modal run modal_inference.py run MODEL # Run a test request against a specific model """ import argparse # Parse command line arguments parser = argparse.ArgumentParser(description="Deploy and manage Modal inference server") parser.add_argument("command", choices=["deploy", "warm", "status", "create-secret", "run"], default="run", nargs="?", help="Command to execute (default: run a test request)") parser.add_argument("model", nargs="?", default=DEFAULT_MODEL, help=f"Model to use (default: {DEFAULT_MODEL})") args = parser.parse_args() # Execute the appropriate command if args.command == "deploy": deploy_and_warm_cli() elif args.command == "warm": warm_containers_cli() elif args.command == "status": check_status_cli() elif args.command == "create-secret": create_secret_cli() elif args.command == "run": # Run a test request against the specified model model = args.model if model not in MODELS: available_models = ", ".join(MODELS.keys()) print(f"❌ Model '{model}' not found. Available models: {available_models}") sys.exit(1) print(f"Running test against the {model} server...") if model == "phi4": serve_phi4.remote("Hello, world!") elif model == "hermes-8b": serve_hermes_8b.remote("Hello, world!") elif model == "hermes-3b": serve_hermes_3b.remote("Hello, world!") elif model == "phi3-mini": serve_phi3_mini.remote("Hello, world!") elif model == "tiny-llama": serve_tiny_llama.remote("Hello, world!") elif model == "qwen3-0.6b": serve_qwen3_0_6b.remote("Hello, world!") elif model == "embeddings": embeddings.remote("Hello, world!")