{ "cells": [ { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "\n", "# Load setting from Json outside of project.\n", "f = open('../../env/ai.json')\n", "settingsJson = json.load(f)\n", "del f\n", "\n", "for key in settingsJson:\n", " os.environ[key] = settingsJson[key]\n", " \n", "del settingsJson\n", " \n", "# # OR manually set them\n", "# os.environ['REQUESTS_CA_BUNDLE'] = '../../env/ZCert.pem'\n", "# os.environ['HUGGING_FACE_API_KEY'] = 'Get here: https://huggingface.co/settings/tokens'\n", "# os.environ['OPENAI_API_KEY'] = 'Get here: https://platform.openai.com/account/api-keys'\n", "# os.environ[\"SERPAPI_API_KEY\"] = 'serpapi KEY, Get here: https://serpapi.com/manage-api-key'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Setup Web Crawler and Lookup functions" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "import requests\n", "from bs4 import BeautifulSoup\n", "import json\n", "\n", "def remove_keys(dictionary: dict, keyList: list):\n", " for key in keyList: \n", " if key in dictionary:\n", " del dictionary[key] \n", "\n", "def get_recipe_as_json(url: str) -> dict: \n", " url = url.replace(\"'\", \"\").replace('\"', '')\n", " html = requests.get(url).text \n", " soup = BeautifulSoup(html)\n", " script = soup.find_all(\"script\", {\"id\": \"allrecipes-schema_1-0\"})\n", "\n", " recipeDict = json.loads(script[0].text)[0]\n", " remove_keys(recipeDict, ['review', 'image', 'mainEntityOfPage', 'publisher'])\n", " # del recipeDict['review']\n", " # del recipeDict['image']\n", " # del recipeDict['mainEntityOfPage']\n", " # del recipeDict['publisher']\n", " \n", " return recipeDict\n", "\n", "# url = \"https://www.allrecipes.com/recipe/212498/easy-chicken-and-broccoli-alfredo/\"\n", "# obj = get_recipe_as_json(url)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Static recipe lists" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "dessertList = [\n", " {\n", " \"title\": \"Chocolate Snack Cake\",\n", " \"url\": \"https://www.allrecipes.com/chocolate-snack-cake-recipe-8350343\"\n", " },\n", " {\n", " \"title\": \"Charred Spiced Pears with Smoky Vanilla Cherry Sauce\",\n", " \"url\": \"https://www.allrecipes.com/charred-spiced-pears-with-smoky-vanilla-cherry-sauce-recipe-8347080\"\n", " },\n", " {\n", " \"title\": \"Meringue Topped Banana Pudding\",\n", " \"url\": \"https://www.allrecipes.com/meringue-topped-banana-pudding-recipe-8347040\"\n", " },\n", " {\n", " \"title\": \"White Chocolate Cinnamon Toast Crunch Bars\",\n", " \"url\": \"https://www.allrecipes.com/white-chocolate-cinnamon-toast-crunch-bars-recipe-7556790\"\n", " },\n", " {\n", " \"title\": \"Plum Cobbler for Two\",\n", " \"url\": \"https://www.allrecipes.com/plum-cobbler-for-two-recipe-8304143\"\n", " },\n", " {\n", " \"title\": \"Pumpkin Cheesecake Cookies\",\n", " \"url\": \"https://www.allrecipes.com/pumpkin-cheesecake-cookies-recipe-7972485\"\n", " },\n", " {\n", " \"title\": \"Chocolate Whipped Cottage Cheese\",\n", " \"url\": \"https://www.allrecipes.com/chocolate-whipped-cottage-cheese-recipe-8303272\"\n", " },\n", " {\n", " \"title\": \"Nutella Ice Cream\",\n", " \"url\": \"https://www.allrecipes.com/nutella-ice-cream-recipe-7508716\"\n", " },\n", " {\n", " \"title\": \"3-Ingredient Banana Oatmeal Cookies\",\n", " \"url\": \"https://www.allrecipes.com/3-ingredient-banana-oatmeal-cookies-recipe-7972686\"\n", " },\n", " {\n", " \"title\": \"Caramel Apple Pie Cookies\",\n", " \"url\": \"https://www.allrecipes.com/caramel-apple-pie-cookies-recipe-7642173\"\n", " }\n", "]\n", "\n", "chickenDishList = [\n", " {\n", " \"title\": \"Crispy Roasted Chicken\",\n", " \"url\": \"https://www.allrecipes.com/recipe/228363/crispy-roasted-chicken/\"\n", " },\n", " {\n", " \"title\": \"Roasted Spatchcocked Chicken With Potatoes\",\n", " \"url\": \"https://www.allrecipes.com/recipe/254877/roasted-spatchcocked-chicken-with-potatoes/\"\n", " },\n", " {\n", " \"title\": \"Easy Baked Chicken Thighs\",\n", " \"url\": \"https://www.allrecipes.com/recipe/235153/easy-baked-chicken-thighs/\"\n", " },\n", " {\n", " \"title\": \"Crispy Baked Chicken Thighs\",\n", " \"url\": \"https://www.allrecipes.com/recipe/258878/crispy-baked-chicken-thighs/\"\n", " },\n", " {\n", " \"title\": \"Crispy and Tender Baked Chicken Thighs\",\n", " \"url\": \"https://www.allrecipes.com/recipe/235151/crispy-and-tender-baked-chicken-thighs/\"\n", " },\n", " {\n", " \"title\": \"Million Dollar Chicken\",\n", " \"url\": \"https://www.allrecipes.com/recipe/233953/million-dollar-chicken/\"\n", " },\n", " {\n", " \"title\": \"Simple Whole Roasted Chicken\",\n", " \"url\": \"https://www.allrecipes.com/recipe/70679/simple-whole-roasted-chicken/\"\n", " },\n", " {\n", " \"title\": \"Beer Can Chicken\",\n", " \"url\": \"https://www.allrecipes.com/recipe/214618/beer-can-chicken/\"\n", " },\n", " {\n", " \"title\": \"Air Fryer Chicken Thighs\",\n", " \"url\": \"https://www.allrecipes.com/recipe/272858/air-fryer-chicken-thighs/\"\n", " },\n", " {\n", " \"title\": \"Happy Roast Chicken\",\n", " \"url\": \"https://www.allrecipes.com/recipe/214478/happy-roast-chicken/\"\n", " }\n", "]\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Setup Tools" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "# Tools \n", "from langchain.agents import Tool\n", "from langchain.tools import BaseTool\n", "\n", "# Chicken functions\n", "def list_chicken_recipes(query: str): \n", " return chickenDishList\n", "\n", "list_chicken_recipes_tool = Tool(name='Chicken Recipes tool', func= list_chicken_recipes, description=\"This tools lists the available Chicken Recipes it returns a list of recipes with a TITLE and a URL where you can fetch the recipe.\")\n", "\n", "# Dessert functions\n", "def list_dessert_recipes(query: str): \n", " return dessertList\n", "\n", "list_dessert_recipes_tool = Tool(name='Dessert Recipes tool', func=list_dessert_recipes, \n", " description=\"This tools lists the available Dessert Recipes it returns a list of recipes with a TITLE and a URL where you can fetch the recipe.\")\n", "\n", "# Recipe fetcher functions\n", "def get_recipe(url: str): \n", " return get_recipe_as_json(url)\n", "\n", "get_recipe_as_json_tool = Tool(name='Get a Recipe tool', func=get_recipe, description=\"\"\"\n", " Useful for fetching a particular recipe, you can only fetch a recipe with it's url, you must get that using another tool\n", " It uses the https://schema.org/Recipe format to store it's recipes. \n", " \"\"\")\n", "\n", "# Tool list\n", "tools = [list_chicken_recipes_tool, list_dessert_recipes_tool, get_recipe_as_json_tool]" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Chicken dishes:\n", "Crispy Roasted Chicken\n", "Roasted Spatchcocked Chicken With Potatoes\n", "Easy Baked Chicken Thighs\n", "Crispy Baked Chicken Thighs\n", "Crispy and Tender Baked Chicken Thighs\n", "Million Dollar Chicken\n", "Simple Whole Roasted Chicken\n", "Beer Can Chicken\n", "Air Fryer Chicken Thighs\n", "Happy Roast Chicken\n", "\n", "Desserts:\n", "Chocolate Snack Cake\n", "Charred Spiced Pears with Smoky Vanilla Cherry Sauce\n", "Meringue Topped Banana Pudding\n", "White Chocolate Cinnamon Toast Crunch Bars\n", "Plum Cobbler for Two\n", "Pumpkin Cheesecake Cookies\n", "Chocolate Whipped Cottage Cheese\n", "Nutella Ice Cream\n", "3-Ingredient Banana Oatmeal Cookies\n", "Caramel Apple Pie Cookies\n" ] } ], "source": [ "print('Chicken dishes:')\n", "for i in chickenDishList:\n", " print(i['title'])\n", " \n", "print()\n", "print('Desserts:')\n", "for i in dessertList:\n", " print(i['title'])" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", "\u001b[32;1m\u001b[1;3mThis question is about astronomy, which is not related to the tools I have access to. I don't have the information to answer this question.\n", "Final Answer: I'm sorry, I don't have the information to answer this question.\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n" ] } ], "source": [ "from langchain.agents import load_tools\n", "from langchain.agents import initialize_agent\n", "from langchain.llms import OpenAI\n", "from langchain.chat_models import ChatOpenAI\n", "\n", "from langchain.agents import initialize_agent\n", "llm = ChatOpenAI(temperature=0, model_name='gpt-4') # 'gpt-3.5-turbo'\n", "\n", "agent = initialize_agent(\n", " agent=\"zero-shot-react-description\", \n", " tools=tools, \n", " llm=llm,\n", " verbose=True,\n", " max_iterations=7, \n", " return_intermediate_steps=True\n", ")\n", "system = \"SYSTEM: If the answer is not in the tools or context passed to you then don't answer. If you don't know the answer then say so. QUESTION: \" \n", "#agent.run(\"Can you show tell me what ingredients I need for the first baked chicken recipe? \")\n", "#agent.run(\"Can you show tell me what ingredients I need for the last baked chicken recipe? \")\n", "#agent.run(\"What is the best baked chicken recipe? Please look across all recipes with the word 'baked' in the title\") # There are 3 baked chicken recipes\n", "#agent.run(\"Is there a Chicken recipe that's prepared with an alchohol? And if so how long does it take in total from start time to finish?\")\n", "#agent.run(\"Which is healthier the Cheesecake or the beer chicken? Please explain how you got to your answer.\")\n", "\n", "#agent.run(\"What tools do I need for the Nutella Ice Cream?\")\n", "#agent.run(\"My bowl is broken, can I still make Nutella Ice Cream?\")\n", "\n", "#response = agent({\"input\": f\"{system} Is the moon closer to earth or the sun?\"})\n", "response = agent({\"input\": f\"{system} My bowl is broken, can I still make Nutella Ice Cream?\"})\n", "\n", "#print(\"################\")\n", "#print(print(response[\"intermediate_steps\"]))\n", "\n" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[]\n" ] } ], "source": [ "print(response[\"intermediate_steps\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# UI" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running on local URL: http://127.0.0.1:7862\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", "\u001b[32;1m\u001b[1;3mI need to find a recipe for ice cream using the Dessert Recipes tool.\n", "Action: Dessert Recipes tool\n", "Action Input: Ice cream\u001b[0m\n", "Observation: \u001b[33;1m\u001b[1;3m[{'title': 'Chocolate Snack Cake', 'url': 'https://www.allrecipes.com/chocolate-snack-cake-recipe-8350343'}, {'title': 'Charred Spiced Pears with Smoky Vanilla Cherry Sauce', 'url': 'https://www.allrecipes.com/charred-spiced-pears-with-smoky-vanilla-cherry-sauce-recipe-8347080'}, {'title': 'Meringue Topped Banana Pudding', 'url': 'https://www.allrecipes.com/meringue-topped-banana-pudding-recipe-8347040'}, {'title': 'White Chocolate Cinnamon Toast Crunch Bars', 'url': 'https://www.allrecipes.com/white-chocolate-cinnamon-toast-crunch-bars-recipe-7556790'}, {'title': 'Plum Cobbler for Two', 'url': 'https://www.allrecipes.com/plum-cobbler-for-two-recipe-8304143'}, {'title': 'Pumpkin Cheesecake Cookies', 'url': 'https://www.allrecipes.com/pumpkin-cheesecake-cookies-recipe-7972485'}, {'title': 'Chocolate Whipped Cottage Cheese', 'url': 'https://www.allrecipes.com/chocolate-whipped-cottage-cheese-recipe-8303272'}, {'title': 'Nutella Ice Cream', 'url': 'https://www.allrecipes.com/nutella-ice-cream-recipe-7508716'}, {'title': '3-Ingredient Banana Oatmeal Cookies', 'url': 'https://www.allrecipes.com/3-ingredient-banana-oatmeal-cookies-recipe-7972686'}, {'title': 'Caramel Apple Pie Cookies', 'url': 'https://www.allrecipes.com/caramel-apple-pie-cookies-recipe-7642173'}]\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3mThe first ice cream recipe I found is for Nutella Ice Cream. I will use the Get a Recipe tool to fetch the recipe.\n", "Action: Get a Recipe tool\n", "Action Input: https://www.allrecipes.com/nutella-ice-cream-recipe-7508716\u001b[0m\n", "Observation: \u001b[38;5;200m\u001b[1;3m{'@context': 'http://schema.org', '@type': ['Recipe'], 'headline': 'Nutella Ice Cream', 'datePublished': '2023-09-28T17:27:33.088-04:00', 'dateModified': '2023-10-12T11:27:16.725-04:00', 'author': [{'@type': 'Person', 'name': 'Laka kuharika - Easy Cook', 'url': 'https://www.allrecipes.com/cook/lakakuharica'}], 'description': 'This exquisite homemade Nutella ice cream is full of nutty flavor, and everyone will simply love it. Nutella gives this ice cream an unbelievable hazelnut taste.', 'name': 'Nutella Ice Cream', 'cookTime': 'PT15M', 'nutrition': {'@type': 'NutritionInformation', 'calories': '305 kcal', 'carbohydrateContent': '16 g', 'cholesterolContent': '156 mg', 'fiberContent': '1 g', 'proteinContent': '8 g', 'saturatedFatContent': '14 g', 'sodiumContent': '78 mg', 'sugarContent': '14 g', 'fatContent': '23 g', 'unsaturatedFatContent': '0 g'}, 'prepTime': 'PT10M', 'recipeCategory': ['Dessert'], 'recipeCuisine': ['American'], 'recipeIngredient': ['2 cups whole milk', '1 cup heavy cream, divided', '4 egg yolks', '1/2 teaspoon vanilla extract', '1/2\\xa0 cup cocoa hazelnut spread (such as Nutella®)', 'Hazelnuts, crushed, for garnish'], 'recipeInstructions': [{'@type': 'HowToStep', 'text': 'Combine milk, cream, and 1/2 cup sugar in a saucepan over medium heat. Cook until sugar dissolves, about 5 minutes.'}, {'@type': 'HowToStep', 'text': 'Beat egg yolks with the remaining sugar in a bowl with an electric mixer until eggs become thick and pale yellow, about 4 minutes.'}, {'@type': 'HowToStep', 'text': 'Pour 1/2 cup warm milk mixture into egg mixture and stir. Add this mixture back into the saucepan. Cook over very low heat, stirring constantly, until the mixture becomes thick enough to coat the back of a wooden spoon, 7 to 10 minutes.'}, {'@type': 'HowToStep', 'text': 'Place a strainer over a bowl and pour the warm custard mixture through the strainer. Stir in vanilla and hazelnut spread until it dissolves.'}, {'@type': 'HowToStep', 'text': 'Chill mixture completely, about 1 hour. Pour into an ice cream maker and churn until frozen according to manufacturer’s instructions, 15 to 20 minutes.'}, {'@type': 'HowToStep', 'text': 'Transfer to a plastic container and place in the freezer for an hour before serving. Top with crushed hazelnuts for serving.'}], 'recipeYield': ['8'], 'totalTime': 'PT160M', 'about': []}\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3mI now know the final answer\n", "Final Answer: To make Nutella Ice Cream, follow these steps:\n", "1. Combine 2 cups of whole milk, 1 cup of heavy cream, and 1/2 cup of sugar in a saucepan over medium heat. Cook until sugar dissolves, about 5 minutes.\n", "2. Beat 4 egg yolks with the remaining sugar in a bowl with an electric mixer until eggs become thick and pale yellow, about 4 minutes.\n", "3. Pour 1/2 cup warm milk mixture into egg mixture and stir. Add this mixture back into the saucepan. Cook over very low heat, stirring constantly, until the mixture becomes thick enough to coat the back of a wooden spoon, 7 to 10 minutes.\n", "4. Place a strainer over a bowl and pour the warm custard mixture through the strainer. Stir in 1/2 teaspoon of vanilla and 1/2 cup of cocoa hazelnut spread (such as Nutella®) until it dissolves.\n", "5. Chill mixture completely, about 1 hour. Pour into an ice cream maker and churn until frozen according to manufacturer’s instructions, 15 to 20 minutes.\n", "6. Transfer to a plastic container and place in the freezer for an hour before serving. Top with crushed hazelnuts for serving.\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n" ] } ], "source": [ "import gradio as gr\n", "\n", "# # Import langchain stuff\n", "# from langchain.agents import load_tools, initialize_agent, AgentType\n", "# from langchain.llms import OpenAI\n", "\n", "\n", "# # Initializing the LLM and the Toolset\n", "# llm = OpenAI(temperature=0)\n", "# tools = load_tools([\"wikipedia\"], llm=llm)\n", "# agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n", "\n", "def langchain_bot(prompt):\n", " if prompt:\n", " text = agent.run(prompt)\n", " return text\n", " return \"Type a prompt to get a Wikipedia-like response!\"\n", "\n", "# Customize the appearance and style of the interface\n", "iface = gr.Interface(fn=langchain_bot, inputs=gr.Textbox(lines=5, placeholder=\"Type your prompt here...\"), \n", " outputs=gr.Textbox(), title=\"Wikipedia Langchain Bot 🦜\",\n", " description=\"Generate Wikipedia-like responses using Langchain AI.\")\n", "\n", "# Launch the interface\n", "iface.launch()" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.6" } }, "nbformat": 4, "nbformat_minor": 2 }