emp3hack icon

Notebook product assitant

emp3hack | PRO | 07/11/23 01:28:35 PM UTC | 0 ⭐ | 439 👁️ | Never ⏰ | []
text |

7.02 KB

|

None

|

0 👍

/

0 👎

# L5 Process Inputs: Chaining Prompts
  ## Setup
#### Load the API key and relevant Python libaries.
In this course, we've provided some code that loads the OpenAI API key for you.
 import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
 openai.api_key  = os.environ['OPENAI_API_KEY']
 def get_completion_from_messages(messages, 
                                 model="gpt-3.5-turbo", 
                                 temperature=0, 
                                 max_tokens=500):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, 
        max_tokens=max_tokens, 
    )
    return response.choices[0].message["content"]
 ## Implement a complex task with multiple prompts
 ### Extract relevant product and category names
 delimiter = "####"
system_message = f"""
You will be provided with customer service queries. \
The customer service query will be delimited with \
{delimiter} characters.
Output a python list of objects, where each object has \
the following format:
    'category': <one of ovens, \
    Washer dryer, \
    Televisions and Home Theater Systems, \
    Gaming Consoles and Accessories, 
    Audio Equipment, Cameras and Camcorders>,
OR
    'products': <a list of products that must \
    be found in the allowed products below>
 Where the categories and products must be found in \
the customer service query.
If a product is mentioned, it must be associated with \
the correct category in the allowed products list below.
If no products or categories are found, output an \
empty list.
 Allowed products: 
 ovens category:
Omnichef Galileo Oven
 Washer dryer:
Omnichef Galileo Oven
 Televisions and Home Theater Systems category:
CineView 4K TV
SoundMax Home Theater
CineView 8K TV
SoundMax Soundbar
CineView OLED TV
 Gaming Consoles and Accessories category:
GameSphere X
ProGamer Controller
GameSphere Y
ProGamer Racing Wheel
GameSphere VR Headset
 Audio Equipment category:
AudioPhonic Noise-Canceling Headphones
WaveSound Bluetooth Speaker
AudioPhonic True Wireless Earbuds
WaveSound Soundbar
AudioPhonic Turntable
 Cameras and Camcorders category:
FotoSnap DSLR Camera
ActionCam 4K
FotoSnap Mirrorless Camera
ZoomMaster Camcorder
FotoSnap Instant Camera
 Only output the list of objects, with nothing else.
"""
user_message_1 = f"""
 tell me about the Omnichef Galileo Oven . \
 Also tell me about other products """
messages =  [  
{'role':'system', 
 'content': system_message},    
{'role':'user', 
 'content': f"{delimiter}{user_message_1}{delimiter}"},  
] 
category_and_product_response_1 = get_completion_from_messages(messages)
print(category_and_product_response_1)
 user_message_2 = f"""
my router isn't working"""
messages =  [  
{'role':'system',
 'content': system_message},    
{'role':'user',
 'content': f"{delimiter}{user_message_2}{delimiter}"},  
] 
response = get_completion_from_messages(messages)
print(response)
 ### Retrieve detailed product information for extracted products and categories
 products = {
    "Omnichef Galileo Oven": {
        "name": "Wi-Fi Omnichef Galileo Oven",
        "category": "ovens",
        "brand": "Smeg",
        "model_number": "SO6606WAPNR",
        "warranty": "4 year",
        "rating": 5.0,
        "features": ["SmegConnect", "vapor clean", "Galileo Multicooking"],
        "description": "Compact oven that combines traditional, steam and microwave cooking, to experiment new opportunities in the kitchen and achieve professional results right from home",
        "price": 4799.99
    },
    "Free-standing washer dryer": {
        "name": "Free-standing washer dryer",
        "category": "Washer dryer",
        "brand": "Smeg",
        "model_number": "LSF147E",
        "warranty": "2 years",
        "rating": 4.7,
        "features": ["1400rpm", "15 programs", "Drying function", "LED display"],
        "description": "A high-performance gaming laptop for an immersive experience.",
        "price": 1199.99
    },
 }
 def get_product_by_name(name):
    return products.get(name, None)
 def get_products_by_category(category):
    return [product for product in products.values() if product["category"] == category]
 print(get_product_by_name("Free-standing washer dryer"))
 print(get_products_by_category("Washer dryer"))
 print(user_message_1)
 print(category_and_product_response_1)
 ### Read Python string into Python list of dictionaries
 import json 
 def read_string_to_list(input_string):
    if input_string is None:
        return None
     try:
        input_string = input_string.replace("'", "\"")  # Replace single quotes with double quotes for valid JSON
        data = json.loads(input_string)
        return data
    except json.JSONDecodeError:
        print("Error: Invalid JSON string")
        return None   
  category_and_product_list = read_string_to_list(category_and_product_response_1)
print(category_and_product_list)
 #### Retrieve detailed product information for the relevant products and categories
 def generate_output_string(data_list):
    output_string = ""
     if data_list is None:
        return output_string
     for data in data_list:
        try:
            if "products" in data:
                products_list = data["products"]
                for product_name in products_list:
                    product = get_product_by_name(product_name)
                    if product:
                        output_string += json.dumps(product, indent=4) + "\n"
                    else:
                        print(f"Error: Product '{product_name}' not found")
            elif "category" in data:
                category_name = data["category"]
                category_products = get_products_by_category(category_name)
                for product in category_products:
                    output_string += json.dumps(product, indent=4) + "\n"
            else:
                print("Error: Invalid object format")
        except Exception as e:
            print(f"Error: {e}")
     return output_string 
 product_information_for_user_message_1 = generate_output_string(category_and_product_list)
print(product_information_for_user_message_1)
 ### Generate answer to user query based on detailed product information
 system_message = f"""
You are a customer service assistant for a \
large appliance manufacturer. \
Respond in a friendly and helpful tone, \
with very concise answers. \
Make sure to ask the user relevant follow up questions.
"""
user_message_1 = f"""
tell me about the Omnichef Galileo Oven and \
the Free-standing washer dryer."""
messages =  [  
{'role':'system',
 'content': system_message},   
{'role':'user',
 'content': user_message_1},  
{'role':'assistant',
 'content': f"""Relevant product information:\n\
 {product_information_for_user_message_1}"""},   
]
final_response = get_completion_from_messages(messages)
print(final_response)

Comments