Real-time, hyper-accurate air quality intelligence for AI agents and applications
Get scientifically-validated Air Quality Index data from anywhere on Earth. This actor aggregates readings from multiple ground-level PM2.5 sensors, applies advanced statistical cleaning (IQR outlier removal), and delivers reliable AQI calculations with confidence scoring—purpose-built for AI agents, health apps, and intelligent automation systems.
🎯 Built for the Apify $1M Challenge — solving real-world air quality monitoring challenges at scale.
Air quality affects 91% of the world's population living in areas exceeding WHO guidelines. However:
- ❌ Single-sensor readings are unreliable (sensor malfunctions, local interference)
- ❌ City-wide averages miss hyperlocal variations (pollution can vary 10x within kilometers)
- ❌ No standardized confidence metrics for AI decision-making
- ❌ Existing APIs lack real-time aggregation and statistical validation
This actor provides statistically-validated, hyperlocal AQI by:
✅ Aggregating multiple sensors within your specified radius
✅ Cleaning outliers using IQR (Interquartile Range) statistical method
✅ Calculating confidence scores (0-100%) based on data quality
✅ Delivering actionable insights optimized for AI agent consumption
Perfect for: AI chatbots answering health queries, smart home automation, fitness apps, location-based services, environmental monitoring, and public health systems.
Unlike city-wide averages, get AQI for specific neighborhoods, parks, or addresses by aggregating sensors within 1-25km radius.
- Removes sensor malfunctions and outliers using proven IQR method
- Calculates mean, median, and standard deviation
- Filters stale data (only readings <48 hours old)
Structured JSON output designed for LLM function calling and programmatic decision-making with built-in confidence scores.
Works anywhere with OpenAQ sensor network coverage (200+ countries, 10,000+ locations).
- Concurrent sensor querying (10 parallel requests)
- Automatic retries on failures
- Typical execution: 5-30 seconds
{
"result": {
"aqi": 42, // EPA-standard Air Quality Index (0-500)
"category": "Good", // Good, Moderate, Unhealthy, etc.
"pm25_concentration": 10.5, // PM2.5 in µg/m³
"confidence_score": 87 // 0-100% reliability metric
},
"health_context": {
"advice": "Air quality is satisfactory.",
"is_safe_for_jogging": true // Boolean for quick AI decisions
},
"metadata": {
"sensors_found": 45, // Total sensors discovered
"sensors_used": 38, // Valid readings after cleaning
"outliers_removed": 7 // Statistical outliers filtered
}
}
Full output schema available in .actor/output_schema.json
Visit OpenAQ Registration and create a free account to get your API key.
Example: Check air quality in London
{
"locationName": "London",
"radiusKm": 10,
"maxSensors": 50,
"openaqApiKey": "your_api_key_here"
}
Example: Use precise coordinates (Tokyo)
{
"latitude": 35.6762,
"longitude": 139.6503,
"radiusKm": 15,
"maxSensors": 50,
"openaqApiKey": "your_api_key_here"
}
AQI calculation with confidence score, health advice, and metadata—ready for your application or AI agent.
User: "Is it safe to run outside in Delhi right now?"
Agent: [Queries actor]
→ "Delhi AQI is 156 (Unhealthy). Running outdoors
not recommended. Confidence: 92%"
- Real-time workout safety recommendations
- Location-based exercise route planning
- Personalized outdoor activity alerts
- Asthma/allergy trigger warnings
- Auto-control air purifiers based on outdoor AQI
- Intelligent window opening/closing systems
- HVAC optimization based on external air quality
- Home ventilation scheduling
- Map overlays showing neighborhood-level AQI
- Destination air quality assessments for travelers
- Real estate insights (property + air quality data)
- Event planning (outdoor venues, timing)
- Urban planning and environmental studies
- Public health research and policy-making
- Climate change impact tracking
- Hyperlocal pollution pattern analysis
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| locationName | String | No* | — | City or place name (e.g., "Paris", "Mumbai") |
| latitude | Number | No* | — | Latitude coordinate (e.g., 40.7128) |
| longitude | Number | No* | — | Longitude coordinate (e.g., -74.0060) |
| radiusKm | Integer | No | 10 | Search radius in kilometers (1-25) |
| maxSensors | Integer | No | 50 | Max sensors to process (1-500) |
| openaqApiKey | String | Yes | — | Your OpenAQ API key (get one free) |
*Either locationName OR both latitude+longitude must be provided.
| AQI | Category | Health Impact | Use Case |
|---|---|---|---|
| 0-50 | 🟢 Good | Air quality satisfactory | Safe for all outdoor activities |
| 51-100 | 🟡 Moderate | Acceptable for most people | Unusually sensitive people should limit prolonged outdoor exertion |
| 101-150 | 🟠 Unhealthy for Sensitive Groups | Sensitive groups may experience health effects | Children, elderly, people with respiratory conditions should reduce outdoor activities |
| 151-200 | 🔴 Unhealthy | Everyone may experience health effects | Everyone should reduce prolonged outdoor exertion |
| 201-300 | 🟣 Very Unhealthy | Health alert: serious effects for everyone | Everyone should avoid outdoor activities |
| 301-500 | 🟤 Hazardous | Emergency health conditions | Everyone should remain indoors |
The actor calculates confidence based on three factors:
Quantity (40%) — Number of sensors with valid readings
- More sensors = higher confidence
- Minimum 4 sensors recommended
Consensus (40%) — Agreement between sensors (low standard deviation)
- Tight clustering = higher confidence
- High variation suggests localized pollution sources
Quality (20%) — Data retention after outlier removal
- Higher retention rate = better quality
- Low retention suggests sensor issues or extreme variability
Input Location → Geocoding → Sensor Discovery → Data Collection → Statistical Cleaning → AQI Calculation → Output
1. Location Resolution
- City name → OpenStreetMap Nominatim geocoding
- Or use provided latitude/longitude directly
2. Sensor Discovery
- Query OpenAQ API for all PM2.5 sensors within radius
- Filter for sensors with readings <48 hours old
- Limit to
maxSensorsfor performance optimization
3. Concurrent Data Collection
- Fetch latest readings from each sensor (10 parallel requests)
- Built-in retry logic for reliability
- 5-second timeout per sensor
4. Statistical Data Cleaning
Raw values → Filter invalid → Calculate IQR → Remove outliers → Statistics
- Remove null, negative, or >2000 µg/m³ values
- Apply Interquartile Range (IQR) method for outlier detection
- Calculate mean, median, standard deviation
5. AQI Calculation
- Apply EPA AQI breakpoints to cleaned PM2.5 mean
- Map to category (Good → Hazardous)
- Generate health advice
6. Confidence Scoring
confidence = quantity_score(40%) + consensus_score(40%) + quality_score(20%)
- Apify SDK 3.2+ — Serverless actor framework
- Crawlee 3.15+ — Concurrent web scraping with retries
- TypeScript — Type-safe development
- OpenAQ API v3 — Global air quality data network
- OpenStreetMap Nominatim — Geocoding service
- PM2.5 Sensors: Ground-level particulate matter monitors
- OpenAQ Network: 10,000+ locations across 200+ countries
- Community-powered: Government agencies, research institutions, citizen scientists
- Concurrency: 10 simultaneous requests
- Retry Logic: 2 automatic retries on failures
- Pre-Filtering: We check sensor "Last Updated" timestamps before fetching detailed data, saving API calls.
- Concurrency Control: Requests are batched to prevent memory spikes.
- Configurable Limits: Use maxSensors to hard-cap execution time.
- OpenAQ API: Free tier available (check current limits)
- Nominatim Geocoding: Free (rate-limited to 1 req/sec)
Cost Optimization Tips:
- Use coordinates instead of city names (saves geocoding call)
- Reduce
maxSensorsfor faster/cheaper execution - Smaller radius when high sensor density exists
Question: "Can my child with asthma play outside?"
Actor Input:
{
"locationName": "San Francisco",
"radiusKm": 5,
"maxSensors": 30,
"openaqApiKey": "..."
}
Response: AQI 68 (Moderate, 88% confidence) AI Output: "Air quality is acceptable, but sensitive children should limit prolonged outdoor play. Consider indoor activities instead."
Trigger: Every 30 minutes
Actor Input:
{
"latitude": 51.5074,
"longitude": -0.1278,
"radiusKm": 3,
"maxSensors": 20,
"openaqApiKey": "..."
}
Automation Logic:
if (aqi > 100) {
closeWindows();
turnOnAirPurifier();
sendNotification("Poor air quality detected");
}
Use Case: Recommend safest jogging routes
Actor Input: Check multiple neighborhoods
[
{"locationName": "Central Park", ...},
{"locationName": "Brooklyn Bridge Park", ...},
{"locationName": "Prospect Park", ...}
]
Output: Rank locations by AQI + confidence score
# Clone repository
git clone https://github.com/cryptomafiaPB/hyper-local-aqi-actor.git
cd hyper-local-aqi-actor
# Install dependencies
npm install
# Build TypeScript
npm run build
# Setup input
mkdir -p storage/key_value_stores/default
cp INPUT.json storage/key_value_stores/default/
# Run locally
npm start
# Install Apify CLI globally
npm install -g apify-cli
# Run actor locally
apify run
# Deploy to Apify platform
apify push
Edit INPUT.json with various test cases:
- Major cities (London, Tokyo, Delhi, New York)
- Rural areas (to test low sensor availability)
- High-pollution areas (to test outlier removal)
- Coastal vs inland (to compare patterns)
Causes:
- Remote/rural location with no nearby sensors
- All sensors in area are offline or stale (>48 hours)
Solutions:
- Increase
radiusKmto 20-25km - Check sensor coverage on OpenAQ Map
- Try a nearby major city
Causes:
- Misspelled city name
- Ambiguous location (e.g., "Cambridge" without country)
Solutions:
- Add country suffix: "Cambridge, UK" or "Cambridge, USA"
- Use more specific names: "Central London" instead of "London"
- Switch to latitude/longitude for precision
Causes:
- Few sensors in area (<10)
- High sensor disagreement (local pollution sources)
- Many outliers removed (sensor malfunctions)
Solutions:
- Increase
radiusKmto include more sensors - Run multiple times and compare trends
- Check if specific sensors are consistently outliers
Causes:
- Invalid or expired OpenAQ API key
- Rate limit exceeded on free tier
- Incorrect key format
Solutions:
- Generate new key at OpenAQ
- Check API usage dashboard for rate limits
- Ensure no extra spaces/characters in key
Solves Real Problems: Addresses critical need for reliable, hyperlocal air quality data in health, automation, and AI applications
Built for AI Agents: Structured output with confidence scores optimized for LLM function calling and decision-making
Scientifically Sound: Uses proven statistical methods (IQR outlier removal, EPA AQI standards)
Global Scale: Works across 200+ countries with OpenAQ network
Production Ready: Comprehensive error handling, retries, timeouts, and validation
Well Documented: Complete README, input/output schemas, examples, and troubleshooting
- 🌐 OpenAQ Platform — Explore global sensor network
- 📖 EPA AQI Guide — Official AQI documentation
- 📊 WHO Air Quality Guidelines — Health impact research
- 🔬 IQR Outlier Detection — Statistical methodology
Need Help?
Feature Requests? Submit ideas via GitHub issues or reach out directly!
Apache License 2.0
- Get your free OpenAQ API key
- Run this actor with your location
- Integrate the results into your app, AI agent, or automation system
Let's make air quality data accessible to everyone. 🌍💚