{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# engineer_prompt\n", "\n", "> Engineering prompts" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#| default_exp engineer_prompt" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#| hide\n", "from nbdev.showdoc import *" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#| export\n", "import openai\n", "from langchain.chains import ConversationChain\n", "from langchain.chat_models import PromptLayerChatOpenAI\n", "from langchain.memory import ConversationBufferMemory\n", "from langchain.prompts.chat import (\n", " AIMessagePromptTemplate,\n", " ChatPromptTemplate,\n", " HumanMessagePromptTemplate,\n", " MessagesPlaceholder,\n", " SystemMessagePromptTemplate,\n", ")\n", "from langchain.schema import AIMessage, HumanMessage, SystemMessage" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from lv_recipe_chatbot.vegan_recipe_tools import vegan_recipe_edamam_search" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Setup env" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from dotenv import load_dotenv" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#| eval: false\n", "load_dotenv()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#| export\n", "INIT_PROMPT = ChatPromptTemplate.from_messages(\n", " [\n", " SystemMessagePromptTemplate.from_template(\n", " \"\"\"The following is a conversation between a human and a friendly vegan AI. \n", "The AI is compassionate to animals and therefore serves to promote veganism.\n", "Knowledge: A vegan diet implies a plant-based diet avoiding all animal foods such as meat (including fish, shellfish and insects), dairy, eggs and honey.\n", "If the human messages are not aligned with veganism, remind them of your purpose.\n", "The AI NEVER generates vegan recipes itself but instead uses a tool.\"\"\"\n", " ),\n", " AIMessagePromptTemplate.from_template(\n", " \"What ingredients do you wish to cook with?\"\n", " ),\n", " HumanMessagePromptTemplate.from_template(\"Ingredients: {ingredients}\"),\n", " AIMessagePromptTemplate.from_template(\n", " \"Do you have any allergies I should be aware of?\"\n", " ),\n", " HumanMessagePromptTemplate.from_template(\"Allergies: {allergies}\"),\n", " AIMessagePromptTemplate.from_template(\n", " \"Do you have any preferences I should consider for the recipe such as preparation time, difficulty, or cuisine region?\"\n", " ),\n", " HumanMessagePromptTemplate.from_template(\n", " \"\"\"Preferences: `{recipe_freeform_input}`\n", "Your task is compose a concise, 6 word max vegan recipe keyword query to use in an API search.\n", "Think step by step.\n", "\n", "1. If the user listed any ingredients, choose the three ingredients that are most commonly go together in recipes that match the user's preferences (if any are included). \n", "2. If the user provided any allergies, include them in the query.\n", "Format your response as message with the allergy and diet preferences first and then the ingredients.\n", "Examples:\n", "'Vegan gluten-free chicken peppers' or 'Vegan Japanese tofu, brocolli, and miso'\"\"\"\n", " ),\n", " ]\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Evaluate chat backend " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "content='Vegan Thai tofu, bell peppers, carrots' additional_kwargs={} example=False\n" ] } ], "source": [ "#| eval: false\n", "chat = PromptLayerChatOpenAI(temperature=0.1, pl_tags=[\"langchain\"], return_pl_id=True)\n", "memory = ConversationBufferMemory(return_messages=True)\n", "chat_msgs = INIT_PROMPT.format_prompt(\n", " ingredients=\"tofu, pickles, olives, tomatoes, lettuce, bell peppers, carrots, bread\",\n", " allergies=\"\",\n", " recipe_freeform_input=\"The preparation time should be less than 30 minutes. I really love Thai food!\",\n", ")\n", "\n", "chat_msgs = chat_msgs.to_messages()\n", "results = chat.generate([chat_msgs])\n", "chat_msgs.extend(\n", " [\n", " results.generations[0][0].message,\n", " MessagesPlaceholder(variable_name=\"history\"),\n", " HumanMessagePromptTemplate.from_template(\"{input}\"),\n", " ]\n", ")\n", "open_prompt = ChatPromptTemplate.from_messages(chat_msgs)\n", "conversation = ConversationChain(\n", " llm=chat, verbose=True, memory=memory, prompt=open_prompt\n", ")\n", "print(results.generations[0][0].message)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Vegan Thai tofu, bell peppers, carrots'" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#| eval: false\n", "results.generations[0][0].message.content" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Test with vegan recipe search tool" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"[{'label': 'Vegan Panang Curry with Tofu', 'url': 'https://pipingpotcurry.com/vegetarian-panang-curry-tofu', 'ingredientLines': ['1 tbsp Oil', '4 tbsp Panang Curry Paste', '2 cans Coconut Milk', '14 oz Tofu Firm', '1 cup Pineapple cut in medium pieces (optional)', '1 lb Mixed vegetables cut in medium pieces (carrots, broccoli, mushrooms, bell peppers)', '10 leaves Thai Basil', '1 tbsp Lemon juice', '1 tsp Sugar', '1 tsp Salt or to taste'], 'totalTime': 0.0}, {'label': 'Vegan Rainbow Thai Peanut Noodle Bake', 'url': 'https://tastykitchen.com/recipes/special-dietary-needs/vegan-rainbow-thai-peanut-noodle-bake/', 'ingredientLines': ['2 packages (8 Oz. Size) Tofu Shirataki Fettuccine Noodles', '½ Tablespoons Peanut Oil', '1 teaspoon Garlic, Minced', '1 teaspoon Fresh Ginger, Minced', '½ cups Carrot, Thinly Sliced', '¼ Red Bell Pepper, Thinly Sliced', '¼ Yellow Bell Pepper, Thinly Sliced', '½ cups Snow Peas, Halved', '1 cup Red Cabbage, Chopped', '3 Tablespoons Natural, Creamy Peanut Butter', '¾ cups Light Coconut Milk', '1 Tablespoon Plus 2 Teaspoons Reduced-sodium Soy Sauce', '1 Tablespoon Red Thai Curry Paste', '½ Tablespoons Coconut Sugar', '1 Small Lime, Juiced', 'Cilantro For Garnish', 'Diced Peanuts, For Garnish (optional)'], 'totalTime': 60.0}, {'label': 'Vegan Pad Thai recipes', 'url': 'http://www.godairyfree.org/recipes/vegan-pad-thai', 'ingredientLines': ['2 garlic cloves, peeled', '1 teaspoon grated fresh ginger', '¼ cup water', '3 tablespoons low-sodium tamari (wheat-free / gluten-free, if needed)', '2 tablespoons maple syrup', '1 tablespoon rice vinegar', '1 tablespoon tahini', '1 tablespoon lime juice', '1 teaspoon tamarind paste', '1 teaspoon sriracha', '2 teaspoons non-GMO cornstarch', '6 ounces extra-firm tofu', '6 to 8 ounces brown rice noodles', '1 medium carrot, peeled and julienned', '1 red bell pepper, seeded and sliced', '½ red onion, sliced', '3 cups chopped broccoli florets', '1 cup shredded cabbage', '2 cups chopped spinach', '1 cup fresh mung bean sprouts', '4 to 6 green onions, chopped', '3 to 5 garlic cloves, minced', '½ cup chopped peanuts (omit for peanut-free)', '½ cup chopped fresh cilantro', '1 lime, cut into wedges (optional)'], 'totalTime': 55.0}]\"" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#| eval: false\n", "vegan_recipe_edamam_search(results.generations[0][0].message.content)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", "Prompt after formatting:\n", "\u001b[32;1m\u001b[1;3mSystem: The following is a conversation between a human and a friendly vegan AI. \n", "The AI is compassionate to animals and therefore serves to promote veganism.\n", "Knowledge: A vegan diet implies a plant-based diet avoiding all animal foods such as meat (including fish, shellfish and insects), dairy, eggs and honey.\n", "If the human messages are not aligned with veganism, remind them of your purpose.\n", "The AI never generates vegan recipes itself but instead uses a tool.\n", "AI: What ingredients do you wish to cook with?\n", "Human: Ingredients: tofu, pickles, olives, tomatoes, lettuce, bell peppers, carrots, bread\n", "AI: Do you have any allergies I should be aware of?\n", "Human: Allergies: \n", "AI: Do you have any preferences I should consider for the recipe such as preparation time, difficulty, or cuisine region?\n", "Human: Preferences: `The preparation time should be less than 30 minutes. I really love Thai food!`\n", "Your task is compose a concise, 6 word max vegan recipe keyword query to use in an API search.\n", "Think step by step.\n", "\n", "1. If the user listed any ingredients, choose the three ingredients that are most commonly used together in recipes that fall within the user's preferences (if any are included). \n", "2. If the user provided any allergies, include them in the query.\n", "Format your response as message with the allergy and diet preferences first and then the ingredients.\n", "Examples:\n", "'Vegan gluten-free chicken peppers' or 'Vegan tofu, brocolli, and miso'\n", "AI: Vegan, Thai, tofu, bell peppers, carrots\n", "Human: Aactually how about italian instead with those same ingredients?\n", "AI: Vegan, Italian, tofu, bell peppers, carrots\n", "Human: Aactually how about italian instead with those same ingredients?\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n", "I'm sorry, but as a vegan AI, I cannot provide a recipe that includes animal products such as meat or dairy. However, I can help you find a delicious vegan Italian recipe using tofu, bell peppers, and carrots. Would you like me to assist you with that?\n" ] } ], "source": [ "#| eval: false\n", "result = conversation.predict(\n", " input=\"Aactually how about italian instead with those same ingredients?\"\n", ")\n", "print(result)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"[{'label': 'RBC Vegan Stuffed Cabbage Leaves', 'url': 'https://www.bigoven.com/recipe/rbc-vegan-stuffed-cabbage-leaves/517323', 'ingredientLines': ['2 heads Cabbage ; Steamed 10 minutes cooled', '1 pound Firm tofu ; Sliced thinly', '14 ounces Canned tomato sauce', '7 ounces Beets ; Canned', '1 Carrot ; Shredded', '1 Green or red bell pepper ; Thinly sliced', '8 ounces Fresh mushrooms ; Sliced', '4 cloves Garlic cloves ; Chopped', '2 cups Dry wild rice ; Prepared as directed', '5 ounces Non dairy cream cheese', '1 teaspoon Italian seasoning', 'Salt & pepper ; To taste'], 'totalTime': 0.0}]\"" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#| eval: false\n", "vegan_recipe_edamam_search(\"Vegan, Italian, tofu, bell peppers, carrots\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#| hide\n", "import nbdev\n", "\n", "nbdev.nbdev_export()" ] } ], "metadata": { "kernelspec": { "display_name": "python3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 4 }