Modal cloud execution framework
Move your local Claude-run Python workflows to Modal so they run in the cloud.
Tools featured in this playbook
This article was originally posted on Google Docs
This document explains how to convert local Python execution scripts into cloud-hosted Modal webhooks. It provides everything needed to replicate the pattern established in this codebase.
\---
\#\# Quick Start for Users
If you're setting this up for the first time, follow these steps:
\#\#\# 1\. Install Modal CLI
\`\`\`bash
pip install modal
modal token new \# Authenticate with Modal
\`\`\`
\#\#\# 2\. Check What Secrets Exist
\`\`\`bash
modal secret list
\`\`\`
\#\#\# 3\. Identify Missing Secrets
Compare what exists against what the workflow needs. See \[Identifying Required Secrets\](\#identifying-required-secrets) below.
\#\#\# 4\. Create Missing Secrets
For each missing secret, you'll need to:
1\. Get the API key from the service's dashboard
2\. Create it in Modal:
\`\`\`bash
modal secret create \<secret-name\> \<ENV\_VAR\_NAME\>=\<value\>
\`\`\`
See \[Handling Missing Secrets\](\#handling-missing-secrets) for detailed guidance on what to do when you don't have all credentials.
\#\#\# 5\. Deploy
\`\`\`bash
modal deploy execution/modal\_webhook.py
\`\`\`
\#\#\# 6\. Test
\`\`\`bash
curl "https\://\<your-modal-url\>/endpoint?param=value"
\`\`\`
\---
\#\# Overview
The DOE (Directive-Orchestration-Execution) framework separates concerns:
\- \*\*Directives\*\*: SOPs in markdown describing what to do
\- \*\*Orchestration\*\*: Claude (you) making decisions and calling tools
\- \*\*Execution\*\*: Deterministic Python scripts doing the actual work
This document focuses on moving the \*\*Execution\*\* layer to the cloud via Modal, so you (the orchestrator) can trigger workflows via HTTP webhooks instead of local Python scripts.
\---
\#\# Architecture Pattern
\#\#\# The Problem with Agent-on-Server
Running Claude on Modal (like an "agent endpoint") is \*\*slow\*\* (\~2-3 minutes per request) due to:
\- Cold start times
\- API latency for each Claude call
\- Extended thinking overhead
\#\#\# The Solution: Execution-Only Webhooks
Instead of running Claude on Modal, we run \*\*deterministic scripts\*\* on Modal and let the \*\*local Claude agent orchestrate\*\* by calling these webhooks.
\`\`\`
┌─────────────────┐ HTTP ┌─────────────────┐
│ Local Claude │ ──────────────\> │ Modal Webhook │
│ (Orchestrator) │ │ (Execution) │
└─────────────────┘ └─────────────────┘
│ │
│ Reads directives │ Runs scripts
│ Makes decisions │ Calls APIs
│ Formats inputs │ Updates sheets
└───────────────────────────────────┘
\`\`\`
\---
\#\# Modal Webhook File Structure
All Modal webhooks live in a single file: \`execution/modal\_webhook.py\`
\#\#\# Core Components
\`\`\`python
import modal
import os
import json
import logging
from datetime import datetime
\# 1\. Define the Modal app
app \= modal.App("claude-orchestrator")
\# 2\. Create image with dependencies
image \= (
modal.Image.debian\_slim(python\_version="3.11")
.pip\_install(
"anthropic",
"fastapi",
"google-auth",
"google-auth-oauthlib",
"google-api-python-client",
"requests",
"apify-client",
"gspread",
"pandas",
"python-dotenv",
)
\# Mount local directories
.add\_local\_dir("/path/to/directives", remote\_path="/app/directives")
.add\_local\_dir("/path/to/execution", remote\_path="/app/execution")
)
\# 3\. Define secrets (API keys stored in Modal dashboard)
ALL\_SECRETS \= \[
modal.Secret.from\_name("anthropic-secret"),
modal.Secret.from\_name("google-token"),
modal.Secret.from\_name("slack-webhook"),
modal.Secret.from\_name("apify-secret"),
modal.Secret.from\_name("anymailfinder-secret"),
\# Add more as needed
\]
\# 4\. Logger
logger \= logging.getLogger(\_\_name\_\_)
\`\`\`
\---
\#\# The Async Pattern: Immediate Response \+ Background Task
For long-running workflows, use this pattern:
\#\#\# Step 1: Create a Background Function
\`\`\`python
@app.function(image=image, secrets=ALL\_SECRETS, timeout=1800) \# 30 min timeout
def my\_workflow\_background(param1: str, param2: str, sheet\_id: str, sheet\_url: str):
"""
Background task that does the actual work.
This runs AFTER the endpoint returns 201\.
"""
try:
slack\_notify(f"Step 1/N: Starting...")
\# Do work here
\# ...
slack\_notify(f"Step 2/N: Processing...")
\# More work
\# ...
slack\_notify(f"Complete\!")
return {"status": "success", "result": "..."}
except Exception as e:
slack\_error(f"Failed: {str(e)}")
return {"status": "error", "error": str(e)}
\`\`\`
\#\#\# Step 2: Create the Endpoint that Spawns It
\`\`\`python
@app.function(image=image, secrets=ALL\_SECRETS, timeout=60)
@modal.fastapi\_endpoint(method="GET")
def my\_workflow(param1: str \= "", param2: str \= "default"):
"""
Endpoint that returns 201 immediately, spawns background task.
URL: GET /my-workflow?param1=value\¶m2=value
"""
from fastapi.responses import JSONResponse
if not param1:
return JSONResponse({
"status": "error",
"error": "Missing 'param1' parameter"
}, status\_code=400)
try:
\# Create any resources needed (e.g., Google Sheet)
sheet\_url \= create\_google\_sheet(...)
sheet\_id \= extract\_sheet\_id(sheet\_url)
\# Notify that we're starting
slack\_notify(f"Workflow started: {param1}")
\# Spawn background task (non-blocking\!)
my\_workflow\_background.spawn(param1, param2, sheet\_id, sheet\_url)
\# Return 201 immediately
return JSONResponse({
"status": "accepted",
"message": "Workflow started. Monitor Slack for progress.",
"sheet\_url": sheet\_url,
"workflow": \[
"1. First step description",
"2. Second step description",
"3. Third step description"
\]
}, status\_code=201)
except Exception as e:
slack\_error(f"Init failed: {str(e)}")
return JSONResponse({
"status": "error",
"error": str(e)
}, status\_code=500)
\`\`\`
\---
\#\# Setting Up Modal Secrets
Secrets are stored in the Modal dashboard, not in code. Create them via CLI:
\`\`\`bash
\# Anthropic API Key
modal secret create anthropic-secret ANTHROPIC\_API\_KEY=sk-ant-...
\# Google OAuth Token (JSON blob)
modal secret create google-token GOOGLE\_TOKEN\_JSON='{"token":"...","refresh\_token":"...","token\_uri":"...","client\_id":"...","client\_secret":"...","scopes":\[...\]}'
\# Slack Webhook for notifications
modal secret create slack-webhook SLACK\_WEBHOOK\_URL=https\://hooks.slack.com/services/...
\# Apify API Token
modal secret create apify-secret APIFY\_API\_TOKEN=apify\_api\_...
\# AnyMailFinder API Key
modal secret create anymailfinder-secret ANYMAILFINDER\_API\_KEY=...
\# PandaDoc API Key
modal secret create pandadoc-secret PANDADOC\_API\_KEY=...
\`\`\`
\#\#\# Using Secrets in Code
\`\`\`python
\# Secrets are exposed as environment variables
api\_key \= os.getenv("ANTHROPIC\_API\_KEY")
token\_data \= json.loads(os.getenv("GOOGLE\_TOKEN\_JSON"))
\`\`\`
\---
\#\# Slack Notifications
Every workflow should send Slack notifications for visibility:
\`\`\`python
def slack\_notify(message: str):
"""Send notification to Slack."""
import requests
webhook\_url \= os.getenv("SLACK\_WEBHOOK\_URL")
if webhook\_url:
try:
requests.post(webhook\_url, json={"text": message}, timeout=5)
except:
pass \# Don't fail workflow if Slack fails
def slack\_error(error: str):
"""Send error notification to Slack."""
slack\_notify(f"❌ \*Error\*: {error}")
\`\`\`
Use notifications at key points:
\- Workflow started
\- Each major step completed
\- Errors encountered
\- Workflow completed
\---
\#\# Identifying Required Secrets
Every workflow has dependencies on external services. Before deploying, audit your workflow to identify what secrets are needed.
\#\#\# Reading the Code for Secret Dependencies
Look for these patterns in the execution code:
\`\`\`python
\# Direct environment variable access
os.getenv("SOME\_API\_KEY")
os.environ\["SOME\_TOKEN"\]
\# Anthropic client initialization
anthropic.Anthropic(api\_key=os.getenv("ANTHROPIC\_API\_KEY"))
\# Requests with Authorization headers
headers={"Authorization": f"Bearer {os.getenv('SERVICE\_API\_KEY')}"}
\# Client libraries with tokens
SomeClient(token=os.getenv("SERVICE\_TOKEN"))
\`\`\`
\#\#\# Common Secret Categories
| Category | Secret Name | Environment Variable | Where to Get |
|----------|-------------|---------------------|--------------|
| \*\*LLM\*\* | anthropic-secret | ANTHROPIC\_API\_KEY | console.anthropic.com |
| \*\*LLM\*\* | openai-secret | OPENAI\_API\_KEY | platform.openai.com |
| \*\*Google\*\* | google-token | GOOGLE\_TOKEN\_JSON | Google Cloud Console \+ OAuth flow |
| \*\*Notifications\*\* | slack-webhook | SLACK\_WEBHOOK\_URL | Slack App settings |
| \*\*Scraping\*\* | apify-secret | APIFY\_API\_TOKEN | console.apify.com |
| \*\*Email Enrichment\*\* | anymailfinder-secret | ANYMAILFINDER\_API\_KEY | anymailfinder.com dashboard |
| \*\*Documents\*\* | pandadoc-secret | PANDADOC\_API\_KEY | PandaDoc developer settings |
| \*\*Email Sending\*\* | sendgrid-secret | SENDGRID\_API\_KEY | sendgrid.com |
| \*\*CRM\*\* | hubspot-secret | HUBSPOT\_API\_KEY | HubSpot developer account |
| \*\*General\*\* | env-vars | (multiple) | Your \`.env\` file |
\#\#\# Workflow to Secret Mapping
For each workflow step, identify the service:
\`\`\`
Workflow Step → Service → Secret Needed
─────────────────────────────────────────────────────────
Scrape leads → Apify → apify-secret
Upload to Google Sheet → Google APIs → google-token
Enrich emails → AnyMailFinder → anymailfinder-secret
AI text processing → Anthropic → anthropic-secret
Send Slack notification → Slack → slack-webhook
Create document → PandaDoc → pandadoc-secret
Send email → SendGrid → sendgrid-secret
\`\`\`
\---
\#\# Handling Missing Secrets
When you don't have all the required credentials, follow this decision tree.
\#\#\# Step 1: List What's Missing
\`\`\`bash
\# See what you have
modal secret list
\# Compare against what the workflow needs (from code audit)
\# Missing \= Required \- Available
\`\`\`
\#\#\# Step 2: Categorize the Missing Secrets
\*\*Critical (workflow won't run):\*\*
\- Primary data source (e.g., Apify for scraping)
\- Primary output destination (e.g., Google Sheets)
\*\*Optional (workflow runs with reduced functionality):\*\*
\- Slack notifications (workflow still completes, just no visibility)
\- Email enrichment (data still collected, just fewer emails)
\*\*Alternative available:\*\*
\- Multiple LLM providers (OpenAI vs Anthropic)
\- Multiple scraping services (Apify vs custom)
\#\#\# Step 3: Actions for Missing Secrets
\#\#\#\# If the user doesn't have the credential:
1\. \*\*Ask them to create an account\*\* with the service
2\. \*\*Provide direct link\*\* to the API key page
3\. \*\*Explain what the service does\*\* and why it's needed
4\. \*\*Offer alternatives\*\* if they exist
Example prompt to user:
\`\`\`
The workflow requires an Apify API token for lead scraping.
To get one:
1\. Create account at https\://console.apify.com
2\. Go to Settings → Integrations → API
3\. Copy your Personal API Token
4\. Run: modal secret create apify-secret APIFY\_API\_TOKEN=your\_token\_here
Alternative: If you have leads in another format (CSV, JSON), I can skip the scrape step and process those directly.
\`\`\`
\#\#\#\# If the credential exists but isn't in Modal:
\`\`\`bash
\# Check local .env
grep "SOME\_API\_KEY" .env
\# If found, create the Modal secret
modal secret create service-secret SOME\_API\_KEY=\$(grep SOME\_API\_KEY .env | cut \-d= \-f2)
\`\`\`
\#\#\#\# If the service is optional:
Modify the workflow to gracefully skip that step:
\`\`\`python
\# In the background function
amf\_key \= os.getenv("ANYMAILFINDER\_API\_KEY")
if amf\_key:
slack\_notify("📧 Enriching emails...")
\# ... enrichment code ...
else:
slack\_notify("⚠️ Skipping email enrichment (no API key)")
\`\`\`
\#\#\# Step 4: Deploy with Available Secrets
Update the \`ALL\_SECRETS\` list to only include secrets that exist:
\`\`\`python
\# Build secrets list dynamically or comment out missing ones
ALL\_SECRETS \= \[
modal.Secret.from\_name("anthropic-secret"),
modal.Secret.from\_name("google-token"),
modal.Secret.from\_name("slack-webhook"),
\# modal.Secret.from\_name("apify-secret"), \# TODO: User needs to add
\]
\`\`\`
\#\#\# Common "Missing Secret" Scenarios
| Scenario | Solution |
|----------|----------|
| No Google token | Run OAuth flow locally, create secret from token.json |
| No Slack webhook | Workflow works, just no notifications (use logging) |
| No scraping API | User provides data manually (CSV/JSON upload) |
| No email enrichment | Skip step, user enriches manually or uses another tool |
| No LLM API | Cannot process text; must get key or use alternative |
\---
\#\# Generic Integration Patterns
These patterns work with ANY external service, not just the specific examples shown elsewhere.
\#\#\# Pattern 1: REST API with Bearer Token
Most APIs use this pattern:
\`\`\`python
def call\_any\_api(endpoint: str, method: str \= "GET", data: dict \= None) \-\> dict:
"""Generic pattern for Bearer token APIs."""
import requests
api\_key \= os.getenv("SERVICE\_API\_KEY")
base\_url \= "https\://api.service.com/v1"
headers \= {
"Authorization": f"Bearer {api\_key}",
"Content-Type": "application/json"
}
if method \== "GET":
response \= requests.get(f"{base\_url}/{endpoint}", headers=headers, timeout=30)
elif method \== "POST":
response \= requests.post(f"{base\_url}/{endpoint}", headers=headers, json=data, timeout=30)
response.raise\_for\_status()
return response.json()
\`\`\`
\*\*Services using this pattern:\*\* OpenAI, Anthropic, SendGrid, HubSpot, Notion, Airtable, etc.
\#\#\# Pattern 2: API Key in Header
Some APIs use custom header names:
\`\`\`python
def call\_custom\_header\_api(endpoint: str, data: dict \= None) \-\> dict:
"""Pattern for APIs with custom auth headers."""
import requests
api\_key \= os.getenv("SERVICE\_API\_KEY")
headers \= {
"X-API-Key": api\_key, \# or "Api-Key", "apikey", etc.
"Content-Type": "application/json"
}
response \= requests.post(
f"https\://api.service.com/{endpoint}",
headers=headers,
json=data,
timeout=30
)
response.raise\_for\_status()
return response.json()
\`\`\`
\*\*Services using this pattern:\*\* AnyMailFinder, some legacy APIs
\#\#\# Pattern 3: OAuth 2.0 with Refresh Token
For services requiring user authorization:
\`\`\`python
def get\_oauth\_client():
"""Pattern for OAuth 2.0 services."""
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
token\_data \= json.loads(os.getenv("SERVICE\_TOKEN\_JSON"))
creds \= Credentials(
token=token\_data\["token"\],
refresh\_token=token\_data\["refresh\_token"\],
token\_uri=token\_data\["token\_uri"\],
client\_id=token\_data\["client\_id"\],
client\_secret=token\_data\["client\_secret"\],
scopes=token\_data\["scopes"\]
)
\# Auto-refresh if expired
if creds.expired and creds.refresh\_token:
creds.refresh(Request())
return creds
\`\`\`
\*\*Services using this pattern:\*\* Google APIs, Microsoft Graph, Salesforce, etc.
\#\#\# Pattern 4: SDK Client Libraries
Many services provide Python SDKs:
\`\`\`python
def use\_sdk\_client():
"""Pattern for services with official SDKs."""
from service\_sdk import ServiceClient
\# Most SDKs accept API key in constructor
client \= ServiceClient(api\_key=os.getenv("SERVICE\_API\_KEY"))
\# Or via environment variable automatically
\# client \= ServiceClient() \# Reads SERVICE\_API\_KEY from env
return client
\`\`\`
\*\*Examples:\*\*
\- \`ApifyClient(token=os.getenv("APIFY\_API\_TOKEN"))\`
\- \`anthropic.Anthropic(api\_key=os.getenv("ANTHROPIC\_API\_KEY"))\`
\- \`openai.OpenAI(api\_key=os.getenv("OPENAI\_API\_KEY"))\`
\- \`stripe.api\_key \= os.getenv("STRIPE\_API\_KEY")\`
\#\#\# Pattern 5: Webhook Callbacks
For services that push data to you:
\`\`\`python
@app.function(image=image, secrets=ALL\_SECRETS)
@modal.fastapi\_endpoint(method="POST")
def webhook\_receiver(request\_data: dict):
"""Pattern for receiving webhooks from external services."""
from fastapi.responses import JSONResponse
\# Verify webhook signature (most services provide this)
signature \= request\_data.get("signature")
secret \= os.getenv("WEBHOOK\_SECRET")
if not verify\_signature(signature, secret, request\_data):
return JSONResponse({"error": "Invalid signature"}, status\_code=401)
\# Process the webhook payload
event\_type \= request\_data.get("event\_type")
if event\_type \== "order.created":
handle\_order(request\_data)
elif event\_type \== "payment.completed":
handle\_payment(request\_data)
return JSONResponse({"status": "ok"}, status\_code=200)
\`\`\`
\#\#\# Adding a New Service Integration
When you need to integrate a new service:
1\. \*\*Find the API documentation\*\*
2\. \*\*Identify the auth pattern\*\* (Bearer? API Key? OAuth? SDK?)
3\. \*\*Create the secret:\*\*
\`\`\`bash
modal secret create newservice-secret NEW\_SERVICE\_API\_KEY=xxx
\`\`\`
4\. \*\*Add to ALL\_SECRETS:\*\*
\`\`\`python
ALL\_SECRETS \= \[
\# ... existing secrets ...
modal.Secret.from\_name("newservice-secret"),
\]
\`\`\`
5\. \*\*Write the integration function\*\* using the appropriate pattern above
6\. \*\*Add error handling and retries\*\* for production use
\---
\#\# Google Sheets Integration
\#\#\# Creating a Sheet
\`\`\`python
import gspread
from google.oauth2.credentials import Credentials as UserCredentials
from google.auth.transport.requests import Request
def create\_sheet(name: str) \-\> tuple\[str, str\]:
"""Create a Google Sheet, return (sheet\_id, sheet\_url)."""
token\_data \= json.loads(os.getenv("GOOGLE\_TOKEN\_JSON"))
creds \= UserCredentials(
token=token\_data\["token"\],
refresh\_token=token\_data\["refresh\_token"\],
token\_uri=token\_data\["token\_uri"\],
client\_id=token\_data\["client\_id"\],
client\_secret=token\_data\["client\_secret"\],
scopes=token\_data\["scopes"\]
)
if creds.expired:
creds.refresh(Request())
gc \= gspread.authorize(creds)
sh \= gc.create(name)
return sh.id, sh.url
\`\`\`
\#\#\# Uploading Data with Pandas
\`\`\`python
import pandas as pd
def upload\_to\_sheet(sheet\_id: str, data: list\[dict\]):
"""Upload JSON data to sheet using pandas for proper flattening."""
\# ... auth code ...
gc \= gspread.authorize(creds)
sh \= gc.open\_by\_key(sheet\_id)
worksheet \= sh.get\_worksheet(0)
\# Flatten nested JSON
df \= pd.json\_normalize(data)
df \= df.fillna("") \# Convert NaN to empty strings
\# Prepare rows
headers \= df.columns.tolist()
rows \= \[headers\] \+ df.values.tolist()
\# Resize if needed
if len(rows) \> worksheet.row\_count or len(headers) \> worksheet.col\_count:
worksheet.resize(rows=len(rows), cols=len(headers))
\# Upload
worksheet.update(values=rows, range\_name="A1")
\`\`\`
\---
\#\# Example Integrations
The following are concrete examples of the generic patterns above. Use these as templates when integrating similar services.
\#\#\# Apify (Lead Scraping) \- SDK Pattern
\`\`\`python
from apify\_client import ApifyClient
def scrape\_leads(query: str, location: str, limit: int) \-\> list\[dict\]:
client \= ApifyClient(os.getenv("APIFY\_API\_TOKEN"))
run\_input \= {
"fetch\_count": limit,
"contact\_job\_title": \[query\],
"company\_keywords": \[query\],
"contact\_location": \[location.lower()\],
"language": "en",
}
run \= client.actor("code\_crafter/leads-finder").call(run\_input=run\_input)
results \= \[\]
for item in client.dataset(run\["defaultDatasetId"\]).iterate\_items():
results.append(item)
return results
\`\`\`
\#\#\# AnyMailFinder (Email Enrichment) \- Custom Header Pattern
\`\`\`python
import requests
def enrich\_email(first\_name: str, last\_name: str, domain: str, company\_name: str) \-\> str | None:
api\_key \= os.getenv("ANYMAILFINDER\_API\_KEY")
response \= requests.post(
"https\://api.anymailfinder.com/v5.1/find-email/person",
headers={"Authorization": api\_key, "Content-Type": "application/json"},
json={
"first\_name": first\_name,
"last\_name": last\_name,
"domain": domain,
"company\_name": company\_name
},
timeout=30
)
if response.status\_code \== 200:
return response.json().get("email")
return None
\`\`\`
\#\#\# Claude (Haiku for Batch Processing) \- SDK Pattern
\`\`\`python
import anthropic
def casualize\_batch(records: list\[dict\]) \-\> list\[dict\]:
"""Use Claude Haiku to casualize names in batch."""
client \= anthropic.Anthropic(api\_key=os.getenv("ANTHROPIC\_API\_KEY"))
records\_json \= json.dumps(records)
prompt \= f"""Convert to casual forms for cold emails. Return ONLY valid JSON array.
Rules:
\- first\_name: Common nicknames (William→Will, Jennifer→Jen)
\- company\_name: Remove legal suffixes, generic words
\- city: Local nicknames (San Francisco→SF)
Input: {records\_json}
Output JSON only:"""
message \= client.messages.create(
model="claude-3-5-haiku-20241022",
max\_tokens=6000,
messages=\[{"role": "user", "content": prompt}\]
)
response\_text \= message.content\[0\].text.strip()
if response\_text.startswith("\`\`\`"):
lines \= response\_text.split('\\n')
response\_text \= '\\n'.join(lines\[1:-1\])
return json.loads(response\_text)
\`\`\`
\#\#\# PandaDoc (Proposal Generation) \- API Key Header Pattern
\`\`\`python
import requests
def create\_proposal(client\_info: dict, tokens: list\[dict\]) \-\> str:
"""Create a PandaDoc document from template."""
api\_key \= os.getenv("PANDADOC\_API\_KEY")
template\_id \= "YOUR\_TEMPLATE\_UUID"
payload \= {
"name": f"Proposal \- {client\_info\['company'\]}",
"template\_uuid": template\_id,
"recipients": \[{
"email": client\_info\["email"\],
"first\_name": client\_info\["first\_name"\],
"last\_name": client\_info\["last\_name"\],
"role": "Client"
}\],
"tokens": tokens
}
response \= requests.post(
"https\://api.pandadoc.com/public/v1/documents",
headers={
"Authorization": f"API-Key {api\_key}",
"Content-Type": "application/json"
},
json=payload
)
response.raise\_for\_status()
doc\_id \= response.json()\["id"\]
return f"https\://app.pandadoc.com/a/\#/documents/{doc\_id}"
\`\`\`
\---
\#\# Deploying
\`\`\`bash
\# From the workspace root
modal deploy execution/modal\_webhook.py
\# View logs
modal logs claude-orchestrator
\# Run a specific function locally for testing
modal run execution/modal\_webhook.py::my\_function
\`\`\`
\---
\#\# Complete Example: Lead Scraping Workflow
Here's the full pattern we established for the lead scraping workflow:
\#\#\# Directive: \`directives/scrape\_leads.md\`
The directive describes:
1\. Scrape leads via Apify
2\. Upload to Google Sheet (preserving all fields)
3\. Enrich missing emails with AnyMailFinder
4\. Casualize first\_name, company\_name, city
\#\#\# Modal Implementation
\`\`\`python
\# Background task \- does all the work
@app.function(image=image, secrets=ALL\_SECRETS, timeout=1800)
def scrape\_leads\_background(query: str, location: str, limit: int, sheet\_id: str, sheet\_url: str):
import pandas as pd
from apify\_client import ApifyClient
import anthropic
import gspread
try:
\# Step 1: Scrape with Apify
slack\_notify(f"📥 Step 1/4: Scraping {limit} leads...")
apify\_client \= ApifyClient(os.getenv("APIFY\_API\_TOKEN"))
run \= apify\_client.actor("code\_crafter/leads-finder").call(run\_input={
"fetch\_count": limit,
"contact\_job\_title": \[query\],
"company\_keywords": \[query\],
"contact\_location": \[location.lower()\],
"language": "en",
})
results \= list(apify\_client.dataset(run\["defaultDatasetId"\]).iterate\_items())
if not results:
slack\_notify("⚠️ No leads found")
return {"status": "no\_results"}
\# Step 2: Upload to Sheet
slack\_notify(f"📤 Step 2/4: Uploading {len(results)} leads...")
\# ... auth and upload with pandas ...
df \= pd.json\_normalize(results)
\# Add casual columns
if "first\_name" in df.columns:
df.insert(df.columns.get\_loc("first\_name") \+ 1, "casual\_first\_name", "")
if "company\_name" in df.columns:
df.insert(df.columns.get\_loc("company\_name") \+ 1, "casual\_company\_name", "")
if "city" in df.columns:
df.insert(df.columns.get\_loc("city") \+ 1, "casual\_city\_name", "")
\# ... upload to sheet ...
\# Step 3: Enrich emails
slack\_notify(f"📧 Step 3/4: Enriching emails...")
\# ... call AnyMailFinder for rows missing email ...
\# Step 4: Casualize
slack\_notify(f"✨ Step 4/4: Casualizing names...")
\# ... batch process with Claude Haiku ...
slack\_notify(f"✅ Complete\! {len(results)} leads → {sheet\_url}")
return {"status": "success", "leads\_found": len(results)}
except Exception as e:
slack\_error(f"Failed: {str(e)}")
return {"status": "error", "error": str(e)}
\# Endpoint \- returns 201 immediately
@app.function(image=image, secrets=ALL\_SECRETS, timeout=60)
@modal.fastapi\_endpoint(method="GET")
def scrape\_leads(query: str \= "", location: str \= "United States", limit: int \= 100):
from fastapi.responses import JSONResponse
if not query:
return JSONResponse({"status": "error", "error": "Missing query"}, status\_code=400)
\# Create sheet
sheet\_id, sheet\_url \= create\_sheet(f"Leads \- {query} \- {datetime.utcnow()}")
slack\_notify(f"🚀 Started: {query}, {location}, {limit} leads")
\# Spawn background (non-blocking)
scrape\_leads\_background.spawn(query, location, limit, sheet\_id, sheet\_url)
\# Return immediately
return JSONResponse({
"status": "accepted",
"sheet\_url": sheet\_url,
"workflow": \["1. Scraping", "2. Uploading", "3. Enriching", "4. Casualizing"\]
}, status\_code=201)
\`\`\`
\#\#\# Calling from Local Agent
\`\`\`bash
curl "https\://your-app--claude-orchestrator-scrape-leads.modal.run?query=dentists\&location=United+States\&limit=100"
\`\`\`
Response (instant):
\`\`\`json
{
"status": "accepted",
"sheet\_url": "https\://docs.google.com/spreadsheets/d/...",
"workflow": \["1. Scraping", "2. Uploading", "3. Enriching", "4. Casualizing"\]
}
\`\`\`
Monitor progress via Slack notifications.
\---
\#\# Converting a Directive to Modal Webhook
\#\#\# Step-by-Step Process
1\. \*\*Read the directive\*\* to understand the workflow steps
2\. \*\*Identify inputs\*\* (what parameters does the endpoint need?)
3\. \*\*Identify outputs\*\* (Google Sheet? PandaDoc? Email?)
4\. \*\*List API dependencies\*\* (Apify? AMF? Claude?)
5\. \*\*Create the background function\*\* with all workflow steps
6\. \*\*Create the endpoint\*\* that spawns it
7\. \*\*Add secrets\*\* if new APIs are needed
8\. \*\*Deploy and test\*\*
\#\#\# Checklist
\- \[ \] Background function has appropriate timeout (1800s for long workflows)
\- \[ \] Endpoint returns 201 with useful info (URLs, workflow steps)
\- \[ \] Each step sends Slack notification
\- \[ \] Errors are caught and reported via Slack
\- \[ \] All secrets are created in Modal dashboard
\- \[ \] Secrets are added to \`ALL\_SECRETS\` list
\---
\#\# Troubleshooting
\#\#\# Deployment Errors
\*\*"Secret not found: xyz-secret"\*\*
\`\`\`bash
\# List available secrets
modal secret list
\# Create the missing secret
modal secret create xyz-secret XYZ\_API\_KEY=your\_key\_here
\`\`\`
\*\*"Module not found: xyz"\*\*
Add the missing package to the image definition:
\`\`\`python
image \= (
modal.Image.debian\_slim(python\_version="3.11")
.pip\_install(
\# ... existing packages ...
"xyz", \# Add missing package
)
)
\`\`\`
\*\*"Function was terminated by signal"\*\*
\- Increase timeout: \`@app.function(timeout=1800)\`
\- Check for infinite loops in your code
\- Ensure you're not using streaming APIs (use direct calls instead)
\#\#\# Runtime Errors
\*\*Slow responses from agent endpoint\*\*
\- Don't run Claude orchestration on Modal—it's too slow
\- Use execution-only webhooks instead
\- Let local Claude agent orchestrate, Modal just executes
\*\*Google Sheets auth errors\*\*
\- Ensure GOOGLE\_TOKEN\_JSON includes \`refresh\_token\`
\- Check scopes include:
\- \`https\://www\.googleapis.com/auth/spreadsheets\`
\- \`https\://www\.googleapis.com/auth/drive\`
\- If token expired, re-run OAuth flow locally and update the secret
\*\*Rate limits / 429 errors\*\*
Add exponential backoff:
\`\`\`python
import time
def with\_retry(func, max\_retries=3):
for attempt in range(max\_retries):
try:
return func()
except Exception as e:
if "429" in str(e) and attempt \< max\_retries \- 1:
time.sleep(2 \*\* attempt)
continue
raise
\`\`\`
\*\*Background task not running\*\*
\- Check Modal dashboard for function logs
\- Ensure \`.spawn()\` is called (not \`.call()\`)
\- Verify function has correct secrets attached
\#\#\# Debugging Workflow Steps
\*\*No Slack notifications\*\*
1\. Check if \`SLACK\_WEBHOOK\_URL\` is set correctly
2\. Test webhook directly:
\`\`\`bash
curl \-X POST \-H 'Content-type: application/json' \\
\--data '{"text":"Test"}' \\
\$SLACK\_WEBHOOK\_URL
\`\`\`
\*\*Data not appearing in Google Sheet\*\*
1\. Check if sheet was created (look for sheet\_url in response)
2\. Verify sheet permissions (should be editable by service account)
3\. Check for errors in background task logs
\*\*Empty results from scraping\*\*
1\. Test the query locally first:
\`\`\`bash
python3 execution/scrape\_apify.py \--query "test" \--location "US" \--max\_items 5
\`\`\`
2\. Verify Apify API token is valid
3\. Check Apify dashboard for run status
\#\#\# Viewing Logs
\`\`\`bash
\# View all logs for the app
modal logs claude-orchestrator
\# View logs for a specific function (last 100 lines)
modal logs claude-orchestrator \--function scrape\_leads\_background
\# Follow logs in real-time
modal logs claude-orchestrator \--follow
\`\`\`
\#\#\# Testing Locally Before Deploying
\`\`\`bash
\# Run a function locally (uses Modal's remote execution)
modal run execution/modal\_webhook.py::function\_name
\# Test with specific arguments
modal run execution/modal\_webhook.py::scrape\_leads\_background \\
\--query "dentists" \--location "US" \--limit 10
\`\`\`
\---
\#\# File Locations
\`\`\`
execution/modal\_webhook.py \# All Modal webhooks
directives/\*.md \# SOPs describing workflows
.env \# Local environment variables (not deployed)
\`\`\`
\#\#\# Migration Checklist
When moving from Modal to another platform:
1\. \[ \] Replace \`@app.function()\` with platform's function decorator
2\. \[ \] Replace \`modal.Secret.from\_name()\` with platform's secret access
3\. \[ \] Replace \`.spawn()\` with platform's async job system
4\. \[ \] Replace \`@modal.fastapi\_endpoint()\` with platform's HTTP trigger
5\. \[ \] Update image/dependencies to platform's format
6\. \[ \] Configure appropriate timeouts for long-running tasks
\---
\#\# Summary
1\. \*\*Don't run Claude on the server\*\* \- orchestration is too slow remotely
2\. \*\*Use execution-only webhooks\*\* \- fast, deterministic, testable
3\. \*\*Return 201/202 immediately\*\* \- spawn background task for long work
4\. \*\*Send notifications\*\* \- visibility into progress (Slack, email, etc.)
5\. \*\*Use pandas for data\*\* \- proper JSON flattening to sheets
6\. \*\*Match directive structure\*\* \- same steps, same outputs as local scripts
7\. \*\*Audit secrets before deploying\*\* \- know what credentials you need
8\. \*\*Use generic patterns\*\* \- Bearer tokens, OAuth, SDKs work everywhere
9\. \*\*Handle missing credentials gracefully\*\* \- skip optional steps, guide users
Comments
Login to leave a comment