newsmode
search
Меню
arrow_back Назад

Expanding – Hamel’s Blog - Hamel Husain

auto_awesomeКраткое саммари

Статья из курса Hamel Husain по промпт-инжинирингу посвящена технике «расширения» (Expanding) — генерации персонализированных писем службы поддержки на основе отзывов клиентов. Показан пример использования OpenAI API (модель gpt-3.5-turbo) для автоматического создания ответного письма, учитывающего тональность отзыва: при негативном — извинение и предложение обратиться в поддержку, при позитивном — благодарность. Демонстрируется, как параметр temperature влияет на вариативность генерируемого ответа, и подчёркивается важность указания модели использовать конкретные детали из отзыва клиента.

Generate customer service emails that are tailored to each customer’s review.

Генерация писем службы поддержки, персонализированных под отзыв каждого клиента.

Setup

Подготовка

import openai import os from dotenv import load_dotenv, find_dotenv _ = load_dotenv(find_dotenv()) # read local .env file openai.api_key = os.getenv('OPENAI_API_KEY')

import openai import os from dotenv import load_dotenv, find_dotenv _ = load_dotenv(find_dotenv()) # read local .env file openai.api_key = os.getenv('OPENAI_API_KEY')

def get_completion(prompt, model="gpt-3.5-turbo",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature, # this is the degree of randomness of the model's output ) return response.choices[0].message["content"]

def get_completion(prompt, model="gpt-3.5-turbo",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=temperature, # this is the degree of randomness of the model's output ) return response.choices[0].message["content"]

Customize the automated reply to a customer email

Настройка автоматического ответа на письмо клиента

# given the sentiment from the lesson on "inferring", # and the original customer message, customize the email sentiment = "negative" # review for a blender review = f""" So, they still had the 17 piece system on seasonal \ sale for around $49 in the month of November, about \ half off, but for some reason (call it price gouging) \ around the second week of December the prices all went \ up to about anywhere from between $70-$89 for the same \ system. And the 11 piece system went up around $10 or \ so in price also from the earlier sale price of $29. \ So it looks okay, but if you look at the base, the part \ where the blade locks into place doesn’t look as good \ as in previous editions from a few years ago, but I \ plan to be very gentle with it (example, I crush \ very hard items like beans, ice, rice, etc. in the \ blender first then pulverize them in the serving size \ I want in the blender then switch to the whipping \ blade for a finer flour, and use the cross cutting blade \ first when making smoothies, then use the flat blade \ if I need them finer/less pulpy). Special tip when making \ smoothies, finely cut and freeze the fruits and \ vegetables (if using spinach-lightly stew soften the \ spinach then freeze until ready for use-and if making \ sorbet, use a small to medium sized food processor) \ that you plan to use that way you can avoid adding so \ much ice if at all-when making your smoothie. \ After about a year, the motor was making a funny noise. \ I called customer service but the warranty expired \ already, so I had to buy another one. FYI: The overall \ quality has gone done in these types of products, so \ they are kind of counting on brand recognition and \ consumer loyalty to maintain sales. Got it in about \ two days. """

# на основе тональности из урока «Извлечение выводов», # и исходного сообщения клиента, персонализируем письмо sentiment = "negative" # отзыв на блендер review = f""" Итак, набор из 17 предметов всё ещё продавался на сезонной \ распродаже примерно за $49 в ноябре, то есть \ примерно за полцены, но по какой-то причине (назовём это завышением цен) \ примерно на второй неделе декабря цены взлетели \ до $70–$89 за тот же \ набор. А набор из 11 предметов подорожал примерно на $10 \ по сравнению с прежней акционной ценой в $29. \ В целом выглядит нормально, но если посмотреть на основание — ту часть, \ где нож фиксируется на месте — оно выглядит не так хорошо, \ как в предыдущих моделях несколько лет назад, но я \ планирую обращаться с ним очень бережно (например, я сначала \ измельчаю твёрдые продукты вроде бобов, льда, риса и т. д. в \ блендере, затем перемалываю их до нужной порции \ в блендере, потом переключаюсь на взбивающий \ нож для более тонкого помола, а при приготовлении смузи сначала использую перекрёстный нож, \ затем плоский нож, \ если нужна более мелкая/менее волокнистая консистенция). Совет для приготовления \ смузи: мелко нарежьте и заморозьте фрукты и \ овощи (если используете шпинат — слегка потушите его, чтобы \ размягчить, затем заморозьте до использования; а если готовите \ сорбет, используйте небольшой или средний кухонный комбайн) — \ так вы сможете не добавлять столько \ льда (или вообще обойтись без него) при приготовлении смузи. \ Примерно через год мотор начал издавать странный звук. \ Я позвонил в службу поддержки, но гарантия уже \ истекла, поэтому мне пришлось купить новый. К сведению: общее \ качество таких продуктов снизилось, и \ производители, похоже, рассчитывают на узнаваемость бренда и \ лояльность потребителей для поддержания продаж. Доставили примерно \ за два дня. """

prompt = f""" You are a customer service AI assistant. Your task is to send an email reply to a valued customer. Given the customer email delimited by ```, \ Generate a reply to thank the customer for their review. If the sentiment is positive or neutral, thank them for \ their review. If the sentiment is negative, apologize and suggest that \ they can reach out to customer service. Make sure to use specific details from the review. Write in a concise and professional tone. Sign the email as `AI customer agent`. Customer review: ```{review}``` Review sentiment: {sentiment} """ response = get_completion(prompt) print(response)

prompt = f""" Вы — ИИ-ассистент службы поддержки клиентов. Ваша задача — отправить ответное письмо ценному клиенту. На основе письма клиента, ограниченного ```, \ сгенерируйте ответ с благодарностью за отзыв. Если тональность позитивная или нейтральная, поблагодарите за \ отзыв. Если тональность негативная, извинитесь и предложите \ обратиться в службу поддержки. Обязательно используйте конкретные детали из отзыва. Пишите в лаконичном и профессиональном тоне. Подпишите письмо как `AI customer agent`. Отзыв клиента: ```{review}``` Тональность отзыва: {sentiment} """ response = get_completion(prompt) print(response)

Remind the model to use details from the customer’s email

Напомните модели использовать детали из письма клиента

prompt = f""" You are a customer service AI assistant. Your task is to send an email reply to a valued customer. Given the customer email delimited by ```, \ Generate a reply to thank the customer for their review. If the sentiment is positive or neutral, thank them for \ their review. If the sentiment is negative, apologize and suggest that \ they can reach out to customer service. Make sure to use specific details from the review. Write in a concise and professional tone. Sign the email as `AI customer agent`. Customer review: ```{review}``` Review sentiment: {sentiment} """ response = get_completion(prompt, temperature=0.7) print(response)

prompt = f""" Вы — ИИ-ассистент службы поддержки клиентов. Ваша задача — отправить ответное письмо ценному клиенту. На основе письма клиента, ограниченного ```, \ сгенерируйте ответ с благодарностью за отзыв. Если тональность позитивная или нейтральная, поблагодарите за \ отзыв. Если тональность негативная, извинитесь и предложите \ обратиться в службу поддержки. Обязательно используйте конкретные детали из отзыва. Пишите в лаконичном и профессиональном тоне. Подпишите письмо как `AI customer agent`. Отзыв клиента: ```{review}``` Тональность отзыва: {sentiment} """ response = get_completion(prompt, temperature=0.7) print(response)

Try experimenting on your own!

Попробуйте поэкспериментировать самостоятельно!