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

Inferring – Hamel’s Blog - Hamel Husain

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

Заметка показывает, как извлекать информацию из текстов с помощью LLM на примере отзыва о лампе и новостной статьи. Приведены промпты для определения тональности (positive/negative), списка эмоций, наличия гнева, а также извлечения названия товара и компании (Lumina) в формате JSON. Демонстрируется выполнение нескольких задач одним промптом с возвращением ключей Sentiment, Anger, Item и Brand. Во второй части на примере правительственного опроса (NASA — 95% удовлетворённости, Social Security Administration — 45%) выводятся пять основных тем текста. Финальный пример сопоставляет заранее заданный список тем с текстом и формирует новостной алерт, если статья касается NASA. Весь код использует функцию get_completion поверх openai.ChatCompletion с температурой 0.

Infer sentiment and topics from product reviews and news articles.

Извлечение тональности и тем из отзывов о товарах и новостных статей.

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()) # читаем локальный .env файл openai.api_key = os.getenv('OPENAI_API_KEY')

def get_completion(prompt, model="gpt-3.5-turbo"): messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, # 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"): messages = [{"role": "user", "content": prompt}] response = openai.ChatCompletion.create( model=model, messages=messages, temperature=0, # степень случайности вывода модели ) return response.choices[0].message["content"]

Product review text

Текст отзыва о товаре

lamp_review = """ Needed a nice lamp for my bedroom, and this one had \ additional storage and not too high of a price point. \ Got it fast. The string to our lamp broke during the \ transit and the company happily sent over a new one. \ Came within a few days as well. It was easy to put \ together. I had a missing part, so I contacted their \ support and they very quickly got me the missing piece! \ Lumina seems to me to be a great company that cares \ about their customers and products!! """

lamp_review = """ Нужна была красивая лампа в спальню, и у этой \ было дополнительное место для хранения и невысокая цена. \ Получили быстро. Шнур у лампы порвался при \ транспортировке, и компания с радостью прислала новую. \ Тоже пришла за несколько дней. Лампу было легко \ собрать. Не хватало одной детали, поэтому я связался \ с поддержкой, и они очень быстро прислали недостающую часть! \ Lumina кажется мне отличной компанией, которая заботится \ о своих клиентах и продуктах!! """

Sentiment (positive/negative)

Тональность (positive/negative)

prompt = f""" What is the sentiment of the following product review, which is delimited with triple backticks? Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Какая тональность у следующего отзыва о товаре, который ограничен тройными обратными кавычками? Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" What is the sentiment of the following product review, which is delimited with triple backticks? Give your answer as a single word, either "positive" \ or "negative". Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Какая тональность у следующего отзыва о товаре, который ограничен тройными обратными кавычками? Дай ответ одним словом — либо "positive" \ либо "negative". Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

Identify types of emotions

Определение типов эмоций

prompt = f""" Identify a list of emotions that the writer of the \ following review is expressing. Include no more than \ five items in the list. Format your answer as a list of \ lower-case words separated by commas. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Определи список эмоций, которые автор следующего \ отзыва выражает. Включи в список не более \ пяти пунктов. Сформатируй ответ как список \ слов в нижнем регистре через запятую. Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

Identify anger

Определение гнева

prompt = f""" Is the writer of the following review expressing anger?\ The review is delimited with triple backticks. \ Give your answer as either yes or no. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Выражает ли автор следующего отзыва гнев?\ Отзыв ограничен тройными обратными кавычками. \ Дай ответ yes или no. Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

Extract product and company name from customer reviews

Извлечение названия товара и компании из отзывов покупателей

prompt = f""" Identify the following items from the review text: - Item purchased by reviewer - Company that made the item The review is delimited with triple backticks. \ Format your response as a JSON object with \ "Item" and "Brand" as the keys. If the information isn't present, use "unknown" \ as the value. Make your response as short as possible. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Извлеки следующие данные из текста отзыва: - Товар, купленный автором отзыва - Компания, которая произвела этот товар Отзыв ограничен тройными обратными кавычками. \ Сформатируй ответ как JSON-объект с \ ключами "Item" и "Brand". Если информация отсутствует, используй "unknown" \ как значение. Сделай ответ как можно более коротким. Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

Doing multiple tasks at once

Выполнение нескольких задач одновременно

prompt = f""" Identify the following items from the review text: - Sentiment (positive or negative) - Is the reviewer expressing anger? (true or false) - Item purchased by reviewer - Company that made the item The review is delimited with triple backticks. \ Format your response as a JSON object with \ "Sentiment", "Anger", "Item" and "Brand" as the keys. If the information isn't present, use "unknown" \ as the value. Make your response as short as possible. Format the Anger value as a boolean. Review text: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

prompt = f""" Извлеки следующие данные из текста отзыва: - Тональность (positive или negative) - Выражает ли автор отзыва гнев? (true или false) - Товар, купленный автором отзыва - Компания, которая произвела этот товар Отзыв ограничен тройными обратными кавычками. \ Сформатируй ответ как JSON-объект с \ ключами "Sentiment", "Anger", "Item" и "Brand". Если информация отсутствует, используй "unknown" \ как значение. Сделай ответ как можно более коротким. Сформатируй значение Anger как булево. Текст отзыва: '''{lamp_review}''' """ response = get_completion(prompt) print(response)

Inferring topics

Извлечение тем

story = """ In a recent survey conducted by the government, public sector employees were asked to rate their level of satisfaction with the department they work at. The results revealed that NASA was the most popular department with a satisfaction rating of 95%. One NASA employee, John Smith, commented on the findings, stating, "I'm not surprised that NASA came out on top. It's a great place to work with amazing people and incredible opportunities. I'm proud to be a part of such an innovative organization." The results were also welcomed by NASA's management team, with Director Tom Johnson stating, "We are thrilled to hear that our employees are satisfied with their work at NASA. We have a talented and dedicated team who work tirelessly to achieve our goals, and it's fantastic to see that their hard work is paying off." The survey also revealed that the Social Security Administration had the lowest satisfaction rating, with only 45% of employees indicating they were satisfied with their job. The government has pledged to address the concerns raised by employees in the survey and work towards improving job satisfaction across all departments. """

story = """ В недавнем опросе, проведённом правительством, сотрудников госсектора попросили оценить уровень их удовлетворённости ведомством, в котором они работают. Результаты показали, что NASA — самое популярное ведомство с рейтингом удовлетворённости 95%. Один сотрудник NASA, John Smith, прокомментировал результаты, заявив: «Я не удивлён, что NASA оказалось на первом месте. Это отличное место для работы с потрясающими людьми и невероятными возможностями. Я горжусь тем, что являюсь частью такой инновационной организации». Результаты также с радостью приняла команда руководства NASA, директор Tom Johnson заявил: «Мы в восторге от того, что наши сотрудники довольны работой в NASA. У нас талантливая и преданная команда, которая неустанно работает над достижением наших целей, и здорово видеть, что их труд приносит плоды». Опрос также показал, что у Social Security Administration самый низкий рейтинг удовлетворённости — лишь 45% сотрудников указали, что они довольны своей работой. Правительство пообещало разобраться с проблемами, поднятыми сотрудниками в опросе, и работать над повышением удовлетворённости работой во всех ведомствах. """

Infer 5 topics

Извлечение 5 тем

prompt = f""" Determine five topics that are being discussed in the \ following text, which is delimited by triple backticks. Make each item one or two words long. Format your response as a list of items separated by commas. Text sample: '''{story}''' """ response = get_completion(prompt) print(response)

prompt = f""" Определи пять тем, которые обсуждаются в \ следующем тексте, ограниченном тройными обратными кавычками. Каждый пункт сделай длиной в одно-два слова. Сформатируй ответ как список пунктов через запятую. Пример текста: '''{story}''' """ response = get_completion(prompt) print(response)

response.split(sep=',')

response.split(sep=',')

topic_list = [ "nasa", "local government", "engineering", "employee satisfaction", "federal government" ]

topic_list = [ "nasa", "local government", "engineering", "employee satisfaction", "federal government" ]

Make a news alert for certain topics

Создание новостного алерта по определённым темам

prompt = f""" Determine whether each item in the following list of \ topics is a topic in the text below, which is delimited with triple backticks. Give your answer as list with 0 or 1 for each topic.\ List of topics: {", ".join(topic_list)} Text sample: '''{story}''' """ response = get_completion(prompt) print(response)

prompt = f""" Определи, является ли каждый пункт в следующем списке \ тем темой в тексте ниже, который ограничен тройными обратными кавычками. Дай ответ списком с 0 или 1 для каждой темы.\ Список тем: {", ".join(topic_list)} Пример текста: '''{story}''' """ response = get_completion(prompt) print(response)

topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')} if topic_dict['nasa'] == 1: print("ALERT: New NASA story!")

topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')} if topic_dict['nasa'] == 1: print("ALERT: New NASA story!")

Try experimenting on your own!

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