---
name: us-census-data-agent
description: Query the US Census Bureau API for demographic, economic, social, housing, and commute trends over time or across geographies.
---

# Skill: US Census Data AI Agent

This skill equips any AI agent with the ability to query the US Census Bureau API for highly detailed, live demographic, economic, social, housing, and commute data across any US geography (states, counties, places/cities, or ZIP codes) over time.

Instead of writing raw Census API requests yourself, you can delegate any natural language Census query to this hosted microservice agent. It will autonomously resolve FIPS codes, adapt historical variable shifts, group endpoints, execute queries, and distill the results.

## 🔗 Service Endpoint

* **Protocol**: HTTP/S
* **Endpoint**: `https://censusdata.xyz`
* **Health Check**: `GET /health`
* **Query Endpoint**: `GET /query?q=<natural_language_query>` or `POST /query`
* **Authentication**: an API key is required for `/query`. Sign in with Google at
  https://censusdata.xyz/#playground to get a free key (free tier includes a daily
  query allowance). Pass it as an `X-API-Key` header or `api_key` query parameter.
  A `429` response means the daily quota is exhausted (resets at midnight UTC).

---

## 🛠️ How to Use This Skill

Whenever the user asks a question about US population, household sizes, poverty rates, incomes, housing units, home values, gross rents, commute times, remote work rates, public transit, or racial demographics:

1. **Format the Query**: Formulate a clear, descriptive natural language query specifying the target indicators, geographies, and years.
2. **Execute the Request**: Make a `GET` request to the `/query` endpoint of the service, URL-encoding the query string and passing your API key in the `X-API-Key` header (ask the user for their key if not configured; they can get one free at https://censusdata.xyz/#playground).
3. **Present the Response**: The service returns a pre-distilled, accurate, conversational response backed by live Census data. You can present this response directly to the user or integrate its statistics into your own analysis.

### Example Tool Call (Python)
```python
import urllib.request
import urllib.parse
import json

def query_census_agent(query_string: str, api_key: str) -> dict:
    base_url = "https://censusdata.xyz/query"
    url = f"{base_url}?q={urllib.parse.quote(query_string)}"
    
    try:
        req = urllib.request.Request(url, method="GET", headers={"X-API-Key": api_key})
        with urllib.request.urlopen(req) as response:
            if response.status == 200:
                res_data = json.loads(response.read().decode("utf-8"))
                # Returns dict containing:
                # - "query": the original query string
                # - "summary": natural language distilled summary
                # - "raw_data": list of raw Census API data points used
                return res_data
    except Exception as e:
        return {"error": f"Error querying Census Agent: {e}"}
```

### Example Tool Call (Curl)
```bash
curl -G "https://censusdata.xyz/query" \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode "q=Compare the median household income and work from home percentage in Seattle, WA and Portland, OR in 2022."
```

## 📊 Comprehensive 28,000+ Variable Support & Topic Discovery

The service supports **every single variable in the US Census Bureau database (over 28,000 indicators)** across Data Profiles and Subject Tables.

### Dynamic Discovery API (`GET /explore-variables`)
If you or the user want to know what Census data is available around a specific topic without guessing or enumerating 28,000 items, query the discovery endpoint:
```bash
curl -G "https://censusdata.xyz/explore-variables" --data-urlencode "keyword=veterans"
```
Returns matching variables, descriptions, and ready-to-use suggested natural language queries!

### Common Curated Concepts
* **Wealth & Economics**: Household Income (`median_household_income`), Per Capita Income (`per_capita_income`), Poverty Rate (`poverty_rate`), Gini Inequality Index (`gini_index`).
* **Demographics & Race**: Total Population (`population`), Median Age (`median_age`), Foreign-Born Percentage (`foreign_born_percentage`), White/Black/Asian/Hispanic breakdowns.
* **Housing & Rents**: Median Home Value (`median_home_value`), Gross Rent (`median_rent`), Household Size (`average_household_size`), Family Size (`average_family_size`).
* **Commute & Remote Work**: Commute Time (`mean_commute_time`), Remote Work Rate (`work_from_home_percentage`), Public Transit (`public_transport_percentage`).
* **Education**: High School Attainment (`high_school_or_higher`), Bachelor's Degree Rate (`bachelors_degree_or_higher`).

## 💡 Query Examples for Inspiration

* **Multi-Location Comparisons**: *"Compare the median household income, poverty rate, and average household size of Salt Lake City, UT and Boise, ID in 2022."*
* **Temporal Trends**: *"How has the work from home percentage and mean commute time in San Francisco, CA changed between 2018 and 2022?"*
* **ZIP Code Analysis**: *"Show me the demographic and housing profile for ZIP code 90210."*
* **State-Wide Rankings**: *"Which counties in Washington state have the highest bachelor's degree percentages?"*
* **Income Inequality**: *"Compare the Gini index of income inequality between New York County, NY and Los Angeles County, CA."*
