DEV Community

Cover image for Nieruchomosci Online RAG in Python: Keep Sales Offices Out of Home Locations
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

Nieruchomosci Online RAG in Python: Keep Sales Offices Out of Home Locations

Your relocation assistant can cite a real address and still put the home in the wrong city.

Picture it finding a district name beside a phone number and confidently placing the development there, while you stare at a citation that looks perfectly respectable. Wrong building.

Lab note 159: can we preserve property location without letting contact addresses steer retrieval? The fixture below is constructed, not evidence of an error rate. Separating roles can't repair an incorrect property address at the source.

Which address did your retriever actually use?

A sales-office address is contact evidence, not evidence of where the development stands.

Our property Actor exposes property-location fields alongside sales-office fields in project records, and agent contact fields in detail records. That distinction survives extraction.

A serializer such as "\n".join(str(value) for value in row.values()) promptly throws it away, leaving your retriever to distinguish addresses after you've removed the information that distinguished them.

Good luck, retriever.

A location question can now retrieve the office because its address matches the requested district, even when every value in the original record was assigned to the correct field.

The filter starts with explicit projections:

PROPERTY_FIELDS = (
    "address", "city", "district", "region", "country",
    "latitude", "longitude",
)
SALES_FIELDS = (
    "developerName", "developerUrl", "salesOfficeName",
    "salesOfficeAddress", "salesOfficeCity",
    "salesOfficePostalCode", "agentPhone",
)
AGENT_FIELDS = ("agentName", "agentAddress", "agentPhone")

def pick(row, fields):
    return {
        key: row[key]
        for key in fields
        if key in row
        and row[key] is not None
        and (not isinstance(row[key], str) or row[key].strip())
    }
Enter fullscreen mode Exit fullscreen mode

These are allowlists. Adding another address-bearing field upstream won't silently add it to your location corpus, which matters when extraction changes without a matching change to your embedding job.

Evidence Retrieval destination
Property-location fields Property location
Sales-office fields Sales contact
Agent fields Agent contact
Unrestricted description text Separate policy and processing

That last row matters.

A description can discuss offices, nearby landmarks, or transport connections. Keeping it beside the filtered location fields would reopen the ambiguity through text that your allowlist never inspected.

For this location collection, we'd rather leave that text out than guess. You can retain descriptions for other retrieval tasks without making every sentence eligible evidence for the property's location.

The same field name can describe a different entity

Filtering out agentAddress isn't enough.

Directory entries also expose address and city, but those belong to a company or office. Apply a property allowlist blindly across every mode and the business address passes every field-name check you've written.

The filter therefore checks the ingestion mode before projecting fields:

PROPERTY_MODES = frozenset({"search", "investments", "byUrl"})

def property_location(row, mode):
    if mode not in PROPERTY_MODES:
        return {}
    return pick(row, PROPERTY_FIELDS)
Enter fullscreen mode Exit fullscreen mode

Carry mode from the request into your ingestion envelope. It's pipeline provenance, not something to infer from a populated address.

For an existing mixed dataset whose provenance is missing, quarantine ambiguous rows until you can establish their entity type. An address that parses beautifully still doesn't tell you whose address it's.

This changes geographic analytics, too: a map of developer offices answers a question about business presence, even if your dashboard happens to call those points developments.

The coordinates won't object.

A successful geocode can certify the wrong choice

Empty fields are omitted. That makes a fallback chain tempting: property address, otherwise office address, otherwise agent address.

It produces a usable string. It also changes the entity being located, which is a fairly expensive meaning to hide inside an or expression.

A geocoder may resolve that office address successfully, giving the wrong location a neat coordinate pair and an undeserved air of authority. Successful resolution checks whether an address can be located, not whether you selected the property's address.

For a pipeline that needs text geocoding, this adapter accepts only the property projection and refuses contact-field fallbacks:

def geocoding_query(location):
    if set(location) - set(PROPERTY_FIELDS):
        raise ValueError("Expected a property-location projection")

    if not any(
        isinstance(location.get(key), str) and location[key].strip()
        for key in ("address", "city")
    ):
        return None

    parts = (
        location.get(key)
        for key in ("address", "district", "city", "region", "country")
    )
    return ", ".join(
        value.strip()
        for value in parts
        if isinstance(value, str) and value.strip()
    )
Enter fullscreen mode Exit fullscreen mode

A missing query should become an explicit unresolved state in your job queue. Resist the helpful fallback.

A city-only query remains city-level evidence, so a returned city centroid shouldn't become the building's position merely because the downstream schema expects coordinates.

This filter protects address selection. Matching precision needs its own checks.

Chunking can erase the boundary again

Labels help, but placing every role in the same document still gives the chunker permission to mix them.

A heading may land in an adjacent chunk while the office address survives alone. Overlap can then copy that address into neighboring passages, spending your location task's token budget on contact evidence it shouldn't have retrieved.

Split the roles before chunking:

source record
  |-- property projection ----> location collection
  |-- sales-office projection -> sales-contact collection
  `-- agent projection -------> agent-contact collection
Enter fullscreen mode Exit fullscreen mode

Deduplication needs the same boundary.

Using only the source URL as a document ID in a shared index lets a contact passage overwrite a location passage. Using an office address as a property identity can collapse unrelated developments marketed from that office.

Neither collision requires a model.

The combined filter gives every passage a role, a source URL, and an identity derived from both; contact routing also uses the ingestion mode because agentPhone appears in different record families:

import hashlib

def make_passage(source_url, role, values):
    if not values or not isinstance(source_url, str) or not source_url.strip():
        return None

    identity = f"{role}\0{source_url}".encode("utf-8")
    text = "\n".join(
        [f"role: {role}"]
        + [f"{key}: {value}" for key, value in values.items()]
    )
    return {
        "id": hashlib.sha256(identity).hexdigest(),
        "text": text,
        "metadata": {"url": source_url, "role": role},
    }

def route_record(row, mode):
    if mode not in PROPERTY_MODES:
        return {}

    projections = {
        "property_location": property_location(row, mode),
    }
    if mode == "investments":
        projections["sales_office_contact"] = pick(row, SALES_FIELDS)
    else:
        projections["agent_contact"] = pick(row, AGENT_FIELDS)

    routed = {}
    for role, values in projections.items():
        document = make_passage(row.get("url"), role, values)
        if document is not None:
            routed[role] = document
    return routed
Enter fullscreen mode Exit fullscreen mode

Write each returned document to the collection named by its role, using its id as the upsert key. A location request queries only property_location; an authorized contact workflow selects the relevant contact collection.

Documents without a source URL stay out of these collections because the filter can't assign a source-based identity. Retain those rows for inspection rather than manufacturing one from an address.

This identity preserves separate passages within a source. It doesn't establish that different URLs describe different physical properties, so cross-source property resolution remains a separate decision.

Role labels help with inspection, but collection routing supplies the retrieval boundary. A prompt asking the model to “use the correct address” can't remove an office passage already admitted as location evidence.

A fixture makes the contamination visible

The useful regression check is whether contact geography can enter the property passage, including when property fields disappear and the contact address becomes the most complete location left.

That's the awkward case.

The Example fixture below is fictional and deliberately assigns the property, sales office, and agent to different cities.

fixture = {
    "address": "Example property street, Krakow",
    "city": "Krakow",
    "district": "Nowa Huta",
    "salesOfficeName": "Example sales office",
    "salesOfficeAddress": "Example sales street, Warszawa",
    "salesOfficeCity": "Warszawa",
    "agentName": "Example agent",
    "agentAddress": "Example agent street, Gdansk",
    "agentPhone": "Example phone",
    "url": "https://example.invalid/project",
}

documents = route_record(fixture, "investments")
location_text = documents["property_location"]["text"]

assert "Krakow" in location_text
assert "Warszawa" not in location_text
assert "Gdansk" not in location_text
assert "Warszawa" in documents["sales_office_contact"]["text"]
assert "Gdansk" in route_record(fixture, "byUrl")["agent_contact"]["text"]
assert len({document["id"] for document in documents.values()}) == len(documents)
assert route_record(fixture, "developers") == {}

contact_only = {
    key: value for key, value in fixture.items()
    if key not in PROPERTY_FIELDS
}
assert "property_location" not in route_record(contact_only, "investments")
assert geocoding_query(property_location(contact_only, "investments")) is None
Enter fullscreen mode Exit fullscreen mode

The fixture combines field families to exercise the routing boundary; it doesn't imply that every mode returns every contact field.

These assertions check ingestion behavior, not the model's geography knowledge. They protect the uncomfortable decision to keep a property unresolved while a perfectly usable office address sits nearby, practically volunteering.

Keep the uncertainty attached to the property

The worked example is Nieruchomosci-online Property & Agency Directory Scraper. Its separate fields give the ingestion pipeline enough information to preserve address roles.

The verdict: keep contact geography out of location retrieval.

This doesn't establish that a property address is complete, current, or precise enough for a neighborhood answer. If district is absent, the assistant shouldn't borrow one from an office passage to finish the sentence.

An absent district isn't an invitation.

For token budgets, the benefit is task relevance: location requests spend context on property-location evidence. For deduplication, the benefit is retaining distinct source-and-role documents without pretending that a source URL is a universal property identifier.

The assistant can still be wrong about geography after this filter. It should at least be reasoning about the property you asked it to locate.

Reproduce the boundary

  • Execute the Python cells above to check the constructed fixture.
  • Fetch project records with the input below, then route each row into the corresponding collection.
  • Query the location collection separately and retain unresolved locations for review.

This Example request selects a nationwide project feed for the ingestion check.

import os
from apify_client import ApifyClient

run_input = {
    "mode": "investments",
    "city": "",
    "maxItems": 3,
}

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "vexaloom-labs/nieruchomosci-online-property-and-agency-directory"
).call(run_input=run_input)

if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Actor finished with status {run['status']}")

items = client.dataset(run["defaultDatasetId"]).list_items().items
routed_records = [
    route_record(item, run_input["mode"])
    for item in items
]
Enter fullscreen mode Exit fullscreen mode

Use this exact Example input when submitting the same request through the Actor's input form:

{
  "mode": "investments",
  "city": "",
  "maxItems": 3
}
Enter fullscreen mode Exit fullscreen mode

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)