in projects/conversational-commerce-agent/conversational-agent-examples/assets/apparel-search-cf/main.py [0:0]
def search():
"""
returns products based on a search query from product catalog.
"""
app.logger.debug("REACHED /SEARCH")
request_json = request.get_json(silent=False)
app.logger.debug("REQUEST: %s", request_json)
# Capture the user's search query.
query = request_json["search"]
start_index = request_json[
"offset"
] # index number from which the products should be returned
session_id = str(uuid.uuid4())
visitorid = session_id
placement = "default_search" # A search model name which was configured while creating product catalog
# Retail API search request
search_request = {
"placement": "projects/"
+ PROJECT_NUMBER
+ "/locations/global/catalogs/default_catalog/placements/"
+ placement,
"query": query,
"visitor_id": visitorid,
"query_expansion_spec": {"condition": "AUTO"},
}
try:
with telemetry.tool_context_manager(_USER_AGENT):
# Retail Search API call
response = client.search(search_request)
res = MessageToDict(response._pb)
app.logger.debug("RAW RESULT: %s", res["results"])
# extract products based on the offset index from the returned products
if start_index > len(res["results"]) - 1:
return flask.jsonify(
{"message": "No more products available to show"}
)
num_products = 3 # number of products to display in the UI
end_index = start_index + num_products
end_index = (
end_index
if len(res["results"]) > end_index
else len(res["results"])
)
products = res["results"][start_index:end_index]
# remove unnecessary fields from product's data
data = get_minimal_payload(products)
app.logger.debug("RESULT: %s", data)
# Transform the product's data into a customer template format to display in the UI
response = generate_custom_template(data)
return flask.jsonify(response)
except Exception as e:
app.logger.warning("Retail Search Exception: %s", e)
return flask.jsonify({})