Skip to main content

etter logo

etter /ˈɛtɐ/ n. (Swiss German) — the boundary or enclosure marking the edge of a village or commune; a natural demarcation between settled and unsettled land.

Natural language geographic query parsing using LLMs.

Overview

etter transforms natural language location queries into structured geographic filters that can be used by search engines and spatial databases. It uses Large Language Models (LLMs) to understand multilingual queries and extract spatial relationships.

Key Principle: etter's sole purpose is to extract the geographic filter from user queries. It does NOT handle feature/activity identification or search execution.

Sponsorship

camptocamp logo

The development of this library is sponsored by Camptocamp.

Features

  • Geographic Filters Only: Extracts spatial relationships from queries, ignoring non-geographic content
  • Multilingual Support: Parse queries in English, German, French, Italian, and more
  • Rich Spatial Relations: Support for containment, buffer, and directional queries
  • Structured Output: Pydantic models with full type safety
  • Streaming Support: Real-time feedback with reasoning transparency for responsive UIs
  • Flexible Configuration: Customizable spatial relations and confidence thresholds
  • LLM Provider Agnostic: Works with OpenAI, Anthropic, or local models

What etter Does (and Doesn't Do)

✅ etter extracts:

  • Spatial relations: "north of", "in", "near", etc.
  • Reference locations: "Lausanne", "Lake Geneva", etc.
  • Distance parameters: "within 5km", "around 2 miles", etc.

❌ etter does NOT handle:

  • Feature/activity identification: "hiking", "restaurants", "hotels"
  • Attribute filtering: "with children", "vegetarian", "4-star"
  • Search execution or database queries

Integration Pattern: Parent application handles feature/activity filtering and combines it with etter's geographic filter for complete search functionality.

Installation

pip install etter

etter depends on langchain-core only. Install your model provider, and langchain for init_chat_model as in the Quick Start:

pip install langchain langchain-openai

With the file-backed datasources (SwissNames3D, swissBOUNDARIES3D, IGN BD-CARTO), which need geopandas:

pip install "etter[files]"

With PostGIS datasource support:

pip install etter[postgis]

Development setup

This project uses uv for dependency management.

git clone https://github.com/geoblocks/etter.git
cd etter
uv sync --extra dev

Demos

For all the demos, set a valid model name and API key in .env file:

cat <<EOF > .env
LLM_API_KEY="sk-..."
LLM_MODEL="gpt-4o"
EOF

REPL

An interactive REPL is available for testing queries interactively:

uv run python repl.py

Demo API Server

A FastAPI demo server is available that combines query parsing with geographic resolution using SwissNames3D data.

uv run uvicorn demo.main:app --port 8000 --reload

The API will be available at http://localhost:8000.

Quick Start

from langchain.chat_models import init_chat_model
from etter import GeoFilterParser
import os

# Initialize LLM
llm = init_chat_model(
    model=os.getenv("LLM_MODEL", "gpt-4o"),
    temperature=0,
    api_key=os.getenv("LLM_API_KEY")
)

# Initialize parser
parser = GeoFilterParser(
    llm=llm,
    confidence_threshold=0.6,
    strict_mode=False
)

# Strict mode - raises error on low confidence
parser = GeoFilterParser(
    llm=llm,
    confidence_threshold=0.8,
    strict_mode=True
)

Custom Spatial Relations

from etter import SpatialRelationConfig, RelationConfig

config = SpatialRelationConfig()
config.register_relation(RelationConfig(
    name="close_to",
    category="buffer",
    description="Very close proximity",
    default_distance_m=1000,
    buffer_from="center"
))

parser = GeoFilterParser(llm=llm, spatial_config=config)

API Reference

GeoFilterParser

Main class for parsing queries.

Methods:

  • parse(query: str) -> GeoQuery: Parse a single query
  • aparse(query: str) -> GeoQuery: Async version of parse (awaits ainvoke on the LLM)
  • parse_stream(query: str) -> AsyncGenerator[dict]: Parse with streaming events
  • parse_batch(queries: List[str], max_concurrency: int = 1) -> List[GeoQuery]: Parse multiple queries, optionally in parallel threads
  • aparse_batch(queries: List[str], max_concurrency: int = 1) -> List[GeoQuery]: Async version of parse_batch
  • get_available_relations(category: Optional[str]) -> List[str]: List available relations
  • describe_relation(name: str) -> str: Get relation description

Constructor options (selected):

  • confidence_threshold: Minimum confidence to accept (0–1, default 0.6)
  • strict_mode: Raise LowConfidenceError instead of warning (default False)
  • include_examples: Include few-shot examples in the prompt (default True)
  • datasource: GeoDataSource instance — informs the LLM of available concrete types
  • additional_instructions: Free-form text injected as a system message after the main prompt and before few-shot examples. Use for region-specific endonyms, domain aliases, or organization-specific place names.

GeoQuery

Structured output model representing the parsed geographic filter.

Attributes:

  • query_type: Type of query (simple, compound, split, boolean)
  • spatial_relation: Spatial relationship (e.g., "north_of", "in", "near")
  • reference_location: Reference location (e.g., "Lausanne"), or None for attribute-only queries
  • buffer_config: Buffer parameters (optional)
  • confidence_breakdown: Confidence scores
  • original_query: Original input text

Note: etter is fully implemented with three integrated layers: parsing, geographic resolution via datasources, and spatial operations. The demo API shows a complete end-to-end workflow that resolves locations and computes search areas.

Composing With Your Own Schema

To extract your own fields from the same query in a single LLM call, nest GeoQuery in your output model, reuse etter's prompt, and validate the nested result with finalize_geo_query:

from pydantic import BaseModel
from etter import GeoQuery, SpatialRelationConfig, build_geo_prompt_template, finalize_geo_query

class Output(BaseModel):
    geo: GeoQuery
    language: str

config = SpatialRelationConfig()
prompt = build_geo_prompt_template(config, additional_instructions="Also return the ISO 639-1 code of the query language.")

result = llm.with_structured_output(Output).invoke(prompt.format_messages(query=query))
geo = finalize_geo_query(result.geo, config, query)

Available Spatial Relations

Containment

  • in: Exact boundary matching

Buffer/Proximity

  • near: Proximity with context-aware distance (default 5km, LLM infers based on activity, feature scale, and intent)
  • on_shores_of: 1km ring buffer (excludes water body)
  • along: 500m buffer for linear features
  • left_bank, right_bank: Buffer on one side of a linear feature (river, road) relative to its flow direction
  • in_the_heart_of: Erosion for central areas (default -500m, LLM infers based on area size)
  • bordering: 2km ring outside the reference boundary, for land-border adjacency queries (e.g. "cities bordering Germany")

Clipping

  • northern_part_of, southern_part_of, eastern_part_of, western_part_of: Clips the reference geometry to the corresponding directional half (bbox intersection)

Directional

  • Cardinal: north_of, south_of, east_of, west_of: 10km sector (90° each)
  • Diagonal: northeast_of, southeast_of, southwest_of, northwest_of: 10km sector (90° each)

Error Handling

from etter import LLMInvocationError, ParsingError, UnknownRelationError, LowConfidenceError

try:
    result = parser.parse("some query")
except LLMInvocationError as e:
    print(f"LLM call failed (retryable): {e.original_error}")
except ParsingError as e:
    print(f"Failed to parse: {e}")
    print(f"Raw LLM response: {e.raw_response}")
except UnknownRelationError as e:
    print(f"Unknown relation: {e.relation_name}")
except LowConfidenceError as e:
    print(f"Low confidence: {e.confidence}")
    print(f"Reasoning: {e.reasoning}")

Demo Examples

Here are some good example queries to try with the demo application:

  • walk in the Gros-de-Vaud
  • on the shores of the lac Morat
  • near Lausanne
  • south west of Lausanne
  • 5km north of Lausanne
  • walking distance from Zurich main railway station
  • 15 min biking from Zurich main railway station
  • along l'Orbe
  • 2km right bank of the Rhône

Architecture

See ARCHITECTURE.md for detailed system design.

Development

# Install dev dependencies
uv sync --extra dev

# Run tests
uv run pytest

# Format code
uv run ruff format

# Linting
uv run ruff check

# Type checking
uv run ty check

Releases

Releases are automated via Release Please. The version and changelog are determined by PR titles using the Conventional Commits format:

PR title prefix Version bump
feat: ... minor (0.x.0)
fix: ..., perf: ... patch (0.0.x)
feat!: ... or BREAKING CHANGE major (x.0.0)

All other prefixes (chore:, docs:, refactor:, test:, ci:) do not trigger a release.

When a releasable commit lands on main, Release Please opens a release PR. Merging it tags the commit and triggers the PyPI publish workflow.

Metadata

Release files for etter 0.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for etter 0.10.0
File Size Uploaded Provenance Actions
etter-0.10.0.tar.gz 81.2 kB Without provenance Details for etter-0.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for etter 0.10.0
File Interpreter ABI Platform Actions
etter-0.10.0-py3-none-any.whl Python 3 none any Details for etter-0.10.0-py3-none-any.whl

Total release size: 145.4 kB

Release files / etter-0.10.0.tar.gz

Download URL etter-0.10.0.tar.gz
Size 81.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f8c4ef2e014b746194e6c4b0e90e1364b6acf754f9ec7184b1f61bb4128c85d9
BLAKE2b-256 checksum
How to use checksums
69bbdbcaba7de2053f590d73e114e731e571484d92a546762c2939920aeadb8f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / etter-0.10.0-py3-none-any.whl

Download URL etter-0.10.0-py3-none-any.whl
Size 64.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e11966cf0df331a915fa96536d3089e52f08acfc9390ae3353faef41afb37775
BLAKE2b-256 checksum
How to use checksums
0e1c0653d10e987ca23aaa485169e70e6a5ea97bbbe7e8539720a05711a0a7c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for etter 0.10.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page