def search_filter()

in projects/conversational-commerce-agent/conversational-agent-examples/assets/apparel-search-cf/main.py [0:0]


def search_filter():
    """
    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']
     # index number from which the products should be returned
    start_index = request_json['offset']
    search_filter = request_json['filter']
    # Workaround that the conversation Agent Tool
    # cannot parse '\"' in request body.
    search_filter = search_filter.replace("^", "\"")
    session_id = str(uuid.uuid4())
    visitorid = session_id
    # A search model name which was configured while creating product catalog
    placement = 'default_search'

    # 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'
        },
        'filter': search_filter
    }
    try:
        # Retail Search API call
        with telemetry.tool_context_manager(_USER_AGENT):
            response = client.search(search_request)
            res = MessageToDict(response._pb)

        # 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

        # b/405944679
        # In our use case, top 3 products always been returned
        # Add a random start index so different product are returned
        if "offset" in request_json:
            start_index = request_json['offset']
        else:
            start_index = 0

        if len(res["results"]) <= num_products:
            start_index = 0
        elif start_index == 0:
            start_index = random.randint(0, len(res["results"])- 1 - num_products)
        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]
        app.logger.debug("RAW RESULTS: %s", res["results"])
        # 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)
        app.logger.debug("response: %s", response)
        return flask.jsonify(response)
    except Exception as e:
        app.logger.warning("Retail Search Exception: %s", e)
        return flask.jsonify({})