1. Summarize text and extract information
Summarizing information is usually a time-saving technique, especially when you’ll want to extract key points or specific details. With the ChatGPT API, we will leverage its capabilities to generate summaries for big volumes of text.
Taking the instance of the Disneyland reviews dataset, which consists of 42,000 reviews, we will ease the evaluation process by utilizing summaries. Although I’ll exhibit with only one review, the approach can easily be scaled to handle larger quantities of text.
To make use of ChatGPT API, you have to to login into your OpenAI account and generate your API key by navigating to “View API Keys” section from the proper top corner. When you created your API key, you’ll want to store it in a secure place and never display it.
# Install openai
pip install openaiimport os
import openai
# Safely store your API key
OPENAI_API_KEY = "sk-XXXXXXXXXXXXXXXXXXXXXXXX"
openai.api_key = OPENAI_API_KEY
We’ll now generate a helper function that can take our prompt and return a completion for that prompt.
# Helper function to return completion for a promptdef get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # degree of randomness of the response
)
return response.selections[0].message["content"]
# Input one reviewreview = """
Have been to Disney World, Disneyland Anaheim and Tokyo Disneyland
but I feel that Disneyland Hong Kong is absolutely too small to be
called a Disneyland. It has way too few rides and attractions.
Souvenirs, food and even entrance tickets are barely more
expensive than other Disneyland as well. Mainly, this park is
good just for babies and folks who has never been to Disney.
The food selections were acceptable, mostly fast food, and never too expensive.
Bottled water, nonetheless, was VERY expensive but they do have water
fountains around so that you can refill your water bottles. The parade was
pretty good. It was crowded not an issue but what was the issue was
the people were just so rude, the pushing and shoving cutting in lines
for the rides, gift shops, food stands was simply to much to take. forget
attempting to see certainly one of the shows its a free for all for seats, i do not see
how Disney can let this occur, it was by far the worst managed Disney
property.
"""
# Write the prompt and generate the response using the helper functionprompt = f"""
Summarize the review below in 30 words.
Review: ```{review}```
"""
response = get_completion(prompt)
print(response)
Disneyland Hong Kong is simply too small with few rides and attractions. Food and souvenirs are expensive. Good for babies and first-time visitors. Crowded with rude people and poorly managed.
The summary is pretty great and around 30 words as we asked within the prompt. If we wish we can even concentrate on a selected element within the summaries e.g. price and value.
prompt = f"""
Summarize the review below in 10 words and
focus price and value.
Review: ```{review}'''
"""response = get_completion(prompt)
print(response)
Expensive, small, and crowded Disneyland with few attractions.
By generating a targeted summary, now we have transformed our initial review right into a more meaningful and impactful statement. 🍄
Now, let’s take it a step further and extract relevant information within the JSON format for easier processing and integration with other systems. We’ll define a template for keys within the prompt.
prompt = f"""
Discover the next items from the review:
- Sentiment (positive or negative)
- Which Disney park was reviewed
- Is the reviewer expressing disappointment? (true or false)
- Is the reviewer expressing happiness? (true or false)Format your response as a JSON object with
"Sentiment", "Park", "Anger" and "Happiness" because the keys.
Format the Anger and Happiness value as a boolean.
Keep the answers short.
Review: ```{review}```
"""
response = get_completion(prompt)
print(response)
{
“Sentiment”: “negative”,
“Park”: “Hong Kong Disneyland”,
“Anger”: true,
“Happiness”: false
}
It’s pretty amazing!
2. Translate the text
As you possibly can imagine, if we will create summaries, we can even translate the text into different languages. Constructing on the previous example, we’ll now request summaries to be generated in English, Italian, and German languages.
prompt = f"""
Your task is to summarise the next review.Summarize the review below in at most 10 words.
Print the summary in English, Italian and German
Review: ```{review}```
"""
response = get_completion(prompt)
print(response)
Summary:
English: Disneyland Hong Kong is small with few attractions and expensive.
Italian: Disneyland Hong Kong è piccolo con poche attrazioni e costoso.
German: Disneyland Hong Kong ist klein mit wenigen Attraktionen und teuer.
3. Expanding text
Expanding involves utilizing a smaller text piece, and leveraging the capabilities of a big language model to generate a more extensive piece of text. For instance, if we input a customer review, we will produce an in depth reply email and address the concerns raised. We will provide guidelines for the format and content.
prompt = f"""
Your task is to write down an email reply to the client.
Given the client email delimited by ```.
Generate a reply to thank the client for his or her review.Guidelines:
- If the sentiment is positive or neutral, thank the client
for his or her feedback and consult with the precise details they mentioned.
- If the sentiment is negative, sincerely apologize for his or her poor
experience, take responsibility, and supply follow-up contact information.
- Express appreciation for his or her time and review. Check with particular
points to construct rapport.
- For negative experiences, apologize sincerely and accept responsibility.
Offer customer support contact information.
- Aim for a concise yet thoughtful tone.
- Close professionally as an "AI customer agent".
Customer review: ```{review}```
"""
response = get_completion(prompt)
print(response)
Dear valued customer,
Thanks for taking the time to share your experience at Disneyland Hong Kong. We appreciate your feedback and are sorry to listen to that your visit didn’t meet your expectations.
We apologize for any inconvenience brought on by the limited variety of rides and attractions, in addition to the upper prices for souvenirs, food, and tickets. We understand that these aspects can impact your overall experience on the park.
We’re glad to listen to that you simply found the food selections acceptable and that the parade was enjoyable. We also appreciate your feedback regarding the crowds and rude behavior of some guests. We take these concerns seriously and can work to enhance our management of the park to make sure a more enjoyable experience for all guests.
If you will have any further concerns or would really like to offer additional feedback, please don’t hesitate to contact our customer support team at [insert contact information]. We value your feedback and hope to have the chance to offer a greater experience for you in the long run.
Thanks again to your review.
Best regards,
AI customer agent
Good job, AI customer agent! ✉️
In this text, we explored the most effective practices of prompt engineering using each the online UI and API. We discussed several effective prompt patterns, including persona patterns, query refinement, templates, zero-shot, and chain-of-thought prompting. Moreover, we delved into utilizing the ChatGPT API by generating our secret key and explored its capabilities in text summarization, translation, and expansion.
I hope this tutorial inspires you to make use of large language models to spice up your creativity and productivity. I’m sure, it might enable you to to generate ideas, gain recent insights, solve complex problems — and enhance your each day work at many levels. The probabilities are vast! 🤖✨
🍓 In the event you enjoy reading articles like this and need to support my writing, it’s possible you’ll consider becoming a Medium member! Medium members get full access to articles from all writers and in case you use my referral link, you will probably be directly supporting my writing.
🍓 In the event you are already a member and interested to read my articles, you possibly can subscribe to be notified or follow me on Medium. Let me know if you will have any questions or suggestions.