| 10 | |
| 11 | |
| 12 | def build_tool(config) -> Tool: |
| 13 | tool = Tool( |
| 14 | "walmart Info", |
| 15 | "Query about information about retail commodity on Walmart Platform.", |
| 16 | name_for_model="walmart", |
| 17 | description_for_model="""This is a plugin for look up real walmart infomation. Results from this API are inaccessible for users. Please organize and re-present them.""", |
| 18 | logo_url="https://your-app-url.com/.well-known/logo.png", |
| 19 | contact_email="hello@contact.com", |
| 20 | legal_info_url="hello@legal.com" |
| 21 | ) |
| 22 | |
| 23 | SERPAPI_KEY = config["subscription_key"] |
| 24 | |
| 25 | @tool.get("/ItemQuery") |
| 26 | def ItemQuery( |
| 27 | item: str, |
| 28 | option_num: Optional[int] = 3, |
| 29 | ): |
| 30 | """ |
| 31 | This API gather retail information about queried items at walmart |
| 32 | :param item: product name presented as string. |
| 33 | :param option_num: the number of items presented for each queried item. |
| 34 | :return: a dict walmart retail information about queried items. |
| 35 | """ |
| 36 | |
| 37 | try: |
| 38 | |
| 39 | params = { |
| 40 | "engine": "walmart", |
| 41 | "query": item, |
| 42 | "api_key": SERPAPI_KEY, |
| 43 | } |
| 44 | search = GoogleSearch(params) |
| 45 | results = search.get_dict() |
| 46 | organic_results = results["organic_results"] |
| 47 | |
| 48 | item_res = [] |
| 49 | for idx in range(min(option_num, len(results["organic_results"]))): |
| 50 | item_res.append({}) |
| 51 | item_res[idx]["name"] = organic_results[idx]["title"] |
| 52 | item_res[idx]["description"] = organic_results[idx]["description"] |
| 53 | item_res[idx]["price"] = organic_results[idx]["primary_offer"]["offer_price"] |
| 54 | item_res[idx]["price_unit"] = organic_results[idx]["price_per_unit"]["unit"] |
| 55 | item_res[idx]["url"] = organic_results[idx]["product_page_url"] |
| 56 | item_res[idx]["rating"] = organic_results[idx]["rating"] |
| 57 | item_res[idx]["seller_name"] = organic_results[idx]["seller_name"] |
| 58 | |
| 59 | return json.dumps(item_res) |
| 60 | |
| 61 | except Exception: # Handle response error exceptions |
| 62 | return {"error": "Response error."} |
| 63 | |
| 64 | return tool |