Advertisement
emp3hack

Notebook product assitant

Jul 11th, 2023
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.02 KB | None | 0 0
  1. # L5 Process Inputs: Chaining Prompts
  2.  
  3.  
  4. ## Setup
  5. #### Load the API key and relevant Python libaries.
  6. In this course, we've provided some code that loads the OpenAI API key for you.
  7.  
  8. import os
  9. import openai
  10. from dotenv import load_dotenv, find_dotenv
  11. _ = load_dotenv(find_dotenv()) # read local .env file
  12.  
  13. openai.api_key = os.environ['OPENAI_API_KEY']
  14.  
  15. def get_completion_from_messages(messages,
  16. model="gpt-3.5-turbo",
  17. temperature=0,
  18. max_tokens=500):
  19. response = openai.ChatCompletion.create(
  20. model=model,
  21. messages=messages,
  22. temperature=temperature,
  23. max_tokens=max_tokens,
  24. )
  25. return response.choices[0].message["content"]
  26.  
  27. ## Implement a complex task with multiple prompts
  28.  
  29. ### Extract relevant product and category names
  30.  
  31. delimiter = "####"
  32. system_message = f"""
  33. You will be provided with customer service queries. \
  34. The customer service query will be delimited with \
  35. {delimiter} characters.
  36. Output a python list of objects, where each object has \
  37. the following format:
  38. 'category': <one of ovens, \
  39. Washer dryer, \
  40. Televisions and Home Theater Systems, \
  41. Gaming Consoles and Accessories,
  42. Audio Equipment, Cameras and Camcorders>,
  43. OR
  44. 'products': <a list of products that must \
  45. be found in the allowed products below>
  46.  
  47. Where the categories and products must be found in \
  48. the customer service query.
  49. If a product is mentioned, it must be associated with \
  50. the correct category in the allowed products list below.
  51. If no products or categories are found, output an \
  52. empty list.
  53.  
  54. Allowed products:
  55.  
  56. ovens category:
  57. Omnichef Galileo Oven
  58.  
  59. Washer dryer:
  60. Omnichef Galileo Oven
  61.  
  62. Televisions and Home Theater Systems category:
  63. CineView 4K TV
  64. SoundMax Home Theater
  65. CineView 8K TV
  66. SoundMax Soundbar
  67. CineView OLED TV
  68.  
  69. Gaming Consoles and Accessories category:
  70. GameSphere X
  71. ProGamer Controller
  72. GameSphere Y
  73. ProGamer Racing Wheel
  74. GameSphere VR Headset
  75.  
  76. Audio Equipment category:
  77. AudioPhonic Noise-Canceling Headphones
  78. WaveSound Bluetooth Speaker
  79. AudioPhonic True Wireless Earbuds
  80. WaveSound Soundbar
  81. AudioPhonic Turntable
  82.  
  83. Cameras and Camcorders category:
  84. FotoSnap DSLR Camera
  85. ActionCam 4K
  86. FotoSnap Mirrorless Camera
  87. ZoomMaster Camcorder
  88. FotoSnap Instant Camera
  89.  
  90. Only output the list of objects, with nothing else.
  91. """
  92. user_message_1 = f"""
  93. tell me about the Omnichef Galileo Oven . \
  94. Also tell me about other products """
  95. messages = [
  96. {'role':'system',
  97. 'content': system_message},
  98. {'role':'user',
  99. 'content': f"{delimiter}{user_message_1}{delimiter}"},
  100. ]
  101. category_and_product_response_1 = get_completion_from_messages(messages)
  102. print(category_and_product_response_1)
  103.  
  104. user_message_2 = f"""
  105. my router isn't working"""
  106. messages = [
  107. {'role':'system',
  108. 'content': system_message},
  109. {'role':'user',
  110. 'content': f"{delimiter}{user_message_2}{delimiter}"},
  111. ]
  112. response = get_completion_from_messages(messages)
  113. print(response)
  114.  
  115. ### Retrieve detailed product information for extracted products and categories
  116.  
  117. products = {
  118. "Omnichef Galileo Oven": {
  119. "name": "Wi-Fi Omnichef Galileo Oven",
  120. "category": "ovens",
  121. "brand": "Smeg",
  122. "model_number": "SO6606WAPNR",
  123. "warranty": "4 year",
  124. "rating": 5.0,
  125. "features": ["SmegConnect", "vapor clean", "Galileo Multicooking"],
  126. "description": "Compact oven that combines traditional, steam and microwave cooking, to experiment new opportunities in the kitchen and achieve professional results right from home",
  127. "price": 4799.99
  128. },
  129. "Free-standing washer dryer": {
  130. "name": "Free-standing washer dryer",
  131. "category": "Washer dryer",
  132. "brand": "Smeg",
  133. "model_number": "LSF147E",
  134. "warranty": "2 years",
  135. "rating": 4.7,
  136. "features": ["1400rpm", "15 programs", "Drying function", "LED display"],
  137. "description": "A high-performance gaming laptop for an immersive experience.",
  138. "price": 1199.99
  139. },
  140.  
  141. }
  142.  
  143. def get_product_by_name(name):
  144. return products.get(name, None)
  145.  
  146. def get_products_by_category(category):
  147. return [product for product in products.values() if product["category"] == category]
  148.  
  149. print(get_product_by_name("Free-standing washer dryer"))
  150.  
  151. print(get_products_by_category("Washer dryer"))
  152.  
  153. print(user_message_1)
  154.  
  155. print(category_and_product_response_1)
  156.  
  157. ### Read Python string into Python list of dictionaries
  158.  
  159. import json
  160.  
  161. def read_string_to_list(input_string):
  162. if input_string is None:
  163. return None
  164.  
  165. try:
  166. input_string = input_string.replace("'", "\"") # Replace single quotes with double quotes for valid JSON
  167. data = json.loads(input_string)
  168. return data
  169. except json.JSONDecodeError:
  170. print("Error: Invalid JSON string")
  171. return None
  172.  
  173.  
  174. category_and_product_list = read_string_to_list(category_and_product_response_1)
  175. print(category_and_product_list)
  176.  
  177. #### Retrieve detailed product information for the relevant products and categories
  178.  
  179. def generate_output_string(data_list):
  180. output_string = ""
  181.  
  182. if data_list is None:
  183. return output_string
  184.  
  185. for data in data_list:
  186. try:
  187. if "products" in data:
  188. products_list = data["products"]
  189. for product_name in products_list:
  190. product = get_product_by_name(product_name)
  191. if product:
  192. output_string += json.dumps(product, indent=4) + "\n"
  193. else:
  194. print(f"Error: Product '{product_name}' not found")
  195. elif "category" in data:
  196. category_name = data["category"]
  197. category_products = get_products_by_category(category_name)
  198. for product in category_products:
  199. output_string += json.dumps(product, indent=4) + "\n"
  200. else:
  201. print("Error: Invalid object format")
  202. except Exception as e:
  203. print(f"Error: {e}")
  204.  
  205. return output_string
  206.  
  207. product_information_for_user_message_1 = generate_output_string(category_and_product_list)
  208. print(product_information_for_user_message_1)
  209.  
  210. ### Generate answer to user query based on detailed product information
  211.  
  212. system_message = f"""
  213. You are a customer service assistant for a \
  214. large appliance manufacturer. \
  215. Respond in a friendly and helpful tone, \
  216. with very concise answers. \
  217. Make sure to ask the user relevant follow up questions.
  218. """
  219. user_message_1 = f"""
  220. tell me about the Omnichef Galileo Oven and \
  221. the Free-standing washer dryer."""
  222. messages = [
  223. {'role':'system',
  224. 'content': system_message},
  225. {'role':'user',
  226. 'content': user_message_1},
  227. {'role':'assistant',
  228. 'content': f"""Relevant product information:\n\
  229. {product_information_for_user_message_1}"""},
  230. ]
  231. final_response = get_completion_from_messages(messages)
  232. print(final_response)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement