Scope and Architecture

A production-ready real estate agent needs controlled access to current property data, not permission to improvise listings from model knowledge. In this lesson, the agent interprets a buyer’s request, calls a property-search tool with validated criteria, and returns a predictable response. A separate lead-capture step records contact details only after the person agrees to follow-up. The model can decide when a tool is useful, but application code remains responsible for data access, validation, authorization, and persistence.

Keep these responsibilities distinct. The language model handles natural-language understanding and explanation. The search tool reads a defined data source and applies filters. A structured response contract tells downstream code whether the agent found properties, needs clarification, or encountered a problem. Lead capture writes an explicit, consent-backed record. This separation makes behavior testable and gives operators a clear place to enforce business rules.

Treat property data and lead data as different trust domains. Property records may include listing identifiers, price, location, status, and features. Lead records contain personal information and should be collected only for a stated purpose. Do not send a complete customer record to a model when a minimal set of search criteria is sufficient.

Define the Contracts

Start by deciding what the agent may accept and return. A buyer request can include a city or neighborhood, maximum budget, minimum bedrooms, property type, and selected amenities. Normalize values such as currency and bedroom counts before calling the search tool. If a required constraint is unclear, ask a focused question instead of silently guessing. For instance, “under 700,000” should be represented as a maximum price, while an ambiguous “around 700” may need clarification about currency or units.

The response contract should distinguish outcomes instead of returning an unstructured paragraph. A successful search includes a short explanation and a bounded list of matching properties. A clarification outcome contains the missing question and no fabricated result. A tool error reports that the search could not be completed and does not claim that no properties exist. This distinction is important: an empty result is a valid search outcome, while a database timeout is a failure.

Flow diagram showing buyer request validation, property search tool, structured outcomes for matches, no matches, clarification, and tool failure, followed by consent-gated lead capture

Implement a Local Search Tool

The following Python example is deliberately independent of any vendor-specific agent SDK. It demonstrates the application-side boundary: input validation, a search function over a small fixture, and a structured result. In a deployed system, replace the fixture with an authenticated database or listing-service adapter, keeping the same contract and tests. The example runs with Python 3.10 or later and uses only the standard library.

The input is a dictionary containing a city and maximum price, with optional bedroom and property-type filters. The output is a dictionary with a status and matching records. The tool returns only fields needed for comparison, not internal notes or seller contact information. The fixture is illustrative and must not be presented to users as live inventory.

python
from typing import Any
PROPERTIES = [
{"id": "R-101", "city": "Austin", "price": 625000,
"bedrooms": 3, "type": "house", "status": "active"},
{"id": "R-102", "city": "Austin", "price": 710000,
"bedrooms": 4, "type": "house", "status": "active"},
{"id": "R-103", "city": "Austin", "price": 590000,
"bedrooms": 2, "type": "condo", "status": "pending"},
]
def search_properties(criteria: dict[str, Any]) -> dict[str, Any]:
city = criteria.get("city")
max_price = criteria.get("max_price")
min_bedrooms = criteria.get("min_bedrooms", 0)
property_type = criteria.get("property_type")
if not isinstance(city, str) or not city.strip():
return {"status": "needs_clarification", "question": "Which city should I search?"}
if not isinstance(max_price, int) or max_price <= 0:
return {"status": "invalid_input", "message": "max_price must be a positive integer."}
if not isinstance(min_bedrooms, int) or min_bedrooms < 0:
return {"status": "invalid_input", "message": "min_bedrooms must be zero or greater."}
matches = [
{key: item[key] for key in ("id", "city", "price", "bedrooms", "type")}
for item in PROPERTIES
if item["status"] == "active"
and item["city"].casefold() == city.strip().casefold()
and item["price"] <= max_price
and item["bedrooms"] >= min_bedrooms
and (property_type is None or item["type"] == property_type)
]
return {"status": "ok", "properties": matches}
if __name__ == "__main__":
result = search_properties({"city": "Austin", "max_price": 650000, "min_bedrooms": 3})
print(result)

For the sample request, the output has status `ok` and includes R-101 only: R-102 exceeds the budget, while R-103 is not active and has too few bedrooms. The active-status filter is not an optional detail. Without it, an agent could recommend a pending property as available. Real feeds may have stale or conflicting statuses, so production systems should also expose a last-verified timestamp and define how old records can be before they are excluded.

Connect Tool Calling and Structured Outputs

In an agent framework, register the search operation as a tool with a schema that names each argument, its type, and its constraints. Tool calling is a request from the model to execute a specific operation; it is not execution itself. Your application should parse the proposed arguments, validate them, apply the user’s permissions and query limits, and only then invoke the data adapter. Reject unsupported fields rather than passing arbitrary model-generated values to a database query.

Structured outputs constrain the final answer to an agreed shape, such as a status, a list of property summaries, and an optional clarification question. Validate the returned object before displaying or storing it. A schema can prevent missing fields or invalid status names, but it cannot prove that a listed property exists or that its price is current. Verify identifiers and key facts against the search result, and avoid allowing the model to add unverified listings to the response.

Limit tool scope and results. Set a maximum result count, use pagination when needed, and return the minimum fields required for the task. Apply access controls in the data layer rather than relying on the model to honor instructions. Keep a trace of the request, validated arguments, tool outcome, and response status, while excluding secrets and minimizing personal information in logs.

Capture Qualified Leads Safely

A search request is not consent to sales contact. Ask whether the buyer wants follow-up, explain who will contact them and why, then collect only the necessary details, such as name and one preferred contact method. Record the consent decision, timestamp, purpose, and source alongside the lead. If the person declines, continue helping with property search without creating a contact record. Follow applicable privacy, marketing, and retention requirements for the jurisdictions where the service operates.

Use a separate lead-capture operation with explicit inputs, such as name, email or phone, contact preference, and consent. Validate formats and reject an attempt to submit a lead without affirmative consent. Do not infer consent from a positive response to a property recommendation. Avoid putting contact details into search queries or analytics events. If a capture operation fails, tell the user that the search can still continue, and do not claim that the lead was saved.

Test Failures Before Deployment

Test ordinary matches, no active matches, missing city, invalid budget types, and a simulated data-source timeout. Confirm that no-results responses say that no matching active properties were found in the queried source, rather than claiming no such properties exist anywhere. Confirm that timeouts produce an error outcome and never an empty-list answer that could mislead the buyer. Test boundary values such as a listing exactly at the maximum budget and a city with different letter casing.

A common integration mistake is trusting model-proposed tool arguments without application validation. Another is making the final response schema too permissive, allowing a successful status with missing data or an error status that still contains recommendations. Keep schemas narrow and test them with malformed model outputs. Also handle rate limits, unavailable services, and stale inventory explicitly. Before launch, verify that the listing provider permits the intended access and display, and that the system can explain the source and freshness of results.

Operational Checklist

Deploy the search and lead operations behind server-side credentials; never expose database keys or provider tokens to the browser or model prompt. Add timeouts, bounded retries for transient failures, and request limits to prevent expensive or excessive searches. Monitor tool latency, failure rates, empty-result rates, and consent-backed lead submissions. Review traces for quality without retaining unnecessary personal data.

The key design principle is that the agent coordinates trusted operations rather than replacing them. The model interprets intent and presents verified results; tools access property and lead systems under explicit rules; schemas make outcomes predictable; and tests cover failures as well as successful searches. That boundary produces an agent that is easier to audit and less likely to invent inventory, mishandle personal information, or confuse a service outage with a genuine lack of matches.

Lesson practice

Lesson Checkpoint

Review what you learned and get feedback on your work.

0/1
Answered · 0/1