{ "cells": [ { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# !pip install -q langchain==0.1.9\n", "# !pip install -q openai==1.13.3" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "notebookRunGroups": { "groupValue": "" } }, "outputs": [], "source": [ "from keys import openapi_key\n", "import os\n", "\n", "os.environ['OPENAI_API_KEY'] = openapi_key\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\"Dragon's Den Cuisine\"\n" ] } ], "source": [ "from langchain_community.llms import OpenAI\n", "llm = OpenAI(temperature=0.6)\n", "name = llm.invoke(\"I want to open a restaurant for Chinese food. Suggest a fancy name for this.\")\n", "print(name)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I want to open a restaurant for Mexican food. Suggest a fancy name for this.'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.prompts import PromptTemplate\n", "\n", "prompt_template_name = PromptTemplate(\n", " input_variables = [\"cuisine\"],\n", " template=\"I want to open a restaurant for {cuisine} food. Suggest a fancy name for this.\",\n", ")\n", "\n", "prompt_template_name.format(cuisine=\"Mexican\")" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'cuisine': 'Mexican',\n", " 'text': '\\n\\n\"El Jardín de Sabores\" (The Garden of Flavors)'}" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.chains import LLMChain\n", "\n", "name_chain = LLMChain(llm=llm, prompt=prompt_template_name)\n", "name_chain.invoke({\"cuisine\":\"Mexican\"})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sequential Chains" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "prompt_template_items = PromptTemplate(\n", " input_variables = [\"restaurant_name\"],\n", " template=\"Suggest some menu items for {restaurant_name}. Return it as a comma separated list.\",\n", ")\n", "food_items_chain = LLMChain(llm=llm, prompt=prompt_template_items)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "1. Chicken Tikka Masala\n", "2. Vegetable Samosas\n", "3. Lamb Vindaloo\n", "4. Palak Paneer\n", "5. Tandoori Chicken\n", "6. Garlic Naan\n", "7. Chana Masala\n", "8. Aloo Gobi\n", "9. Butter Chicken\n", "10. Mango Lassi \n", "\n" ] } ], "source": [ "from langchain.chains import SimpleSequentialChain\n", "\n", "chain = SimpleSequentialChain(chains=[name_chain, food_items_chain])\n", "response = chain.run(\"Indian\")\n", "print(response)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sequential Chain" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "llm = OpenAI(temperature=0.7)\n", "\n", "prompt_template_name = PromptTemplate(\n", " input_variables=[\"cuisine\"],\n", " template = \"I want to open a restaurant for {cuisine} food. Suggest a fancy name for this.\",\n", ")\n", "\n", "name_chain = LLMChain(llm=llm, prompt=prompt_template_name, output_key=\"restaurant_name\")\n", "\n", "prompt_template_items = PromptTemplate(\n", " input_variables=[\"restaurant_name\"],\n", " template = \"Suggest some menu items for {restaurant_name}. Return the menu items as a single, comma separated string with no additional preamble.\",\n", ")\n", "\n", "food_items_chain = LLMChain(llm=llm, prompt=prompt_template_items, output_key=\"menu_items\")\n", "\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'cuisine': 'Singaporean',\n", " 'restaurant_name': '\\n\"Straits Flavors\"',\n", " 'menu_items': '\\n\\nSambal Shrimp, Roti Canai, Nasi Lemak, Beef Rendang, Satay Skewers, Hainanese Chicken Rice, Char Kway Teow, Laksa Soup, Rojak Salad, Curry Puffs'}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.chains import SequentialChain\n", "\n", "chain = SequentialChain(\n", " chains=[name_chain, food_items_chain], \n", " input_variables=[\"cuisine\"], \n", " output_variables = [\"restaurant_name\", \"menu_items\"]\n", ")\n", "\n", "chain.invoke({\"cuisine\": \"Singaporean\"})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Agents" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "!pip install -q wikipedia\n", "!pip install -q numexpr # for llm-math" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "notebookRunGroups": { "groupValue": "1" } }, "outputs": [], "source": [ "from langchain.agents import AgentType, initialize_agent, load_tools\n", "from langchain.llms import OpenAI" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "tools = load_tools([\"wikipedia\", \"llm-math\"], llm=llm)\n", "\n", "agent = initialize_agent(\n", " tools,\n", " llm,\n", " agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n", " verbose=True\n", ")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Elon Musk was born on June 28, 1971 and will be 52 years old in 2023.'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "agent.run(\"When was Elon Musk born? What is his age right now in 2023?\")" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", "\u001b[32;1m\u001b[1;3m First, I need to find out when Elon Musk was born\n", "Action: wikipedia\n", "Action Input: Elon Musk\u001b[0m\n", "Observation: \u001b[36;1m\u001b[1;3mPage: Elon Musk\n", "Summary: Elon Reeve Musk (; EE-lon; born June 28, 1971) is a businessman and investor. He is the founder, chairman, CEO, and CTO of SpaceX; angel investor, CEO, product architect, and former chairman of Tesla, Inc.; owner, executive chairman, and CTO of X Corp.; founder of the Boring Company and xAI; co-founder of Neuralink and OpenAI; and president of the Musk Foundation. He is one of the wealthiest people in the world, with an estimated net worth of US$213 billion as of February 2024, according to the Bloomberg Billionaires Index, and $210 billion according to Forbes, primarily from his ownership stakes in Tesla and SpaceX.A member of the wealthy South African Musk family, Elon was born in Pretoria and briefly attended the University of Pretoria before immigrating to Canada at age 18, acquiring citizenship through his Canadian-born mother. Two years later, he matriculated at Queen's University at Kingston in Canada. Musk later transferred to the University of Pennsylvania, and received bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but dropped out after two days and, with his brother Kimbal, co-founded online city guide software company Zip2. The startup was acquired by Compaq for $307 million in 1999, and that same year Musk co-founded X.com, a direct bank. X.com merged with Confinity in 2000 to form PayPal.\n", "In October 2002, eBay acquired PayPal for $1.5 billion, and that same year, with $100 million of the money he made, Musk founded SpaceX, a spaceflight services company. In 2004, he became an early investor in electric vehicle manufacturer Tesla Motors, Inc. (now Tesla, Inc.). He became its chairman and product architect, assuming the position of CEO in 2008. In 2006, Musk helped create SolarCity, a solar-energy company that was acquired by Tesla in 2016 and became Tesla Energy. In 2013, he proposed a hyperloop high-speed vactrain transportation system. In 2015, he co-founded OpenAI, a nonprofit artificial intelligence research company. The following year, Musk co-founded Neuralink—a neurotechnology company developing brain–computer interfaces—and the Boring Company, a tunnel construction company. In 2022, he acquired Twitter for $44 billion. He subsequently merged the company into newly created X Corp. and rebranded the service as X the following year. In March 2023, he founded xAI, an artificial intelligence company.\n", "Musk has expressed views that have made him a polarizing figure. He has been criticized for making unscientific and misleading statements, including COVID-19 misinformation and antisemitic conspiracy theories. His ownership of Twitter has been similarly controversial, being marked by the laying off of a large number of employees, an increase in hate speech and misinformation and disinformation on the website, as well as changes to Twitter Blue verification. In 2018, the U.S. Securities and Exchange Commission (SEC) sued him, alleging that he had falsely announced that he had secured funding for a private takeover of Tesla. To settle the case, Musk stepped down as the chairman of Tesla and paid a $20 million fine.\n", "\n", "\n", "\n", "Page: Twitter under Elon Musk\n", "Summary: Elon Musk completed his acquisition of Twitter in October 2022; Musk acted as CEO of Twitter until June 2023 when he was succeeded by Linda Yaccarino. Twitter was then rebranded to X in July 2023. Initially during Musk's tenure, Twitter introduced a series of reforms and management changes; the company reinstated a number of previously banned accounts, reduced the workforce by approximately 80%, closed one of Twitter's three data centers, and largely eliminated the content moderation team, replacing it with the crowd-sourced fact-checking system Community Notes.\n", "In November 2022, Twitter then began offering paid verification checkmarks, followed by removing legacy verification. In December, the Twitter Files were released and a number of journalists suspended from the platform. The\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3m Now I have the information about Elon Musk's Twitter acquisition and his controversial actions as Twitter's CEO.\n", "Action: wikipedia\n", "Action Input: Elon Musk\u001b[0m\n", "Observation: \u001b[36;1m\u001b[1;3mPage: Elon Musk\n", "Summary: Elon Reeve Musk (; EE-lon; born June 28, 1971) is a businessman and investor. He is the founder, chairman, CEO, and CTO of SpaceX; angel investor, CEO, product architect, and former chairman of Tesla, Inc.; owner, executive chairman, and CTO of X Corp.; founder of the Boring Company and xAI; co-founder of Neuralink and OpenAI; and president of the Musk Foundation. He is one of the wealthiest people in the world, with an estimated net worth of US$213 billion as of February 2024, according to the Bloomberg Billionaires Index, and $210 billion according to Forbes, primarily from his ownership stakes in Tesla and SpaceX.A member of the wealthy South African Musk family, Elon was born in Pretoria and briefly attended the University of Pretoria before immigrating to Canada at age 18, acquiring citizenship through his Canadian-born mother. Two years later, he matriculated at Queen's University at Kingston in Canada. Musk later transferred to the University of Pennsylvania, and received bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but dropped out after two days and, with his brother Kimbal, co-founded online city guide software company Zip2. The startup was acquired by Compaq for $307 million in 1999, and that same year Musk co-founded X.com, a direct bank. X.com merged with Confinity in 2000 to form PayPal.\n", "In October 2002, eBay acquired PayPal for $1.5 billion, and that same year, with $100 million of the money he made, Musk founded SpaceX, a spaceflight services company. In 2004, he became an early investor in electric vehicle manufacturer Tesla Motors, Inc. (now Tesla, Inc.). He became its chairman and product architect, assuming the position of CEO in 2008. In 2006, Musk helped create SolarCity, a solar-energy company that was acquired by Tesla in 2016 and became Tesla Energy. In 2013, he proposed a hyperloop high-speed vactrain transportation system. In 2015, he co-founded OpenAI, a nonprofit artificial intelligence research company. The following year, Musk co-founded Neuralink—a neurotechnology company developing brain–computer interfaces—and the Boring Company, a tunnel construction company. In 2022, he acquired Twitter for $44 billion. He subsequently merged the company into newly created X Corp. and rebranded the service as X the following year. In March 2023, he founded xAI, an artificial intelligence company.\n", "Musk has expressed views that have made him a polarizing figure. He has been criticized for making unscientific and misleading statements, including COVID-19 misinformation and antisemitic conspiracy theories. His ownership of Twitter has been similarly controversial, being marked by the laying off of a large number of employees, an increase in hate speech and misinformation and disinformation on the website, as well as changes to Twitter Blue verification. In 2018, the U.S. Securities and Exchange Commission (SEC) sued him, alleging that he had falsely announced that he had secured funding for a private takeover of Tesla. To settle the case, Musk stepped down as the chairman of Tesla and paid a $20 million fine.\n", "\n", "\n", "\n", "Page: Twitter under Elon Musk\n", "Summary: Elon Musk completed his acquisition of Twitter in October 2022; Musk acted as CEO of Twitter until June 2023 when he was succeeded by Linda Yaccarino. Twitter was then rebranded to X in July 2023. Initially during Musk's tenure, Twitter introduced a series of reforms and management changes; the company reinstated a number of previously banned accounts, reduced the workforce by approximately 80%, closed one of Twitter's three data centers, and largely eliminated the content moderation team, replacing it with the crowd-sourced fact-checking system Community Notes.\n", "In November 2022, Twitter then began offering paid verification checkmarks, followed by removing legacy verification. In December, the Twitter Files were released and a number of journalists suspended from the platform. The\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3m Now I have the information about Elon Musk's Twitter acquisition and his controversial actions as Twitter's CEO. I also know that he stepped down as chairman of Tesla in 2018.\n", "Action: wikipedia\n", "Action Input: Elon Musk\u001b[0m\n", "Observation: \u001b[36;1m\u001b[1;3mPage: Elon Musk\n", "Summary: Elon Reeve Musk (; EE-lon; born June 28, 1971) is a businessman and investor. He is the founder, chairman, CEO, and CTO of SpaceX; angel investor, CEO, product architect, and former chairman of Tesla, Inc.; owner, executive chairman, and CTO of X Corp.; founder of the Boring Company and xAI; co-founder of Neuralink and OpenAI; and president of the Musk Foundation. He is one of the wealthiest people in the world, with an estimated net worth of US$213 billion as of February 2024, according to the Bloomberg Billionaires Index, and $210 billion according to Forbes, primarily from his ownership stakes in Tesla and SpaceX.A member of the wealthy South African Musk family, Elon was born in Pretoria and briefly attended the University of Pretoria before immigrating to Canada at age 18, acquiring citizenship through his Canadian-born mother. Two years later, he matriculated at Queen's University at Kingston in Canada. Musk later transferred to the University of Pennsylvania, and received bachelor's degrees in economics and physics. He moved to California in 1995 to attend Stanford University, but dropped out after two days and, with his brother Kimbal, co-founded online city guide software company Zip2. The startup was acquired by Compaq for $307 million in 1999, and that same year Musk co-founded X.com, a direct bank. X.com merged with Confinity in 2000 to form PayPal.\n", "In October 2002, eBay acquired PayPal for $1.5 billion, and that same year, with $100 million of the money he made, Musk founded SpaceX, a spaceflight services company. In 2004, he became an early investor in electric vehicle manufacturer Tesla Motors, Inc. (now Tesla, Inc.). He became its chairman and product architect, assuming the position of CEO in 2008. In 2006, Musk helped create SolarCity, a solar-energy company that was acquired by Tesla in 2016 and became Tesla Energy. In 2013, he proposed a hyperloop high-speed vactrain transportation system. In 2015, he co-founded OpenAI, a nonprofit artificial intelligence research company. The following year, Musk co-founded Neuralink—a neurotechnology company developing brain–computer interfaces—and the Boring Company, a tunnel construction company. In 2022, he acquired Twitter for $44 billion. He subsequently merged the company into newly created X Corp. and rebranded the service as X the following year. In March 2023, he founded xAI, an artificial intelligence company.\n", "Musk has expressed views that have made him a polarizing figure. He has been criticized for making unscientific and misleading statements, including COVID-19 misinformation and antisemitic conspiracy theories. His ownership of Twitter has been similarly controversial, being marked by the laying off of a large number of employees, an increase in hate speech and misinformation and disinformation on the website, as well as changes to Twitter Blue verification. In 2018, the U.S. Securities and Exchange Commission (SEC) sued him, alleging that he had falsely announced that he had secured funding for a private takeover of Tesla. To settle the case, Musk stepped down as the chairman of Tesla and paid a $20 million fine.\n", "\n", "\n", "\n", "Page: Twitter under Elon Musk\n", "Summary: Elon Musk completed his acquisition of Twitter in October 2022; Musk acted as CEO of Twitter until June 2023 when he was succeeded by Linda Yaccarino. Twitter was then rebranded to X in July 2023. Initially during Musk's tenure, Twitter introduced a series of reforms and management changes; the company reinstated a number of previously banned accounts, reduced the workforce by approximately 80%, closed one of Twitter's three data centers, and largely eliminated the content moderation team, replacing it with the crowd-sourced fact-checking system Community Notes.\n", "In November 2022, Twitter then began offering paid verification checkmarks, followed by removing legacy verification. In December, the Twitter Files were released and a number of journalists suspended from the platform. The\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3m Now I have the information about Elon Musk's Twitter acquisition and his controversial actions as Twitter's CEO. I also know that he stepped down as chairman of Tesla in 2018. Now I can calculate his age in 2023.\n", "Action: Calculator\n", "Action Input: 2023 - 1971\u001b[0m\n", "Observation: \u001b[33;1m\u001b[1;3mAnswer: 52\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n", "Final Answer: Elon Musk will be 52 years old in 2023.\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n" ] }, { "data": { "text/plain": [ "'Elon Musk will be 52 years old in 2023.'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "agent = initialize_agent(\n", " tools,\n", " llm,\n", " agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,\n", " verbose=True\n", ")\n", "agent.run(\"When was Elon Musk born? What is his age right now in 2023?\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "codebasics-langchain-crash-course", "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.13" } }, "nbformat": 4, "nbformat_minor": 2 }