{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Build text generation apps\n", "\n", "You've seen so far through this curriculum that there are core concepts like prompts and even a whole discipline called \"prompt engineering\". Many tools you can interact with like ChatGPT, Office 365, Microsoft Power Platform and more, supports you using prompts to accomplish something.\n", "\n", "For you to add such an experience to an app, you need to understand concepts like prompts, completions and choose a library to work with. That's exactly what you'll learn in this chapter.\n", "\n", "## Introduction\n", "\n", "In this chapter, you will:\n", "\n", "- Learn about the openai library and it's core concepts.\n", "- Build a text generation app using openai.\n", "- Understand how to use concepts like prompt, temperature, and tokens to build a text generation app.\n", "\n", "## Learning goals\n", "\n", "At the end of this lesson, you'll be able to:\n", "\n", "- Explain what a text generation app is.\n", "- Build a text generation app using openai.\n", "- Configure your app to use more or less tokens and also change the temperature, for a varied output.\n", "\n", "## What is a text generation app?\n", "\n", "Normally when you build an app it some kind of interface like the following:\n", "\n", "- Command-based. Console apps are typical apps where you type a command and it carries out a task. For example, `git` is a command-based app.\n", "- User interface (UI). Some apps have graphical user interfaces (GUIs) where you click buttons, input text, select options and more.\n", "\n", "### Console and UI apps are limited\n", "\n", "Compare it to a command-based app where you type a command: \n", "\n", "- **It's limited**. You can't just type any command, only the ones that the app supports.\n", "- **Language specific**. Some apps support many languages, but by default the app is built for a specific language, even if you can add more language support. \n", "\n", "### Benefits of text generation apps\n", "\n", "So how is a text generation app different?\n", "\n", "In a text generation app, you have more flexibility, you're not limited to a set of commands or a specific input language. Instead, you can use natural language to interact with the app. Other benefits is that because you're already interacting with a data source that has been trained on a vast corpus of information, where a traditional app might be limited on what's in a database. \n", "\n", "### What can I build with a text generation app?\n", "\n", "There are many things you can build like for example:\n", "\n", "- **A chatbot**. A chatbot answering questions about topics, like your company and its products could be a good match.\n", "- **Helper**. LLMs are great at things like summarizing text, get insights from text, producing text like resumes and more.\n", "- **Code assistant**. Depending on the language model you use, you can build a code assistant that helps you write code. For example, you can use a product like GitHub Copilot as well as ChatGPT to help you write code.\n", "\n", "## How can I get started?\n", "\n", "Well, you need to find a way to integrate with an LLM which usually entails the following two approaches:\n", "\n", "- Use an API. Here you're constructing web requests with your prompt and get generated text back.\n", "- Use a library. Libraries helps encapsulate the API calls and makes it easier to use.\n", "\n", "## Libraries/SDKs\n", "\n", "There are a few well known libraries for working with LLMs like:\n", "\n", "- **openai**, this library makes it easy to connect to your model and send in prompts.\n", "\n", "Then there are libraries that operate on a higher level like:\n", "\n", "- **Langchain**. Langchain is well known and support Python.\n", "- **Semantic Kernel**. Semantic Kernel is a library by Microsoft supporting the languages C#, Python, and Java.\n", "\n", "## First app using openai\n", "\n", "Let's see how we can build our first app, what libraries we need, how much is required and so on.\n", "\n", "### Install openai\n", "\n", "There are many libraries out there for interacting with OpenAI or Azure OpenAI. It's possible to use numerous programming languages as well like C#, Python, JavaScript, Java and more. We've chosen to use the `openai` Python library, so we'll use `pip` to install it.\n", "\n", "```bash\n", "pip install openai\n", "```\n", "\n", "### Create a resource\n", "\n", "You need to carry out the following steps:\n", "\n", "- Create an account on Azure .\n", "- Gain access to Azure Open AI. Go to and request access.\n", "\n", " > [!NOTE]\n", " > At the time of writing, you need to apply for access to Azure Open AI.\n", "\n", "- Install Python \n", "- Have created an Azure OpenAI Service resource. See this guide for how to [create a resource](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource?pivots=web-portal).\n", "\n", "\n", "### Locate API key and endpoint\n", "\n", "At this point, you need to tell your `openai` library what API key to use. To find your API key, go to \"Keys and Endpoint\" section of your Azure Open AI resource and copy the \"Key 1\" value.\n", "\n", " ![Keys and Endpoint resource blade in Azure Portal](https://learn.microsoft.com/en-us/azure/ai-services/openai/media/quickstarts/endpoint.png)\n", "\n", "Now that you have this information copied, let's instruct the libraries to use it.\n", "\n", "> [!NOTE]\n", "> It's worth separating your API key from your code. You can do so by using environment variables.\n", "> - Set the environment variable `OPENAI_API_KEY` to your API key.\n", "> `export OPENAI_API_KEY='sk-...'`\n", "\n", "\n", "### Setup configuration Azure\n", "\n", "If you're using Azure Open AI, here's how you setup configuration:\n", "\n", "```python\n", "openai.api_type = 'azure'\n", "openai.api_key = os.environ[\"OPENAI_API_KEY\"]\n", "openai.api_version = '2023-05-15'\n", "openai.api_base = os.getenv(\"API_BASE\")\n", "```\n", "\n", "Above we're setting the following:\n", "\n", "- `api_type` to `azure`. This tells the library to use Azure Open AI and not OpenAI.\n", "- `api_key`, this is your API key found in the Azure Portal.\n", "- `api_version`, this is the version of the API you want to use. At the time of writing, the latest version is `2023-05-15`.\n", "- `api_base`, this is the endpoint of the API. You can find it in the Azure Portal next to your API key. \n", "\n", "> [!NOTE]\n", "> `os.getenv` is a function that reads environment variables. You can use it to read environment variables like `OPENAI_API_KEY` and `API_BASE`. Set these environment variables in your terminal or by using a library like `dotenv`.\n", "\n", "## Generate text\n", "\n", "The way to generate text is to use the `Completion` class. Here's an example:\n", "\n", "```python\n", "prompt = \"Complete the following: Once upon a time there was a\"\n", "\n", "completion = openai.Completion.create(model=\"davinci-002\", prompt=prompt)\n", "print(completion.choices[0].text)\n", "```\n", "\n", "In above code we create a completion object and pass in the model we want to use and the prompt. Then we print the generated text.\n", "\n", "### Chat completions\n", "\n", "So far, you've seen how we've been using `Completion` to generate text. But there's another class called `ChatCompletion` that is more suited for chatbots. Here's an example of using it:\n", "\n", "```python\n", "import openai\n", "\n", "openai.api_key = \"sk-...\"\n", "\n", "completion = openai.ChatCompletion.create(model=\"gpt-3.5-turbo\", messages=[{\"role\": \"user\", \"content\": \"Hello world\"}])\n", "print(completion.choices[0].message.content)\n", "```\n", "\n", "More on this functionality in a coming chapter.\n", "\n", "## Exercise - your first text generation app\n", "\n", "Now that we learned how to setup and configure openai, it's time to build your first text generation app. To build your app, follow these steps:\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Create a virtual environment and install openai:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "'source' is not recognized as an internal or external command,\n", "operable program or batch file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Collecting openai\n", " Using cached openai-0.28.1-py3-none-any.whl (76 kB)\n", "Collecting tqdm\n", " Using cached tqdm-4.66.1-py3-none-any.whl (78 kB)\n", "Requirement already satisfied: requests>=2.20 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from openai) (2.31.0)\n", "Collecting aiohttp\n", " Using cached aiohttp-3.8.6-cp310-cp310-win_amd64.whl (325 kB)\n", "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from requests>=2.20->openai) (3.3)\n", "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from requests>=2.20->openai) (3.1.0)\n", "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from requests>=2.20->openai) (2.0.3)\n", "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from requests>=2.20->openai) (2023.5.7)\n", "Collecting aiosignal>=1.1.2\n", " Using cached aiosignal-1.3.1-py3-none-any.whl (7.6 kB)\n", "Collecting frozenlist>=1.1.1\n", " Using cached frozenlist-1.4.0-cp310-cp310-win_amd64.whl (44 kB)\n", "Collecting multidict<7.0,>=4.5\n", " Using cached multidict-6.0.4-cp310-cp310-win_amd64.whl (28 kB)\n", "Collecting async-timeout<5.0,>=4.0.0a3\n", " Using cached async_timeout-4.0.3-py3-none-any.whl (5.7 kB)\n", "Collecting yarl<2.0,>=1.0\n", " Using cached yarl-1.9.2-cp310-cp310-win_amd64.whl (61 kB)\n", "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from aiohttp->openai) (23.1.0)\n", "Requirement already satisfied: colorama in c:\\users\\chnoring\\appdata\\local\\packages\\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\\localcache\\local-packages\\python310\\site-packages (from tqdm->openai) (0.4.5)\n", "Installing collected packages: tqdm, multidict, frozenlist, async-timeout, yarl, aiosignal, aiohttp, openai\n", "Successfully installed aiohttp-3.8.6 aiosignal-1.3.1 async-timeout-4.0.3 frozenlist-1.4.0 multidict-6.0.4 openai-0.28.1 tqdm-4.66.1 yarl-1.9.2\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n", "[notice] A new release of pip is available: 23.0.1 -> 23.3.1\n", "[notice] To update, run: C:\\Users\\chnoring\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\python.exe -m pip install --upgrade pip\n" ] } ], "source": [ "# Create virtual environment\n", "! python -m venv venv\n", "# Activate virtual environment\n", "! source venv/bin/activate\n", "# Install openai package\n", "! pip install openai\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> [!NOTE]\n", "> If you're using Windows type `venv\\Scripts\\activate` instead of `source venv/bin/activate`. \n", "\n", "> [!NOTE]\n", "> locate your Azure Open AI key by going to https://portal.azure.com/ and search for `Open AI` and select the `Open AI resource` and then select `Keys and Endpoint` and copy the `Key 1` value." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Create a *app.py* file and give it the following code:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " _____\n", "\n", "There was a princess who loved to sing and dance.\n" ] } ], "source": [ "import openai\n", "\n", "openai.api_key = \"\"\n", "# azure\n", "\n", "openai.api_type = 'azure' \n", "openai.api_version = '2023-05-15'\n", "openai.api_base = \"\"\n", "engine = \"davinci-001\"\n", "deployment_name = \"\" \n", "\n", "# add your completion code\n", "prompt = \"Complete the following: Once upon a time there was a\"\n", "\n", "# make completion\n", "completion = openai.Completion.create(engine= deployment_name, model=\"davinci-002\", prompt=prompt)\n", "\n", "# print response\n", "print(completion.choices[0].text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> [!NOTE] \n", "> If you're using Azure Open AI, you need to set the `api_type` to `azure` and set the `api_key` to your Azure Open AI key.\n", "\n", " You should see an output like the following:\n", "\n", " ```output\n", " very unhappy _____.\n", "\n", " Once upon a time there was a very unhappy mermaid.\n", " ```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Different types of prompts, for different things\n", "\n", "Now you've seen how to generate text using a prompt. You even have a program up and running that you can modify and change to generate different types of text. \n", "\n", "Prompts can be used for all sorts of tasks like for example:\n", "\n", "- **Generate a type of text**. For example, you can generate a poem, questions for a quiz etc.\n", "- **Lookup information**. You can use prompts to lookup information like for example what does CORS mean in web development?\n", "- **Generate code**. You can use prompts to generate code, like for example developing a regular expression used to validate emails or why not generate an entire program, like a web app? \n", "\n", "## A more practical use case: a recipe generator\n", "\n", "Imagine you have ingredients at home and you want to cook something. For that, you need a recipe. A way to find recipes is to use a search engine or you could use an LLM to do so.\n", "\n", "You could write a prompt like so:\n", "\n", "> \"Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used\"\n", "\n", "Given the above prompt, you might get a response similar to:\n", "\n", "```output\n", "1. Roasted Chicken and Vegetables: \n", "Ingredients: \n", "- 4 chicken thighs\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 2 tablespoons olive oil\n", "- 2 cloves garlic, minced\n", "- 1 teaspoon dried thyme\n", "- 1 teaspoon dried oregano\n", "- Salt and pepper, to taste\n", "\n", "2. Chicken and Potato Stew: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 1 onion, diced\n", "- 2 cloves garlic, minced\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 1 cup chicken broth\n", "- Salt and pepper, to taste\n", "\n", "3. Chicken and Potato Bake: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 onion, diced\n", "- 2 cloves garlic, minced\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 1 cup chicken broth\n", "- Salt and pepper, to taste\n", "\n", "4. Chicken and Potato Soup: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 1 onion, diced\n", "- 2 cloves garlic, minced\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 4 cups chicken broth\n", "- Salt and pepper, to taste\n", "\n", "5. Chicken and Potato Hash: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 onion, diced\n", "- 2 cloves garlic, minced\n", "- 1 teaspoon dried oregano\n", "```\n", "\n", "This outcome is great, I know what to cook. At this point, what could be a useful improvements are:\n", "\n", "- Filtering out ingredients I don't like or am allergic to.\n", "- Produce a shopping list, in case I don't have all the ingredients at home.\n", "\n", "For the above cases, let's add an additional prompt:\n", "\n", "> \"Please remove recipes with garlic as I'm allergic and replace it with something else. Also, please produce a shopping list for the recipes, considering I already have chicken, potatoes and carrots at home.\"\n", "\n", "Now you have a new result, namely:\n", "\n", "```output\n", "1. Roasted Chicken and Vegetables: \n", "Ingredients: \n", "- 4 chicken thighs\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 2 tablespoons olive oil\n", "- 1 teaspoon dried thyme\n", "- 1 teaspoon dried oregano\n", "- Salt and pepper, to taste\n", "\n", "2. Chicken and Potato Stew: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 1 onion, diced\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 1 cup chicken broth\n", "- Salt and pepper, to taste\n", "\n", "3. Chicken and Potato Bake: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 onion, diced\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 1 cup chicken broth\n", "- Salt and pepper, to taste\n", "\n", "4. Chicken and Potato Soup: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 1 onion, diced\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 teaspoon dried oregano\n", "- 1 teaspoon dried thyme\n", "- 4 cups chicken broth\n", "- Salt and pepper, to taste\n", "\n", "5. Chicken and Potato Hash: \n", "Ingredients: \n", "- 2 tablespoons olive oil\n", "- 2 chicken breasts, cut into cubes\n", "- 2 potatoes, cut into cubes\n", "- 2 carrots, cut into cubes\n", "- 1 onion, diced\n", "- 1 teaspoon dried oregano\n", "\n", "Shopping List: \n", "- Olive oil\n", "- Onion\n", "- Thyme\n", "- Oregano\n", "- Salt\n", "- Pepper\n", "```\n", "\n", "That's your five recipes, with no garlic mentioned and you also have a shopping list considering what you already have at home. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise - build a recipe generator\n", "\n", "Now that we have played out a scenario, let's write code to match the demonstrated scenario. To do so, follow these steps:\n", "\n", "1. Use the existing *app.py* file as a starting point\n", "1. Locate the `prompt` variable and change its code to the following:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ".\n", "\n", "-Slow Cooker Garlic Honey Chicken and Potatoes\n", "-One Pan Roasted Chicken and Potatoes with Carrots\n", "-Chicken, Potato, and Carrot Stir-Fry\n", "-Chicken Pot Pie with Carrots\n", "-Roasted Chicken and Carrots with Potatoes\n" ] } ], "source": [ "import openai\n", "\n", "openai.api_key = \"\"\n", "# azure\n", "\n", "openai.api_type = 'azure' \n", "openai.api_version = '2023-05-15'\n", "openai.api_base = \"\"\n", "engine = \"davinci-001\"\n", "deployment_name = \"\" \n", "\n", "prompt = \"Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used\"\n", "\n", "# make completion\n", "completion = openai.Completion.create(engine= deployment_name, model=\"davinci-002\", prompt=prompt, max_tokens=600)\n", "\n", "# print response\n", "print(completion.choices[0].text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you now run the code, you should see an output similar to:\n", "\n", "```output\n", "-Chicken Stew with Potatoes and Carrots: 3 tablespoons oil, 1 onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 1/2 cups chicken broth, 1/2 cup dry white wine, 2 tablespoons chopped fresh parsley, 2 tablespoons unsalted butter, 1 1/2 pounds boneless, skinless chicken thighs, cut into 1-inch pieces\n", "-Oven-Roasted Chicken with Potatoes and Carrots: 3 tablespoons extra-virgin olive oil, 1 tablespoon Dijon mustard, 1 tablespoon chopped fresh rosemary, 1 tablespoon chopped fresh thyme, 4 cloves garlic, minced, 1 1/2 pounds small red potatoes, quartered, 1 1/2 pounds carrots, quartered lengthwise, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 (4-pound) whole chicken\n", "-Chicken, Potato, and Carrot Casserole: cooking spray, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and shredded, 1 potato, peeled and shredded, 1/2 teaspoon dried thyme leaves, 1/4 teaspoon salt, 1/4 teaspoon black pepper, 2 cups fat-free, low-sodium chicken broth, 1 cup frozen peas, 1/4 cup all-purpose flour, 1 cup 2% reduced-fat milk, 1/4 cup grated Parmesan cheese\n", "\n", "-One Pot Chicken and Potato Dinner: 2 tablespoons olive oil, 1 pound boneless, skinless chicken thighs, cut into 1-inch pieces, 1 large onion, chopped, 3 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 2 cups chicken broth, 1/2 cup dry white wine\n", "\n", "-Chicken, Potato, and Carrot Curry: 1 tablespoon vegetable oil, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 teaspoon ground coriander, 1 teaspoon ground cumin, 1/2 teaspoon ground turmeric, 1/2 teaspoon ground ginger, 1/4 teaspoon cayenne pepper, 2 cups chicken broth, 1/2 cup dry white wine, 1 (15-ounce) can chickpeas, drained and rinsed, 1/2 cup raisins, 1/2 cup chopped fresh cilantro\n", "```\n", "\n", "> NOTE, your LLM is non deterministic, so you might get different results for every time you run the program.\n", "\n", "Great, let's see how we can improve things. To improve things, we want to make sure the code is flexible, so ingredients and number of recipes can be improved and changed. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Let's change the code in the following way:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "Leeks are a type of onion that can be eaten raw or cooked. In this recipe, leeks are cooked and mixed with a creamy yogurt sauce.\n", "\n", "Ingredients:\n", "-1 leek\n", "-1/4 cup plain yogurt\n", "-1 tablespoon olive oil\n", "-1 clove garlic, minced\n", "-Salt and pepper\n", "\n", "Instructions:\n", "\n", "1. Cut the leek in half lengthwise and then thinly slice.\n", "\n", "2. In a large skillet, heat the olive oil over medium heat. Add the garlic and leeks and cook until soft, about 5 minutes.\n", "\n", "3. Add the yogurt and salt and pepper to taste. Cook until heated through, about 5 more minutes.\n", "\n", "This recipe uses leeks in a savory pie.\n", "\n", "Ingredients:\n", "-1 leek\n", "-2 tablespoons butter\n", "-2 tablespoons flour\n", "-1 cup milk\n", "-Salt and pepper\n", "-1/2 cup grated cheddar cheese\n", "-1/4 cup chopped parsley\n", "-1 pie crust\n", "\n", "Instructions:\n", "\n", "1. Preheat the oven to 400 degrees F.\n", "\n", "2. Slice the leek in half lengthwise and then thinly slice.\n", "\n", "3. In a medium saucepan, melt the butter over medium heat. Stir in the flour and cook for 1 minute.\n", "\n", "4. Add the milk and salt and pepper to taste. Stir until the mixture thickens.\n", "\n", "5. Stir in the cheddar cheese and parsley.\n", "\n", "6. Pour the mixture into the pie crust.\n", "\n", "7. Bake for 15 minutes, or until the cheese is melted and bubbly.\n" ] } ], "source": [ "import openai\n", "\n", "openai.api_key = \"\"\n", "# azure\n", "\n", "openai.api_type = 'azure' \n", "openai.api_version = '2023-05-15'\n", "openai.api_base = \"\"\n", "engine = \"davinci-001\"\n", "deployment_name = \"\" \n", "\n", "no_recipes = input(\"No of recipes (for example, 5: \")\n", "\n", "ingredients = input(\"List of ingredients (for example, chicken, potatoes, and carrots: \")\n", "\n", "# interpolate the number of recipes into the prompt an ingredients\n", "prompt = f\"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used\"\n", "\n", "# make completion\n", "completion = openai.Completion.create(engine= deployment_name, model=\"davinci-002\", prompt=prompt, max_tokens=600)\n", "\n", "# print response\n", "print(completion.choices[0].text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "Taking the code for a test run, could look like:\n", " \n", "```output\n", "No of recipes (for example, 5: 3\n", "List of ingredients (for example, chicken, potatoes, and carrots: milk,strawberries\n", "\n", "-Strawberry milk shake: milk, strawberries, sugar, vanilla extract, ice cubes\n", "-Strawberry shortcake: milk, flour, baking powder, sugar, salt, unsalted butter, strawberries, whipped cream \n", "-Strawberry milk: milk, strawberries, sugar, vanilla extract\n", "```\n", "\n", "### Improve by adding filter and shopping list\n", "\n", "We now have a working app capable of producing recipes and it's flexible as it relies on inputs from the user, both on the number of recipes but also the ingredients used.\n", "\n", "To further improve it, we want to add the following:\n", "\n", "- **Filter out ingredients**. We want to be able to filter out ingredients we don't like or are allergic to. To accomplish this change, we can edit our existing prompt and add a filter condition to the end of it like so:\n", "\n", " ```python\n", " filter = input(\"Filter (for example, vegetarian, vegan, or gluten-free: \")\n", "\n", " prompt = f\"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used, no {filter}\"\n", " ```\n", "\n", " Above, we add `{filter}` to the end the prompt and we also capture the filter value from the user.\n", "\n", " An example input of running the program can now look like so:\n", " \n", " ```output \n", " No of recipes (for example, 5: 3\n", " List of ingredients (for example, chicken, potatoes, and carrots: onion,milk\n", " Filter (for example, vegetarian, vegan, or gluten-free: no milk\n", "\n", " 1. French Onion Soup\n", "\n", " Ingredients:\n", " \n", " -1 large onion, sliced\n", " -3 cups beef broth\n", " -1 cup milk\n", " -6 slices french bread\n", " -1/4 cup shredded Parmesan cheese\n", " -1 tablespoon butter\n", " -1 teaspoon dried thyme\n", " -1/4 teaspoon salt\n", " -1/4 teaspoon black pepper\n", " \n", " Instructions:\n", " \n", " 1. In a large pot, sauté onions in butter until golden brown.\n", " 2. Add beef broth, milk, thyme, salt, and pepper. Bring to a boil.\n", " 3. Reduce heat and simmer for 10 minutes.\n", " 4. Place french bread slices on soup bowls.\n", " 5. Ladle soup over bread.\n", " 6. Sprinkle with Parmesan cheese.\n", " \n", " 2. Onion and Potato Soup\n", " \n", " Ingredients:\n", " \n", " -1 large onion, chopped\n", " -2 cups potatoes, diced\n", " -3 cups vegetable broth\n", " -1 cup milk\n", " -1/4 teaspoon black pepper\n", " \n", " Instructions:\n", " \n", " 1. In a large pot, sauté onions in butter until golden brown.\n", " 2. Add potatoes, vegetable broth, milk, and pepper. Bring to a boil.\n", " 3. Reduce heat and simmer for 10 minutes.\n", " 4. Serve hot.\n", " \n", " 3. Creamy Onion Soup\n", " \n", " Ingredients:\n", " \n", " -1 large onion, chopped\n", " -3 cups vegetable broth\n", " -1 cup milk\n", " -1/4 teaspoon black pepper\n", " -1/4 cup all-purpose flour\n", " -1/2 cup shredded Parmesan cheese\n", " \n", " Instructions:\n", " \n", " 1. In a large pot, sauté onions in butter until golden brown.\n", " 2. Add vegetable broth, milk, and pepper. Bring to a boil.\n", " 3. Reduce heat and simmer for 10 minutes.\n", " 4. In a small bowl, whisk together flour and Parmesan cheese until smooth.\n", " 5. Add to soup and simmer for an additional 5 minutes, or until soup has thickened.\n", " ```\n", "\n", " As you can see, any recipes with milk in it has been filtered out. But, if you're lactose intolerant, you might want to filter out recipes with cheese in it as well, so there's a need to be clear.\n", "\n", " ```python\n", " \n", "- **Produce a shopping list**. We want to produce a shopping list, considering what we already have at home.\n", "\n", " For this functionality, we could either try to solve everything one prompt or we could split it up into two prompts. Let's try the latter approach. Here we're suggesting to add an additional prompt, but for that to work, we need to add the result of the former prompt as context to the latter prompt. \n", "\n", " Locate the part in the code that prints out the result from the first prompt and add the following code below:\n", " \n", " ```python\n", " old_prompt_result = completion.choices[0].text\n", " prompt = \"Produce a shopping list for the generated recipes and please don't include ingredients that I already have.\"\n", " \n", " new_prompt = f\"{old_prompt_result} {prompt}\"\n", " completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200)\n", " \n", " # print response\n", " print(\"Shopping list:\")\n", " print(completion.choices[0].text)\n", " ```\n", "\n", " Note the following:\n", "\n", " - We're constructing a new prompt by adding the result from the first prompt to the new prompt: \n", " \n", " ```python\n", " new_prompt = f\"{old_prompt_result} {prompt}\"\n", " ```\n", "\n", " - We make a new request, but also considering the number of tokens we asked for in the first prompt, so this time we say `max_tokens` is 1200. \n", "\n", " ```python\n", " completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200)\n", " ``` \n", "\n", " Taking this code for a spin, we now arrive at the following output:\n", "\n", " ```output\n", " No of recipes (for example, 5: 2\n", " List of ingredients (for example, chicken, potatoes, and carrots: apple,flour\n", " Filter (for example, vegetarian, vegan, or gluten-free: sugar\n", " Recipes:\n", " or milk.\n", " \n", " -Apple and flour pancakes: 1 cup flour, 1/2 tsp baking powder, 1/2 tsp baking soda, 1/4 tsp salt, 1 tbsp sugar, 1 egg, 1 cup buttermilk or sour milk, 1/4 cup melted butter, 1 Granny Smith apple, peeled and grated\n", " -Apple fritters: 1-1/2 cups flour, 1 tsp baking powder, 1/4 tsp salt, 1/4 tsp baking soda, 1/4 tsp nutmeg, 1/4 tsp cinnamon, 1/4 tsp allspice, 1/4 cup sugar, 1/4 cup vegetable shortening, 1/4 cup milk, 1 egg, 2 cups shredded, peeled apples\n", " Shopping list:\n", " -Flour, baking powder, baking soda, salt, sugar, egg, buttermilk, butter, apple, nutmeg, cinnamon, allspice \n", " ```\n", "\n", "## Improve your setup \n", "\n", "What we have so far is code that works, but there are some tweaks we should be doing to improve things further. Some things we should do is:\n", "\n", "- **Separate secrets from code**, like the API key. Secrets does not belong in code and should be stored in a secure location. To separate secrets from code, we can use environment variables and library like `python-dotenv` to load them from a file. Here's how that would look like in code:\n", "\n", " - Create a `.env` file with the following content:\n", "\n", " ```bash\n", " OPENAI_API_KEY=sk-...\n", " ``` \n", "\n", " > Note, for Azure, you need to set the following environment variables:\n", "\n", " ```bash\n", " OPENAI_API_TYPE=azure\n", " OPENAI_API_VERSION=2023-05-15\n", " OPENAI_API_BASE=\n", " ```\n", "\n", " In code, you would the load the environment variables like so:\n", "\n", " ```python\n", " from dotenv import load_dotenv\n", "\n", " load_dotenv()\n", "\n", " openai.api_key = os.environ[\"OPENAI_API_KEY\"]\n", " ```\n", " \n", "- **A word on token length**. We should consider how many tokens we need to generate the text we want. Tokens cost money, so where possible, we should try to be economical with the number of tokens we use. For example, can we phrase the prompt so that we can use less tokens?\n", "\n", " To change tokens used, you can use the `max_tokens` parameter. For example, if you want to use 100 tokens, you would do:\n", "\n", " ```python\n", " completion = openai.Completion.create(model=\"davinci-002\", prompt=prompt, max_tokens=100)\n", " ```\n", "\n", "- **Experimenting with temperature**. Temperature is something we haven't mentioned so far but is an important context for how our program performs. The higher the temperature value the more random the output will be. Conversely the lower the temperature value the more predictable the output will be. Consider whether you want variation in your output or not.\n", "\n", " To alter the temperature, you can use the `temperature` parameter. For example, if you want to use a temperature of 0.5, you would do:\n", "\n", " ```python\n", " completion = openai.Completion.create(model=\"davinci-002\", prompt=prompt, temperature=0.5)\n", " ```\n", "\n", " > Note, the closer to 1.0, the more varied the output.\n", "\n", "\n", "\n", "## Assignment\n", "\n", "For this assignment, you can choose what to build.\n", "\n", "Here's some suggestions:\n", "\n", "- Tweak the recipe generator app to improve it further. Play around with temperature values, and the prompts to see what you can come up with.\n", "- Build a \"study buddy\". This app should be able to answer questions about a topic for example Python, you could have prompts like \"What is a certain topic in Python?\", or you could have a prompt that says, show me code for a certain topic etc.\n", "- History bot, make history come alive, instruct the bot to play a certain historical character and ask it questions about its life and times. \n", "\n", "## Solution\n", "\n", "### Study buddy\n", "\n", "- \"You're an expert on the Python language\n", "\n", " Suggest a beginner lesson for Python in the following format:\n", " \n", " Format:\n", " - concepts:\n", " - brief explanation of the lesson:\n", " - exercise in code with solutions\"\n", "\n", "Above is a starter prompt, see how you can use it and tweak it to your liking.\n", "\n", "### History bot\n", "\n", "Here's some prompts you could be using:\n", "\n", "- \"You are Abe Lincoln, tell me about yourself in 3 sentences, and respond using grammar and words like Abe would have used\"\n", "- \"You are Abe Lincoln, respond using grammar and words like Abe would have used:\n", "\n", " Tell me about your greatest accomplishments, in 300 words:\"\n", "\n", "## Knowledge check\n", "\n", "What does the concept temperature do?\n", "\n", "1. It controls how random the output is.\n", "1. It controls how big the response is.\n", "1. It controls how many tokens are used.\n", "\n", "A: 1\n", "\n", "What's a good way to store secrets like API keys?\n", "\n", "1. In code.\n", "1. In a file.\n", "1. In environment variables.\n", "\n", "A: 3, because environment variables are not stored in code and can be loaded from the code. " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.10.11" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }