This prompt is designed for platform engineers building hybrid retrieval systems where vector similarity search alone cannot satisfy spatial constraints. The core job-to-be-done is translating a user's natural language geographic expression—such as 'apartments near downtown Chicago' or 'conference venues within 50 miles of San Francisco'—into a structured, machine-readable filter object. This object can then be passed directly to a geospatial search backend like Elasticsearch, PostGIS, or a custom API. The ideal user is an engineering lead or developer who already has a geocoding service and a search index with latitude/longitude fields, and now needs a reliable extraction layer between the user's query and the database.
Prompt
Geospatial Metadata Extraction Prompt Template

When to Use This Prompt
A practical guide for deciding when to deploy the Geospatial Metadata Extraction prompt in a production retrieval pipeline.
You should use this prompt when your application needs to parse geographic intent from free-text queries and convert it into actionable filter clauses. This includes handling place names ('near Central Park'), coordinate pairs ('around 37.7749, -122.4194'), radius expressions ('within 10 km of the Eiffel Tower'), bounding boxes, and ambiguous location references like 'downtown' or 'the Bay Area'. The prompt is not a geocoder; it does not resolve place names to coordinates. It extracts the intent and structure, leaving coordinate resolution to a dedicated geocoding service in your application harness. Pairing this prompt with a geocoder like Mapbox, Google Maps, or Nominatim is a required architectural pattern, not an optional enhancement.
Do not use this prompt when you need precise coordinate lookups, when the user's query contains no geographic signal, or when your search index lacks geospatial query capabilities. It is also insufficient for real-time navigation, routing, or any use case requiring sub-meter precision. The prompt excels at structured extraction but will fail silently or produce low-confidence output when given purely metaphorical location language ('the center of the debate') or references that require deep cultural knowledge to resolve. Always validate the output against a known schema and implement a confidence threshold below which the filter is discarded or flagged for human review. For high-stakes applications like emergency services or legal compliance, human approval must be a gating step before any extracted filter reaches the search backend.
Use Case Fit
Where this prompt works, where it fails, and what you must provide before putting it into production.
Good Fit: Location-Aware Search
Use when: your application needs to translate natural language queries like 'restaurants near downtown Chicago' or 'warehouses within 50 miles of 90210' into structured geographic filters. Guardrail: The prompt excels at extracting explicit spatial relationships but requires a downstream geocoding service to resolve place names to coordinates.
Bad Fit: Real-Time Navigation
Avoid when: the use case requires live routing, turn-by-turn directions, or real-time traffic-aware queries. Guardrail: This prompt extracts static geographic constraints. It does not understand road networks, dynamic conditions, or route optimization. Pair it with a routing engine if movement is required.
Required Inputs
What you must provide: a natural language query string, a schema defining the expected output (e.g., {place_name, lat, lon, radius_mi}), and a list of known geocoding ambiguities to watch for. Guardrail: Without a strict output schema, the model may return unstructured text instead of machine-readable coordinates or polygons.
Operational Risk: Ambiguous Place Names
Risk: queries like 'Springfield' or 'downtown' resolve to multiple locations. The model may guess or hallucinate coordinates. Guardrail: Always route extracted place names through a geocoding API with a disambiguation strategy (e.g., user context, IP location, or explicit clarification prompts). Never trust raw coordinates from the LLM alone.
Operational Risk: Radius Interpretation
Risk: phrases like 'near', 'close to', or 'in the area' have no standard distance. The model may default to an arbitrary radius. Guardrail: Define explicit default radii per query type in your application logic (e.g., 'near' = 5km, 'in' = city boundary). Use the prompt to extract the expression, but resolve the value in code.
Operational Risk: Coordinate Injection
Risk: users may inject raw coordinates or malformed location strings to bypass intended geographic boundaries. Guardrail: Validate all extracted coordinates against an allowed bounding box or region set. Sanitize inputs to prevent prompt injection that could override system-level geographic restrictions.
Copy-Ready Prompt Template
A reusable prompt for extracting structured geospatial constraints from natural language queries, ready to paste into your prompt management system.
This prompt template converts a user's natural language query into a structured geospatial filter object. It is designed for location-aware search and RAG applications where vector similarity alone cannot enforce geographic constraints. The template uses square-bracket placeholders for all dynamic inputs—replace these at runtime with your application's values. The output is a strict JSON schema that downstream systems can parse into database WHERE clauses, Elasticsearch geo-queries, or vector DB metadata filters.
textYou are a geospatial metadata extraction system. Your job is to read a user query and extract any geographic constraints into a structured JSON object. Do not answer the query. Only extract location metadata. ## Input User Query: [USER_QUERY] ## Context - Current date and time: [CURRENT_DATETIME] - User's approximate location if known: [USER_LOCATION] - Known place catalog (name, canonical_name, centroid_lat, centroid_lon, radius_km, admin_hierarchy): [PLACE_CATALOG] - Default search radius in kilometers when not specified: [DEFAULT_RADIUS_KM] ## Output Schema Return a single JSON object with these fields: - "locations": array of objects, each with: - "place_name": string (canonical name from catalog if matched, otherwise the extracted name) - "place_type": string (one of: "point", "city", "region", "country", "postal_code", "landmark", "custom_area") - "geometry": object with "type" ("Point" or "Polygon"), "coordinates" (GeoJSON coordinate array), and "radius_km" (number, null if Polygon) - "matched_catalog_entry": string or null (canonical name if found in place catalog, null if not) - "confidence": number between 0.0 and 1.0 - "spatial_operator": string (one of: "within", "near", "outside", "intersects") - "ambiguous_locations": array of strings (place names that could not be disambiguated) - "no_location_detected": boolean (true if no geographic constraint was found) ## Constraints 1. If the user mentions a place in the catalog, use the catalog's canonical name, centroid, and radius. 2. If a place is not in the catalog, estimate coordinates conservatively and set confidence below 0.5. 3. For proximity queries ("near", "around", "within X km of"), set spatial_operator to "near" and use the radius from the query or the default. 4. For containment queries ("in", "inside", "within" a named area), set spatial_operator to "within". 5. For exclusion queries ("outside", "not in", "excluding"), set spatial_operator to "outside". 6. Resolve relative location expressions ("near me", "nearby", "local") using the provided user location. 7. If a place name is ambiguous (e.g., "Springfield"), list it in ambiguous_locations and do not guess. 8. If no geographic constraint is detected, set no_location_detected to true and locations to an empty array. 9. Never invent coordinates for real places. If uncertain, set confidence low and flag as ambiguous. ## Examples Query: "apartments in downtown Chicago within 2 miles" Output: {"locations":[{"place_name":"Chicago","place_type":"city","geometry":{"type":"Point","coordinates":[-87.6298,41.8781],"radius_km":3.22},"matched_catalog_entry":"Chicago","confidence":0.95}],"spatial_operator":"near","ambiguous_locations":[],"no_location_detected":false} Query: "best pizza places" Output: {"locations":[],"spatial_operator":"within","ambiguous_locations":[],"no_location_detected":true} Query: "hotels outside Paris city center" Output: {"locations":[{"place_name":"Paris","place_type":"city","geometry":{"type":"Point","coordinates":[2.3522,48.8566],"radius_km":5.0},"matched_catalog_entry":"Paris","confidence":0.9}],"spatial_operator":"outside","ambiguous_locations":[],"no_location_detected":false} ## Risk Level [RISK_LEVEL] If RISK_LEVEL is "high", do not estimate coordinates for uncatalogued places. Set confidence to 0 and add to ambiguous_locations.
To adapt this template for production, replace the placeholders with runtime values from your application context. The [PLACE_CATALOG] should be a pre-loaded list of known places with canonical names and coordinates—this is your grounding source and prevents the model from hallucinating locations. The [RISK_LEVEL] parameter lets you toggle between permissive extraction (low-risk internal analytics) and strict extraction (high-risk applications where wrong coordinates cause real harm). After extraction, always validate the output JSON against the schema before passing it to your search backend. If ambiguous_locations is non-empty or confidence is below your threshold, route the query for human clarification or fall back to a non-geospatial search.
Prompt Variables
Inputs required for the Geospatial Metadata Extraction Prompt to reliably parse location constraints from natural language queries. Each variable must be populated before the prompt is sent to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The raw natural language query containing geographic intent to be parsed. | Show me Italian restaurants within 5 miles of downtown Austin | Required. Non-empty string. Pre-process to remove PII if present. Max 2000 characters. |
[TARGET_SCHEMA] | The JSON schema definition the output must conform to, including field names, types, and enum constraints. | { "location_type": "point|area|route|null", "place_name": "string", "coordinates": { "lat": "float", "lng": "float" }, "radius_miles": "float|null", "polygon": "array|null" } | Required. Must be a valid JSON schema draft. Validate with a JSON schema validator before prompt assembly. Enforce enum values for location_type. |
[GEOCODING_PROVIDER] | Specifies the geocoding service context for place name resolution, influencing how the model interprets ambiguous names. | Google Maps Geocoding API | Required. String enum: 'Google Maps Geocoding API', 'Mapbox', 'OpenStreetMap Nominatim', 'Custom Internal Gazetteer'. Used in prompt instructions to set resolution expectations. |
[DEFAULT_RADIUS_MILES] | The fallback radius in miles to apply when a proximity query like 'near' or 'close to' lacks a specific distance. | 10.0 | Required. Float > 0. Must be provided by the application config. Prevents null radius on proximity queries. |
[MAX_RADIUS_MILES] | The hard upper bound for any extracted radius to prevent overly broad geographic searches. | 100.0 | Required. Float > 0. Any extracted radius exceeding this value should be clamped or flagged. Enforced in post-processing, not just the prompt. |
[AMBIGUITY_THRESHOLD] | The confidence score below which an extracted location is considered ambiguous and requires clarification or human review. | 0.7 | Required. Float between 0.0 and 1.0. Used to trigger a 'needs_clarification' flag in the output. Calibrate against your eval set. |
[KNOWN_LOCATION_ALIASES] | A dictionary mapping common shorthand or internal names to canonical place names or coordinates to improve extraction accuracy. | { "SoCo": "South Congress, Austin, TX", "the bay": "San Francisco Bay Area, CA" } | Optional. Valid JSON object. If null, the prompt should instruct the model to rely solely on the geocoding provider's default resolution. |
Implementation Harness Notes
How to wire the geospatial extraction prompt into a production search pipeline with validation, retries, and geocoding integration.
This prompt is not a standalone geocoder. It extracts structured geographic constraints from natural language text, producing a JSON object with place names, coordinate pairs, radius expressions, and ambiguity flags. The output must be validated against a geocoding service before it becomes a usable spatial filter in your search backend. Treat the LLM output as a parsing and normalization layer, not a source of truth for coordinates.
Wire the prompt as a pre-retrieval step in your RAG or search pipeline. After extraction, pass the place_name fields to a geocoding API (Mapbox, Google, Nominatim) to resolve coordinates and bounding boxes. For radius_meters and proximity expressions, validate that the resolved geometry matches the user's likely intent—a query for 'near downtown Denver' should not resolve to the entire Denver metro area. Implement a validation harness that checks: (1) all extracted place names resolve to valid geocodes, (2) coordinate pairs fall within expected bounds for the mentioned region, (3) radius values are positive and within configurable maximums (e.g., 100 km for 'nearby' queries), and (4) ambiguity scores above a threshold trigger a clarification request to the user rather than a guess. Log extraction confidence alongside resolved geometries for debugging.
For model choice, a fast instruction-tuned model like GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned open-weight model works well for this structured extraction task. The prompt's output schema is strict JSON, so enable structured output mode or JSON mode on your provider. Set a low temperature (0.0–0.1) for deterministic extraction. If the extraction fails schema validation, retry once with the validation error appended to the prompt as feedback. If the second attempt also fails, fall back to a keyword-only search without spatial filters and log the failure for review. For high-traffic systems, cache geocoding results by normalized place name to avoid redundant API calls. Never pass raw user queries directly to the geocoding service without extraction—users phrase locations in ways that geocoders misinterpret without normalization.
Expected Output Contract
Define the exact shape, types, and validation rules for the geospatial metadata object returned by the prompt. Use this contract to build a parser that rejects malformed outputs before they reach your search backend.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
[PLACE_NAME] | string | Must be a non-empty string. If no place is detected, the field must be set to null. | |
[COORDINATES] | object { lat: number, lng: number } | If present, lat must be in [-90, 90] and lng in [-180, 180]. Reject if only one coordinate is provided. | |
[RADIUS_KM] | number | Must be a positive float. If a proximity expression like 'near' is used without a distance, default to null. Reject negative values. | |
[GEO_JSON_POLYGON] | GeoJSON Polygon object | Must conform to RFC 7946. The first and last coordinate pairs must be identical. Reject self-intersecting rings. | |
[CONFIDENCE] | number | Must be a float in the range [0.0, 1.0]. A score of 0.0 indicates no geographic constraint was detected. Use for downstream filtering. | |
[AMBIGUITY_FLAG] | boolean | Must be true if multiple distinct locations match the query (e.g., 'Springfield'). Triggers a disambiguation or human review path. | |
[RESOLVED_CANONICAL_NAME] | string | If [AMBIGUITY_FLAG] is false, this must contain the fully qualified canonical name (e.g., 'Paris, Texas, USA'). Null otherwise. |
Common Failure Modes
Geospatial extraction breaks in predictable ways. These are the most common failure modes in production and the specific guardrails that catch them before they corrupt downstream search filters.
Ambiguous Place Name Resolution
What to watch: Queries containing place names like 'Springfield' or 'Washington' resolve to the wrong location because the model defaults to the most populous or well-known instance. Guardrail: Require a context anchor (user location, previous query, or default region) in the prompt and validate extracted coordinates against a geocoding service. Flag results where multiple high-confidence candidates exist.
Proximity Expression Misinterpretation
What to watch: Phrases like 'near downtown', 'within walking distance', or 'just outside' are interpreted with arbitrary or inconsistent radius values. The model invents a radius without grounding. Guardrail: Define an explicit radius lookup table in the prompt (e.g., 'near' = 5km, 'walking distance' = 1km). Validate that every extracted proximity constraint includes a numeric radius and unit.
Coordinate Hallucination
What to watch: The model generates plausible-looking latitude/longitude pairs for locations it doesn't actually know, especially for obscure landmarks, business names, or informal place references. Guardrail: Never trust model-generated coordinates directly. Always pass extracted place names through a deterministic geocoding API and replace model coordinates with verified results. Flag any extraction where the geocoder returns zero results.
Implicit Location Omission
What to watch: Queries like 'best pizza places' or 'weather forecast' contain implicit location intent but no explicit place reference. The model extracts nothing, and the search returns unfiltered global results. Guardrail: Configure a required fallback location in the prompt harness (user profile, IP geolocation, or session default). Add a validation check that every geospatial query produces at least one location constraint or an explicit null with reason.
Hierarchical Boundary Confusion
What to watch: A query for 'homes in Orange County' is ambiguous between county-level and city-level boundaries. The model may extract a point coordinate instead of a polygon, or conflate administrative boundaries with informal regions. Guardrail: Prompt the model to classify the boundary type (point, radius, polygon, administrative area) explicitly. Validate that administrative area queries use a gazetteer lookup for polygon boundaries rather than centroid points.
Multi-Location Query Fragmentation
What to watch: Queries like 'compare rents in Austin and Denver' require two independent location constraints, but the model extracts only one or merges them into a nonsensical combined region. Guardrail: Structure the output schema as an array of location objects, not a single object. Add a post-extraction count check: if the query contains multiple location signals but the output has fewer entries, trigger a retry or flag for review.
Evaluation Rubric
Use this rubric to test the quality of geospatial metadata extraction before deploying to production. Each criterion targets a known failure mode for location-aware search prompts.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Place Name Extraction | All explicit place names in [USER_QUERY] appear in the output with correct canonical form | Missing place name, hallucinated place name, or place name mapped to wrong canonical entity | Run 50 annotated queries; check recall >= 0.98 and precision >= 0.95 on place name spans |
Coordinate Extraction | Explicit lat/lon pairs extracted exactly as provided; no coordinate drift or precision loss | Truncated decimals, swapped lat/lon order, or coordinates extracted from text that does not contain them | Parse output coordinates; assert exact string match to source when present; assert null when absent |
Proximity Expression Resolution | Expressions like 'near', 'within X miles', 'around' resolve to a radius value and center point with correct unit | Radius defaults to 0, unit confusion (km vs miles), or center point set to wrong location | Test 20 proximity queries; check radius > 0, unit field matches expression, center within 50m of expected |
Ambiguous Location Handling | Output includes a confidence score below threshold or a disambiguation list when location is ambiguous | System silently picks one interpretation of 'Springfield' or 'Washington' without flagging ambiguity | Feed 15 ambiguous queries; assert confidence < 0.8 or disambiguation list populated for each |
Hierarchical Context Preservation | Output preserves city, state, country hierarchy when query provides disambiguating context | State or country context ignored, causing wrong city selection or missing parent region | Query 'Portland, ME' vs 'Portland, OR'; assert state field populated and correct in each case |
Null Handling for Non-Geo Queries | Output returns empty or null geospatial block when query contains no location information | Hallucinated location, default coordinates, or placeholder values injected for non-geo queries | Feed 30 non-geo queries; assert geospatial output block is null or all fields empty |
Schema Adherence | Output matches [OUTPUT_SCHEMA] exactly: all required fields present, correct types, no extra fields | Missing required fields, string where number expected, or extra undeclared fields in JSON | Validate output against JSON Schema; assert validation passes with zero errors |
Geocoding Accuracy | Resolved canonical place name matches a known geocoding reference within acceptable tolerance | Place name resolves to wrong country, centroid off by >100km, or fictional location accepted as real | Compare resolved coordinates to reference geocoder; assert haversine distance < 50km for city-level queries |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and minimal post-processing. Focus on extracting the core fields: [PLACE_NAME], [COORDINATES], [PROXIMITY_EXPRESSION], and [BOUNDING_BOX]. Accept string outputs and parse them loosely in application code.
Prompt modification
Remove strict schema enforcement. Replace JSON output instructions with: Return the extracted geospatial constraints as a bulleted list with field names and values.
Watch for
- Coordinates extracted without datum or precision context
- Proximity expressions like 'near downtown' left unresolved
- Ambiguous place names (e.g., 'Springfield') returned without disambiguation notes

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us