init courses

This commit is contained in:
John 2023-05-11 22:44:49 +02:00
parent e0ecdb5879
commit 87f48c2d1a
64 changed files with 347499 additions and 0 deletions

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,96 @@
## Generative Models
![Generative vs Discriminative models](../../Images/Generative_vs_Discriminative_models.png)
- Discriminative models -> classifiers
- The noise is larger to ensure that what's generated isn't actually the same dog each time
- if you're only generating one class, one Y of a dog, then you probably don't need this conditioning on Y and instead it's just the probability over all the features X
![two of the most popular generative model architectures](../../Images/Generative_Models.png)
The two models in a GAN compete with each other and reach a point where realistic examples are produced by the generator.
In the end, the Generator is not needed anymore, and only some random noise is used as input to generate some realistic image.
## Goal of the generator and the discriminator
Generator learns to make **fake** that looks **real** and tries to fool the discriminator.
Discriminator learns to **distinguish real** from **fake**, by looking to real and fake.
## Competition between generator and the disciminator
In the beginning the generator is not very sophisticatied.
The generator is not to see the real.
The discriminator start to learn the real.
Then the discrinator start to decide what is real and what is fake.
When the generator starts to produce bathes of fake, the discriminator will know in what direction to go and improve to decide faje or real.
End: fakes look real.
## Discriminator
- is a classifier
- not only images, but also eq text
- P(Y|X) => P(Class | Features)
conditional probability distribution
- CLass is fake: so the discriminator will determinate a probalility how fake a class is.
![Disriminator probablility](../../Images/Dicriminator_probability.png)
- this probability is given back to generator.
## Generator
Goal: produce example of a certain class
Noise vector: result is different outputs at every run
![Generator Learning](../../Images/Generator_learning.png)
When good enough save the value θ (theta)
![Saved Theta](../../Images/Saved_theta.png)
If one class then for Generator P(X)
if multiple classes then P(X|Y)
## BCE Cost Function
Binary Cross Entropy function, or BCE for short, is used for training GANs.
Desinged for classification when there are two categories: real and fake.
![BCE_Function](../../Images/BCE_function.png)
Negative sign: ensures that the cost is always>=0
![BCE_LOss_Function](../../Images/BCE_Loss_function.png)
Summary:
- BCE Cost function has two parts
- Close to zero when the label and prediction are similar
- Appraches infinity when the label and prediction are different
## Put it all together
![BCE_LOss_Function](../../Images/GANs_Model.png)
![BCE_LOss_Function](../../Images/Training_GAN_discriminator.png)
Only the parameters of the Discriminator are updated!!
The discriminator looks at real and fake images over time, makes guesses, and gets feedback on whether its guess was right or wrong.
Over time, it learns to discern real from fake better, but note that since the generator is also learning, the fake images get more realistic and harder to discern. This cat and mouse game enables both models to learn in tandem.
![BCE_LOss_Function](../../Images/Training_GANs_Generator.png)
With feedback from the discriminator on whether a fake image looks real or fake, the generator starts producing fake images that are more and more realistic (that tries to fool the discriminator). Images that look “fake” to the discriminator are discarded in favor of those that look “real” to the discriminator; since the discriminator is improving over time as it sees more reals and fakes, the generator needs to continually learn too.
So as you alternate their training, only **one model is trained at a time**, while the other one is held constant. So in training GANs in this alternating fashion, it's important to keep in mind that **both models should improve together and should be kept at similar skill levels** from the beginning of training.
![BCE_LOss_Function](../../Images/Traing_gan_similar_level.png)
One common issue is having a **superior discriminator**, having this discriminator learn too quickly. And when it learns too quickly and it suddenly looks at a fake image and says, this is 100% fake. This 100% is not useful for **the generator at all because it doesn't know which way to grow and learn**
![BCE_LOss_Function](../../Images/Pytorch_vs_Tensorflow.png)

View File

@ -0,0 +1,96 @@
## Generative Models
![Generative vs Discriminative models](Images/Generative_vs_Discriminative_models.png)
- Discriminative models -> classifiers
- The noise is larger to ensure that what's generated isn't actually the same dog each time
- if you're only generating one class, one Y of a dog, then you probably don't need this conditioning on Y and instead it's just the probability over all the features X
![two of the most popular generative model architectures](Images/Generative_Models.png)
The two models in a GAN compete with each other and reach a point where realistic examples are produced by the generator.
In the end, the Generator is not needed anymore, and only some random noise is used as input to generate some realistic image.
## Goal of the generator and the discriminator
Generator learns to make **fake** that looks **real** and tries to fool the discriminator.
Discriminator learns to **distinguish real** from **fake**, by looking to real and fake.
## Competition between generator and the disciminator
In the beginning the generator is not very sophisticatied.
The generator is not to see the real.
The discriminator start to learn the real.
Then the discrinator start to decide what is real and what is fake.
When the generator starts to produce bathes of fake, the discriminator will know in what direction to go and improve to decide faje or real.
End: fakes look real.
## Discriminator
- is a classifier
- not only images, but also eq text
- P(Y|X) => P(Class | Features)
conditional probability distribution
- CLass is fake: so the discriminator will determinate a probalility how fake a class is.
![Disriminator probablility](Images/Dicriminator_probability.png)
- this probability is given back to generator.
## Generator
Goal: produce example of a certain class
Noise vector: result is different outputs at every run
![Generator Learning](Images/Generator_learning.png)
When good enough save the value θ (theta)
![Saved Theta](Images/Saved_theta.png)
If one class then for Generator P(X)
if multiple classes then P(X|Y)
## BCE Cost Function
Binary Cross Entropy function, or BCE for short, is used for training GANs.
Desinged for classification when there are two categories: real and fake.
![BCE_Function](Images/BCE_function.png)
Negative sign: ensures that the cost is always>=0
![BCE_LOss_Function](Images/BCE_Loss_function.png)
Summary:
- BCE Cost function has two parts
- Close to zero when the label and prediction are similar
- Appraches infinity when the label and prediction are different
## Put it all together
![BCE_LOss_Function](Images/GANs_Model.png)
![BCE_LOss_Function](Images/Training_GAN_discriminator.png)
Only the parameters of the Discriminator are updated!!
The discriminator looks at real and fake images over time, makes guesses, and gets feedback on whether its guess was right or wrong.
Over time, it learns to discern real from fake better, but note that since the generator is also learning, the fake images get more realistic and harder to discern. This cat and mouse game enables both models to learn in tandem.
![BCE_LOss_Function](Images/Training_GANs_Generator.png)
With feedback from the discriminator on whether a fake image looks real or fake, the generator starts producing fake images that are more and more realistic (that tries to fool the discriminator). Images that look “fake” to the discriminator are discarded in favor of those that look “real” to the discriminator; since the discriminator is improving over time as it sees more reals and fakes, the generator needs to continually learn too.
So as you alternate their training, only **one model is trained at a time**, while the other one is held constant. So in training GANs in this alternating fashion, it's important to keep in mind that **both models should improve together and should be kept at similar skill levels** from the beginning of training.
![BCE_LOss_Function](Images/Traing_gan_similar_level.png)
One common issue is having a **superior discriminator**, having this discriminator learn too quickly. And when it learns too quickly and it suddenly looks at a fake image and says, this is 100% fake. This 100% is not useful for **the generator at all because it doesn't know which way to grow and learn**
![BCE_LOss_Function](Images/Pytorch_vs_Tensorflow.png)

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 353 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
#
echo "How many loops doe you want?"
read LOOPS
COUNT=1
while [ $COUNT -le $LOOPS ]
do
echo "Loop# $COUNT "
((COUNT++))
done

View File

@ -0,0 +1,9 @@
#!/usr/bin/env bash
touch one.txt \
&& touch two.txt \
&& touch three.txt
ls *.txt | wc -l
rm one.txt two.txt three.txt

View File

@ -0,0 +1,12 @@
#!/bin/sh
#
echo "What food do you like?"
read FOOD
if [ "$FOOD" = "Apple" ]; then
echo "Eat yogurt with your ${FOOD}"
elif [ "$FOOD" = "Milk" ]; then
echo "Eat Cereal with your ${FOOD}"
else
echo "Eat your ${FOOD} by itself"
fi

View File

@ -0,0 +1,5 @@
#!/usr/bin/bash
read -p 'File: ' FILENAME
FPATH=`readlink -f $FILENAME`
echo 'Full path: ' $FPATH

View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
#
declare -a array=("apple" "pear" "cherry")
for i in "${array[@]}"
do
echo "this ${i} is delicious!"
done

@ -0,0 +1 @@
Subproject commit 5a2241c360530b19391d007be9750bb967d3f1c7

Binary file not shown.

View File

@ -0,0 +1,698 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Guidelines for Prompting¶\n",
"In this lesson, you'll practice two prompting principles and their related tactics in order to write effective prompts for large language models.\n",
"\n",
"Setup\n",
"Load the API key and relevant Python libaries."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv())\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"openai.api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### helper function\n",
"Throughout this course, we will use OpenAI's `gpt-3.5-turbo` model and the [chat completions endpoint](https://platform.openai.com/docs/guides/chat). \n",
"\n",
"This helper function will make it easier to use prompts and look at the generated outputs:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prompting Principles\n",
"- **Principle 1: Write clear and specific instructions**\n",
"- **Principle 2: Give the model time to “think”**\n",
"\n",
"### Tactics\n",
"\n",
"#### Tactic 1: Use delimiters to clearly indicate distinct parts of the input\n",
"- Delimiters can be anything like: ```, \"\"\", < >, `<tag> </tag>`, `:`"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clear and specific instructions should be provided to guide a model towards the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"You should express what you want a model to do by \\ \n",
"providing instructions that are as clear and \\ \n",
"specific as you can possibly make them. \\ \n",
"This will guide the model towards the desired output, \\ \n",
"and reduce the chances of receiving irrelevant \\ \n",
"or incorrect responses. Don't confuse writing a \\ \n",
"clear prompt with writing a short prompt. \\ \n",
"In many cases, longer prompts provide more clarity \\ \n",
"and context for the model, which can lead to \\ \n",
"more detailed and relevant outputs.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"Summarize the text delimited by triple backticks \\ \n",
"into a single sentence.\n",
"```{text}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 2: Ask for a structured output\n",
"- JSON, HTML"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[\n",
" {\n",
" \"book_id\": 1,\n",
" \"title\": \"The Lost City of Zorath\",\n",
" \"author\": \"Aria Blackwood\",\n",
" \"genre\": \"Fantasy\"\n",
" },\n",
" {\n",
" \"book_id\": 2,\n",
" \"title\": \"The Last Survivors\",\n",
" \"author\": \"Ethan Stone\",\n",
" \"genre\": \"Science Fiction\"\n",
" },\n",
" {\n",
" \"book_id\": 3,\n",
" \"title\": \"The Secret of the Haunted Mansion\",\n",
" \"author\": \"Lila Rose\",\n",
" \"genre\": \"Mystery\"\n",
" }\n",
"]\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Generate a list of three made-up book titles along \\ \n",
"with their authors and genres. \n",
"Provide them in JSON format with the following keys: \n",
"book_id, title, author, genre.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 3: Ask the model to check whether conditions are satisfied"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for Text 1:\n",
"Step 1 - Get some water boiling.\n",
"Step 2 - Grab a cup and put a tea bag in it.\n",
"Step 3 - Once the water is hot enough, pour it over the tea bag.\n",
"Step 4 - Let it sit for a bit so the tea can steep.\n",
"Step 5 - After a few minutes, take out the tea bag.\n",
"Step 6 - Add some sugar or milk to taste.\n",
"Step 7 - Enjoy your delicious cup of tea!\n"
]
}
],
"source": [
"text_1 = f\"\"\"\n",
"Making a cup of tea is easy! First, you need to get some \\ \n",
"water boiling. While that's happening, \\ \n",
"grab a cup and put a tea bag in it. Once the water is \\ \n",
"hot enough, just pour it over the tea bag. \\ \n",
"Let it sit for a bit so the tea can steep. After a \\ \n",
"few minutes, take out the tea bag. If you \\ \n",
"like, you can add some sugar or milk to taste. \\ \n",
"And that's it! You've got yourself a delicious \\ \n",
"cup of tea to enjoy.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"You will be provided with text delimited by triple quotes. \n",
"If it contains a sequence of instructions, \\ \n",
"re-write those instructions in the following format:\n",
"\n",
"Step 1 - ...\n",
"Step 2 - …\n",
"…\n",
"Step N - …\n",
"\n",
"If the text does not contain a sequence of instructions, \\ \n",
"then simply write \\\"No steps provided.\\\"\n",
"\n",
"\\\"\\\"\\\"{text_1}\\\"\\\"\\\"\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(\"Completion for Text 1:\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for Text 2:\n",
"No steps provided.\n"
]
}
],
"source": [
"text_2 = f\"\"\"\n",
"The sun is shining brightly today, and the birds are \\\n",
"singing. It's a beautiful day to go for a \\ \n",
"walk in the park. The flowers are blooming, and the \\ \n",
"trees are swaying gently in the breeze. People \\ \n",
"are out and about, enjoying the lovely weather. \\ \n",
"Some are having picnics, while others are playing \\ \n",
"games or simply relaxing on the grass. It's a \\ \n",
"perfect day to spend time outdoors and appreciate the \\ \n",
"beauty of nature.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"You will be provided with text delimited by triple quotes. \n",
"If it contains a sequence of instructions, \\ \n",
"re-write those instructions in the following format:\n",
"\n",
"Step 1 - ...\n",
"Step 2 - …\n",
"…\n",
"Step N - …\n",
"\n",
"If the text does not contain a sequence of instructions, \\ \n",
"then simply write \\\"No steps provided.\\\"\n",
"\n",
"\\\"\\\"\\\"{text_2}\\\"\\\"\\\"\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(\"Completion for Text 2:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 4: \"Few-shot\" prompting"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<grandparent>: Resilience is like a tree that bends with the wind but never breaks. It is the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree that grows stronger with each storm it weathers, resilience is a quality that can be developed and strengthened over time.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to answer in a consistent style.\n",
"\n",
"<child>: Teach me about patience.\n",
"\n",
"<grandparent>: The river that carves the deepest \\ \n",
"valley flows from a modest spring; the \\ \n",
"grandest symphony originates from a single note; \\ \n",
"the most intricate tapestry begins with a solitary thread.\n",
"\n",
"<child>: Teach me about resilience.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Principle 2: Give the model time to “think” \n",
"\n",
"#### Tactic 1: Specify the steps required to complete a task"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for prompt 1:\n",
"Two siblings, Jack and Jill, go on a quest to fetch water from a hilltop well, but misfortune strikes as they both fall down the hill, yet they return home slightly battered but with their adventurous spirits undimmed.\n",
"\n",
"Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact. \n",
"Noms: Jack, Jill.\n",
"\n",
"{\n",
"\"french_summary\": \"Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact.\",\n",
"\"num_names\": 2\n",
"}\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"In a charming village, siblings Jack and Jill set out on \\ \n",
"a quest to fetch water from a hilltop \\ \n",
"well. As they climbed, singing joyfully, misfortune \\ \n",
"struck—Jack tripped on a stone and tumbled \\ \n",
"down the hill, with Jill following suit. \\ \n",
"Though slightly battered, the pair returned home to \\ \n",
"comforting embraces. Despite the mishap, \\ \n",
"their adventurous spirits remained undimmed, and they \\ \n",
"continued exploring with delight.\n",
"\"\"\"\n",
"# example 1\n",
"prompt_1 = f\"\"\"\n",
"Perform the following actions: \n",
"1 - Summarize the following text delimited by triple \\\n",
"backticks with 1 sentence.\n",
"2 - Translate the summary into French.\n",
"3 - List each name in the French summary.\n",
"4 - Output a json object that contains the following \\\n",
"keys: french_summary, num_names.\n",
"\n",
"Separate your answers with line breaks.\n",
"\n",
"Text:\n",
"```{text}```\n",
"\"\"\"\n",
"response = get_completion(prompt_1)\n",
"print(\"Completion for prompt 1:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Ask for output in a specified format"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Completion for prompt 2:\n",
"Summary: Jack and Jill go on a quest to fetch water, but misfortune strikes and they tumble down the hill, returning home slightly battered but with their adventurous spirits undimmed. \n",
"Translation: Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.\n",
"Names: Jack, Jill\n",
"Output JSON: {\"french_summary\": \"Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.\", \"num_names\": 2}\n"
]
}
],
"source": [
"prompt_2 = f\"\"\"\n",
"Your task is to perform the following actions: \n",
"1 - Summarize the following text delimited by \n",
" <> with 1 sentence.\n",
"2 - Translate the summary into French.\n",
"3 - List each name in the French summary.\n",
"4 - Output a json object that contains the \n",
" following keys: french_summary, num_names.\n",
"\n",
"Use the following format:\n",
"Text: <text to summarize>\n",
"Summary: <summary>\n",
"Translation: <summary translation>\n",
"Names: <list of names in Italian summary>\n",
"Output JSON: <json with summary and num_names>\n",
"\n",
"Text: <{text}>\n",
"\"\"\"\n",
"response = get_completion(prompt_2)\n",
"print(\"\\nCompletion for prompt 2:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 2: Instruct the model to work out its own solution before rushing to a conclusion"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The student's solution is correct.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine if the student's solution is correct or not.\n",
"\n",
"Question:\n",
"I'm building a solar power installation and I need \\\n",
" help working out the financials. \n",
"- Land costs $100 / square foot\n",
"- I can buy solar panels for $250 / square foot\n",
"- I negotiated a contract for maintenance that will cost \\ \n",
"me a flat $100k per year, and an additional $10 / square \\\n",
"foot\n",
"What is the total cost for the first year of operations \n",
"as a function of the number of square feet.\n",
"\n",
"Student's Solution:\n",
"Let x be the size of the installation in square feet.\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel whethercost: 250x\n",
"3. Maintenance cost: 100,000 + 100x\n",
"Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"#### Note that the student's solution is actually not correct.\n",
"#### We can fix this by instructing the model to work out its own solution first."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Let x be the size of the installation in square feet.\n",
"\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel cost: 250x\n",
"3. Maintenance cost: 100,000 + 10x\n",
"\n",
"Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000\n",
"\n",
"Is the student's solution the same as actual solution just calculated:\n",
"No\n",
"\n",
"Student grade:\n",
"Incorrect\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to determine if the student's solution \\\n",
"is correct or not.\n",
"To solve the problem do the following:\n",
"- First, work out your own solution to the problem. \n",
"- Then compare your solution to the student's solution \\ \n",
"and evaluate if the student's solution is correct or not. \n",
"Don't decide if the student's solution is correct until \n",
"you have done the problem yourself.\n",
"\n",
"Use the following format:\n",
"Question:\n",
"```\n",
"question here\n",
"```\n",
"Student's solution:\n",
"```\n",
"student's solution here\n",
"```\n",
"Actual solution:\n",
"```\n",
"steps to work out the solution and your solution here\n",
"```\n",
"Is the student's solution the same as actual solution \\\n",
"just calculated:\n",
"```\n",
"yes or no\n",
"```\n",
"Student grade:\n",
"```\n",
"correct or incorrect\n",
"```\n",
"\n",
"Question:\n",
"```\n",
"I'm building a solar power installation and I need help \\\n",
"working out the financials. \n",
"- Land costs $100 / square foot\n",
"- I can buy solar panels for $250 / square foot\n",
"- I negotiated a contract for maintenance that will cost \\\n",
"me a flat $100k per year, and an additional $10 / square \\\n",
"foot\n",
"What is the total cost for the first year of operations \\\n",
"as a function of the number of square feet.\n",
"``` \n",
"Student's solution:\n",
"```\n",
"Let x be the size of the installation in square feet.\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel cost: 250x\n",
"3. Maintenance cost: 100,000 + 100x\n",
"Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000\n",
"```\n",
"Actual solution:\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Model Limitations: Hallucinations\n",
"- Boie is a real company, the product name is not real."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The AeroGlide UltraSlim Smart Toothbrush by Boie is a high-tech toothbrush that uses advanced sonic technology to provide a deep and thorough clean. It features a slim and sleek design that makes it easy to hold and maneuver, and it comes with a range of smart features that help you optimize your brushing routine.\n",
"\n",
"One of the key features of the AeroGlide UltraSlim Smart Toothbrush is its sonic technology, which uses high-frequency vibrations to break up plaque and bacteria on your teeth and gums. This technology is highly effective at removing even the most stubborn stains and buildup, and it can help you achieve a brighter, healthier smile in just a few weeks.\n",
"\n",
"In addition to its sonic technology, the AeroGlide UltraSlim Smart Toothbrush also comes with a range of smart features that help you optimize your brushing routine. These include a built-in timer that ensures you brush for the recommended two minutes, as well as a pressure sensor that alerts you if you're brushing too hard.\n",
"\n",
"Overall, the AeroGlide UltraSlim Smart Toothbrush by Boie is a highly advanced and effective toothbrush that can help you achieve a brighter, healthier smile in no time. Whether you're looking to improve your oral hygiene or simply want a more convenient and effective way to brush your teeth, this toothbrush is definitely worth considering.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes on using the OpenAI API outside of this classroom\n",
"\n",
"To install the OpenAI Python library:\n",
"```\n",
"!pip install openai\n",
"```\n",
"\n",
"The library needs to be configured with your account's secret key, which is available on the [website](https://platform.openai.com/account/api-keys). \n",
"\n",
"You can either set it as the `OPENAI_API_KEY` environment variable before using the library:\n",
" ```\n",
" !export OPENAI_API_KEY='sk-...'\n",
" ```\n",
"\n",
"Or, set `openai.api_key` to its value:\n",
"\n",
"```\n",
"import openai\n",
"openai.api_key = \"sk-...\"\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes on using the OpenAI API outside of this classroom\n",
"\n",
"To install the OpenAI Python library:\n",
"```\n",
"!pip install openai\n",
"```\n",
"\n",
"The library needs to be configured with your account's secret key, which is available on the [website](https://platform.openai.com/account/api-keys). \n",
"\n",
"You can either set it as the `OPENAI_API_KEY` environment variable before using the library:\n",
" ```\n",
" !export OPENAI_API_KEY='sk-...'\n",
" ```\n",
"\n",
"Or, set `openai.api_key` to its value:\n",
"\n",
"```\n",
"import openai\n",
"openai.api_key = \"sk-...\"\n",
"```"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@ -0,0 +1,532 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "17e90050-86ad-41bd-8d35-30ffd122d98a",
"metadata": {},
"source": [
"# Iterative Prompt Develelopment\n",
"In this lesson, you'll iteratively analyze and refine your prompts to generate marketing copy from a product fact sheet.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2c9d12c7-ce76-4d7f-946a-5c7a1793dc7e",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d455ad18-df5f-4556-92bd-949e78c523e8",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "b026a41d-4e62-4168-a52c-1fade8ea3208",
"metadata": {},
"source": [
"## Generate a marketing product description from a product fact sheet"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "94112890-73c1-435e-8aab-e66dfcb67226",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"fact_sheet_chair = \"\"\"\n",
"OVERVIEW\n",
"- Part of a beautiful family of mid-century inspired office furniture, \n",
"including filing cabinets, desks, bookcases, meeting tables, and more.\n",
"- Several options of shell color and base finishes.\n",
"- Available with plastic back and front upholstery (SWC-100) \n",
"or full upholstery (SWC-110) in 10 fabric and 6 leather options.\n",
"- Base finish options are: stainless steel, matte black, \n",
"gloss white, or chrome.\n",
"- Chair is available with or without armrests.\n",
"- Suitable for home or business settings.\n",
"- Qualified for contract use.\n",
"\n",
"CONSTRUCTION\n",
"- 5-wheel plastic coated aluminum base.\n",
"- Pneumatic chair adjust for easy raise/lower action.\n",
"\n",
"DIMENSIONS\n",
"- WIDTH 53 CM | 20.87”\n",
"- DEPTH 51 CM | 20.08”\n",
"- HEIGHT 80 CM | 31.50”\n",
"- SEAT HEIGHT 44 CM | 17.32”\n",
"- SEAT DEPTH 41 CM | 16.14”\n",
"\n",
"OPTIONS\n",
"- Soft or hard-floor caster options.\n",
"- Two choices of seat foam densities: \n",
" medium (1.8 lb/ft3) or high (2.8 lb/ft3)\n",
"- Armless or 8 position PU armrests \n",
"\n",
"MATERIALS\n",
"SHELL BASE GLIDER\n",
"- Cast Aluminum with modified nylon PA6/PA66 coating.\n",
"- Shell thickness: 10 mm.\n",
"SEAT\n",
"- HD36 foam\n",
"\n",
"COUNTRY OF ORIGIN\n",
"- Italy\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f5e3513c-c9bb-4bbe-8282-194e9a548fed",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our stunning mid-century inspired office chair, the perfect addition to any home or business setting. Part of a beautiful family of office furniture, including filing cabinets, desks, bookcases, meeting tables, and more, this chair is available in several options of shell color and base finishes to suit your style. Choose from plastic back and front upholstery (SWC-100) or full upholstery (SWC-110) in 10 fabric and 6 leather options.\n",
"\n",
"The chair is constructed with a 5-wheel plastic coated aluminum base and features a pneumatic chair adjust for easy raise/lower action. It is available with or without armrests and is qualified for contract use. The base finish options are stainless steel, matte black, gloss white, or chrome.\n",
"\n",
"Measuring at a width of 53 cm, depth of 51 cm, and height of 80 cm, with a seat height of 44 cm and seat depth of 41 cm, this chair is designed for ultimate comfort. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are available in either an armless or 8 position PU option.\n",
"\n",
"The materials used in the construction of this chair are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating and has a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and durability.\n",
"\n",
"This chair is made in Italy and is the perfect combination of style and functionality. Upgrade your workspace with our mid-century inspired office chair today!\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "9217aa0b-61c5-413e-bfa1-089b03f7594b",
"metadata": {},
"source": [
"## Issue 1: The text is too long \n",
"- Limit the number of words/sentences/characters."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "dda8f0c8-f8e9-497e-9371-9aedc3e70c2a",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for home or business settings. Available in a range of shell colors and base finishes, with or without armrests. Choose from 10 fabric and 6 leather options for full or plastic upholstery. With a 5-wheel base and pneumatic chair adjust, it's both stylish and functional. Made in Italy.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"Use at most 50 words.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "85926c49-9581-41be-a0e9-aca9341e40b2",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"55"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(response.split(\" \"))"
]
},
{
"cell_type": "markdown",
"id": "e46f7130-a92e-4e5b-881f-ec2e0b34d73e",
"metadata": {
"tags": []
},
"source": [
"## Issue 2. Text focuses on the wrong details\n",
"- Ask it to focus on the aspects that are relevant to the intended audience."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "302d7eb6-5925-4b26-852a-fa0081b1019d",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for both home and business settings. With a range of shell colors and base finishes to choose from, this chair is available with or without armrests and features a 5-wheel plastic coated aluminum base with pneumatic chair adjust for easy raise/lower action. Constructed with a cast aluminum shell and HD36 foam seat, this chair is made in Italy and qualified for contract use.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"Use at most 3 sentences.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "e3e3d5e1-f0c3-4585-b90b-5bd5806fc7af",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for home or business settings. With multiple shell color and base finish options, and a choice of plastic or full upholstery, this chair is both stylish and comfortable. Constructed with a 5-wheel plastic coated aluminum base and pneumatic chair adjust, it's also durable and easy to use. Available with or without armrests and suitable for contract use. Product IDs: SWC-100, SWC-110.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"At the end of the description, include every 7-character \n",
"Product ID in the technical specification.\n",
"\n",
"Use at most 280 characters.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "e6852490-595f-42dd-a1e9-3f84611f1d84",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"444"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(response)"
]
},
{
"cell_type": "markdown",
"id": "ed4239e5-48c7-4eab-914c-cef978307c00",
"metadata": {},
"source": [
"## Issue 3. Description needs a table of dimensions\n",
"- Ask it to extract information and organize it in a table."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "f4dba81a-514e-4c12-90df-0370f42d206e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<div>\n",
"<h2>Mid-Century Inspired Office Chair</h2>\n",
"<p>Introducing our mid-century inspired office chair, part of a beautiful family of office furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. This chair is available in several options of shell color and base finishes, allowing you to customize it to your liking. You can choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome. The chair is also available with or without armrests, making it suitable for both home and business settings. Plus, it's qualified for contract use, ensuring its durability and longevity.</p>\n",
"<p>The chair's construction features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are also customizable, with the option of armless or 8 position PU armrests.</p>\n",
"<p>The materials used in the chair's construction are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating, with a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and support.</p>\n",
"<p>Made in Italy, this mid-century inspired office chair is the perfect addition to any office space. Order yours today!</p>\n",
"<h3>Product IDs:</h3>\n",
"<ul>\n",
"<li>SWC-100</li>\n",
"<li>SWC-110</li>\n",
"</ul>\n",
"</div>\n",
"\n",
"<table>\n",
" <caption>Product Dimensions</caption>\n",
" <tr>\n",
" <th>Dimension</th>\n",
" <th>Measurement (inches)</th>\n",
" </tr>\n",
" <tr>\n",
" <td>Width</td>\n",
" <td>20.87\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Depth</td>\n",
" <td>20.08\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Height</td>\n",
" <td>31.50\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Height</td>\n",
" <td>17.32\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Depth</td>\n",
" <td>16.14\"</td>\n",
" </tr>\n",
"</table>\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"At the end of the description, include every 7-character \n",
"Product ID in the technical specification.\n",
"\n",
"After the description, include a table that gives the \n",
"product's dimensions. The table should have two columns.\n",
"In the first column include the name of the dimension. \n",
"In the second column include the measurements in inches only.\n",
"\n",
"Give the table the title 'Product Dimensions'.\n",
"\n",
"Format everything as HTML that can be used in a website. \n",
"Place the description in a <div> element.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "2235fbc9-fa1c-4eb9-a51c-1b833978c5b3",
"metadata": {},
"source": [
"## Load Python libraries to view HTML"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "137ee58f-f6dd-4f2c-aafb-03ca260c9fe7",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from IPython.display import display, HTML"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "1d10bb98-2ced-452a-bcf0-cb9e9fd21200",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<h2>Mid-Century Inspired Office Chair</h2>\n",
"<p>Introducing our mid-century inspired office chair, part of a beautiful family of office furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. This chair is available in several options of shell color and base finishes, allowing you to customize it to your liking. You can choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome. The chair is also available with or without armrests, making it suitable for both home and business settings. Plus, it's qualified for contract use, ensuring its durability and longevity.</p>\n",
"<p>The chair's construction features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are also customizable, with the option of armless or 8 position PU armrests.</p>\n",
"<p>The materials used in the chair's construction are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating, with a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and support.</p>\n",
"<p>Made in Italy, this mid-century inspired office chair is the perfect addition to any office space. Order yours today!</p>\n",
"<h3>Product IDs:</h3>\n",
"<ul>\n",
"<li>SWC-100</li>\n",
"<li>SWC-110</li>\n",
"</ul>\n",
"</div>\n",
"\n",
"<table>\n",
" <caption>Product Dimensions</caption>\n",
" <tr>\n",
" <th>Dimension</th>\n",
" <th>Measurement (inches)</th>\n",
" </tr>\n",
" <tr>\n",
" <td>Width</td>\n",
" <td>20.87\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Depth</td>\n",
" <td>20.08\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Height</td>\n",
" <td>31.50\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Height</td>\n",
" <td>17.32\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Depth</td>\n",
" <td>16.14\"</td>\n",
" </tr>\n",
"</table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"display(HTML(response))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,438 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "87857393-6369-4b66-87c9-5f3253edf28e",
"metadata": {},
"source": [
"# Summarizing\n",
"In this lesson, you will summarize text with a focus on specific topics.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "8ac673e1",
"metadata": {
"height": 147
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "66de8ca6",
"metadata": {
"height": 181
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]\n"
]
},
{
"cell_type": "markdown",
"id": "387b0686-bea6-41a2-b879-88721dc0ec10",
"metadata": {},
"source": [
"## Text to summarize"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0ce2cf3c",
"metadata": {
"height": 198
},
"outputs": [],
"source": [
"prod_review = \"\"\"\n",
"Got this panda plush toy for my daughter's birthday, \\\n",
"who loves it and takes it everywhere. It's soft and \\ \n",
"super cute, and its face has a friendly look. It's \\ \n",
"a bit small for what I paid though. I think there \\ \n",
"might be other options that are bigger for the \\ \n",
"same price. It arrived a day earlier than expected, \\ \n",
"so I got to play with it myself before I gave it \\ \n",
"to her.\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "5d95eba0-7744-491a-a30a-8ee687303b7a",
"metadata": {},
"source": [
"## Summarize with a word/sentence/character limit"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "0c3023c6",
"metadata": {
"height": 249
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "90832908-3b3a-459b-b595-bbe15c2a72fa",
"metadata": {},
"source": [
"## Summarize with a focus on shipping and delivery"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "d850bdd2",
"metadata": {
"height": 283
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The panda plush toy arrived a day earlier than expected, but the customer felt it was a bit small for the price paid.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site to give feedback to the \\\n",
"Shipping deparmtment. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words, and focusing on any aspects \\\n",
"that mention shipping and delivery of the product. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "01204385-1d27-420c-80ee-bd4b524550f6",
"metadata": {},
"source": [
"## Summarize with a focus on price and value"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6d865432",
"metadata": {
"height": 300
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The panda plush toy is soft, cute, and loved by the recipient, but the price may be too high for its size compared to other options.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site to give feedback to the \\\n",
"pricing deparmtment, responsible for determining the \\\n",
"price of the product. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words, and focusing on any aspects \\\n",
"that are relevant to the price and perceived value. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "21a561c4-d9a0-48a8-86c4-725746fb08df",
"metadata": {},
"source": [
"#### Comment\n",
"- Summaries include topics that are not related to the topic of focus."
]
},
{
"cell_type": "markdown",
"id": "9aff99cd-dc09-467c-bd09-897ffe06a232",
"metadata": {},
"source": [
"## Try \"extract\" instead of \"summarize\""
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "190943b0",
"metadata": {
"height": 266
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The product arrived a day earlier than expected.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to extract relevant information from \\ \n",
"a product review from an ecommerce site to give \\\n",
"feedback to the Shipping department. \n",
"\n",
"From the review below, delimited by triple quotes \\\n",
"extract the information relevant to shipping and \\ \n",
"delivery. Limit to 30 words. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "f513da2e-f89c-4c91-8456-b79c630e70c9",
"metadata": {},
"source": [
"## Summarize multiple product reviews"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "027822c2",
"metadata": {
"height": 1286
},
"outputs": [],
"source": [
"\n",
"review_1 = prod_review \n",
"\n",
"# review for a standing lamp\n",
"review_2 = \"\"\"\n",
"Needed a nice lamp for my bedroom, and this one \\\n",
"had additional storage and not too high of a price \\\n",
"point. Got it fast - arrived in 2 days. The string \\\n",
"to the lamp broke during the transit and the company \\\n",
"happily sent over a new one. Came within a few days \\\n",
"as well. It was easy to put together. Then I had a \\\n",
"missing part, so I contacted their support and they \\\n",
"very quickly got me the missing piece! Seems to me \\\n",
"to be a great company that cares about their customers \\\n",
"and products. \n",
"\"\"\"\n",
"\n",
"# review for an electric toothbrush\n",
"review_3 = \"\"\"\n",
"My dental hygienist recommended an electric toothbrush, \\\n",
"which is why I got this. The battery life seems to be \\\n",
"pretty impressive so far. After initial charging and \\\n",
"leaving the charger plugged in for the first week to \\\n",
"condition the battery, I've unplugged the charger and \\\n",
"been using it for twice daily brushing for the last \\\n",
"3 weeks all on the same charge. But the toothbrush head \\\n",
"is too small. Ive seen baby toothbrushes bigger than \\\n",
"this one. I wish the head was bigger with different \\\n",
"length bristles to get between teeth better because \\\n",
"this one doesnt. Overall if you can get this one \\\n",
"around the $50 mark, it's a good deal. The manufactuer's \\\n",
"replacements heads are pretty expensive, but you can \\\n",
"get generic ones that're more reasonably priced. This \\\n",
"toothbrush makes me feel like I've been to the dentist \\\n",
"every day. My teeth feel sparkly clean! \n",
"\"\"\"\n",
"\n",
"# review for a blender\n",
"review_4 = \"\"\"\n",
"So, they still had the 17 piece system on seasonal \\\n",
"sale for around $49 in the month of November, about \\\n",
"half off, but for some reason (call it price gouging) \\\n",
"around the second week of December the prices all went \\\n",
"up to about anywhere from between $70-$89 for the same \\\n",
"system. And the 11 piece system went up around $10 or \\\n",
"so in price also from the earlier sale price of $29. \\\n",
"So it looks okay, but if you look at the base, the part \\\n",
"where the blade locks into place doesnt look as good \\\n",
"as in previous editions from a few years ago, but I \\\n",
"plan to be very gentle with it (example, I crush \\\n",
"very hard items like beans, ice, rice, etc. in the \\ \n",
"blender first then pulverize them in the serving size \\\n",
"I want in the blender then switch to the whipping \\\n",
"blade for a finer flour, and use the cross cutting blade \\\n",
"first when making smoothies, then use the flat blade \\\n",
"if I need them finer/less pulpy). Special tip when making \\\n",
"smoothies, finely cut and freeze the fruits and \\\n",
"vegetables (if using spinach-lightly stew soften the \\ \n",
"spinach then freeze until ready for use-and if making \\\n",
"sorbet, use a small to medium sized food processor) \\ \n",
"that you plan to use that way you can avoid adding so \\\n",
"much ice if at all-when making your smoothie. \\\n",
"After about a year, the motor was making a funny noise. \\\n",
"I called customer service but the warranty expired \\\n",
"already, so I had to buy another one. FYI: The overall \\\n",
"quality has gone done in these types of products, so \\\n",
"they are kind of counting on brand recognition and \\\n",
"consumer loyalty to maintain sales. Got it in about \\\n",
"two days.\n",
"\"\"\"\n",
"\n",
"reviews = [review_1, review_2, review_3, review_4]\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "b7c39cc8",
"metadata": {
"height": 266
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early. \n",
"\n",
"1 Affordable lamp with storage, fast shipping, and excellent customer service. Easy to assemble and missing parts were quickly replaced. \n",
"\n",
"2 Good battery life, small toothbrush head, but effective cleaning. Good deal if bought around $50. \n",
"\n"
]
},
{
"ename": "RateLimitError",
"evalue": "Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mRateLimitError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[12], line 12\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;28mlen\u001b[39m(reviews)):\n\u001b[1;32m 2\u001b[0m prompt \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;124m Your task is to generate a short summary of a product \u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124m \u001b[39m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;124m review from an ecommerce site. \u001b[39m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;124m Review: ```\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mreviews[i]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m```\u001b[39m\n\u001b[1;32m 10\u001b[0m \u001b[38;5;124m \u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[0;32m---> 12\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mget_completion\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprompt\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 13\u001b[0m \u001b[38;5;28mprint\u001b[39m(i, response, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"Cell \u001b[0;32mIn[4], line 3\u001b[0m, in \u001b[0;36mget_completion\u001b[0;34m(prompt, model)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mget_completion\u001b[39m(prompt, model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-3.5-turbo\u001b[39m\u001b[38;5;124m\"\u001b[39m): \u001b[38;5;66;03m# Andrew mentioned that the prompt/ completion paradigm is preferable for this class\u001b[39;00m\n\u001b[1;32m 2\u001b[0m messages \u001b[38;5;241m=\u001b[39m [{\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: prompt}]\n\u001b[0;32m----> 3\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mChatCompletion\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m \u001b[49m\u001b[43mtemperature\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# this is the degree of randomness of the model's output\u001b[39;49;00m\n\u001b[1;32m 7\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/chat_completion.py:25\u001b[0m, in \u001b[0;36mChatCompletion.create\u001b[0;34m(cls, *args, **kwargs)\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[1;32m 24\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 25\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 26\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m TryAgain \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 27\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m time\u001b[38;5;241m.\u001b[39mtime() \u001b[38;5;241m>\u001b[39m start \u001b[38;5;241m+\u001b[39m timeout:\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py:153\u001b[0m, in \u001b[0;36mEngineAPIResource.create\u001b[0;34m(cls, api_key, api_base, api_type, request_id, api_version, organization, **params)\u001b[0m\n\u001b[1;32m 127\u001b[0m \u001b[38;5;129m@classmethod\u001b[39m\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcreate\u001b[39m(\n\u001b[1;32m 129\u001b[0m \u001b[38;5;28mcls\u001b[39m,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 136\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams,\n\u001b[1;32m 137\u001b[0m ):\n\u001b[1;32m 138\u001b[0m (\n\u001b[1;32m 139\u001b[0m deployment_id,\n\u001b[1;32m 140\u001b[0m engine,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 150\u001b[0m api_key, api_base, api_type, api_version, organization, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams\n\u001b[1;32m 151\u001b[0m )\n\u001b[0;32m--> 153\u001b[0m response, _, api_key \u001b[38;5;241m=\u001b[39m \u001b[43mrequestor\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 154\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mpost\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 155\u001b[0m \u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 156\u001b[0m \u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparams\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 157\u001b[0m \u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 158\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 159\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 160\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 161\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 163\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n\u001b[1;32m 164\u001b[0m \u001b[38;5;66;03m# must be an iterator\u001b[39;00m\n\u001b[1;32m 165\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(response, OpenAIResponse)\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:226\u001b[0m, in \u001b[0;36mAPIRequestor.request\u001b[0;34m(self, method, url, params, headers, files, stream, request_id, request_timeout)\u001b[0m\n\u001b[1;32m 205\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrequest\u001b[39m(\n\u001b[1;32m 206\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 207\u001b[0m method,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 214\u001b[0m request_timeout: Optional[Union[\u001b[38;5;28mfloat\u001b[39m, Tuple[\u001b[38;5;28mfloat\u001b[39m, \u001b[38;5;28mfloat\u001b[39m]]] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 215\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], \u001b[38;5;28mbool\u001b[39m, \u001b[38;5;28mstr\u001b[39m]:\n\u001b[1;32m 216\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_raw(\n\u001b[1;32m 217\u001b[0m method\u001b[38;5;241m.\u001b[39mlower(),\n\u001b[1;32m 218\u001b[0m url,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 224\u001b[0m request_timeout\u001b[38;5;241m=\u001b[39mrequest_timeout,\n\u001b[1;32m 225\u001b[0m )\n\u001b[0;32m--> 226\u001b[0m resp, got_stream \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresult\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 227\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp, got_stream, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mapi_key\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:620\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response\u001b[0;34m(self, result, stream)\u001b[0m\n\u001b[1;32m 612\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[1;32m 613\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_interpret_response_line(\n\u001b[1;32m 614\u001b[0m line, result\u001b[38;5;241m.\u001b[39mstatus_code, result\u001b[38;5;241m.\u001b[39mheaders, stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 615\u001b[0m )\n\u001b[1;32m 616\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m line \u001b[38;5;129;01min\u001b[39;00m parse_stream(result\u001b[38;5;241m.\u001b[39miter_lines())\n\u001b[1;32m 617\u001b[0m ), \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 618\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 619\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[0;32m--> 620\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response_line\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 621\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcontent\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mutf-8\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 622\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstatus_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 623\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 624\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 625\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 626\u001b[0m \u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[1;32m 627\u001b[0m )\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:683\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response_line\u001b[0;34m(self, rbody, rcode, rheaders, stream)\u001b[0m\n\u001b[1;32m 681\u001b[0m stream_error \u001b[38;5;241m=\u001b[39m stream \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124merror\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m resp\u001b[38;5;241m.\u001b[39mdata\n\u001b[1;32m 682\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream_error \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;241m200\u001b[39m \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m rcode \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m300\u001b[39m:\n\u001b[0;32m--> 683\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhandle_error_response(\n\u001b[1;32m 684\u001b[0m rbody, rcode, resp\u001b[38;5;241m.\u001b[39mdata, rheaders, stream_error\u001b[38;5;241m=\u001b[39mstream_error\n\u001b[1;32m 685\u001b[0m )\n\u001b[1;32m 686\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
"\u001b[0;31mRateLimitError\u001b[0m: Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method."
]
}
],
"source": [
"for i in range(len(reviews)):\n",
" prompt = f\"\"\"\n",
" Your task is to generate a short summary of a product \\ \n",
" review from an ecommerce site. \n",
"\n",
" Summarize the review below, delimited by triple \\\n",
" backticks in at most 20 words. \n",
"\n",
" Review: ```{reviews[i]}```\n",
" \"\"\"\n",
"\n",
" response = get_completion(prompt)\n",
" print(i, response, \"\\n\")\n"
]
},
{
"cell_type": "markdown",
"id": "e0c9f921-8672-4124-bad6-8bee65078ccb",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d05d8a20-86f2-4613-835e-41c49a504b5b",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,652 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3630c235-f891-4874-bd0a-5277d4d6aa82",
"metadata": {},
"source": [
"# Inferring\n",
"In this lesson, you will infer sentiment and topics from product reviews and news articles.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "39689e67",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e82f5577",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "51d2fdfa-c99f-4750-8574-dba7712cd7f0",
"metadata": {},
"source": [
"## Product review text"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b0f3b49b",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"lamp_review = \"\"\"\n",
"Needed a nice lamp for my bedroom, and this one had \\\n",
"additional storage and not too high of a price point. \\\n",
"Got it fast. The string to our lamp broke during the \\\n",
"transit and the company happily sent over a new one. \\\n",
"Came within a few days as well. It was easy to put \\\n",
"together. I had a missing part, so I contacted their \\\n",
"support and they very quickly got me the missing piece! \\\n",
"Lumina seems to me to be a great company that cares \\\n",
"about their customers and products!!\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "30d6e4bd-3337-45a3-8c99-a734cdd06743",
"metadata": {},
"source": [
"## Sentiment (positive/negative)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "e3157601",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The sentiment of the product review is positive.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"What is the sentiment of the following product review, \n",
"which is delimited with triple backticks?\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "acf9ca16",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"positive\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"What is the sentiment of the following product review, \n",
"which is delimited with triple backticks?\n",
"\n",
"Give your answer as a single word, either \"positive\" \\\n",
"or \"negative\".\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "81d2a973-1fa4-4a35-ae35-a2e746c0e91b",
"metadata": {},
"source": [
"## Identify types of emotions"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8aa7934b",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"happy, satisfied, grateful, impressed, content\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify a list of emotions that the writer of the \\\n",
"following review is expressing. Include no more than \\\n",
"five items in the list. Format your answer as a list of \\\n",
"lower-case words separated by commas.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a428d093-51c9-461c-b41e-114e80876409",
"metadata": {},
"source": [
"## Identify anger"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "dba1a538",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Is the writer of the following review expressing anger?\\\n",
"The review is delimited with triple backticks. \\\n",
"Give your answer as either yes or no.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "936a771e-ca78-4e55-8088-2da6f3820ddc",
"metadata": {},
"source": [
"## Extract product and company name from customer reviews"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a13bea1b",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"Item\": \"lamp\",\n",
" \"Brand\": \"Lumina\"\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify the following items from the review text: \n",
"- Item purchased by reviewer\n",
"- Company that made the item\n",
"\n",
"The review is delimited with triple backticks. \\\n",
"Format your response as a JSON object with \\\n",
"\"Item\" and \"Brand\" as the keys. \n",
"If the information isn't present, use \"unknown\" \\\n",
"as the value.\n",
"Make your response as short as possible.\n",
" \n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a38880a5-088f-4609-9913-f8fa41fb7ba0",
"metadata": {},
"source": [
"## Doing multiple tasks at once"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "e7dda9e5",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"Sentiment\": \"positive\",\n",
" \"Anger\": false,\n",
" \"Item\": \"lamp with additional storage\",\n",
" \"Brand\": \"Lumina\"\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify the following items from the review text: \n",
"- Sentiment (positive or negative)\n",
"- Is the reviewer expressing anger? (true or false)\n",
"- Item purchased by reviewer\n",
"- Company that made the item\n",
"\n",
"The review is delimited with triple backticks. \\\n",
"Format your response as a JSON object with \\\n",
"\"Sentiment\", \"Anger\", \"Item\" and \"Brand\" as the keys.\n",
"If the information isn't present, use \"unknown\" \\\n",
"as the value.\n",
"Make your response as short as possible.\n",
"Format the Anger value as a boolean.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "235fc223-2c89-49ec-ac2d-78a8e74a43ac",
"metadata": {},
"source": [
"## Inferring topics"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "8a74cc3e",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"story = \"\"\"\n",
"In a recent survey conducted by the government, \n",
"public sector employees were asked to rate their level \n",
"of satisfaction with the department they work at. \n",
"The results revealed that NASA was the most popular \n",
"department with a satisfaction rating of 95%.\n",
"\n",
"One NASA employee, John Smith, commented on the findings, \n",
"stating, \"I'm not surprised that NASA came out on top. \n",
"It's a great place to work with amazing people and \n",
"incredible opportunities. I'm proud to be a part of \n",
"such an innovative organization.\"\n",
"\n",
"The results were also welcomed by NASA's management team, \n",
"with Director Tom Johnson stating, \"We are thrilled to \n",
"hear that our employees are satisfied with their work at NASA. \n",
"We have a talented and dedicated team who work tirelessly \n",
"to achieve our goals, and it's fantastic to see that their \n",
"hard work is paying off.\"\n",
"\n",
"The survey also revealed that the \n",
"Social Security Administration had the lowest satisfaction \n",
"rating, with only 45% of employees indicating they were \n",
"satisfied with their job. The government has pledged to \n",
"address the concerns raised by employees in the survey and \n",
"work towards improving job satisfaction across all departments.\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "a8ea91d6-e841-4ee2-bed9-ca4a36df177f",
"metadata": {},
"source": [
"## Infer 5 topics"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "5c267cbe",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"government survey, job satisfaction, NASA, Social Security Administration, employee concerns\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine five topics that are being discussed in the \\\n",
"following text, which is delimited by triple backticks.\n",
"\n",
"Make each item one or two words long. \n",
"\n",
"Format your response as a list of items separated by commas.\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "f92f90fe",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"['government survey',\n",
" ' job satisfaction',\n",
" ' NASA',\n",
" ' Social Security Administration',\n",
" ' employee concerns']"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"response.split(sep=',')"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "94b8fa65",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"topic_list = [\n",
" \"nasa\", \"local government\", \"engineering\", \n",
" \"employee satisfaction\", \"federal government\"\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "34be1d2a-1309-4512-841a-b6f67338938b",
"metadata": {},
"source": [
"## Make a news alert for certain topics"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "626c5b8e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"nasa: 1\n",
"local government: 0\n",
"engineering: 0\n",
"employee satisfaction: 1\n",
"federal government: 1\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Give your answer as list with 0 or 1 for each topic.\\\n",
"\n",
"List of topics: {\", \".join(topic_list)}\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "e460853e-32ae-4171-a372-23b8eedc6cf7",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"nasa\": true,\n",
" \"local government\": false,\n",
" \"engineering\": false,\n",
" \"employee satisfaction\": true,\n",
" \"federal government\": true\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Give your answer in json format with true or false for each topic.\\\n",
"\n",
"List of topics: {\", \".join(topic_list)}\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "4b10755e-9b1f-4033-99dd-f84d704ffaf9",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"article = f\"\"\"\n",
"A fuel depot in the port city of Sevastopol, on the Crimean peninsula illegally annexed by Russia, caught fire on Saturday, causing a major blaze.\n",
"Preliminary information suggested the fire was caused by a drone strike, Mikhail Razvozhayev, the Russia-installed governor of Sevastopol, wrote on Telegram.\n",
"He said the fire at a fuel reserve in Sevastopols Kazachya Bay district engulfed “around 1,000 square meters,” but that the situation was under control and no one was hurt.\n",
"Sevastopol, which houses the naval base for Russias Black Sea fleet, has repeatedly been targeted in air attacks following Russias invasion of Ukraine last year. Russia annexed Crimea in 2014.\n",
"A spokesperson for Ukraines armed forces told Reuters that he did not have any information to suggest Ukraine was responsible for the fire.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "9de2e23b-503d-4b35-95d9-740919ab10b0",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1. Fire at fuel depot in Sevastopol - True\n",
"2. Preliminary information suggests drone strike - True\n",
"3. Fire at fuel reserve in Kazachya Bay district - True\n",
"4. No injuries reported - True\n",
"5. Sevastopol targeted in air attacks following Russia's invasion of Ukraine - True\n",
"6. Ukraine denies responsibility for the fire - True\n",
"\n",
"Summary: A fuel depot in Sevastopol caught fire, with preliminary information suggesting it was caused by a drone strike. The fire engulfed around 1,000 square meters but was under control, and no one was hurt. Sevastopol has been targeted in air attacks following Russia's invasion of Ukraine, but Ukraine denies responsibility for the fire.\n",
"\n",
"False - The text is about a fire at a fuel depot in Sevastopol, not war. However, it does mention that Sevastopol has been targeted in air attacks following Russia's invasion of Ukraine.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following numerated list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Make a summary of the text in not more then 50 words.\n",
"\n",
"Is this an text about war? Indicate this with true or false.\n",
"\n",
"Text sample: '''{article}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9d59121e-3de5-456a-9058-4b84c35eb22a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 15,
"id": "902a7c74",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ALERT: New NASA story!\n"
]
}
],
"source": [
"topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\\n')}\n",
"if topic_dict['nasa'] == 1:\n",
" print(\"ALERT: New NASA story!\")"
]
},
{
"cell_type": "markdown",
"id": "f88408ae-469a-4b02-a043-f6b4f0b14bf9",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1bd3553f",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,648 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "e3993515-9710-4ac4-89e9-b35ebb81e920",
"metadata": {
"id": "rhqRhkElpJ0z"
},
"source": [
"# Transforming\n",
"\n",
"In this notebook, we will explore how to use Large Language Models for text transformation tasks such as language translation, spelling and grammar checking, tone adjustment, and format conversion.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "41df0348",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import openai\n",
"from dotenv import find_dotenv, load_dotenv\n",
"\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv(\"OPENAI_API_KEY\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "6a85ee0f",
"metadata": {
"height": 164,
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\", temperature=0):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=temperature,\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "1d8f0bd8-628e-4c36-bcd0-2110162f25fc",
"metadata": {
"id": "zdxC4c6pwqA5"
},
"source": [
"## Translation\n",
"\n",
"ChatGPT is trained with sources in many languages. This gives the model the ability to do translation. Here are some examples of how to use this capability."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "9c4df6ff",
"metadata": {
"height": 130,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hola, me gustaría ordenar una licuadora.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following English text to Spanish: \\ \n",
"```Hi, I would like to order a blender```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7300ed9b",
"metadata": {
"height": 115,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is French.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Tell me which language this is: \n",
"```Combien coûte le lampadaire?```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "791e789b",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"French pirate: ```Je veux commander un ballon de basket```\n",
"Spanish pirate: ```Quiero pedir una pelota de baloncesto```\n",
"English pirate: ```I want to order a basketball```\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following text to French and Spanish\n",
"and English pirate: \\\n",
"```I want to order a basketball```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "fcf7eb63",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Formal: ¿Le gustaría ordenar una almohada?\n",
"Informal: ¿Te gustaría ordenar una almohada?\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following text to Spanish in both the \\\n",
"formal and informal forms: \n",
"'Would you like to order a pillow?'\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "8edb56d2-a32a-470f-9f40-4fc5b1ea0849",
"metadata": {
"id": "-hN2bczQrRC1"
},
"source": [
"### Universal Translator\n",
"Imagine you are in charge of IT at a large multinational e-commerce company. Users are messaging you with IT issues in all their native languages. Your staff is from all over the world and speaks only their native languages. You need a universal translator!"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "68a40bf0",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [],
"source": [
"user_messages = [\n",
" \"La performance du système est plus lente que d'habitude.\", # System performance is slower than normal\n",
" \"Mi monitor tiene píxeles que no se iluminan.\", # My monitor has pixels that are not lighting\n",
" \"Il mio mouse non funziona\", # My mouse is not working\n",
" \"Mój klawisz Ctrl jest zepsuty\", # My keyboard has a broken control key\n",
" \"我的屏幕在闪烁\", # My screen is flashing\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "552d0db9",
"metadata": {
"height": 215,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original message (This is French.): La performance du système est plus lente que d'habitude.\n",
"English: The system performance is slower than usual.\n",
"Korean: 시스템 성능이 평소보다 느립니다. \n",
"\n",
"Original message (This is Spanish.): Mi monitor tiene píxeles que no se iluminan.\n"
]
},
{
"ename": "RateLimitError",
"evalue": "Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mRateLimitError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[11], line 10\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mOriginal message (\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mlang\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m): \u001b[39m\u001b[38;5;132;01m{\u001b[39;00missue\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 6\u001b[0m prompt \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[1;32m 7\u001b[0m \u001b[38;5;124mTranslate the following text to English \u001b[39m\u001b[38;5;130;01m\\\u001b[39;00m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;124mand Korean: ```\u001b[39m\u001b[38;5;132;01m{\u001b[39;00missue\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m```\u001b[39m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;124m\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[0;32m---> 10\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mget_completion\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprompt\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 11\u001b[0m \u001b[38;5;28mprint\u001b[39m(response, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"Cell \u001b[0;32mIn[2], line 3\u001b[0m, in \u001b[0;36mget_completion\u001b[0;34m(prompt, model, temperature)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mget_completion\u001b[39m(prompt, model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-3.5-turbo\u001b[39m\u001b[38;5;124m\"\u001b[39m, temperature\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m0\u001b[39m):\n\u001b[1;32m 2\u001b[0m messages \u001b[38;5;241m=\u001b[39m [{\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: prompt}]\n\u001b[0;32m----> 3\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mChatCompletion\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m \u001b[49m\u001b[43mtemperature\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtemperature\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 7\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/chat_completion.py:25\u001b[0m, in \u001b[0;36mChatCompletion.create\u001b[0;34m(cls, *args, **kwargs)\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[1;32m 24\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 25\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 26\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m TryAgain \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 27\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m time\u001b[38;5;241m.\u001b[39mtime() \u001b[38;5;241m>\u001b[39m start \u001b[38;5;241m+\u001b[39m timeout:\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py:153\u001b[0m, in \u001b[0;36mEngineAPIResource.create\u001b[0;34m(cls, api_key, api_base, api_type, request_id, api_version, organization, **params)\u001b[0m\n\u001b[1;32m 127\u001b[0m \u001b[38;5;129m@classmethod\u001b[39m\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcreate\u001b[39m(\n\u001b[1;32m 129\u001b[0m \u001b[38;5;28mcls\u001b[39m,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 136\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams,\n\u001b[1;32m 137\u001b[0m ):\n\u001b[1;32m 138\u001b[0m (\n\u001b[1;32m 139\u001b[0m deployment_id,\n\u001b[1;32m 140\u001b[0m engine,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 150\u001b[0m api_key, api_base, api_type, api_version, organization, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams\n\u001b[1;32m 151\u001b[0m )\n\u001b[0;32m--> 153\u001b[0m response, _, api_key \u001b[38;5;241m=\u001b[39m \u001b[43mrequestor\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 154\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mpost\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 155\u001b[0m \u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 156\u001b[0m \u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparams\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 157\u001b[0m \u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 158\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 159\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 160\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 161\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 163\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n\u001b[1;32m 164\u001b[0m \u001b[38;5;66;03m# must be an iterator\u001b[39;00m\n\u001b[1;32m 165\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(response, OpenAIResponse)\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:226\u001b[0m, in \u001b[0;36mAPIRequestor.request\u001b[0;34m(self, method, url, params, headers, files, stream, request_id, request_timeout)\u001b[0m\n\u001b[1;32m 205\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrequest\u001b[39m(\n\u001b[1;32m 206\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 207\u001b[0m method,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 214\u001b[0m request_timeout: Optional[Union[\u001b[38;5;28mfloat\u001b[39m, Tuple[\u001b[38;5;28mfloat\u001b[39m, \u001b[38;5;28mfloat\u001b[39m]]] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 215\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], \u001b[38;5;28mbool\u001b[39m, \u001b[38;5;28mstr\u001b[39m]:\n\u001b[1;32m 216\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_raw(\n\u001b[1;32m 217\u001b[0m method\u001b[38;5;241m.\u001b[39mlower(),\n\u001b[1;32m 218\u001b[0m url,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 224\u001b[0m request_timeout\u001b[38;5;241m=\u001b[39mrequest_timeout,\n\u001b[1;32m 225\u001b[0m )\n\u001b[0;32m--> 226\u001b[0m resp, got_stream \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresult\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 227\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp, got_stream, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mapi_key\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:620\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response\u001b[0;34m(self, result, stream)\u001b[0m\n\u001b[1;32m 612\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[1;32m 613\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_interpret_response_line(\n\u001b[1;32m 614\u001b[0m line, result\u001b[38;5;241m.\u001b[39mstatus_code, result\u001b[38;5;241m.\u001b[39mheaders, stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 615\u001b[0m )\n\u001b[1;32m 616\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m line \u001b[38;5;129;01min\u001b[39;00m parse_stream(result\u001b[38;5;241m.\u001b[39miter_lines())\n\u001b[1;32m 617\u001b[0m ), \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 618\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 619\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[0;32m--> 620\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response_line\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 621\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcontent\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mutf-8\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 622\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstatus_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 623\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 624\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 625\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 626\u001b[0m \u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[1;32m 627\u001b[0m )\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:683\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response_line\u001b[0;34m(self, rbody, rcode, rheaders, stream)\u001b[0m\n\u001b[1;32m 681\u001b[0m stream_error \u001b[38;5;241m=\u001b[39m stream \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124merror\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m resp\u001b[38;5;241m.\u001b[39mdata\n\u001b[1;32m 682\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream_error \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;241m200\u001b[39m \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m rcode \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m300\u001b[39m:\n\u001b[0;32m--> 683\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhandle_error_response(\n\u001b[1;32m 684\u001b[0m rbody, rcode, resp\u001b[38;5;241m.\u001b[39mdata, rheaders, stream_error\u001b[38;5;241m=\u001b[39mstream_error\n\u001b[1;32m 685\u001b[0m )\n\u001b[1;32m 686\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
"\u001b[0;31mRateLimitError\u001b[0m: Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method."
]
}
],
"source": [
"for issue in user_messages:\n",
" prompt = f\"Tell me what language this is: ```{issue}```\"\n",
" lang = get_completion(prompt)\n",
" print(f\"Original message ({lang}): {issue}\")\n",
"\n",
" prompt = f\"\"\"\n",
" Translate the following text to English \\\n",
" and Korean: ```{issue}```\n",
" \"\"\"\n",
" response = get_completion(prompt)\n",
" print(response, \"\\n\")"
]
},
{
"cell_type": "markdown",
"id": "18e660eb-324f-474c-acf3-7e3bf5b7c70e",
"metadata": {},
"source": [
"## Try it yourself!\n",
"Try some translations on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa57158f-d77d-42d1-94fe-17fa59c012f8",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "1d9e54ca-f93a-43c8-a295-bff7a89f77f5",
"metadata": {
"id": "JH3-0vdjsILh"
},
"source": [
"## Tone Transformation\n",
"Writing can vary based on the intended audience. ChatGPT can produce different tones.\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "2deac328",
"metadata": {
"height": 130,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Sir/Madam,\n",
"\n",
"I am writing to bring to your attention a standing lamp that I believe may be of interest to you. Please find attached the specifications for your review.\n",
"\n",
"Thank you for your time and consideration.\n",
"\n",
"Sincerely,\n",
"\n",
"Joe\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following from slang to a business letter: \n",
"'Dude, This is Joe, check out this spec on this standing lamp.'\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a2c7eb73-6b82-442d-b4f8-251c308e89d5",
"metadata": {
"id": "p3e9sZh5tWIa"
},
"source": [
"## Format Conversion\n",
"ChatGPT can translate between formats. The prompt should describe the input and output formats."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "5a37f0a0",
"metadata": {
"height": 232,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<table>\n",
" <caption>Restaurant Employees</caption>\n",
" <thead>\n",
" <tr>\n",
" <th>Name</th>\n",
" <th>Email</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <td>Shyam</td>\n",
" <td>shyamjaiswal@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Bob</td>\n",
" <td>bob32@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Jai</td>\n",
" <td>jai87@gmail.com</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n"
]
}
],
"source": [
"data_json = {\n",
" \"resturant employees\": [\n",
" {\"name\": \"Shyam\", \"email\": \"shyamjaiswal@gmail.com\"},\n",
" {\"name\": \"Bob\", \"email\": \"bob32@gmail.com\"},\n",
" {\"name\": \"Jai\", \"email\": \"jai87@gmail.com\"},\n",
" ]\n",
"}\n",
"\n",
"prompt = f\"\"\"\n",
"Translate the following python dictionary from JSON to an HTML \\\n",
"table with column headers and title: {data_json}\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "481a46b7",
"metadata": {
"height": 62,
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"<table>\n",
" <caption>Restaurant Employees</caption>\n",
" <thead>\n",
" <tr>\n",
" <th>Name</th>\n",
" <th>Email</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <td>Shyam</td>\n",
" <td>shyamjaiswal@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Bob</td>\n",
" <td>bob32@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Jai</td>\n",
" <td>jai87@gmail.com</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from IPython.display import HTML, JSON, Latex, Markdown, display\n",
"\n",
"display(HTML(response))"
]
},
{
"cell_type": "markdown",
"id": "2df1824c-534b-45cb-b0c1-3000bba5adbe",
"metadata": {
"id": "qLTz16qEzyT_"
},
"source": [
"## Spellcheck/Grammar check.\n",
"\n",
"Here are some examples of common grammar and spelling problems and the LLM's response. \n",
"\n",
"To signal to the LLM that you want it to proofread your text, you instruct the model to 'proofread' or 'proofread and correct'."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "52d77283",
"metadata": {
"height": 317,
"tags": []
},
"outputs": [],
"source": [
"import time\n",
"text = [\n",
" \"The girl with the black and white puppies have a ball.\", # The girl has a ball.\n",
" \"Yolanda has her notebook.\", # ok\n",
" \"Its going to be a long day. Does the car need its oil changed?\", # Homonyms\n",
" \"Their goes my freedom. There going to bring theyre suitcases.\", # Homonyms\n",
" \"Your going to need youre notebook.\", # Homonyms\n",
" \"That medicine effects my ability to sleep. Have you heard of the butterfly affect?\", # Homonyms\n",
" \"This phrase is to cherck chatGPT for speling abilitty\", # spelling\n",
"]\n",
"for t in text:\n",
" prompt = f\"\"\"Proofread and correct the following text\n",
" and rewrite the corrected version. If you don't find\n",
" any errors, just say \"No errors found\". Don't use \n",
" any punctuation around the text:\n",
" ```{t}```\"\"\"\n",
" time.sleep(10.0)\n",
" response = get_completion(prompt)\n",
" print(response)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "7543fe7d",
"metadata": {
"height": 249,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I got this for my daughter's birthday because she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. Additionally, it's a bit small for what I paid for it. I think there might be other options that are bigger for the same price. On the positive side, it arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter.\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"Got this for my daughter for her birthday cuz she keeps taking \\\n",
"mine from my room. Yes, adults also like pandas too. She takes \\\n",
"it everywhere with her, and it's super soft and cute. One of the \\\n",
"ears is a bit lower than the other, and I don't think that was \\\n",
"designed to be asymmetrical. It's a bit small for what I paid for it \\\n",
"though. I think there might be other options that are bigger for \\\n",
"the same price. It arrived a day earlier than expected, so I got \\\n",
"to play with it myself before I gave it to my daughter.\n",
"\"\"\"\n",
"prompt = f\"proofread and correct this review: ```{text}```\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "11ac80a0",
"metadata": {
"height": 81,
"tags": []
},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'redlines'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[24], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mredlines\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Redlines\n\u001b[1;32m 3\u001b[0m diff \u001b[38;5;241m=\u001b[39m Redlines(text, response)\n\u001b[1;32m 4\u001b[0m display(Markdown(diff\u001b[38;5;241m.\u001b[39moutput_markdown))\n",
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'redlines'"
]
}
],
"source": [
"from redlines import Redlines\n",
"\n",
"diff = Redlines(text, response)\n",
"display(Markdown(diff.output_markdown))"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "2b4e73fd",
"metadata": {
"height": 164,
"tags": []
},
"outputs": [
{
"data": {
"text/markdown": [
"Title: A Soft and Cute Panda Plush Toy for All Ages\n",
"\n",
"Introduction:\n",
"As a parent, finding the perfect gift for your child's birthday can be a daunting task. However, I stumbled upon a soft and cute panda plush toy that not only made my daughter happy but also brought joy to me as an adult. In this review, I will share my experience with this product and provide an honest assessment of its features.\n",
"\n",
"Product Description:\n",
"The panda plush toy is made of high-quality materials that make it super soft and cuddly. Its cute design is perfect for children and adults alike, making it a versatile gift option. The toy is small enough to carry around, making it an ideal companion for your child on their adventures.\n",
"\n",
"Pros:\n",
"The panda plush toy is incredibly soft and cute, making it an excellent gift for children and adults. Its small size makes it easy to carry around, and its design is perfect for snuggling. The toy arrived a day earlier than expected, which was a pleasant surprise.\n",
"\n",
"Cons:\n",
"One of the ears is a bit lower than the other, which makes the toy asymmetrical. Additionally, the toy is a bit small for its price, and there might be other options that are bigger for the same price.\n",
"\n",
"Conclusion:\n",
"Overall, the panda plush toy is an excellent gift option for children and adults who love cute and cuddly toys. Despite its small size and asymmetrical design, the toy's softness and cuteness make up for its shortcomings. I highly recommend this product to anyone looking for a versatile and adorable gift option."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"prompt = f\"\"\"\n",
"proofread and correct this review. Make it more compelling. \n",
"Ensure it follows APA style guide and targets an advanced reader. \n",
"Output in markdown format.\n",
"Text: ```{text}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"display(Markdown(response))"
]
},
{
"cell_type": "markdown",
"id": "63fb76bc-a742-4b35-9dc2-f7fbc12d38fb",
"metadata": {},
"source": [
"## Try it yourself!\n",
"Try changing the instructions to form your own review."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a2b2ca58",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "3dbf5020-7d7f-4ba5-840b-20e883cd7c99",
"metadata": {
"id": "unsf1JnRr2IC"
},
"source": [
"Thanks to the following sites:\n",
"\n",
"https://writingprompts.com/bad-grammar-examples/\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,270 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "8de529e8-3891-4f47-8585-65b92b80bbf7",
"metadata": {},
"source": [
"# Expanding\n",
"In this lesson, you will generate customer service emails that are tailored to each customer's review.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "e23399a9",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4c943900-98db-40b3-b639-7822ee2c5fd8",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=temperature, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "f8ceea77-990a-4c64-bb49-3ba65eb155d2",
"metadata": {},
"source": [
"## Customize the automated reply to a customer email"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c30c4239",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# given the sentiment from the lesson on \"inferring\",\n",
"# and the original customer message, customize the email\n",
"sentiment = \"negative\"\n",
"\n",
"# review for a blender\n",
"review = f\"\"\"\n",
"So, they still had the 17 piece system on seasonal \\\n",
"sale for around $49 in the month of November, about \\\n",
"half off, but for some reason (call it price gouging) \\\n",
"around the second week of December the prices all went \\\n",
"up to about anywhere from between $70-$89 for the same \\\n",
"system. And the 11 piece system went up around $10 or \\\n",
"so in price also from the earlier sale price of $29. \\\n",
"So it looks okay, but if you look at the base, the part \\\n",
"where the blade locks into place doesnt look as good \\\n",
"as in previous editions from a few years ago, but I \\\n",
"plan to be very gentle with it (example, I crush \\\n",
"very hard items like beans, ice, rice, etc. in the \\ \n",
"blender first then pulverize them in the serving size \\\n",
"I want in the blender then switch to the whipping \\\n",
"blade for a finer flour, and use the cross cutting blade \\\n",
"first when making smoothies, then use the flat blade \\\n",
"if I need them finer/less pulpy). Special tip when making \\\n",
"smoothies, finely cut and freeze the fruits and \\\n",
"vegetables (if using spinach-lightly stew soften the \\ \n",
"spinach then freeze until ready for use-and if making \\\n",
"sorbet, use a small to medium sized food processor) \\ \n",
"that you plan to use that way you can avoid adding so \\\n",
"much ice if at all-when making your smoothie. \\\n",
"After about a year, the motor was making a funny noise. \\\n",
"I called customer service but the warranty expired \\\n",
"already, so I had to buy another one. FYI: The overall \\\n",
"quality has gone done in these types of products, so \\\n",
"they are kind of counting on brand recognition and \\\n",
"consumer loyalty to maintain sales. Got it in about \\\n",
"two days.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "d5403f73",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Valued Customer,\n",
"\n",
"Thank you for taking the time to leave a review about our 17 piece system. We are sorry to hear that you experienced a price increase and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused.\n",
"\n",
"We would like to assure you that we take all feedback seriously and we are constantly working to improve our products and services. If you have any further concerns, please do not hesitate to reach out to our customer service team who will be happy to assist you.\n",
"\n",
"Thank you again for your review and for choosing our brand. We hope to have the opportunity to serve you better in the future.\n",
"\n",
"Best regards,\n",
"\n",
"AI customer agent\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"You are a customer service AI assistant.\n",
"Your task is to send an email reply to a valued customer.\n",
"Given the customer email delimited by ```, \\\n",
"Generate a reply to thank the customer for their review.\n",
"If the sentiment is positive or neutral, thank them for \\\n",
"their review.\n",
"If the sentiment is negative, apologize and suggest that \\\n",
"they can reach out to customer service. \n",
"Make sure to use specific details from the review.\n",
"Write in a concise and professional tone.\n",
"Sign the email as `AI customer agent`.\n",
"Customer review: ```{review}```\n",
"Review sentiment: {sentiment}\n",
"Target language is English.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "55605ee0-118c-4c46-a917-4981a43fcad3",
"metadata": {},
"source": [
"## Remind the model to use details from the customer's email"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "1d5ea7c8",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Valued Customer,\n",
"\n",
"Thank you for taking the time to share your feedback with us. We're sorry to hear that you had a negative experience with our product. We apologize for any inconvenience this may have caused you.\n",
"\n",
"If you're still experiencing issues with the product, please don't hesitate to contact our customer service department for further assistance. We're here to help you in any way we can.\n",
"\n",
"Thank you again for your feedback, and we hope to have the opportunity to serve you better in the future.\n",
"\n",
"Sincerely,\n",
"\n",
"AI customer agent\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"You are a customer service AI assistant.\n",
"Your task is to send an email reply to a valued customer.\n",
"Given the customer email delimited by ```, \\\n",
"Generate a reply to thank the customer for their review.\n",
"If the sentiment is positive or neutral, thank them for \\\n",
"their review.\n",
"If the sentiment is negative, apologize and suggest that \\\n",
"they can reach out to customer service. \n",
"Make sure to use specific details from the review.\n",
"Write in a concise and professional tone.\n",
"Sign the email as `AI customer agent`.\n",
"Customer review: ```{review}```\n",
"Review sentiment: {sentiment}\n",
"\"\"\"\n",
"response = get_completion(prompt, temperature=0.7)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "31e317ad-9e51-4e7a-90c3-d88e7bf8a98c",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "ffa65c7e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Als AI-assistent heb ik geen emoties en kan ik geen verslag schrijven over hoe mensen op social media denken over de CTIVD. Echter, ik kan wel informatie geven over wat de CTIVD is en waarom mensen erover praten op social media.\n",
"\n",
"De CTIVD staat voor Commissie van Toezicht op de Inlichtingen- en Veiligheidsdiensten. Het is een onafhankelijke commissie die toezicht houdt op de activiteiten van de Nederlandse inlichtingen- en veiligheidsdiensten, zoals de AIVD en de MIVD. De CTIVD controleert of deze diensten zich houden aan de wet- en regelgeving en of hun activiteiten noodzakelijk en proportioneel zijn.\n",
"\n",
"Op social media wordt er regelmatig over de CTIVD gesproken, vooral in het kader van privacy en veiligheid. Sommige mensen vinden dat de CTIVD niet genoeg macht heeft om de inlichtingen- en veiligheidsdiensten te controleren en dat er meer transparantie nodig is. Anderen vinden juist dat de CTIVD te veel macht heeft en dat de inlichtingen- en veiligheidsdiensten hierdoor belemmerd worden in hun werk.\n",
"\n",
"Er zijn ook mensen die vinden dat de CTIVD niet goed genoeg functioneert en dat er meer aandacht moet worden besteed aan de bescherming van privacy en burgerrechten. Aan de andere kant zijn er ook mensen die vinden dat de CTIVD juist goed werk doet en dat het belangrijk is dat er toezicht is op de inlichtingen- en veiligheidsdiensten.\n",
"\n",
"Kortom, er zijn verschillende meningen over de CTIVD op social media. Het is belangrijk dat er een open discussie blijft plaatsvinden over de rol en functie van de CTIVD en hoe deze kan bijdragen aan een veilige en rechtvaardige samenleving.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Schrijf een verslag van hoe op social media gedacht wordt over de CTIVD.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,698 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Guidelines for Prompting¶\n",
"In this lesson, you'll practice two prompting principles and their related tactics in order to write effective prompts for large language models.\n",
"\n",
"Setup\n",
"Load the API key and relevant Python libaries."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv())\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"openai.api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### helper function\n",
"Throughout this course, we will use OpenAI's `gpt-3.5-turbo` model and the [chat completions endpoint](https://platform.openai.com/docs/guides/chat). \n",
"\n",
"This helper function will make it easier to use prompts and look at the generated outputs:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prompting Principles\n",
"- **Principle 1: Write clear and specific instructions**\n",
"- **Principle 2: Give the model time to “think”**\n",
"\n",
"### Tactics\n",
"\n",
"#### Tactic 1: Use delimiters to clearly indicate distinct parts of the input\n",
"- Delimiters can be anything like: ```, \"\"\", < >, `<tag> </tag>`, `:`"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clear and specific instructions should be provided to guide a model towards the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"You should express what you want a model to do by \\ \n",
"providing instructions that are as clear and \\ \n",
"specific as you can possibly make them. \\ \n",
"This will guide the model towards the desired output, \\ \n",
"and reduce the chances of receiving irrelevant \\ \n",
"or incorrect responses. Don't confuse writing a \\ \n",
"clear prompt with writing a short prompt. \\ \n",
"In many cases, longer prompts provide more clarity \\ \n",
"and context for the model, which can lead to \\ \n",
"more detailed and relevant outputs.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"Summarize the text delimited by triple backticks \\ \n",
"into a single sentence.\n",
"```{text}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 2: Ask for a structured output\n",
"- JSON, HTML"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[\n",
" {\n",
" \"book_id\": 1,\n",
" \"title\": \"The Lost City of Zorath\",\n",
" \"author\": \"Aria Blackwood\",\n",
" \"genre\": \"Fantasy\"\n",
" },\n",
" {\n",
" \"book_id\": 2,\n",
" \"title\": \"The Last Survivors\",\n",
" \"author\": \"Ethan Stone\",\n",
" \"genre\": \"Science Fiction\"\n",
" },\n",
" {\n",
" \"book_id\": 3,\n",
" \"title\": \"The Secret of the Haunted Mansion\",\n",
" \"author\": \"Lila Rose\",\n",
" \"genre\": \"Mystery\"\n",
" }\n",
"]\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Generate a list of three made-up book titles along \\ \n",
"with their authors and genres. \n",
"Provide them in JSON format with the following keys: \n",
"book_id, title, author, genre.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 3: Ask the model to check whether conditions are satisfied"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for Text 1:\n",
"Step 1 - Get some water boiling.\n",
"Step 2 - Grab a cup and put a tea bag in it.\n",
"Step 3 - Once the water is hot enough, pour it over the tea bag.\n",
"Step 4 - Let it sit for a bit so the tea can steep.\n",
"Step 5 - After a few minutes, take out the tea bag.\n",
"Step 6 - Add some sugar or milk to taste.\n",
"Step 7 - Enjoy your delicious cup of tea!\n"
]
}
],
"source": [
"text_1 = f\"\"\"\n",
"Making a cup of tea is easy! First, you need to get some \\ \n",
"water boiling. While that's happening, \\ \n",
"grab a cup and put a tea bag in it. Once the water is \\ \n",
"hot enough, just pour it over the tea bag. \\ \n",
"Let it sit for a bit so the tea can steep. After a \\ \n",
"few minutes, take out the tea bag. If you \\ \n",
"like, you can add some sugar or milk to taste. \\ \n",
"And that's it! You've got yourself a delicious \\ \n",
"cup of tea to enjoy.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"You will be provided with text delimited by triple quotes. \n",
"If it contains a sequence of instructions, \\ \n",
"re-write those instructions in the following format:\n",
"\n",
"Step 1 - ...\n",
"Step 2 - …\n",
"…\n",
"Step N - …\n",
"\n",
"If the text does not contain a sequence of instructions, \\ \n",
"then simply write \\\"No steps provided.\\\"\n",
"\n",
"\\\"\\\"\\\"{text_1}\\\"\\\"\\\"\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(\"Completion for Text 1:\")\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for Text 2:\n",
"No steps provided.\n"
]
}
],
"source": [
"text_2 = f\"\"\"\n",
"The sun is shining brightly today, and the birds are \\\n",
"singing. It's a beautiful day to go for a \\ \n",
"walk in the park. The flowers are blooming, and the \\ \n",
"trees are swaying gently in the breeze. People \\ \n",
"are out and about, enjoying the lovely weather. \\ \n",
"Some are having picnics, while others are playing \\ \n",
"games or simply relaxing on the grass. It's a \\ \n",
"perfect day to spend time outdoors and appreciate the \\ \n",
"beauty of nature.\n",
"\"\"\"\n",
"prompt = f\"\"\"\n",
"You will be provided with text delimited by triple quotes. \n",
"If it contains a sequence of instructions, \\ \n",
"re-write those instructions in the following format:\n",
"\n",
"Step 1 - ...\n",
"Step 2 - …\n",
"…\n",
"Step N - …\n",
"\n",
"If the text does not contain a sequence of instructions, \\ \n",
"then simply write \\\"No steps provided.\\\"\n",
"\n",
"\\\"\\\"\\\"{text_2}\\\"\\\"\\\"\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(\"Completion for Text 2:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 4: \"Few-shot\" prompting"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<grandparent>: Resilience is like a tree that bends with the wind but never breaks. It is the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree that grows stronger with each storm it weathers, resilience is a quality that can be developed and strengthened over time.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to answer in a consistent style.\n",
"\n",
"<child>: Teach me about patience.\n",
"\n",
"<grandparent>: The river that carves the deepest \\ \n",
"valley flows from a modest spring; the \\ \n",
"grandest symphony originates from a single note; \\ \n",
"the most intricate tapestry begins with a solitary thread.\n",
"\n",
"<child>: Teach me about resilience.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Principle 2: Give the model time to “think” \n",
"\n",
"#### Tactic 1: Specify the steps required to complete a task"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Completion for prompt 1:\n",
"Two siblings, Jack and Jill, go on a quest to fetch water from a hilltop well, but misfortune strikes as they both fall down the hill, yet they return home slightly battered but with their adventurous spirits undimmed.\n",
"\n",
"Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact. \n",
"Noms: Jack, Jill.\n",
"\n",
"{\n",
"\"french_summary\": \"Deux frères et sœurs, Jack et Jill, partent en quête d'eau d'un puits au sommet d'une colline, mais ils tombent tous les deux et retournent chez eux légèrement meurtris mais avec leur esprit d'aventure intact.\",\n",
"\"num_names\": 2\n",
"}\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"In a charming village, siblings Jack and Jill set out on \\ \n",
"a quest to fetch water from a hilltop \\ \n",
"well. As they climbed, singing joyfully, misfortune \\ \n",
"struck—Jack tripped on a stone and tumbled \\ \n",
"down the hill, with Jill following suit. \\ \n",
"Though slightly battered, the pair returned home to \\ \n",
"comforting embraces. Despite the mishap, \\ \n",
"their adventurous spirits remained undimmed, and they \\ \n",
"continued exploring with delight.\n",
"\"\"\"\n",
"# example 1\n",
"prompt_1 = f\"\"\"\n",
"Perform the following actions: \n",
"1 - Summarize the following text delimited by triple \\\n",
"backticks with 1 sentence.\n",
"2 - Translate the summary into French.\n",
"3 - List each name in the French summary.\n",
"4 - Output a json object that contains the following \\\n",
"keys: french_summary, num_names.\n",
"\n",
"Separate your answers with line breaks.\n",
"\n",
"Text:\n",
"```{text}```\n",
"\"\"\"\n",
"response = get_completion(prompt_1)\n",
"print(\"Completion for prompt 1:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Ask for output in a specified format"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"Completion for prompt 2:\n",
"Summary: Jack and Jill go on a quest to fetch water, but misfortune strikes and they tumble down the hill, returning home slightly battered but with their adventurous spirits undimmed. \n",
"Translation: Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.\n",
"Names: Jack, Jill\n",
"Output JSON: {\"french_summary\": \"Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.\", \"num_names\": 2}\n"
]
}
],
"source": [
"prompt_2 = f\"\"\"\n",
"Your task is to perform the following actions: \n",
"1 - Summarize the following text delimited by \n",
" <> with 1 sentence.\n",
"2 - Translate the summary into French.\n",
"3 - List each name in the French summary.\n",
"4 - Output a json object that contains the \n",
" following keys: french_summary, num_names.\n",
"\n",
"Use the following format:\n",
"Text: <text to summarize>\n",
"Summary: <summary>\n",
"Translation: <summary translation>\n",
"Names: <list of names in Italian summary>\n",
"Output JSON: <json with summary and num_names>\n",
"\n",
"Text: <{text}>\n",
"\"\"\"\n",
"response = get_completion(prompt_2)\n",
"print(\"\\nCompletion for prompt 2:\")\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tactic 2: Instruct the model to work out its own solution before rushing to a conclusion"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The student's solution is correct.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine if the student's solution is correct or not.\n",
"\n",
"Question:\n",
"I'm building a solar power installation and I need \\\n",
" help working out the financials. \n",
"- Land costs $100 / square foot\n",
"- I can buy solar panels for $250 / square foot\n",
"- I negotiated a contract for maintenance that will cost \\ \n",
"me a flat $100k per year, and an additional $10 / square \\\n",
"foot\n",
"What is the total cost for the first year of operations \n",
"as a function of the number of square feet.\n",
"\n",
"Student's Solution:\n",
"Let x be the size of the installation in square feet.\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel whethercost: 250x\n",
"3. Maintenance cost: 100,000 + 100x\n",
"Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"#### Note that the student's solution is actually not correct.\n",
"#### We can fix this by instructing the model to work out its own solution first."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Let x be the size of the installation in square feet.\n",
"\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel cost: 250x\n",
"3. Maintenance cost: 100,000 + 10x\n",
"\n",
"Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000\n",
"\n",
"Is the student's solution the same as actual solution just calculated:\n",
"No\n",
"\n",
"Student grade:\n",
"Incorrect\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to determine if the student's solution \\\n",
"is correct or not.\n",
"To solve the problem do the following:\n",
"- First, work out your own solution to the problem. \n",
"- Then compare your solution to the student's solution \\ \n",
"and evaluate if the student's solution is correct or not. \n",
"Don't decide if the student's solution is correct until \n",
"you have done the problem yourself.\n",
"\n",
"Use the following format:\n",
"Question:\n",
"```\n",
"question here\n",
"```\n",
"Student's solution:\n",
"```\n",
"student's solution here\n",
"```\n",
"Actual solution:\n",
"```\n",
"steps to work out the solution and your solution here\n",
"```\n",
"Is the student's solution the same as actual solution \\\n",
"just calculated:\n",
"```\n",
"yes or no\n",
"```\n",
"Student grade:\n",
"```\n",
"correct or incorrect\n",
"```\n",
"\n",
"Question:\n",
"```\n",
"I'm building a solar power installation and I need help \\\n",
"working out the financials. \n",
"- Land costs $100 / square foot\n",
"- I can buy solar panels for $250 / square foot\n",
"- I negotiated a contract for maintenance that will cost \\\n",
"me a flat $100k per year, and an additional $10 / square \\\n",
"foot\n",
"What is the total cost for the first year of operations \\\n",
"as a function of the number of square feet.\n",
"``` \n",
"Student's solution:\n",
"```\n",
"Let x be the size of the installation in square feet.\n",
"Costs:\n",
"1. Land cost: 100x\n",
"2. Solar panel cost: 250x\n",
"3. Maintenance cost: 100,000 + 100x\n",
"Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000\n",
"```\n",
"Actual solution:\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Model Limitations: Hallucinations\n",
"- Boie is a real company, the product name is not real."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The AeroGlide UltraSlim Smart Toothbrush by Boie is a high-tech toothbrush that uses advanced sonic technology to provide a deep and thorough clean. It features a slim and sleek design that makes it easy to hold and maneuver, and it comes with a range of smart features that help you optimize your brushing routine.\n",
"\n",
"One of the key features of the AeroGlide UltraSlim Smart Toothbrush is its sonic technology, which uses high-frequency vibrations to break up plaque and bacteria on your teeth and gums. This technology is highly effective at removing even the most stubborn stains and buildup, and it can help you achieve a brighter, healthier smile in just a few weeks.\n",
"\n",
"In addition to its sonic technology, the AeroGlide UltraSlim Smart Toothbrush also comes with a range of smart features that help you optimize your brushing routine. These include a built-in timer that ensures you brush for the recommended two minutes, as well as a pressure sensor that alerts you if you're brushing too hard.\n",
"\n",
"Overall, the AeroGlide UltraSlim Smart Toothbrush by Boie is a highly advanced and effective toothbrush that can help you achieve a brighter, healthier smile in no time. Whether you're looking to improve your oral hygiene or simply want a more convenient and effective way to brush your teeth, this toothbrush is definitely worth considering.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes on using the OpenAI API outside of this classroom\n",
"\n",
"To install the OpenAI Python library:\n",
"```\n",
"!pip install openai\n",
"```\n",
"\n",
"The library needs to be configured with your account's secret key, which is available on the [website](https://platform.openai.com/account/api-keys). \n",
"\n",
"You can either set it as the `OPENAI_API_KEY` environment variable before using the library:\n",
" ```\n",
" !export OPENAI_API_KEY='sk-...'\n",
" ```\n",
"\n",
"Or, set `openai.api_key` to its value:\n",
"\n",
"```\n",
"import openai\n",
"openai.api_key = \"sk-...\"\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes on using the OpenAI API outside of this classroom\n",
"\n",
"To install the OpenAI Python library:\n",
"```\n",
"!pip install openai\n",
"```\n",
"\n",
"The library needs to be configured with your account's secret key, which is available on the [website](https://platform.openai.com/account/api-keys). \n",
"\n",
"You can either set it as the `OPENAI_API_KEY` environment variable before using the library:\n",
" ```\n",
" !export OPENAI_API_KEY='sk-...'\n",
" ```\n",
"\n",
"Or, set `openai.api_key` to its value:\n",
"\n",
"```\n",
"import openai\n",
"openai.api_key = \"sk-...\"\n",
"```"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View File

@ -0,0 +1,545 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "17e90050-86ad-41bd-8d35-30ffd122d98a",
"metadata": {},
"source": [
"# Iterative Prompt Develelopment\n",
"In this lesson, you'll iteratively analyze and refine your prompts to generate marketing copy from a product fact sheet.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2c9d12c7-ce76-4d7f-946a-5c7a1793dc7e",
"metadata": {
"tags": []
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'os' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[1], line 6\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mdotenv\u001b[39;00m \u001b[39mimport\u001b[39;00m load_dotenv, find_dotenv\n\u001b[1;32m 4\u001b[0m _ \u001b[39m=\u001b[39m load_dotenv(find_dotenv()) \u001b[39m# read local .env file\u001b[39;00m\n\u001b[0;32m----> 6\u001b[0m openai\u001b[39m.\u001b[39mapi_key \u001b[39m=\u001b[39m os\u001b[39m.\u001b[39mgetenv(\u001b[39m'\u001b[39m\u001b[39mOPENAI_API_KEY\u001b[39m\u001b[39m'\u001b[39m)\n",
"\u001b[0;31mNameError\u001b[0m: name 'os' is not defined"
]
}
],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d455ad18-df5f-4556-92bd-949e78c523e8",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "b026a41d-4e62-4168-a52c-1fade8ea3208",
"metadata": {},
"source": [
"## Generate a marketing product description from a product fact sheet"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "94112890-73c1-435e-8aab-e66dfcb67226",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"fact_sheet_chair = \"\"\"\n",
"OVERVIEW\n",
"- Part of a beautiful family of mid-century inspired office furniture, \n",
"including filing cabinets, desks, bookcases, meeting tables, and more.\n",
"- Several options of shell color and base finishes.\n",
"- Available with plastic back and front upholstery (SWC-100) \n",
"or full upholstery (SWC-110) in 10 fabric and 6 leather options.\n",
"- Base finish options are: stainless steel, matte black, \n",
"gloss white, or chrome.\n",
"- Chair is available with or without armrests.\n",
"- Suitable for home or business settings.\n",
"- Qualified for contract use.\n",
"\n",
"CONSTRUCTION\n",
"- 5-wheel plastic coated aluminum base.\n",
"- Pneumatic chair adjust for easy raise/lower action.\n",
"\n",
"DIMENSIONS\n",
"- WIDTH 53 CM | 20.87”\n",
"- DEPTH 51 CM | 20.08”\n",
"- HEIGHT 80 CM | 31.50”\n",
"- SEAT HEIGHT 44 CM | 17.32”\n",
"- SEAT DEPTH 41 CM | 16.14”\n",
"\n",
"OPTIONS\n",
"- Soft or hard-floor caster options.\n",
"- Two choices of seat foam densities: \n",
" medium (1.8 lb/ft3) or high (2.8 lb/ft3)\n",
"- Armless or 8 position PU armrests \n",
"\n",
"MATERIALS\n",
"SHELL BASE GLIDER\n",
"- Cast Aluminum with modified nylon PA6/PA66 coating.\n",
"- Shell thickness: 10 mm.\n",
"SEAT\n",
"- HD36 foam\n",
"\n",
"COUNTRY OF ORIGIN\n",
"- Italy\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "f5e3513c-c9bb-4bbe-8282-194e9a548fed",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our stunning mid-century inspired office chair, the perfect addition to any home or business setting. Part of a beautiful family of office furniture, including filing cabinets, desks, bookcases, meeting tables, and more, this chair is available in several options of shell color and base finishes to suit your style. Choose from plastic back and front upholstery (SWC-100) or full upholstery (SWC-110) in 10 fabric and 6 leather options.\n",
"\n",
"The chair is constructed with a 5-wheel plastic coated aluminum base and features a pneumatic chair adjust for easy raise/lower action. It is available with or without armrests and is qualified for contract use. The base finish options are stainless steel, matte black, gloss white, or chrome.\n",
"\n",
"Measuring at a width of 53 cm, depth of 51 cm, and height of 80 cm, with a seat height of 44 cm and seat depth of 41 cm, this chair is designed for ultimate comfort. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are available in either an armless or 8 position PU option.\n",
"\n",
"The materials used in the construction of this chair are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating and has a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and durability.\n",
"\n",
"This chair is made in Italy and is the perfect combination of style and functionality. Upgrade your workspace with our mid-century inspired office chair today!\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "9217aa0b-61c5-413e-bfa1-089b03f7594b",
"metadata": {},
"source": [
"## Issue 1: The text is too long \n",
"- Limit the number of words/sentences/characters."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "dda8f0c8-f8e9-497e-9371-9aedc3e70c2a",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for home or business settings. Available in a range of shell colors and base finishes, with or without armrests. Choose from 10 fabric and 6 leather options for full or plastic upholstery. With a 5-wheel base and pneumatic chair adjust, it's both stylish and functional. Made in Italy.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"Use at most 50 words.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "85926c49-9581-41be-a0e9-aca9341e40b2",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"55"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(response.split(\" \"))"
]
},
{
"cell_type": "markdown",
"id": "e46f7130-a92e-4e5b-881f-ec2e0b34d73e",
"metadata": {
"tags": []
},
"source": [
"## Issue 2. Text focuses on the wrong details\n",
"- Ask it to focus on the aspects that are relevant to the intended audience."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "302d7eb6-5925-4b26-852a-fa0081b1019d",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for both home and business settings. With a range of shell colors and base finishes to choose from, this chair is available with or without armrests and features a 5-wheel plastic coated aluminum base with pneumatic chair adjust for easy raise/lower action. Constructed with a cast aluminum shell and HD36 foam seat, this chair is made in Italy and qualified for contract use.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"Use at most 3 sentences.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "e3e3d5e1-f0c3-4585-b90b-5bd5806fc7af",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing our mid-century inspired office chair, perfect for home or business settings. With multiple shell color and base finish options, and a choice of plastic or full upholstery, this chair is both stylish and comfortable. Constructed with a 5-wheel plastic coated aluminum base and pneumatic chair adjust, it's also durable and easy to use. Available with or without armrests and suitable for contract use. Product IDs: SWC-100, SWC-110.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"At the end of the description, include every 7-character \n",
"Product ID in the technical specification.\n",
"\n",
"Use at most 280 characters.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "e6852490-595f-42dd-a1e9-3f84611f1d84",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"444"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(response)"
]
},
{
"cell_type": "markdown",
"id": "ed4239e5-48c7-4eab-914c-cef978307c00",
"metadata": {},
"source": [
"## Issue 3. Description needs a table of dimensions\n",
"- Ask it to extract information and organize it in a table."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "f4dba81a-514e-4c12-90df-0370f42d206e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<div>\n",
"<h2>Mid-Century Inspired Office Chair</h2>\n",
"<p>Introducing our mid-century inspired office chair, part of a beautiful family of office furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. This chair is available in several options of shell color and base finishes, allowing you to customize it to your liking. You can choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome. The chair is also available with or without armrests, making it suitable for both home and business settings. Plus, it's qualified for contract use, ensuring its durability and longevity.</p>\n",
"<p>The chair's construction features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are also customizable, with the option of armless or 8 position PU armrests.</p>\n",
"<p>The materials used in the chair's construction are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating, with a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and support.</p>\n",
"<p>Made in Italy, this mid-century inspired office chair is the perfect addition to any office space. Order yours today!</p>\n",
"<h3>Product IDs:</h3>\n",
"<ul>\n",
"<li>SWC-100</li>\n",
"<li>SWC-110</li>\n",
"</ul>\n",
"</div>\n",
"\n",
"<table>\n",
" <caption>Product Dimensions</caption>\n",
" <tr>\n",
" <th>Dimension</th>\n",
" <th>Measurement (inches)</th>\n",
" </tr>\n",
" <tr>\n",
" <td>Width</td>\n",
" <td>20.87\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Depth</td>\n",
" <td>20.08\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Height</td>\n",
" <td>31.50\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Height</td>\n",
" <td>17.32\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Depth</td>\n",
" <td>16.14\"</td>\n",
" </tr>\n",
"</table>\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to help a marketing team create a \n",
"description for a retail website of a product based \n",
"on a technical fact sheet.\n",
"\n",
"Write a product description based on the information \n",
"provided in the technical specifications delimited by \n",
"triple backticks.\n",
"\n",
"The description is intended for furniture retailers, \n",
"so should be technical in nature and focus on the \n",
"materials the product is constructed from.\n",
"\n",
"At the end of the description, include every 7-character \n",
"Product ID in the technical specification.\n",
"\n",
"After the description, include a table that gives the \n",
"product's dimensions. The table should have two columns.\n",
"In the first column include the name of the dimension. \n",
"In the second column include the measurements in inches only.\n",
"\n",
"Give the table the title 'Product Dimensions'.\n",
"\n",
"Format everything as HTML that can be used in a website. \n",
"Place the description in a <div> element.\n",
"\n",
"Technical specifications: ```{fact_sheet_chair}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "2235fbc9-fa1c-4eb9-a51c-1b833978c5b3",
"metadata": {},
"source": [
"## Load Python libraries to view HTML"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "137ee58f-f6dd-4f2c-aafb-03ca260c9fe7",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from IPython.display import display, HTML"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "1d10bb98-2ced-452a-bcf0-cb9e9fd21200",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<h2>Mid-Century Inspired Office Chair</h2>\n",
"<p>Introducing our mid-century inspired office chair, part of a beautiful family of office furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. This chair is available in several options of shell color and base finishes, allowing you to customize it to your liking. You can choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome. The chair is also available with or without armrests, making it suitable for both home and business settings. Plus, it's qualified for contract use, ensuring its durability and longevity.</p>\n",
"<p>The chair's construction features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are also customizable, with the option of armless or 8 position PU armrests.</p>\n",
"<p>The materials used in the chair's construction are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating, with a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and support.</p>\n",
"<p>Made in Italy, this mid-century inspired office chair is the perfect addition to any office space. Order yours today!</p>\n",
"<h3>Product IDs:</h3>\n",
"<ul>\n",
"<li>SWC-100</li>\n",
"<li>SWC-110</li>\n",
"</ul>\n",
"</div>\n",
"\n",
"<table>\n",
" <caption>Product Dimensions</caption>\n",
" <tr>\n",
" <th>Dimension</th>\n",
" <th>Measurement (inches)</th>\n",
" </tr>\n",
" <tr>\n",
" <td>Width</td>\n",
" <td>20.87\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Depth</td>\n",
" <td>20.08\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Height</td>\n",
" <td>31.50\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Height</td>\n",
" <td>17.32\"</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Seat Depth</td>\n",
" <td>16.14\"</td>\n",
" </tr>\n",
"</table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"display(HTML(response))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,438 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "87857393-6369-4b66-87c9-5f3253edf28e",
"metadata": {},
"source": [
"# Summarizing\n",
"In this lesson, you will summarize text with a focus on specific topics.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "8ac673e1",
"metadata": {
"height": 147
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "66de8ca6",
"metadata": {
"height": 181
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]\n"
]
},
{
"cell_type": "markdown",
"id": "387b0686-bea6-41a2-b879-88721dc0ec10",
"metadata": {},
"source": [
"## Text to summarize"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "0ce2cf3c",
"metadata": {
"height": 198
},
"outputs": [],
"source": [
"prod_review = \"\"\"\n",
"Got this panda plush toy for my daughter's birthday, \\\n",
"who loves it and takes it everywhere. It's soft and \\ \n",
"super cute, and its face has a friendly look. It's \\ \n",
"a bit small for what I paid though. I think there \\ \n",
"might be other options that are bigger for the \\ \n",
"same price. It arrived a day earlier than expected, \\ \n",
"so I got to play with it myself before I gave it \\ \n",
"to her.\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "5d95eba0-7744-491a-a30a-8ee687303b7a",
"metadata": {},
"source": [
"## Summarize with a word/sentence/character limit"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "0c3023c6",
"metadata": {
"height": 249
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "90832908-3b3a-459b-b595-bbe15c2a72fa",
"metadata": {},
"source": [
"## Summarize with a focus on shipping and delivery"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "d850bdd2",
"metadata": {
"height": 283
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The panda plush toy arrived a day earlier than expected, but the customer felt it was a bit small for the price paid.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site to give feedback to the \\\n",
"Shipping deparmtment. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words, and focusing on any aspects \\\n",
"that mention shipping and delivery of the product. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "01204385-1d27-420c-80ee-bd4b524550f6",
"metadata": {},
"source": [
"## Summarize with a focus on price and value"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "6d865432",
"metadata": {
"height": 300
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The panda plush toy is soft, cute, and loved by the recipient, but the price may be too high for its size compared to other options.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to generate a short summary of a product \\\n",
"review from an ecommerce site to give feedback to the \\\n",
"pricing deparmtment, responsible for determining the \\\n",
"price of the product. \n",
"\n",
"Summarize the review below, delimited by triple \n",
"backticks, in at most 30 words, and focusing on any aspects \\\n",
"that are relevant to the price and perceived value. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"id": "21a561c4-d9a0-48a8-86c4-725746fb08df",
"metadata": {},
"source": [
"#### Comment\n",
"- Summaries include topics that are not related to the topic of focus."
]
},
{
"cell_type": "markdown",
"id": "9aff99cd-dc09-467c-bd09-897ffe06a232",
"metadata": {},
"source": [
"## Try \"extract\" instead of \"summarize\""
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "190943b0",
"metadata": {
"height": 266
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The product arrived a day earlier than expected.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Your task is to extract relevant information from \\ \n",
"a product review from an ecommerce site to give \\\n",
"feedback to the Shipping department. \n",
"\n",
"From the review below, delimited by triple quotes \\\n",
"extract the information relevant to shipping and \\ \n",
"delivery. Limit to 30 words. \n",
"\n",
"Review: ```{prod_review}```\n",
"\"\"\"\n",
"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "f513da2e-f89c-4c91-8456-b79c630e70c9",
"metadata": {},
"source": [
"## Summarize multiple product reviews"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "027822c2",
"metadata": {
"height": 1286
},
"outputs": [],
"source": [
"\n",
"review_1 = prod_review \n",
"\n",
"# review for a standing lamp\n",
"review_2 = \"\"\"\n",
"Needed a nice lamp for my bedroom, and this one \\\n",
"had additional storage and not too high of a price \\\n",
"point. Got it fast - arrived in 2 days. The string \\\n",
"to the lamp broke during the transit and the company \\\n",
"happily sent over a new one. Came within a few days \\\n",
"as well. It was easy to put together. Then I had a \\\n",
"missing part, so I contacted their support and they \\\n",
"very quickly got me the missing piece! Seems to me \\\n",
"to be a great company that cares about their customers \\\n",
"and products. \n",
"\"\"\"\n",
"\n",
"# review for an electric toothbrush\n",
"review_3 = \"\"\"\n",
"My dental hygienist recommended an electric toothbrush, \\\n",
"which is why I got this. The battery life seems to be \\\n",
"pretty impressive so far. After initial charging and \\\n",
"leaving the charger plugged in for the first week to \\\n",
"condition the battery, I've unplugged the charger and \\\n",
"been using it for twice daily brushing for the last \\\n",
"3 weeks all on the same charge. But the toothbrush head \\\n",
"is too small. Ive seen baby toothbrushes bigger than \\\n",
"this one. I wish the head was bigger with different \\\n",
"length bristles to get between teeth better because \\\n",
"this one doesnt. Overall if you can get this one \\\n",
"around the $50 mark, it's a good deal. The manufactuer's \\\n",
"replacements heads are pretty expensive, but you can \\\n",
"get generic ones that're more reasonably priced. This \\\n",
"toothbrush makes me feel like I've been to the dentist \\\n",
"every day. My teeth feel sparkly clean! \n",
"\"\"\"\n",
"\n",
"# review for a blender\n",
"review_4 = \"\"\"\n",
"So, they still had the 17 piece system on seasonal \\\n",
"sale for around $49 in the month of November, about \\\n",
"half off, but for some reason (call it price gouging) \\\n",
"around the second week of December the prices all went \\\n",
"up to about anywhere from between $70-$89 for the same \\\n",
"system. And the 11 piece system went up around $10 or \\\n",
"so in price also from the earlier sale price of $29. \\\n",
"So it looks okay, but if you look at the base, the part \\\n",
"where the blade locks into place doesnt look as good \\\n",
"as in previous editions from a few years ago, but I \\\n",
"plan to be very gentle with it (example, I crush \\\n",
"very hard items like beans, ice, rice, etc. in the \\ \n",
"blender first then pulverize them in the serving size \\\n",
"I want in the blender then switch to the whipping \\\n",
"blade for a finer flour, and use the cross cutting blade \\\n",
"first when making smoothies, then use the flat blade \\\n",
"if I need them finer/less pulpy). Special tip when making \\\n",
"smoothies, finely cut and freeze the fruits and \\\n",
"vegetables (if using spinach-lightly stew soften the \\ \n",
"spinach then freeze until ready for use-and if making \\\n",
"sorbet, use a small to medium sized food processor) \\ \n",
"that you plan to use that way you can avoid adding so \\\n",
"much ice if at all-when making your smoothie. \\\n",
"After about a year, the motor was making a funny noise. \\\n",
"I called customer service but the warranty expired \\\n",
"already, so I had to buy another one. FYI: The overall \\\n",
"quality has gone done in these types of products, so \\\n",
"they are kind of counting on brand recognition and \\\n",
"consumer loyalty to maintain sales. Got it in about \\\n",
"two days.\n",
"\"\"\"\n",
"\n",
"reviews = [review_1, review_2, review_3, review_4]\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "b7c39cc8",
"metadata": {
"height": 266
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early. \n",
"\n",
"1 Affordable lamp with storage, fast shipping, and excellent customer service. Easy to assemble and missing parts were quickly replaced. \n",
"\n",
"2 Good battery life, small toothbrush head, but effective cleaning. Good deal if bought around $50. \n",
"\n"
]
},
{
"ename": "RateLimitError",
"evalue": "Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mRateLimitError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[12], line 12\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;28mlen\u001b[39m(reviews)):\n\u001b[1;32m 2\u001b[0m prompt \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;124m Your task is to generate a short summary of a product \u001b[39m\u001b[38;5;124m\\\u001b[39m\u001b[38;5;124m \u001b[39m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;124m review from an ecommerce site. \u001b[39m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;124m Review: ```\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mreviews[i]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m```\u001b[39m\n\u001b[1;32m 10\u001b[0m \u001b[38;5;124m \u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[0;32m---> 12\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mget_completion\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprompt\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 13\u001b[0m \u001b[38;5;28mprint\u001b[39m(i, response, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"Cell \u001b[0;32mIn[4], line 3\u001b[0m, in \u001b[0;36mget_completion\u001b[0;34m(prompt, model)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mget_completion\u001b[39m(prompt, model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-3.5-turbo\u001b[39m\u001b[38;5;124m\"\u001b[39m): \u001b[38;5;66;03m# Andrew mentioned that the prompt/ completion paradigm is preferable for this class\u001b[39;00m\n\u001b[1;32m 2\u001b[0m messages \u001b[38;5;241m=\u001b[39m [{\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: prompt}]\n\u001b[0;32m----> 3\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mChatCompletion\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m \u001b[49m\u001b[43mtemperature\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# this is the degree of randomness of the model's output\u001b[39;49;00m\n\u001b[1;32m 7\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/chat_completion.py:25\u001b[0m, in \u001b[0;36mChatCompletion.create\u001b[0;34m(cls, *args, **kwargs)\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[1;32m 24\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 25\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 26\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m TryAgain \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 27\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m time\u001b[38;5;241m.\u001b[39mtime() \u001b[38;5;241m>\u001b[39m start \u001b[38;5;241m+\u001b[39m timeout:\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py:153\u001b[0m, in \u001b[0;36mEngineAPIResource.create\u001b[0;34m(cls, api_key, api_base, api_type, request_id, api_version, organization, **params)\u001b[0m\n\u001b[1;32m 127\u001b[0m \u001b[38;5;129m@classmethod\u001b[39m\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcreate\u001b[39m(\n\u001b[1;32m 129\u001b[0m \u001b[38;5;28mcls\u001b[39m,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 136\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams,\n\u001b[1;32m 137\u001b[0m ):\n\u001b[1;32m 138\u001b[0m (\n\u001b[1;32m 139\u001b[0m deployment_id,\n\u001b[1;32m 140\u001b[0m engine,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 150\u001b[0m api_key, api_base, api_type, api_version, organization, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams\n\u001b[1;32m 151\u001b[0m )\n\u001b[0;32m--> 153\u001b[0m response, _, api_key \u001b[38;5;241m=\u001b[39m \u001b[43mrequestor\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 154\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mpost\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 155\u001b[0m \u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 156\u001b[0m \u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparams\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 157\u001b[0m \u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 158\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 159\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 160\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 161\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 163\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n\u001b[1;32m 164\u001b[0m \u001b[38;5;66;03m# must be an iterator\u001b[39;00m\n\u001b[1;32m 165\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(response, OpenAIResponse)\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:226\u001b[0m, in \u001b[0;36mAPIRequestor.request\u001b[0;34m(self, method, url, params, headers, files, stream, request_id, request_timeout)\u001b[0m\n\u001b[1;32m 205\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrequest\u001b[39m(\n\u001b[1;32m 206\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 207\u001b[0m method,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 214\u001b[0m request_timeout: Optional[Union[\u001b[38;5;28mfloat\u001b[39m, Tuple[\u001b[38;5;28mfloat\u001b[39m, \u001b[38;5;28mfloat\u001b[39m]]] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 215\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], \u001b[38;5;28mbool\u001b[39m, \u001b[38;5;28mstr\u001b[39m]:\n\u001b[1;32m 216\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_raw(\n\u001b[1;32m 217\u001b[0m method\u001b[38;5;241m.\u001b[39mlower(),\n\u001b[1;32m 218\u001b[0m url,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 224\u001b[0m request_timeout\u001b[38;5;241m=\u001b[39mrequest_timeout,\n\u001b[1;32m 225\u001b[0m )\n\u001b[0;32m--> 226\u001b[0m resp, got_stream \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresult\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 227\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp, got_stream, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mapi_key\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:620\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response\u001b[0;34m(self, result, stream)\u001b[0m\n\u001b[1;32m 612\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[1;32m 613\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_interpret_response_line(\n\u001b[1;32m 614\u001b[0m line, result\u001b[38;5;241m.\u001b[39mstatus_code, result\u001b[38;5;241m.\u001b[39mheaders, stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 615\u001b[0m )\n\u001b[1;32m 616\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m line \u001b[38;5;129;01min\u001b[39;00m parse_stream(result\u001b[38;5;241m.\u001b[39miter_lines())\n\u001b[1;32m 617\u001b[0m ), \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 618\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 619\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[0;32m--> 620\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response_line\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 621\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcontent\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mutf-8\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 622\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstatus_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 623\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 624\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 625\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 626\u001b[0m \u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[1;32m 627\u001b[0m )\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:683\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response_line\u001b[0;34m(self, rbody, rcode, rheaders, stream)\u001b[0m\n\u001b[1;32m 681\u001b[0m stream_error \u001b[38;5;241m=\u001b[39m stream \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124merror\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m resp\u001b[38;5;241m.\u001b[39mdata\n\u001b[1;32m 682\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream_error \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;241m200\u001b[39m \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m rcode \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m300\u001b[39m:\n\u001b[0;32m--> 683\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhandle_error_response(\n\u001b[1;32m 684\u001b[0m rbody, rcode, resp\u001b[38;5;241m.\u001b[39mdata, rheaders, stream_error\u001b[38;5;241m=\u001b[39mstream_error\n\u001b[1;32m 685\u001b[0m )\n\u001b[1;32m 686\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
"\u001b[0;31mRateLimitError\u001b[0m: Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method."
]
}
],
"source": [
"for i in range(len(reviews)):\n",
" prompt = f\"\"\"\n",
" Your task is to generate a short summary of a product \\ \n",
" review from an ecommerce site. \n",
"\n",
" Summarize the review below, delimited by triple \\\n",
" backticks in at most 20 words. \n",
"\n",
" Review: ```{reviews[i]}```\n",
" \"\"\"\n",
"\n",
" response = get_completion(prompt)\n",
" print(i, response, \"\\n\")\n"
]
},
{
"cell_type": "markdown",
"id": "e0c9f921-8672-4124-bad6-8bee65078ccb",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d05d8a20-86f2-4613-835e-41c49a504b5b",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,652 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "3630c235-f891-4874-bd0a-5277d4d6aa82",
"metadata": {},
"source": [
"# Inferring\n",
"In this lesson, you will infer sentiment and topics from product reviews and news articles.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "39689e67",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e82f5577",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=0, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "51d2fdfa-c99f-4750-8574-dba7712cd7f0",
"metadata": {},
"source": [
"## Product review text"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b0f3b49b",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"lamp_review = \"\"\"\n",
"Needed a nice lamp for my bedroom, and this one had \\\n",
"additional storage and not too high of a price point. \\\n",
"Got it fast. The string to our lamp broke during the \\\n",
"transit and the company happily sent over a new one. \\\n",
"Came within a few days as well. It was easy to put \\\n",
"together. I had a missing part, so I contacted their \\\n",
"support and they very quickly got me the missing piece! \\\n",
"Lumina seems to me to be a great company that cares \\\n",
"about their customers and products!!\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "30d6e4bd-3337-45a3-8c99-a734cdd06743",
"metadata": {},
"source": [
"## Sentiment (positive/negative)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "e3157601",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The sentiment of the product review is positive.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"What is the sentiment of the following product review, \n",
"which is delimited with triple backticks?\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "acf9ca16",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"positive\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"What is the sentiment of the following product review, \n",
"which is delimited with triple backticks?\n",
"\n",
"Give your answer as a single word, either \"positive\" \\\n",
"or \"negative\".\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "81d2a973-1fa4-4a35-ae35-a2e746c0e91b",
"metadata": {},
"source": [
"## Identify types of emotions"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "8aa7934b",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"happy, satisfied, grateful, impressed, content\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify a list of emotions that the writer of the \\\n",
"following review is expressing. Include no more than \\\n",
"five items in the list. Format your answer as a list of \\\n",
"lower-case words separated by commas.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a428d093-51c9-461c-b41e-114e80876409",
"metadata": {},
"source": [
"## Identify anger"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "dba1a538",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Is the writer of the following review expressing anger?\\\n",
"The review is delimited with triple backticks. \\\n",
"Give your answer as either yes or no.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "936a771e-ca78-4e55-8088-2da6f3820ddc",
"metadata": {},
"source": [
"## Extract product and company name from customer reviews"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "a13bea1b",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"Item\": \"lamp\",\n",
" \"Brand\": \"Lumina\"\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify the following items from the review text: \n",
"- Item purchased by reviewer\n",
"- Company that made the item\n",
"\n",
"The review is delimited with triple backticks. \\\n",
"Format your response as a JSON object with \\\n",
"\"Item\" and \"Brand\" as the keys. \n",
"If the information isn't present, use \"unknown\" \\\n",
"as the value.\n",
"Make your response as short as possible.\n",
" \n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a38880a5-088f-4609-9913-f8fa41fb7ba0",
"metadata": {},
"source": [
"## Doing multiple tasks at once"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "e7dda9e5",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"Sentiment\": \"positive\",\n",
" \"Anger\": false,\n",
" \"Item\": \"lamp with additional storage\",\n",
" \"Brand\": \"Lumina\"\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Identify the following items from the review text: \n",
"- Sentiment (positive or negative)\n",
"- Is the reviewer expressing anger? (true or false)\n",
"- Item purchased by reviewer\n",
"- Company that made the item\n",
"\n",
"The review is delimited with triple backticks. \\\n",
"Format your response as a JSON object with \\\n",
"\"Sentiment\", \"Anger\", \"Item\" and \"Brand\" as the keys.\n",
"If the information isn't present, use \"unknown\" \\\n",
"as the value.\n",
"Make your response as short as possible.\n",
"Format the Anger value as a boolean.\n",
"\n",
"Review text: '''{lamp_review}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "235fc223-2c89-49ec-ac2d-78a8e74a43ac",
"metadata": {},
"source": [
"## Inferring topics"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "8a74cc3e",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"story = \"\"\"\n",
"In a recent survey conducted by the government, \n",
"public sector employees were asked to rate their level \n",
"of satisfaction with the department they work at. \n",
"The results revealed that NASA was the most popular \n",
"department with a satisfaction rating of 95%.\n",
"\n",
"One NASA employee, John Smith, commented on the findings, \n",
"stating, \"I'm not surprised that NASA came out on top. \n",
"It's a great place to work with amazing people and \n",
"incredible opportunities. I'm proud to be a part of \n",
"such an innovative organization.\"\n",
"\n",
"The results were also welcomed by NASA's management team, \n",
"with Director Tom Johnson stating, \"We are thrilled to \n",
"hear that our employees are satisfied with their work at NASA. \n",
"We have a talented and dedicated team who work tirelessly \n",
"to achieve our goals, and it's fantastic to see that their \n",
"hard work is paying off.\"\n",
"\n",
"The survey also revealed that the \n",
"Social Security Administration had the lowest satisfaction \n",
"rating, with only 45% of employees indicating they were \n",
"satisfied with their job. The government has pledged to \n",
"address the concerns raised by employees in the survey and \n",
"work towards improving job satisfaction across all departments.\n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "a8ea91d6-e841-4ee2-bed9-ca4a36df177f",
"metadata": {},
"source": [
"## Infer 5 topics"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "5c267cbe",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"government survey, job satisfaction, NASA, Social Security Administration, employee concerns\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine five topics that are being discussed in the \\\n",
"following text, which is delimited by triple backticks.\n",
"\n",
"Make each item one or two words long. \n",
"\n",
"Format your response as a list of items separated by commas.\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "f92f90fe",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"['government survey',\n",
" ' job satisfaction',\n",
" ' NASA',\n",
" ' Social Security Administration',\n",
" ' employee concerns']"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"response.split(sep=',')"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "94b8fa65",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"topic_list = [\n",
" \"nasa\", \"local government\", \"engineering\", \n",
" \"employee satisfaction\", \"federal government\"\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "34be1d2a-1309-4512-841a-b6f67338938b",
"metadata": {},
"source": [
"## Make a news alert for certain topics"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "626c5b8e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"nasa: 1\n",
"local government: 0\n",
"engineering: 0\n",
"employee satisfaction: 1\n",
"federal government: 1\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Give your answer as list with 0 or 1 for each topic.\\\n",
"\n",
"List of topics: {\", \".join(topic_list)}\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "e460853e-32ae-4171-a372-23b8eedc6cf7",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\n",
" \"nasa\": true,\n",
" \"local government\": false,\n",
" \"engineering\": false,\n",
" \"employee satisfaction\": true,\n",
" \"federal government\": true\n",
"}\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Give your answer in json format with true or false for each topic.\\\n",
"\n",
"List of topics: {\", \".join(topic_list)}\n",
"\n",
"Text sample: '''{story}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "4b10755e-9b1f-4033-99dd-f84d704ffaf9",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"article = f\"\"\"\n",
"A fuel depot in the port city of Sevastopol, on the Crimean peninsula illegally annexed by Russia, caught fire on Saturday, causing a major blaze.\n",
"Preliminary information suggested the fire was caused by a drone strike, Mikhail Razvozhayev, the Russia-installed governor of Sevastopol, wrote on Telegram.\n",
"He said the fire at a fuel reserve in Sevastopols Kazachya Bay district engulfed “around 1,000 square meters,” but that the situation was under control and no one was hurt.\n",
"Sevastopol, which houses the naval base for Russias Black Sea fleet, has repeatedly been targeted in air attacks following Russias invasion of Ukraine last year. Russia annexed Crimea in 2014.\n",
"A spokesperson for Ukraines armed forces told Reuters that he did not have any information to suggest Ukraine was responsible for the fire.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "9de2e23b-503d-4b35-95d9-740919ab10b0",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1. Fire at fuel depot in Sevastopol - True\n",
"2. Preliminary information suggests drone strike - True\n",
"3. Fire at fuel reserve in Kazachya Bay district - True\n",
"4. No injuries reported - True\n",
"5. Sevastopol targeted in air attacks following Russia's invasion of Ukraine - True\n",
"6. Ukraine denies responsibility for the fire - True\n",
"\n",
"Summary: A fuel depot in Sevastopol caught fire, with preliminary information suggesting it was caused by a drone strike. The fire engulfed around 1,000 square meters but was under control, and no one was hurt. Sevastopol has been targeted in air attacks following Russia's invasion of Ukraine, but Ukraine denies responsibility for the fire.\n",
"\n",
"False - The text is about a fire at a fuel depot in Sevastopol, not war. However, it does mention that Sevastopol has been targeted in air attacks following Russia's invasion of Ukraine.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Determine whether each item in the following numerated list of \\\n",
"topics is a topic in the text below, which\n",
"is delimited with triple backticks.\n",
"\n",
"Make a summary of the text in not more then 50 words.\n",
"\n",
"Is this an text about war? Indicate this with true or false.\n",
"\n",
"Text sample: '''{article}'''\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9d59121e-3de5-456a-9058-4b84c35eb22a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 15,
"id": "902a7c74",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ALERT: New NASA story!\n"
]
}
],
"source": [
"topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\\n')}\n",
"if topic_dict['nasa'] == 1:\n",
" print(\"ALERT: New NASA story!\")"
]
},
{
"cell_type": "markdown",
"id": "f88408ae-469a-4b02-a043-f6b4f0b14bf9",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1bd3553f",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,648 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "e3993515-9710-4ac4-89e9-b35ebb81e920",
"metadata": {
"id": "rhqRhkElpJ0z"
},
"source": [
"# Transforming\n",
"\n",
"In this notebook, we will explore how to use Large Language Models for text transformation tasks such as language translation, spelling and grammar checking, tone adjustment, and format conversion.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "41df0348",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [],
"source": [
"import os\n",
"\n",
"import openai\n",
"from dotenv import find_dotenv, load_dotenv\n",
"\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv(\"OPENAI_API_KEY\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "6a85ee0f",
"metadata": {
"height": 164,
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\", temperature=0):\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=temperature,\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "1d8f0bd8-628e-4c36-bcd0-2110162f25fc",
"metadata": {
"id": "zdxC4c6pwqA5"
},
"source": [
"## Translation\n",
"\n",
"ChatGPT is trained with sources in many languages. This gives the model the ability to do translation. Here are some examples of how to use this capability."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "9c4df6ff",
"metadata": {
"height": 130,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hola, me gustaría ordenar una licuadora.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following English text to Spanish: \\ \n",
"```Hi, I would like to order a blender```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "7300ed9b",
"metadata": {
"height": 115,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is French.\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Tell me which language this is: \n",
"```Combien coûte le lampadaire?```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "791e789b",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"French pirate: ```Je veux commander un ballon de basket```\n",
"Spanish pirate: ```Quiero pedir una pelota de baloncesto```\n",
"English pirate: ```I want to order a basketball```\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following text to French and Spanish\n",
"and English pirate: \\\n",
"```I want to order a basketball```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "fcf7eb63",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Formal: ¿Le gustaría ordenar una almohada?\n",
"Informal: ¿Te gustaría ordenar una almohada?\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following text to Spanish in both the \\\n",
"formal and informal forms: \n",
"'Would you like to order a pillow?'\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "8edb56d2-a32a-470f-9f40-4fc5b1ea0849",
"metadata": {
"id": "-hN2bczQrRC1"
},
"source": [
"### Universal Translator\n",
"Imagine you are in charge of IT at a large multinational e-commerce company. Users are messaging you with IT issues in all their native languages. Your staff is from all over the world and speaks only their native languages. You need a universal translator!"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "68a40bf0",
"metadata": {
"height": 147,
"tags": []
},
"outputs": [],
"source": [
"user_messages = [\n",
" \"La performance du système est plus lente que d'habitude.\", # System performance is slower than normal\n",
" \"Mi monitor tiene píxeles que no se iluminan.\", # My monitor has pixels that are not lighting\n",
" \"Il mio mouse non funziona\", # My mouse is not working\n",
" \"Mój klawisz Ctrl jest zepsuty\", # My keyboard has a broken control key\n",
" \"我的屏幕在闪烁\", # My screen is flashing\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "552d0db9",
"metadata": {
"height": 215,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original message (This is French.): La performance du système est plus lente que d'habitude.\n",
"English: The system performance is slower than usual.\n",
"Korean: 시스템 성능이 평소보다 느립니다. \n",
"\n",
"Original message (This is Spanish.): Mi monitor tiene píxeles que no se iluminan.\n"
]
},
{
"ename": "RateLimitError",
"evalue": "Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mRateLimitError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[11], line 10\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mOriginal message (\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mlang\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m): \u001b[39m\u001b[38;5;132;01m{\u001b[39;00missue\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 6\u001b[0m prompt \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[1;32m 7\u001b[0m \u001b[38;5;124mTranslate the following text to English \u001b[39m\u001b[38;5;130;01m\\\u001b[39;00m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;124mand Korean: ```\u001b[39m\u001b[38;5;132;01m{\u001b[39;00missue\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m```\u001b[39m\n\u001b[1;32m 9\u001b[0m \u001b[38;5;124m\u001b[39m\u001b[38;5;124m\"\"\"\u001b[39m\n\u001b[0;32m---> 10\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mget_completion\u001b[49m\u001b[43m(\u001b[49m\u001b[43mprompt\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 11\u001b[0m \u001b[38;5;28mprint\u001b[39m(response, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;130;01m\\n\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"Cell \u001b[0;32mIn[2], line 3\u001b[0m, in \u001b[0;36mget_completion\u001b[0;34m(prompt, model, temperature)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mget_completion\u001b[39m(prompt, model\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mgpt-3.5-turbo\u001b[39m\u001b[38;5;124m\"\u001b[39m, temperature\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m0\u001b[39m):\n\u001b[1;32m 2\u001b[0m messages \u001b[38;5;241m=\u001b[39m [{\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrole\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124muser\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m: prompt}]\n\u001b[0;32m----> 3\u001b[0m response \u001b[38;5;241m=\u001b[39m \u001b[43mopenai\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mChatCompletion\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mmessages\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mmessages\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m \u001b[49m\u001b[43mtemperature\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mtemperature\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 7\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 8\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m response\u001b[38;5;241m.\u001b[39mchoices[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mmessage[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcontent\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/chat_completion.py:25\u001b[0m, in \u001b[0;36mChatCompletion.create\u001b[0;34m(cls, *args, **kwargs)\u001b[0m\n\u001b[1;32m 23\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[1;32m 24\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m---> 25\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 26\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m TryAgain \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 27\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m timeout \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m time\u001b[38;5;241m.\u001b[39mtime() \u001b[38;5;241m>\u001b[39m start \u001b[38;5;241m+\u001b[39m timeout:\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_resources/abstract/engine_api_resource.py:153\u001b[0m, in \u001b[0;36mEngineAPIResource.create\u001b[0;34m(cls, api_key, api_base, api_type, request_id, api_version, organization, **params)\u001b[0m\n\u001b[1;32m 127\u001b[0m \u001b[38;5;129m@classmethod\u001b[39m\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcreate\u001b[39m(\n\u001b[1;32m 129\u001b[0m \u001b[38;5;28mcls\u001b[39m,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 136\u001b[0m \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams,\n\u001b[1;32m 137\u001b[0m ):\n\u001b[1;32m 138\u001b[0m (\n\u001b[1;32m 139\u001b[0m deployment_id,\n\u001b[1;32m 140\u001b[0m engine,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 150\u001b[0m api_key, api_base, api_type, api_version, organization, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mparams\n\u001b[1;32m 151\u001b[0m )\n\u001b[0;32m--> 153\u001b[0m response, _, api_key \u001b[38;5;241m=\u001b[39m \u001b[43mrequestor\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 154\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mpost\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 155\u001b[0m \u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 156\u001b[0m \u001b[43m \u001b[49m\u001b[43mparams\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparams\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 157\u001b[0m \u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 158\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstream\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 159\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_id\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_id\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 160\u001b[0m \u001b[43m \u001b[49m\u001b[43mrequest_timeout\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mrequest_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 161\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 163\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream:\n\u001b[1;32m 164\u001b[0m \u001b[38;5;66;03m# must be an iterator\u001b[39;00m\n\u001b[1;32m 165\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(response, OpenAIResponse)\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:226\u001b[0m, in \u001b[0;36mAPIRequestor.request\u001b[0;34m(self, method, url, params, headers, files, stream, request_id, request_timeout)\u001b[0m\n\u001b[1;32m 205\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mrequest\u001b[39m(\n\u001b[1;32m 206\u001b[0m \u001b[38;5;28mself\u001b[39m,\n\u001b[1;32m 207\u001b[0m method,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 214\u001b[0m request_timeout: Optional[Union[\u001b[38;5;28mfloat\u001b[39m, Tuple[\u001b[38;5;28mfloat\u001b[39m, \u001b[38;5;28mfloat\u001b[39m]]] \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[1;32m 215\u001b[0m ) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], \u001b[38;5;28mbool\u001b[39m, \u001b[38;5;28mstr\u001b[39m]:\n\u001b[1;32m 216\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mrequest_raw(\n\u001b[1;32m 217\u001b[0m method\u001b[38;5;241m.\u001b[39mlower(),\n\u001b[1;32m 218\u001b[0m url,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 224\u001b[0m request_timeout\u001b[38;5;241m=\u001b[39mrequest_timeout,\n\u001b[1;32m 225\u001b[0m )\n\u001b[0;32m--> 226\u001b[0m resp, got_stream \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response\u001b[49m\u001b[43m(\u001b[49m\u001b[43mresult\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 227\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp, got_stream, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mapi_key\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:620\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response\u001b[0;34m(self, result, stream)\u001b[0m\n\u001b[1;32m 612\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[1;32m 613\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_interpret_response_line(\n\u001b[1;32m 614\u001b[0m line, result\u001b[38;5;241m.\u001b[39mstatus_code, result\u001b[38;5;241m.\u001b[39mheaders, stream\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 615\u001b[0m )\n\u001b[1;32m 616\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m line \u001b[38;5;129;01min\u001b[39;00m parse_stream(result\u001b[38;5;241m.\u001b[39miter_lines())\n\u001b[1;32m 617\u001b[0m ), \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[1;32m 618\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m 619\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m (\n\u001b[0;32m--> 620\u001b[0m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_interpret_response_line\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 621\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcontent\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mutf-8\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 622\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mstatus_code\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 623\u001b[0m \u001b[43m \u001b[49m\u001b[43mresult\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mheaders\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 624\u001b[0m \u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;28;43;01mFalse\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[1;32m 625\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[1;32m 626\u001b[0m \u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[1;32m 627\u001b[0m )\n",
"File \u001b[0;32m~/mambaforge/envs/chatgpt_api/lib/python3.11/site-packages/openai/api_requestor.py:683\u001b[0m, in \u001b[0;36mAPIRequestor._interpret_response_line\u001b[0;34m(self, rbody, rcode, rheaders, stream)\u001b[0m\n\u001b[1;32m 681\u001b[0m stream_error \u001b[38;5;241m=\u001b[39m stream \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124merror\u001b[39m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;129;01min\u001b[39;00m resp\u001b[38;5;241m.\u001b[39mdata\n\u001b[1;32m 682\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m stream_error \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;241m200\u001b[39m \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m rcode \u001b[38;5;241m<\u001b[39m \u001b[38;5;241m300\u001b[39m:\n\u001b[0;32m--> 683\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mhandle_error_response(\n\u001b[1;32m 684\u001b[0m rbody, rcode, resp\u001b[38;5;241m.\u001b[39mdata, rheaders, stream_error\u001b[38;5;241m=\u001b[39mstream_error\n\u001b[1;32m 685\u001b[0m )\n\u001b[1;32m 686\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m resp\n",
"\u001b[0;31mRateLimitError\u001b[0m: Rate limit reached for default-gpt-3.5-turbo in organization org-irpvE5ZRVljUds1FrS83sCOu on requests per min. Limit: 3 / min. Please try again in 20s. Contact support@openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method."
]
}
],
"source": [
"for issue in user_messages:\n",
" prompt = f\"Tell me what language this is: ```{issue}```\"\n",
" lang = get_completion(prompt)\n",
" print(f\"Original message ({lang}): {issue}\")\n",
"\n",
" prompt = f\"\"\"\n",
" Translate the following text to English \\\n",
" and Korean: ```{issue}```\n",
" \"\"\"\n",
" response = get_completion(prompt)\n",
" print(response, \"\\n\")"
]
},
{
"cell_type": "markdown",
"id": "18e660eb-324f-474c-acf3-7e3bf5b7c70e",
"metadata": {},
"source": [
"## Try it yourself!\n",
"Try some translations on your own!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa57158f-d77d-42d1-94fe-17fa59c012f8",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "1d9e54ca-f93a-43c8-a295-bff7a89f77f5",
"metadata": {
"id": "JH3-0vdjsILh"
},
"source": [
"## Tone Transformation\n",
"Writing can vary based on the intended audience. ChatGPT can produce different tones.\n"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "2deac328",
"metadata": {
"height": 130,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Sir/Madam,\n",
"\n",
"I am writing to bring to your attention a standing lamp that I believe may be of interest to you. Please find attached the specifications for your review.\n",
"\n",
"Thank you for your time and consideration.\n",
"\n",
"Sincerely,\n",
"\n",
"Joe\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Translate the following from slang to a business letter: \n",
"'Dude, This is Joe, check out this spec on this standing lamp.'\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "a2c7eb73-6b82-442d-b4f8-251c308e89d5",
"metadata": {
"id": "p3e9sZh5tWIa"
},
"source": [
"## Format Conversion\n",
"ChatGPT can translate between formats. The prompt should describe the input and output formats."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "5a37f0a0",
"metadata": {
"height": 232,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<table>\n",
" <caption>Restaurant Employees</caption>\n",
" <thead>\n",
" <tr>\n",
" <th>Name</th>\n",
" <th>Email</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <td>Shyam</td>\n",
" <td>shyamjaiswal@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Bob</td>\n",
" <td>bob32@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Jai</td>\n",
" <td>jai87@gmail.com</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n"
]
}
],
"source": [
"data_json = {\n",
" \"resturant employees\": [\n",
" {\"name\": \"Shyam\", \"email\": \"shyamjaiswal@gmail.com\"},\n",
" {\"name\": \"Bob\", \"email\": \"bob32@gmail.com\"},\n",
" {\"name\": \"Jai\", \"email\": \"jai87@gmail.com\"},\n",
" ]\n",
"}\n",
"\n",
"prompt = f\"\"\"\n",
"Translate the following python dictionary from JSON to an HTML \\\n",
"table with column headers and title: {data_json}\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "481a46b7",
"metadata": {
"height": 62,
"tags": []
},
"outputs": [
{
"data": {
"text/html": [
"<table>\n",
" <caption>Restaurant Employees</caption>\n",
" <thead>\n",
" <tr>\n",
" <th>Name</th>\n",
" <th>Email</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <td>Shyam</td>\n",
" <td>shyamjaiswal@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Bob</td>\n",
" <td>bob32@gmail.com</td>\n",
" </tr>\n",
" <tr>\n",
" <td>Jai</td>\n",
" <td>jai87@gmail.com</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from IPython.display import HTML, JSON, Latex, Markdown, display\n",
"\n",
"display(HTML(response))"
]
},
{
"cell_type": "markdown",
"id": "2df1824c-534b-45cb-b0c1-3000bba5adbe",
"metadata": {
"id": "qLTz16qEzyT_"
},
"source": [
"## Spellcheck/Grammar check.\n",
"\n",
"Here are some examples of common grammar and spelling problems and the LLM's response. \n",
"\n",
"To signal to the LLM that you want it to proofread your text, you instruct the model to 'proofread' or 'proofread and correct'."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "52d77283",
"metadata": {
"height": 317,
"tags": []
},
"outputs": [],
"source": [
"import time\n",
"text = [\n",
" \"The girl with the black and white puppies have a ball.\", # The girl has a ball.\n",
" \"Yolanda has her notebook.\", # ok\n",
" \"Its going to be a long day. Does the car need its oil changed?\", # Homonyms\n",
" \"Their goes my freedom. There going to bring theyre suitcases.\", # Homonyms\n",
" \"Your going to need youre notebook.\", # Homonyms\n",
" \"That medicine effects my ability to sleep. Have you heard of the butterfly affect?\", # Homonyms\n",
" \"This phrase is to cherck chatGPT for speling abilitty\", # spelling\n",
"]\n",
"for t in text:\n",
" prompt = f\"\"\"Proofread and correct the following text\n",
" and rewrite the corrected version. If you don't find\n",
" any errors, just say \"No errors found\". Don't use \n",
" any punctuation around the text:\n",
" ```{t}```\"\"\"\n",
" time.sleep(10.0)\n",
" response = get_completion(prompt)\n",
" print(response)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "7543fe7d",
"metadata": {
"height": 249,
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I got this for my daughter's birthday because she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. Additionally, it's a bit small for what I paid for it. I think there might be other options that are bigger for the same price. On the positive side, it arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter.\n"
]
}
],
"source": [
"text = f\"\"\"\n",
"Got this for my daughter for her birthday cuz she keeps taking \\\n",
"mine from my room. Yes, adults also like pandas too. She takes \\\n",
"it everywhere with her, and it's super soft and cute. One of the \\\n",
"ears is a bit lower than the other, and I don't think that was \\\n",
"designed to be asymmetrical. It's a bit small for what I paid for it \\\n",
"though. I think there might be other options that are bigger for \\\n",
"the same price. It arrived a day earlier than expected, so I got \\\n",
"to play with it myself before I gave it to my daughter.\n",
"\"\"\"\n",
"prompt = f\"proofread and correct this review: ```{text}```\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "11ac80a0",
"metadata": {
"height": 81,
"tags": []
},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'redlines'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[24], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01mredlines\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Redlines\n\u001b[1;32m 3\u001b[0m diff \u001b[38;5;241m=\u001b[39m Redlines(text, response)\n\u001b[1;32m 4\u001b[0m display(Markdown(diff\u001b[38;5;241m.\u001b[39moutput_markdown))\n",
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'redlines'"
]
}
],
"source": [
"from redlines import Redlines\n",
"\n",
"diff = Redlines(text, response)\n",
"display(Markdown(diff.output_markdown))"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "2b4e73fd",
"metadata": {
"height": 164,
"tags": []
},
"outputs": [
{
"data": {
"text/markdown": [
"Title: A Soft and Cute Panda Plush Toy for All Ages\n",
"\n",
"Introduction:\n",
"As a parent, finding the perfect gift for your child's birthday can be a daunting task. However, I stumbled upon a soft and cute panda plush toy that not only made my daughter happy but also brought joy to me as an adult. In this review, I will share my experience with this product and provide an honest assessment of its features.\n",
"\n",
"Product Description:\n",
"The panda plush toy is made of high-quality materials that make it super soft and cuddly. Its cute design is perfect for children and adults alike, making it a versatile gift option. The toy is small enough to carry around, making it an ideal companion for your child on their adventures.\n",
"\n",
"Pros:\n",
"The panda plush toy is incredibly soft and cute, making it an excellent gift for children and adults. Its small size makes it easy to carry around, and its design is perfect for snuggling. The toy arrived a day earlier than expected, which was a pleasant surprise.\n",
"\n",
"Cons:\n",
"One of the ears is a bit lower than the other, which makes the toy asymmetrical. Additionally, the toy is a bit small for its price, and there might be other options that are bigger for the same price.\n",
"\n",
"Conclusion:\n",
"Overall, the panda plush toy is an excellent gift option for children and adults who love cute and cuddly toys. Despite its small size and asymmetrical design, the toy's softness and cuteness make up for its shortcomings. I highly recommend this product to anyone looking for a versatile and adorable gift option."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"prompt = f\"\"\"\n",
"proofread and correct this review. Make it more compelling. \n",
"Ensure it follows APA style guide and targets an advanced reader. \n",
"Output in markdown format.\n",
"Text: ```{text}```\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"display(Markdown(response))"
]
},
{
"cell_type": "markdown",
"id": "63fb76bc-a742-4b35-9dc2-f7fbc12d38fb",
"metadata": {},
"source": [
"## Try it yourself!\n",
"Try changing the instructions to form your own review."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a2b2ca58",
"metadata": {
"height": 30
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "3dbf5020-7d7f-4ba5-840b-20e883cd7c99",
"metadata": {
"id": "unsf1JnRr2IC"
},
"source": [
"Thanks to the following sites:\n",
"\n",
"https://writingprompts.com/bad-grammar-examples/\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@ -0,0 +1,263 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "8de529e8-3891-4f47-8585-65b92b80bbf7",
"metadata": {},
"source": [
"# Expanding\n",
"In this lesson, you will generate customer service emails that are tailored to each customer's review.\n",
"\n",
"## Setup"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "e23399a9",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"\n",
"from dotenv import load_dotenv, find_dotenv\n",
"_ = load_dotenv(find_dotenv()) # read local .env file\n",
"\n",
"openai.api_key = os.getenv('OPENAI_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4c943900-98db-40b3-b639-7822ee2c5fd8",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"def get_completion(prompt, model=\"gpt-3.5-turbo\",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class\n",
" messages = [{\"role\": \"user\", \"content\": prompt}]\n",
" response = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=temperature, # this is the degree of randomness of the model's output\n",
" )\n",
" return response.choices[0].message[\"content\"]"
]
},
{
"cell_type": "markdown",
"id": "f8ceea77-990a-4c64-bb49-3ba65eb155d2",
"metadata": {},
"source": [
"## Customize the automated reply to a customer email"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "c30c4239",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# given the sentiment from the lesson on \"inferring\",\n",
"# and the original customer message, customize the email\n",
"sentiment = \"negative\"\n",
"\n",
"# review for a blender\n",
"review = f\"\"\"\n",
"So, they still had the 17 piece system on seasonal \\\n",
"sale for around $49 in the month of November, about \\\n",
"half off, but for some reason (call it price gouging) \\\n",
"around the second week of December the prices all went \\\n",
"up to about anywhere from between $70-$89 for the same \\\n",
"system. And the 11 piece system went up around $10 or \\\n",
"so in price also from the earlier sale price of $29. \\\n",
"So it looks okay, but if you look at the base, the part \\\n",
"where the blade locks into place doesnt look as good \\\n",
"as in previous editions from a few years ago, but I \\\n",
"plan to be very gentle with it (example, I crush \\\n",
"very hard items like beans, ice, rice, etc. in the \\ \n",
"blender first then pulverize them in the serving size \\\n",
"I want in the blender then switch to the whipping \\\n",
"blade for a finer flour, and use the cross cutting blade \\\n",
"first when making smoothies, then use the flat blade \\\n",
"if I need them finer/less pulpy). Special tip when making \\\n",
"smoothies, finely cut and freeze the fruits and \\\n",
"vegetables (if using spinach-lightly stew soften the \\ \n",
"spinach then freeze until ready for use-and if making \\\n",
"sorbet, use a small to medium sized food processor) \\ \n",
"that you plan to use that way you can avoid adding so \\\n",
"much ice if at all-when making your smoothie. \\\n",
"After about a year, the motor was making a funny noise. \\\n",
"I called customer service but the warranty expired \\\n",
"already, so I had to buy another one. FYI: The overall \\\n",
"quality has gone done in these types of products, so \\\n",
"they are kind of counting on brand recognition and \\\n",
"consumer loyalty to maintain sales. Got it in about \\\n",
"two days.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "d5403f73",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Valued Customer,\n",
"\n",
"Thank you for taking the time to leave a review about our 17 piece system. We are sorry to hear that you experienced a price increase and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused.\n",
"\n",
"We would like to assure you that we take all feedback seriously and we are constantly working to improve our products and services. If you have any further concerns, please do not hesitate to reach out to our customer service team who will be happy to assist you.\n",
"\n",
"Thank you again for your review and for choosing our brand. We hope to have the opportunity to serve you better in the future.\n",
"\n",
"Best regards,\n",
"\n",
"AI customer agent\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"You are a customer service AI assistant.\n",
"Your task is to send an email reply to a valued customer.\n",
"Given the customer email delimited by ```, \\\n",
"Generate a reply to thank the customer for their review.\n",
"If the sentiment is positive or neutral, thank them for \\\n",
"their review.\n",
"If the sentiment is negative, apologize and suggest that \\\n",
"they can reach out to customer service. \n",
"Make sure to use specific details from the review.\n",
"Write in a concise and professional tone.\n",
"Sign the email as `AI customer agent`.\n",
"Customer review: ```{review}```\n",
"Review sentiment: {sentiment}\n",
"Target language is English.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "55605ee0-118c-4c46-a917-4981a43fcad3",
"metadata": {},
"source": [
"## Remind the model to use details from the customer's email"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "1d5ea7c8",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dear Valued Customer,\n",
"\n",
"Thank you for taking the time to share your feedback with us. We're sorry to hear that you had a negative experience with our product. We apologize for any inconvenience this may have caused you.\n",
"\n",
"If you're still experiencing issues with the product, please don't hesitate to contact our customer service department for further assistance. We're here to help you in any way we can.\n",
"\n",
"Thank you again for your feedback, and we hope to have the opportunity to serve you better in the future.\n",
"\n",
"Sincerely,\n",
"\n",
"AI customer agent\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"You are a customer service AI assistant.\n",
"Your task is to send an email reply to a valued customer.\n",
"Given the customer email delimited by ```, \\\n",
"Generate a reply to thank the customer for their review.\n",
"If the sentiment is positive or neutral, thank them for \\\n",
"their review.\n",
"If the sentiment is negative, apologize and suggest that \\\n",
"they can reach out to customer service. \n",
"Make sure to use specific details from the review.\n",
"Write in a concise and professional tone.\n",
"Sign the email as `AI customer agent`.\n",
"Customer review: ```{review}```\n",
"Review sentiment: {sentiment}\n",
"\"\"\"\n",
"response = get_completion(prompt, temperature=0.7)\n",
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "31e317ad-9e51-4e7a-90c3-d88e7bf8a98c",
"metadata": {},
"source": [
"## Try experimenting on your own!"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "ffa65c7e",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"**De CTIVD is een goede werkgever omdat zij zich inzetten voor de bescherming van de privacy van burgers en de controle op de inlichtingen- en veiligheidsdiensten. Het is een organisatie met een belangrijke maatschappelijke taak en er heerst een professionele en collegiale werksfeer. De medewerkers krijgen de ruimte om zich te ontwikkelen en er wordt veel waarde gehecht aan persoonlijke groei en ontwikkeling. Daarnaast biedt de CTIVD goede arbeidsvoorwaarden en is er aandacht voor een goede balans tussen werk en privé. Kortom, de CTIVD is een werkgever waar je trots op kunt zijn!**\n"
]
}
],
"source": [
"prompt = f\"\"\"\n",
"Schrijf een verslag, in 100 woorden, waarom de CTIVD een goede werkgever is.\n",
"Output formaat is markdown. Het woord 'CTIVD' is in vet weergegeven.\n",
"\"\"\"\n",
"response = get_completion(prompt)\n",
"print(response)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

File diff suppressed because one or more lines are too long