Plan with Code (Full Response)
<execute_python>
from tinydb import Query
import re

# 1) Parse constraints from the user_request
# Extract shape keyword (e.g., "round")
shape_match = re.search(r"(round)\s+sunglasses", user_request, re.IGNORECASE)
shape = shape_match.group(1).lower() if shape_match else None

# Extract a maximum price if mentioned (e.g., "under $100")
price_match = re.search(r"under\s*\$?(\d+)", user_request, re.IGNORECASE)
max_price = float(price_match.group(1)) if price_match else None

# 2) Build the TinyDB query conditionally
S = Query()

# Helper for case-insensitive substring match without capturing outer vars
def contains(val, key):
    return key in val.lower()

condition = (S.quantity_in_stock > 0)
if shape:
    shape_cond = (S.name.test(contains, shape)) | (S.description.test(contains, shape))
    condition = condition & shape_cond
if max_price is not None:
    condition = condition & (S.price < max_price)

# 3) Perform the read-only search
results = inventory_tbl.search(condition)

if results:
    # 4a) Success: at least one match
    item = results[0]
    answer_text = f"Yes, we have our {item['name']} round sunglasses for ${item['price']}."
    STATUS = "success"
    print(f"LOG: ACTION=read DRY_RUN=True STATUS={STATUS}")
else:
    # 4b) No match: suggest closest alternative if available
    # Look for any round sunglasses in stock regardless of price
    alt_condition = (S.quantity_in_stock > 0)
    if shape:
        alt_condition = alt_condition & ((S.name.test(contains, shape)) | (S.description.test(contains, shape)))
    alt_results = inventory_tbl.search(alt_condition)
    if alt_results and max_price is not None:
        # pick the cheapest alternative
        alt = sorted(alt_results, key=lambda x: x['price'])[0]
        answer_text = (f"We don’t have round frames under ${int(max_price)} in stock right now, "
                       f"but our {alt['name']} round frame is available at ${alt['price']}.")
    else:
        answer_text = "We don’t have round sunglasses in stock right now—can I help you find another style?"
    STATUS = "no_match"
    print(f"LOG: ACTION=read DRY_RUN=True STATUS={STATUS}")
</execute_python>