The hotel is real; the offer your model assembled from its details may not be.
You're turning hotel records into retrieval chunks, and the recommendation combines a cheap rate, a different provider, and free cancellation. Each detail looks plausible. The combination needs evidence.
Lab note 155: can we preserve useful hotel context without letting retrieval assemble a booking option nobody supplied? The catch comes before chunking: cancellation and freebies belong to the cheapest rate, so they can't safely become property facts.
Where a hotel paragraph becomes an unsupported join
A hotel corpus should separate property facts from offer terms because a provider, price, and cancellation policy must remain attached to the same rate.
That boundary matters more than paragraph length. A pool describes the property; free cancellation describes a booking option under particular search conditions.
The corpus should make that distinction visible:
hotel record
├─ property facts → descriptive retrieval text
├─ cheapest rate → terms kept together
└─ additional providers → separate structured evidence
Splitting every field into its own chunk also fails. Retrieve cancellation without its provider and stay context, and you've merely made the unsupported join easier.
We want atomic claims with enough context to remain true.
Collect the stay context alongside the records
The Actor is our worked example: hotel records include property attributes, nightly and total prices, cheapest-provider details, and up to 10 provider offers.
Hotel searches have no fallback when live access is blocked. Check the run status message before interpreting an empty corpus as evidence that nothing matched.
This Example search fixes the stay and occupancy so the collection has an explicit scope:
import hashlib
import json
import os
import re
from apify_client import ApifyClient
run_input = {
"mode": "searchHotels",
"site": "kayak.com",
"destination": "London",
"departDate": "2026-12-10",
"returnDate": "2026-12-17",
"adults": 2,
"rooms": 1,
"hotelSortBy": "price_low",
"maxItems": 40,
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
"vexaloom-labs/kayak-flight-hotel-and-cheap-destination-finder"
).call(run_input=run_input)
if run["status"] != "SUCCEEDED":
raise RuntimeError(f"Collection ended with status {run['status']}")
items = client.dataset(run["defaultDatasetId"]).iterate_items()
The request belongs in provenance. It shouldn't silently fill missing output fields: “we requested these dates” and “this record supplies these dates” are different assertions.
We also leave rate filters unset. A corpus for studying cancellation language becomes a peculiar training set if collection excludes everything without free cancellation.
Give every unit a scope and a parent
Our corpus uses the following shapes. These are corpus fields we create, rather than additional Actor output fields.
| Unit type | Text used for retrieval | Structured evidence |
|---|---|---|
property |
Identity, location, amenities, labeled ratings | Supplied property fields |
cheapest_rate |
Price bundle with supplied stay context | Provider, terms, links, prices |
provider_evidence |
None by default | Unmodified provider entry and shared stay context |
Each unit gets a content identifier, provenance, and a property grouping key. Offer units point to the exact property unit produced from their source record.
These helpers select supplied values and build stable identifiers without treating a missing cancellation flag as false:
def canonical(value):
return json.dumps(
value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
def digest(value):
return hashlib.sha256(canonical(value).encode("utf-8")).hexdigest()
def pick(record, fields):
return {
key: value
for key, value in record.items()
if key in fields and value not in (None, "", [], {})
}
def make_unit(kind, entity, parent, evidence, context, observation, label=None):
identity = [kind, entity, parent, evidence, context]
text = None
if label is not None:
text = re.sub(
r"\s+", " ",
label + "\n" + canonical({"facts": evidence, "stay": context})
).strip()
return {
"unit_id": digest(identity),
"unit_type": kind,
"parent_id": parent,
"split_group": entity,
"text": text,
"evidence": evidence,
"context": context,
"observations": [observation],
}
A missing value stays missing. We'd rather leave the field out than turn uncertainty into a booking promise.
Keep the cheapest bundle closed
Stars describe property classification; rating describes guest reviews. Keeping both numbers while dropping their labels makes a lovely ambiguity generator.
For rates, price is nightly and totalPrice covers the stay. We preserve both without calculating a substitute total. Multiplying a displayed nightly price isn't evidence of the supplied stay total.
This transformation separates those scopes and retains additional provider entries without guessing their nested schema:
property_fields = {
"hotelId", "hotelName", "city", "latitude", "longitude",
"distanceFromCenter", "stars", "rating", "ratingCategory",
"reviewCount", "amenities", "amenityCodes",
}
rate_fields = {
"price", "totalPrice", "currency", "providerName", "providerCode",
"freeCancellation", "freebies", "bookingUrl", "deepLink",
}
stay_fields = {"checkIn", "checkOut", "nights", "adults", "rooms"}
def units_for(row):
if row.get("recordType") != "kayakHotel":
return
hotel_id = row.get("hotelId") or row.get("flightId")
if not hotel_id:
return
entity = digest([run_input["site"], hotel_id])
observation = pick(row, {"accessMethod", "sourceUrl", "scrapedAt"})
observation["requested_search"] = run_input.copy()
context = pick(row, stay_fields)
property_unit = make_unit(
"property", entity, None, pick(row, property_fields), {},
observation,
"Property facts. stars: property classification. "
"rating: guest review score.",
)
yield property_unit
rate = pick(row, rate_fields)
if rate:
ready = (
{"price", "currency"} <= rate.keys()
and {"checkIn", "checkOut", "adults", "rooms"} <= context.keys()
)
rate_unit = make_unit(
"cheapest_rate", entity, property_unit["unit_id"],
rate, context, observation,
)
if ready:
visible = {
key: value for key, value in rate.items()
if key not in {"bookingUrl", "deepLink"}
}
rate_unit["text"] = (
"Cheapest-rate bundle. price: nightly rate. "
"totalPrice: total stay price. "
+ canonical({"facts": visible, "stay": context})
)
yield rate_unit
providers = row.get("providers")
if isinstance(providers, list):
for provider in providers:
yield make_unit(
"provider_evidence", entity, property_unit["unit_id"],
provider, context, observation,
)
Incomplete rates remain structured evidence, with no embedding text. That's an intentional eligibility filter, not an invitation to repair the record using the search request.
Additional provider entries receive shared stay context, but no cheapest-rate price, cancellation flag, freebies, or booking link. Their absence doesn't mean the terms are unfavorable. It means this transformation can't establish them.
Deduplicate assertions without deleting observations
Deduplicating by hotel name can collapse unrelated properties. Deduplicating by hotel identifier alone can erase rate changes.
Here, exact property versions can collapse while distinct offer evidence survives. Collection timestamps stay outside the content identifier, so a repeated observation doesn't automatically create another embedding.
This cell merges duplicate units, preserves their provenance, and writes the private corpus:
unique_units = {}
for item in items:
for candidate in units_for(item):
existing = unique_units.get(candidate["unit_id"])
if existing is None:
unique_units[candidate["unit_id"]] = candidate
else:
for observation in candidate["observations"]:
if observation not in existing["observations"]:
existing["observations"].append(observation)
with open("hotel-corpus.jsonl", "w", encoding="utf-8") as destination:
for unit in unique_units.values():
destination.write(canonical(unit) + "\n")
This is conservative deduplication. Changed amenity ordering or differently formatted prices can retain separate units. Normalize those only after deciding which differences your application considers equivalent.
The in-memory map suits a bounded collection. For sustained ingestion, keep the same identity policy in durable storage and batch writes.
What still breaks outside the chunker
Chunk boundaries don't enforce generation behavior. Your answer layer must select an offer unit, cite its identifier, and take its commercial terms from that unit. Property retrieval can enrich the description; it can't authorize a cancellation claim.
A provider list isn't automatically a comparable offer table. Without established nested fields and matching terms, ranking those entries would require assumptions this pipeline deliberately avoids.
Randomly splitting chunks also leaks property language and near-identical offers between training and evaluation. Use split_group to hold a property's units together when evaluating generalization to unseen properties.
For future-rate evaluation, use collection time as the boundary instead. Keep duplicate content and repeated observations under review across that boundary, or yesterday's copy can become tomorrow's suspiciously easy test.
Privacy needs a separate decision. The corpus omits descriptions and images from retrieval text, while booking links, source URLs, and provider blobs remain in restricted evidence. Those values can contain tracking or session material. Review them before exporting, strip query strings and fragments where appropriate, and inspect paths and opaque blobs too.
A cleaned embedding string doesn't make its metadata safe to publish.
Budget the serialization without cutting the offer apart
The worked example is Kayak Flight, Hotel & Cheap Destination Finder.
Our verdict: embed property descriptions separately, and preserve each rate bundle as a unit. The additional provider evidence needs a schema-aware adapter before it earns retrieval text.
This cell measures the actual text serialization and marks oversized units for review:
import tiktoken
encoding = tiktoken.get_encoding("cl100k_base")
token_budget = 1000
token_audit = []
for corpus_unit in unique_units.values():
corpus_text = corpus_unit["text"]
if corpus_text is None:
continue
token_count = len(encoding.encode(corpus_text, disallowed_special=()))
token_audit.append({
"unit_id": corpus_unit["unit_id"],
"unit_type": corpus_unit["unit_type"],
"tokens": token_count,
"over_budget": token_count > token_budget,
})
The audit produces values for your corpus; it doesn't establish savings in advance. Use your embedding model's tokenizer when choosing the production budget.
Avoid truncating an oversized rate string. Losing the end of a cancellation statement is a remarkably efficient way to reverse its meaning.
Property facts and offers can also follow different refresh policies. Repeated property descriptions need not consume another embedding merely because a price observation changed.
Reproduce the boundary
Install apify-client and tiktoken, set APIFY_TOKEN, and execute the Python cells in order.
Inspect hotel-corpus.jsonl and token_audit. Check that every eligible rate retains its provider and supplied stay context, then verify that additional provider evidence received no inherited cheapest-rate terms.
Use this exact Example input for the collection:
{
"mode": "searchHotels",
"site": "kayak.com",
"destination": "London",
"departDate": "2026-12-10",
"returnDate": "2026-12-17",
"adults": 2,
"rooms": 1,
"hotelSortBy": "price_low",
"maxItems": 40
}
Drafted with AI assistance and reviewed for accuracy.
Top comments (1)
The boundary rule is the whole game here — "rate X with cancellation terms Y" is only trustworthy if X and Y were extracted together and stored together. The failure I see most in document pipelines is the same join happening silently one level down: a table split across two PDF pages gets reassembled as one row, and the price from page 1 ends up wearing the cancellation terms from page 2. Same unsupported join, no error raised.
The check that catches it: for every retrieved rate unit, verify it carries its provider and stay context (your reproduce step does this), and add one more field — the source page. In PDF work I keep per-page provenance on every extracted unit: which page it came from, and whether that page had a real text layer or went through OCR — so a chunk can never silently claim text from a page it didn't come from. I built that rule into pdf-slice (github.com/kamalmosadegh/pdf-slice) after a scanned page indexed as empty while the rest of the document looked fine — the retrieval looked healthy and the answer was wrong.
One number to watch: your 1000-token budget truncates oversized rate strings, and the tail of a rate string is usually where the cancellation statement lives. I'd log how many units hit the truncation path — your token_audit is already counting tokens, so it's one extra counter — rather than trusting the truncated text. If it's more than a handful of units, the corpus is silently losing the exact field your evaluation checks.