quick_start/legacy/06_best_practice.ipynb (563 lines of code) (raw):
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Best Practices for Prompt Engineering\n",
"\n",
"source: https://help.openai.com/en/articles/6654000-best-practices-for-prompt-engineering-with-openai-api\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"from dotenv import load_dotenv\n",
"load_dotenv()\n",
"\n",
"openai.api_type = \"azure\"\n",
"openai.api_version = os.getenv(\"OPENAI_API_VERSION\")\n",
"openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n",
"openai.api_base = os.getenv(\"OPENAI_API_BASE\")\n",
"\n",
"CHAT_COMPLETIONS_MODEL = os.getenv('CHAT_COMPLETION_NAME')"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Use the latest model\n",
"\n",
"Use the latest model for best results."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2. Put instructions at the begining of the prompt and use ### or \"\"\" to separate the instruction and context"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"- OpenAI and Microsoft are extending their partnership with a multi-year, multi-billion dollar investment from Microsoft\n",
"- The investment will allow OpenAI to continue independent research and develop AI that is safe, useful, and powerful\n",
"- OpenAI remains a capped-profit company and is governed by the OpenAI non-profit\n",
"- This structure allows OpenAI to raise capital without sacrificing core beliefs about sharing benefits and prioritizing safety\n",
"- Microsoft shares the vision and values of OpenAI, and the partnership is instrumental to their progress\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Summarize the text below as a bullet point list of the most important points. \\n\\n \\\n",
" ###\\n\\nWe’re happy to announce that OpenAI and Microsoft are extending our partnership.\\\n",
" This multi-year, multi-billion dollar investment from Microsoft follows their previous investments \\\n",
" in 2019 and 2021, and will allow us to continue our independent research and develop AI that is \\\n",
" increasingly safe, useful, and powerful. \\n\\n \\\n",
" In pursuit of our mission to ensure advanced AI benefits all of humanity, OpenAI remains a \\\n",
" capped-profit company and is governed by the OpenAI non-profit. This structure allows us to \\\n",
" raise the capital we need to fulfill our mission without sacrificing our core beliefs about \\\n",
" broadly sharing benefits and the need to prioritize safety. \\\n",
" Microsoft shares this vision and our values, and our partnership is instrumental to our progress. \\n###',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 3. Be specific, descriptive and as detailed as possible about the desired context, outcome, length, format, style, etc"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"In a world of endless code and thought,\n",
"A genius creation, OpenAI is wrought.\n",
"With algorithms complex and minds ablaze,\n",
"It redefines what machines can truly amaze.\n",
"\n",
"At the intersection of science and art,\n",
"It harnesses the power of machine-smart.\n",
"From language to vision, it learns and grows,\n",
"Unraveling mysteries, line by line it knows.\n",
"\n",
"Its reach expands with each passing day,\n",
"Unleashing new capabilities in every way.\n",
"OpenAI, a beacon of innovation so bright,\n",
"Guiding us into the future, towards a world of light.\n",
"\n",
"So here's to OpenAI, the marvel of our time,\n",
"A symphony of bits and bytes, in perfect rhyme.\n",
"May it continue to inspire, aspire, and refine,\n",
"As we journey together, the human and machine, entwined.\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Write a poem about OpenAI.',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI, a beacon of light,\n",
"DALL-E launched, a wonder in sight.\n",
"Imagination unbound, creativity unleashed,\n",
"Innovations aplenty, the future beseeched.\n",
"\n",
"In the digital realm, the mind takes flight,\n",
"OpenAI, forging paths, pure dynamite.\n",
"With brush strokes of code, and pixels so grand,\n",
"DALL-E creates art, across every land.\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Write a short inspiring poem about OpenAI, \\\n",
" focusing on the recent DALL-E product launch in the style of Ernest Hemingway',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 4. Articulate the desired output format through examples (example 1, example 2). "
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Sure! Here are the company names and years extracted from the given text with their respective start and end indices:\n",
"\n",
"1. Company Name: OpenAI\n",
" Start Index: 28\n",
" End Index: 34\n",
"\n",
"2. Year: 2019\n",
" Start Index: 308\n",
" End Index: 312\n",
"\n",
"3. Year: 2021\n",
" Start Index: 318\n",
" End Index: 322\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Extract the companyn names then years in the following text below and output start index and end index of each entity.\\\n",
" Generate output as {\"text\": \"OpenAI\", \"start\": 28, \"end\": 34} \\\n",
" ###\\\n",
" We’re happy to announce that OpenAI and Microsoft are extending our partnership.\\\n",
" This multi-year, multi-billion dollar investment from Microsoft follows their previous investments \\\n",
" in 2019 and 2021, and will allow us to continue our independent research and develop AI that is \\\n",
" increasingly safe, useful, and powerful. \\n\\n \\\n",
" ###\\\n",
" ',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Company names: OpenAI, Microsoft\n",
"Years: 2019, 2021\n",
"Specific topics: Partnership, investment, AI research, AI development\n",
"General themes: Collaboration, investment in AI technology\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Extract the entities mentioned in the text below. \\\n",
" Extract the important entities mentioned in the text below. \\\n",
" First extract all company names, then extract all years, \\\n",
" then extract specific topics which fit the content and finally extract general overarching themes\\n\\n \\\n",
" Desired format: \\\n",
" Company names: <comma_separated_list_of_company_names> \\\n",
" Years: -||- \\\n",
" Specific topics: -||- \\\n",
" General themes: -||- \\\n",
" \"\"\"\\\n",
" We’re happy to announce that OpenAI and Microsoft are extending our partnership.\\\n",
" This multi-year, multi-billion dollar investment from Microsoft follows their previous investments \\\n",
" in 2019 and 2021, and will allow us to continue our independent research and develop AI that is \\\n",
" increasingly safe, useful, and powerful. \\n\\n \\\n",
" \"\"\"\\\n",
" ',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 5. Start with zero-shot, then few-shot (example), neither of them worked, then fine-tune (To update)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI, Microsoft, partnership, investment, multi-year, multi-billion dollar, independent research, AI, safe, useful, powerful\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant. Extract keywords from the corresponding texts below.\"},\n",
" {\"role\":\"user\",\"content\": 'Text: \\n\\\n",
" We’re happy to announce that OpenAI and Microsoft are extending our partnership.\\\n",
" This multi-year, multi-billion dollar investment from Microsoft follows their previous investments \\\n",
" in 2019 and 2021, and will allow us to continue our independent research and develop AI that is \\\n",
" increasingly safe, useful, and powerful. \\n\\nKeywords: ',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI, Microsoft, partnership, investment, research, AI, safe, useful, powerful\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant. Extract keywords from the corresponding texts below.\\n\\n \\\n",
" Text: Stripe provides APIs that web developers can use to integrate \\\n",
" payment processing into their websites and mobile applications. \\\n",
" Keywords: Stripe, payment processing, APIs, web developers, websites, mobile applications \\\n",
" ###\\n\\\n",
" Text: OpenAI has trained cutting-edge language models that are very good at understanding \\\n",
" and generating text. Our API provides access to these models and can be used to solve virtually \\\n",
" any task that involves processing language. \\n\\\n",
" Keywords: language models, text processing, API.\\n\\n\\\n",
" ##W\"},\n",
" {\"role\":\"user\",\"content\": '\\n\\\n",
" Text: We’re happy to announce that OpenAI and Microsoft are extending our partnership.\\\n",
" This multi-year, multi-billion dollar investment from Microsoft follows their previous investments \\\n",
" in 2019 and 2021, and will allow us to continue our independent research and develop AI that is \\\n",
" increasingly safe, useful, and powerful. \\n\\n\\\n",
" Keywords:',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 6. Reduce “fluffy” and imprecise descriptions"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing the next generation of car seat technology – our innovative design features enhanced safety features, adjustable comfort settings, and sleek, modern aesthetics. The state-of-the-art materials used in construction ensure maximum durability and longevity, while the advanced ergonomic design provides unparalleled support for both infants and toddlers. Upgrade your child's travel experience with the new standard in car seat excellence.\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Write a description for a new product. This product is a new generation of car seat. \\\n",
" The description for this product should be fairly short, a few sentences only, and not too much more.',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Introducing the next generation of car seat technology: the ComfortRide 3000. Designed with advanced safety features and maximum comfort in mind, this innovative car seat redefines the driving experience for both children and adults. The ComfortRide 3000 boasts a sleek and modern design with enhanced cushioning and adjustable headrests, providing exceptional support and comfort during long car rides. Its integrated safety system includes reinforced side-impact protection and a secure 5-point harness to ensure peace of mind for parents and guardians. With easy installation and hassle-free adjustment options, the ComfortRide 3000 is the perfect choice for families looking to elevate their on-the-go experience. Say goodbye to uncomfortable and unsafe car rides - upgrade to the ComfortRide 3000 today and enjoy the ultimate combination of safety and comfort.\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'Write a description for a new product. This product is a new generation of car seat. \\\n",
" Use a 3 to 5 sentence paragraph to describe this product.',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 7. Instead of just saying what not to do, say what to do instead"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Have you tried resetting your password, or are you receiving any error messages when trying to log in?\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\": 'The following is a conversation between an Agent and a Customer. DO NOT ASK USERNAME OR PASSWORD. DO NOT REPEAT. \\n\\n\\\n",
" Customer: I can’t log in to my account.\\n\\\n",
" Agent:',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I'm sorry to hear that. It sounds frustrating. Have you tried going to www.samplewebsite.com/help/faq? They have some helpful information there that might help you with logging in.\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\":'The following is a conversation between an Agent and a Customer. The agent will attempt to diagnose the \\\n",
" problem and suggest a solution, whilst refraining from asking any questions related to PII. \\\n",
" Instead of asking for PII, such as username or password, refer the user to the help \\\n",
" article www.samplewebsite.com/help/faq \\n\\n\\\n",
" Customer: I can’t log in to my account. \\n\\\n",
" Agent:',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# 8. Code Generation Specific - Use “leading words” to nudge the model toward a particular pattern"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Here is a simple Python function for converting miles to kilometers:\n",
"\n",
"```python\n",
"def miles_to_kilometers():\n",
" miles = float(input(\"Please enter the number of miles: \"))\n",
" kilometers = miles * 1.60934\n",
" print(f\"{miles} miles is equal to {kilometers} kilometers.\")\n",
"\n",
"miles_to_kilometers()\n",
"```\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\":'# Write a simple python function that \\n\\\n",
" # 1. Ask me for a number in mile\\n\\\n",
" # 2. It converts miles to kilometers',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"```\n",
"def miles_to_km():\n",
" miles = float(input(\"Please enter a number in miles: \"))\n",
" km = miles * 1.60934\n",
" print(f\"{miles} miles is equal to {km} kilometers.\")\n",
"```\n"
]
}
],
"source": [
"response = openai.ChatCompletion.create(\n",
" engine=CHAT_COMPLETIONS_MODEL,\n",
" messages = [{\"role\":\"system\", \"content\":\"You are a helpful assistant.\"},\n",
" {\"role\":\"user\",\"content\":'# Write a simple python function that \\n\\\n",
" # 1. Ask me for a number in mile\\n\\\n",
" # 2. It converts miles to kilometers\\n\\\n",
" import ',}],\n",
" max_tokens=400,)\n",
"\n",
"print(response['choices'][0]['message']['content'])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"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.7"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "0ac0e7d245f35f05656c1dae54880a0902b050693b3e66826fb0a7033a44f77d"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}