Complete "Structuring Property Criteria and Listing Data" first to unlock this lesson.Go to previous lesson

Scope and Goal

A property-search agent is useful only when it can turn a user request into a controlled retrieval workflow. The agent should not answer from memory or invent listings. It should call a retrieval tool, receive structured property records, apply explicit filters, rank the remaining results, and return an organized shortlist with reasons for relevance.

This lesson focuses on the connection between an agent and a listing retrieval tool. The main pattern is simple: normalize the user request into search criteria, validate the criteria, retrieve matching records, rank them, and format the output for the next agent step or for the user interface. A production system may retrieve data from a database, a partner API, or a search index, but the interface should remain stable.

The most important design decision is separating retrieval from reasoning. Retrieval answers which records match the constraints. The agent then explains why those records are relevant, identifies missing information, and asks a follow-up question when the query is too broad or invalid.

Define a Reliable Tool Contract

A tool contract describes the input fields the agent is allowed to send and the output shape it can expect. For example, a normalized request can contain a city, minimum price, maximum price, minimum bedroom count, property type, and optional preferred features. These fields should have clear types and validation rules.

The agent should not send an unstructured paragraph directly to a database function. Natural language such as I want a family home near downtown under a certain budget must first be converted into explicit values. If the request does not provide a necessary value, the agent should ask for clarification or apply a documented default. It should never silently guess a price limit or location.

A useful output contains the original criteria, a result count, and a list of normalized properties. Each property should include a stable identifier, address or location, price, bedrooms, property type, available features, and a relevance score or match explanation. Stable identifiers are important because later steps may need to retrieve full details, compare properties, or save a shortlist.

Flowchart showing a user request becoming normalized criteria, passing through validation and listing retrieval, then moving into ranking and an organized property shortlist

Build the Retrieval Workflow

The workflow should begin with validation. Check that required fields exist, numeric values are actually numeric, the minimum price is not greater than the maximum price, and categorical values such as property type are supported. Validation errors should be explicit enough for the agent to recover. A message such as max_price must be greater than or equal to min_price is more useful than a generic failure.

After validation, apply hard filters first. City, price range, minimum bedrooms, and property type are usually hard constraints because violating them makes a property unsuitable. Only after this filtering step should the workflow calculate relevance. This prevents an attractive but invalid listing from ranking above a property that actually satisfies the request.

Ranking should be transparent. In a basic workflow, a property can receive points for matching preferred features, falling comfortably inside the budget, or meeting more than the minimum bedroom requirement. The score is not a replacement for business rules. It is an ordering mechanism that helps the agent present a manageable shortlist.

Runnable Python Example

The following program uses an in-memory listing collection so it can run without external credentials or undocumented services. The retrieval function represents the boundary where a real database or listing API can later be connected. Its input is a normalized criteria dictionary. Its output is an organized dictionary containing the count and ranked properties.

python
from typing import Any
LISTINGS = [
{
'id': 'AUS-101',
'city': 'Austin',
'price': 425000,
'bedrooms': 3,
'property_type': 'house',
'features': ['garage', 'garden', 'home office']
},
{
'id': 'AUS-204',
'city': 'Austin',
'price': 510000,
'bedrooms': 4,
'property_type': 'house',
'features': ['garage', 'pool', 'home office']
},
{
'id': 'DAL-309',
'city': 'Dallas',
'price': 390000,
'bedrooms': 3,
'property_type': 'house',
'features': ['garage', 'garden']
}
]
def validate_criteria(criteria: dict[str, Any]) -> None:
required = [
'city',
'min_price',
'max_price',
'min_bedrooms',
'property_type'
]
missing = [key for key in required if key not in criteria]
if missing:
raise ValueError(f'Missing required fields: {", ".join(missing)}')
if not isinstance(criteria['city'], str) or not criteria['city'].strip():
raise ValueError('city must be a non-empty string')
numeric_fields = ['min_price', 'max_price', 'min_bedrooms']
for field in numeric_fields:
if not isinstance(criteria[field], (int, float)):
raise ValueError(f'{field} must be numeric')
if criteria['min_price'] < 0 or criteria['max_price'] < 0:
raise ValueError('Prices cannot be negative')
if criteria['min_price'] > criteria['max_price']:
raise ValueError('max_price must be greater than or equal to min_price')
if criteria['min_bedrooms'] < 0:
raise ValueError('min_bedrooms cannot be negative')
def retrieve_and_rank(criteria: dict[str, Any]) -> dict[str, Any]:
validate_criteria(criteria)
preferred_features = criteria.get('preferred_features', [])
matches = []
for listing in LISTINGS:
same_city = listing['city'].lower() == criteria['city'].lower()
in_budget = criteria['min_price'] <= listing['price'] <= criteria['max_price']
enough_bedrooms = listing['bedrooms'] >= criteria['min_bedrooms']
right_type = listing['property_type'].lower() == criteria['property_type'].lower()
if not (same_city and in_budget and enough_bedrooms and right_type):
continue
matched_features = [
feature for feature in preferred_features
if feature in listing['features']
]
score = 70 + (10 * len(matched_features))
if listing['bedrooms'] > criteria['min_bedrooms']:
score += 5
matches.append({
'id': listing['id'],
'city': listing['city'],
'price': listing['price'],
'bedrooms': listing['bedrooms'],
'property_type': listing['property_type'],
'matched_features': matched_features,
'relevance_score': score
})
matches.sort(key=lambda item: (-item['relevance_score'], item['price']))
return {
'criteria': criteria,
'count': len(matches),
'properties': matches
}
if __name__ == '__main__':
criteria = {
'city': 'Austin',
'min_price': 400000,
'max_price': 550000,
'min_bedrooms': 3,
'property_type': 'house',
'preferred_features': ['garage', 'home office']
}
try:
result = retrieve_and_rank(criteria)
print(f"Found {result['count']} matching properties")
for property_item in result['properties']:
features = ', '.join(property_item['matched_features']) or 'none'
print(
f"{property_item['id']} | "
f"${property_item['price']:,} | "
f"score {property_item['relevance_score']} | "
f"matched features: {features}"
)
except ValueError as error:
print(f'Input error: {error}')

For the sample input, the program returns two Austin houses within the specified price range and bedroom requirement. The property with both preferred features ranks above the other property. In a real agent, the result object could be passed to a response-generation step that explains the shortlist without changing the retrieved facts.

Connect the Tool to an Agent

When connecting this workflow to an agent framework, expose the retrieval operation as one tool with a documented schema. The agent should decide when to call it, but the tool should own validation and filtering. This creates a clear boundary: the agent interprets intent, while the retrieval layer enforces data rules.

A practical agent sequence is to identify missing constraints, produce normalized criteria, call the retrieval tool, inspect the result count, and choose the next response. If the count is zero, the agent should explain which hard constraints produced no matches and ask whether the user wants to widen the budget, change the location, reduce the bedroom requirement, or remove a preferred feature.

If the result count is very large, the agent should not dump every record. It should either apply a reasonable ranking limit or ask for another constraint. The limit should be explicit and configurable. Returning a short list with reasons is more useful than returning an unstructured data payload.

Common Failures and Summary

One common failure is allowing the model to invent unsupported filters such as school quality, commute time, or renovation status when the retrieval source does not provide those fields. The tool should reject unknown fields or clearly mark them as unsupported. Another failure is mixing hard constraints and soft preferences. A preferred feature should affect ranking, but it should not exclude every property unless the user explicitly made it mandatory.

Empty results also require careful handling. An empty list is not a technical error, but it is a meaningful search outcome. The agent should distinguish no matches from a failed connector, malformed response, timeout, or authentication problem. These cases require different user messages and different recovery actions.

The core pattern is a validated retrieval tool followed by transparent ranking and structured presentation. Keep the tool contract stable, preserve listing identifiers, expose clear errors, and make every ranking reason traceable to the input criteria. This foundation can later support market analysis, comparable-property selection, price benchmarking, and follow-up searches without changing the basic workflow.

Lesson practice

Lesson Checkpoint

Review what you learned and get feedback on your work.

0/1
Answered · 0/1