{ "cells": [ { "cell_type": "markdown", "id": "8311cbd8-ac55-4ebc-9f20-1d8c69e5c6a1", "metadata": {}, "source": [ "# Blog: Getting Started with LangChain: A Beginner’s Guide to Building LLM-Powered Applications\n", "- https://towardsdatascience.com/getting-started-with-langchain-a-beginners-guide-to-building-llm-powered-applications-95fc8898732c" ] }, { "cell_type": "code", "execution_count": 15, "id": "800b7b5d-68e3-4070-9555-d911b37372d7", "metadata": { "tags": [] }, "outputs": [], "source": [ "# import os\n", "# os.environ[\"OPENAI_API_KEY\"]=', client=, model_name='text-davinci-003', temperature=0.7, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0, n=1, best_of=1, model_kwargs={}, openai_api_key=None, batch_size=20, request_timeout=None, logit_bias={}, max_retries=6, streaming=False)" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "llm" ] }, { "cell_type": "markdown", "id": "5b229730-ba74-409f-b2cb-e7bfdba3d8ec", "metadata": {}, "source": [ "# Embedding" ] }, { "cell_type": "code", "execution_count": 6, "id": "a8cae536-9527-4649-a930-b6f28ea4ebb6", "metadata": { "tags": [] }, "outputs": [], "source": [ "from langchain.embeddings import OpenAIEmbeddings\n", "embeddings = OpenAIEmbeddings()\n", "\n", "# The embeddings model takes a text as an input and outputs a list of floats\n", "text = \"Alice has a parrot. What animal is Alice's pet?\"\n", "text_embedding = embeddings.embed_query(text)" ] }, { "cell_type": "code", "execution_count": 9, "id": "fb27b8e0-3ccb-4397-a657-c267b684424f", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "OpenAIEmbeddings(client=, model='text-embedding-ada-002', document_model_name='text-embedding-ada-002', query_model_name='text-embedding-ada-002', embedding_ctx_length=-1, openai_api_key=None, chunk_size=1000, max_retries=6)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "embeddings" ] }, { "cell_type": "code", "execution_count": 10, "id": "f1206191-e690-4da7-8fa0-ab1465308bbb", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dimentsion size: 1536\n" ] } ], "source": [ "print(\"dimentsion size: \", len(text_embedding))" ] }, { "cell_type": "code", "execution_count": 11, "id": "081646fb-2610-48d3-a18e-fb0bb070a580", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a little bit of dimentsion : [0.013288114219903946, -0.009326402097940445, -0.008071756921708584, -0.011409236118197441, -0.013473529368638992, 0.011149654164910316, -0.005432675592601299, 0.0032571330666542053, -0.0020812894217669964, -0.0018170722760260105]\n" ] } ], "source": [ "print(\"a little bit of dimentsion : \", text_embedding[0:10])" ] }, { "cell_type": "markdown", "id": "24f4c99d-1067-4a71-afcb-11169797021f", "metadata": {}, "source": [ "# Prompts: Managing LLM inputs" ] }, { "cell_type": "markdown", "id": "626dc49c-85ff-4e55-8507-6c891291187f", "metadata": {}, "source": [ "## Zero-shot pormpt" ] }, { "cell_type": "code", "execution_count": 18, "id": "2df10cdb-b722-423f-b930-5fb5f0b6554c", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "'What is a good name for a company that makes colorful socks?'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain import PromptTemplate\n", "\n", "template = \"What is a good name for a company that makes {product}?\"\n", "\n", "prompt = PromptTemplate(\n", " input_variables=[\"product\"],\n", " template=template,\n", ")\n", "\n", "prompt.format(product=\"colorful socks\")" ] }, { "cell_type": "markdown", "id": "7fa5d80e-8a9d-4b15-9429-6f4c9fd8a5bc", "metadata": {}, "source": [ "# few-shot prompt" ] }, { "cell_type": "code", "execution_count": 19, "id": "735be27b-e4dd-4951-aa9f-54870d159a16", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "'Give the antonym of every input\\n\\nWord: happy\\nAntonym: sad\\n\\n\\n\\nWord: tall\\nAntonym: short\\n\\n\\nWord: big\\nAntonym:'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain import PromptTemplate, FewShotPromptTemplate\n", "\n", "examples = [\n", " {\"word\": \"happy\", \"antonym\": \"sad\"},\n", " {\"word\": \"tall\", \"antonym\": \"short\"},\n", "]\n", "\n", "example_template = \"\"\"\n", "Word: {word}\n", "Antonym: {antonym}\\n\n", "\"\"\"\n", "\n", "example_prompt = PromptTemplate(\n", " input_variables=[\"word\", \"antonym\"],\n", " template=example_template,\n", ")\n", "\n", "few_shot_prompt = FewShotPromptTemplate(\n", " examples=examples,\n", " example_prompt=example_prompt,\n", " prefix=\"Give the antonym of every input\",\n", " suffix=\"Word: {input}\\nAntonym:\",\n", " input_variables=[\"input\"],\n", " example_separator=\"\\n\",\n", ")\n", "\n", "few_shot_prompt.format(input=\"big\")" ] }, { "cell_type": "markdown", "id": "e9398955-2893-4fae-b441-3b638a5a57e0", "metadata": {}, "source": [ "# Chains: Combining LLMs " ] }, { "cell_type": "code", "execution_count": 22, "id": "e386179f-ed0f-4b94-b189-2dee29efd383", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "prompt: \n", " input_variables=['product'] output_parser=None partial_variables={} template='What is a good name for a company that makes {product}?' template_format='f-string' validate_template=True\n" ] } ], "source": [ "print(\"prompt: \\n\", prompt)" ] }, { "cell_type": "code", "execution_count": 21, "id": "994a3764-f6ae-43fd-9260-eedf158b629b", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "'\\n\\nHappy Socks & Co.'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.chains import LLMChain\n", "\n", "chain = LLMChain(llm = llm, \n", " prompt = prompt)\n", "\n", "# Run the chain only specifying the input variable.\n", "chain.run(\"colorful socks\")" ] }, { "cell_type": "markdown", "id": "fc72a348-1343-4d03-8b93-4a90abdf3528", "metadata": {}, "source": [ "## Chaining Two LLMs\n", "- Prompt (Product) --> LLM(Product):Compnay Name -> LLM(Company Name): Catchphrase --> Catchphrase\n", "- 흐름\n", " - Prompt 제공 \n", " - What is a good name for a company that makes {colorful socks}\n", " - 첫번째 LLM 으로 부터 회사 이름 답변 받음\n", " - Rainbow Toes\n", " - 두번째 prompt 제공 (위의 회사 이름을 입력으로 제공)\n", " - Write a catchphrase for the following company: {Rainbow Toes} \n", " - 두번째 LLM 으로 부터 catchphrase 답변 받음\n", " - \"Put a little rainbow in your step!\"\n", " " ] }, { "cell_type": "code", "execution_count": 25, "id": "36312acf-c7e9-4d49-b872-b6a1eb507ca7", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n", "\u001b[36;1m\u001b[1;3m\n", "\n", "Rainbow Toes.\u001b[0m\n", "\u001b[33;1m\u001b[1;3m\n", "\n", "\"Put a little rainbow in your step!\"\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n", "catchphrase: \n", " \n", "\n", "\"Put a little rainbow in your step!\"\n" ] } ], "source": [ "from langchain.chains import LLMChain, SimpleSequentialChain\n", "\n", "# Define the first chain as in the previous code example\n", "# ...\n", "\n", "# Create a second chain with a prompt template and an LLM\n", "second_prompt = PromptTemplate(\n", " input_variables=[\"company_name\"],\n", " template=\"Write a catchphrase for the following company: {company_name}\",\n", ")\n", "\n", "chain_two = LLMChain(llm=llm, prompt=second_prompt)\n", "\n", "# Combine the first and the second chain \n", "overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)\n", "\n", "# Run the chain specifying only the input variable for the first chain.\n", "catchphrase = overall_chain.run(\"colorful socks\")\n", "print(\"catchphrase: \\n\", catchphrase)" ] }, { "cell_type": "markdown", "id": "fcb6d5db-e862-45e0-841a-676c804755fa", "metadata": {}, "source": [ "# Indexes: Accessing external data" ] }, { "cell_type": "code", "execution_count": 28, "id": "3045c0b1-8d68-4aa0-8923-9b9e271bee03", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n", "\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n", "\u001b[0m" ] } ], "source": [ "! pip install youtube-transcript-api --quiet\n", "! pip install pytube --quiet\n" ] }, { "cell_type": "markdown", "id": "adcaeef5-5a85-446b-88c8-ca5ed1edef57", "metadata": {}, "source": [ "![youtube_Next_js13.png](img/youtube_Next_js13.png)" ] }, { "cell_type": "code", "execution_count": 30, "id": "5d7e4e8a-8158-4ebb-a2e2-cf0ff961a6d2", "metadata": { "tags": [] }, "outputs": [], "source": [ "\n", "from langchain.document_loaders import YoutubeLoader\n", "\n", "# loader = YoutubeLoader.from_youtube_url(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\")\n", "loader = YoutubeLoader(\"_w0Ikk4JY7U\", True)\n", " \n", "documents = loader.load()" ] }, { "cell_type": "code", "execution_count": 31, "id": "f3bc8418-5ebe-4a84-8640-bc8679bfd8dc", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "[Document(page_content=\"it is October 26 2022 and you're watching the code report just when you thought you had web development all figured out Along Comes an entirely new build tool and a complete overhaul of your favorite framework we're ready for a new paradigm not enough men's and disease of evil the reality [Music] JavaScript it's a wild ride next JS comp happened yesterday and they made an extremely ballsy move to take the world's most popular JavaScript framework and linchpin of a unicorn startup and totally change up the developer experience as you're about to see these new features are game changing and blazingly fast but they're not without their trade-offs buckle up because we've got a lot to unpack starting with a brand new build tool called turbo pack now I know you just switched over to the next gen build tool V last week but a new character is spawned versel employs Tobias coppers the creator of webpack who knows a thing or two about module bundling turbo pack was built from the ground up with rust which appeals to our novelty bias and it integrates turbo repo to Cache duplicate operations together these factors can satisfy your need for blazingly fast speed turbo pack shows updates 10 times faster than Veet and 700 times faster than webpack shots fired shots fired turbo pack sounds amazing but it's currently an alpha and I'm a bit skeptical there's a massive ecosystem of webpack plugins that will likely make migration very hard for existing apps Versa will likely need to count on community contributions with some kind of plug-in system and that might be difficult because JavaScript developers like me are too dumb and lazy to learn rust furthermore these speed gains are mostly relevant to Big Enterprise projects where teams over engineer these giant monstrosities to guarantee job security Veet with es build is already fast enough for most projects and it's got an awesome developer experience that's hard to beat you should also know that Purcell has an angle to make money on this by remotely caching builds in the cloud and parcel has been using this architecture for a long time as well what's way more exciting for me is the brand new routing system the best possible router which adds a smorgasbord of new possibilities and performance improvements to the framework these are huge changes that they worked on directly with the react core team but before you freak out everything can be incrementally adopted so it won't break your existing project next 13 adds a new app directory that also uses file system-based routing like before but now it's all directory based along with a bunch of naming conventions for different use cases to create a page you give the direct the name of the route then add a page.js file to it that exports the component you want to display there nice and simple however because it's a directory we can co-locate extra components here as well instead of needing to create a separate components directory or some other kind of convention more importantly though it opens the door to layouts and nested routing when you give a file the name of layout.js it creates a UI that can be inherited by the child routes and when you navigate to a route inside of a layout only the inner UI is rendered as opposed to the entire page this is really cool because we also have file naming conventions for loading and error that can render a different UI at the component level based on its current state for example if the component breaks it will render error.js instead of page.js while the rest of the UI stays intact and this just makes life so much easier but by far the most epic feature in this new release is data fetching next is what you would almost call the official react framework now that's our endorsement that this is the data fetching solution for react that everyone I think has been been waiting for what I I haven't told you yet is that all of these components are react server components by default server components are a low level primitive in react that enables server-side rendering but until now they've always been kind of difficult for the common developer to use it's a huge deal because now we can totally get rid of things like get static props and get server-side props instead we can just write a plain JavaScript function that uses Fetch and then await the result of that function directly in a component no need to pass props back and forth between client and server it feels totally natural like you're just using vanilla JavaScript and you don't even need to serialize data which can be a major pain Point furthermore you can take Concepts like ISR SSR and SSG and remove them from your brain the new mental model revolves entirely around caching by default all pages will be cached to provide the performance of a static site but if you want new data on every request like SSR you can add the Cache no store option to fetch or for incremental static regeneration use the next option with the number of rebalidate seconds and what's also amazing about all this is that the UI can be incrementally streamed in thanks to react suspense all you have to do is Define a loading.js file to define the UI if a component is still awaiting data it will automatically show it at the component level while rendering everything else in the application game changing but many of these features are clearly inspired by remix credit where credit is due but all is fair in love and MIT license code but one thing next is missing is a way to write data similar to remix forms which I think is a really great feature and weirdly there's no way to write API routes in the new app directory as far as I can tell and to me that just seems like a sloppy loose end as I showed data fetching looks amazing but mutations are an entirely different story in the docs it says the next team is working on a new RFC for mutating data but currently you would use a client-side component write your mutation logic then pass a callback function of refresh to update any data on that route after the mutation is complete this is kind of similar to how things work in react query but it seems like the framework could provide a more intuitive solution here overall I think next 13 looks amazing however these are major changes that basically make every next JS tutorial out there obsolete even if these changes are a step forward the reality is that people don't like change like people were riding in the streets when view 2 went to view 3 even though it too can be adopted incrementally right now everybody's super excited about these new features but if you're the guy that has to migrate all that code your initial excitement might soon turn to anger another criticism is that a Hello World app is still 90 kilobytes of JavaScript it seems like it should be able to ship zero JavaScript apps like Astro quick and so on but that doesn't appear to be the case in addition to the features I mentioned there are all kinds of small optimizations and one of them was even inspired by a video I made Edge functions can now be set to a specific region and it's great to see these big companies recognize that the shape of the planet is not an oblate sphere but rather a level plane and lastly I'm working on a longer full tutorial for next 13 which will be on my new channel Beyond fireship so make sure to subscribe over there this has been the code report thanks for watching and I will see you in the next one [Music]\", metadata={'source': '_w0Ikk4JY7U', 'title': 'Next.js 13… this changes everything', 'description': None, 'view_count': 657697, 'thumbnail_url': 'https://i.ytimg.com/vi/_w0Ikk4JY7U/hq720.jpg', 'publish_date': datetime.datetime(2022, 10, 26, 0, 0), 'length': 376, 'author': 'Fireship'})]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "documents" ] }, { "cell_type": "code", "execution_count": 33, "id": "5e010494-489d-475a-bad0-9e734ab0850d", "metadata": { "tags": [] }, "outputs": [], "source": [ "# pip install faiss-cpu\n", "from langchain.vectorstores import FAISS\n", "\n", "# create the vectorestore to use as the index\n", "db = FAISS.from_documents(documents, embeddings)\n" ] }, { "cell_type": "markdown", "id": "1446d7ab-2f5a-44f7-9998-d4c91aac268e", "metadata": {}, "source": [ "하나의 문서가 저장이 되어 있음" ] }, { "cell_type": "code", "execution_count": 36, "id": "2f17d2d5-7bb8-4fcc-85d1-ef5809930af0", "metadata": { "tags": [] }, "outputs": [ { "data": { "text/plain": [ "{0: '55c2880c-7075-4b9e-9d09-8b5f471adfe7'}" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "db.index_to_docstore_id" ] }, { "cell_type": "markdown", "id": "f3afb359-6aff-400c-bad4-350cc1827b7b", "metadata": {}, "source": [ "### 위의 임베딩 정보를 가지고 Question & Answer 를 함." ] }, { "cell_type": "code", "execution_count": 35, "id": "4d605679-4a04-48f1-a260-6d9900bc335e", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " You are never going to write data similar to remix forms in the new app directory.\n" ] } ], "source": [ "from langchain.chains import RetrievalQA\n", "\n", "retriever = db.as_retriever()\n", "\n", "qa = RetrievalQA.from_chain_type(\n", " llm=llm, \n", " chain_type=\"stuff\", \n", " retriever=retriever, \n", " return_source_documents=True)\n", "\n", "query = \"What am I never going to do?\"\n", "result = qa({\"query\": query})\n", "\n", "print(result['result'])" ] }, { "cell_type": "markdown", "id": "665e39a2-ee5e-4af1-b4c7-c6ad7b920dd5", "metadata": {}, "source": [ "# Memory: Remembering previous conversations" ] }, { "cell_type": "code", "execution_count": 39, "id": "523e2596-c221-4a5d-8e06-14fc51bf8290", "metadata": { "tags": [] }, "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;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", "\n", "Current conversation:\n", "\n", "Human: Alice has a parrot.\n", "AI:\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n", "\n", "\n", "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", "Prompt after formatting:\n", "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", "\n", "Current conversation:\n", "Human: Alice has a parrot.\n", "AI: That's interesting. What kind of parrot does Alice have?\n", "Human: Bob has two cats.\n", "AI:\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n", "\n", "\n", "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", "Prompt after formatting:\n", "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", "\n", "Current conversation:\n", "Human: Alice has a parrot.\n", "AI: That's interesting. What kind of parrot does Alice have?\n", "Human: Bob has two cats.\n", "AI: Interesting. What breed of cats does Bob have?\n", "Human: How many pets do Alice and Bob have?\n", "AI:\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n" ] }, { "data": { "text/plain": [ "' It looks like Alice has one pet, a parrot, and Bob has two pets, two cats.'" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain import ConversationChain\n", "\n", "conversation = ConversationChain(llm=llm, verbose=True)\n", "\n", "conversation.predict(input=\"Alice has a parrot.\")\n", "\n", "conversation.predict(input=\"Bob has two cats.\")\n", "\n", "conversation.predict(input=\"How many pets do Alice and Bob have?\")" ] }, { "cell_type": "markdown", "id": "b9de8428-711a-4d05-93ad-e2d9b6dc7fdc", "metadata": {}, "source": [ "# Agents: Accessing other tools" ] }, { "cell_type": "code", "execution_count": 43, "id": "c1bd3e7c-475c-436f-9f05-1a31b8dcde9d", "metadata": { "tags": [] }, "outputs": [], "source": [ "# ! pip install wikipedia --quiet" ] }, { "cell_type": "code", "execution_count": 44, "id": "9cb24108-909c-47e8-8f45-f59aabb91fb4", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", "\u001b[32;1m\u001b[1;3m I should look up information about Barack Obama.\n", "Action: Wikipedia\n", "Action Input: Barack Obama\u001b[0m\n", "Observation: \u001b[36;1m\u001b[1;3mPage: Barack Obama\n", "Summary: Barack Hussein Obama II ( (listen) bə-RAHK hoo-SAYN oh-BAH-mə; born August 4, 1961) is an American politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African-American president of the United States. Obama previously served as a U.S. senator representing Illinois from 2005 to 2008 and as an Illinois state senator from 1997 to 2004, and worked as a civil rights lawyer before holding public office. \n", "Obama was born in Honolulu, Hawaii. After graduating from Columbia University in 1983, he worked as a community organizer in Chicago. In 1988, he enrolled in Harvard Law School, where he was the first black president of the Harvard Law Review. After graduating, he became a civil rights attorney and an academic, teaching constitutional law at the University of Chicago Law School from 1992 to 2004. Turning to elective politics, he represented the 13th district in the Illinois Senate from 1997 until 2004, when he ran for the U.S. Senate. Obama received national attention in 2004 with his March Senate primary win, his well-received keynote address at the July Democratic National Convention, and his landslide November election to the Senate. In 2008, after a close primary campaign against Hillary Clinton, he was nominated by the Democratic Party for president and chose Joe Biden as his running mate. Obama was elected over Republican nominee John McCain in the presidential election and was inaugurated on January 20, 2009. Nine months later, he was named the 2009 Nobel Peace Prize laureate, a decision that drew a mixture of praise and criticism.\n", "Obama's first-term actions addressed the global financial crisis and included a major stimulus package, a partial extension of George W. Bush's tax cuts, legislation to reform health care, a major financial regulation reform bill, and the end of a major US military presence in Iraq. Obama also appointed Supreme Court justices Sonia Sotomayor and Elena Kagan, the former being the first Hispanic American on the Supreme Court. He ordered the counterterrorism raid which killed Osama bin Laden and downplayed Bush's counterinsurgency model, expanding air strikes and making extensive use of special forces while encouraging greater reliance on host-government militaries.\n", "After winning re-election by defeating Republican opponent Mitt Romney, Obama was sworn in for a second term on January 20, 2013. In his second term, Obama took steps to combat climate change, signing a major international climate agreement and an executive order to limit carbon emissions. Obama also presided over the implementation of the Affordable Care Act and other legislation passed in his first term, and he negotiated a nuclear agreement with Iran and normalized relations with Cuba. The number of American soldiers in Afghanistan fell dramatically during Obama's second term, though U.S. soldiers remained in Afghanistan throughout Obama's presidency.\n", "During Obama's terms as president, the United States' reputation abroad and the American economy improved significantly, although the country experienced high levels of partisan divide. Obama left office on January 20, 2017, and continues to reside in Washington, D.C. His presidential library in Chicago began construction in 2021. Since leaving office, Obama has remained active in Democratic politics, including campaigning for candidates in various American elections. Outside of politics, Obama has published three bestselling books: Dreams from My Father (1995), The Audacity of Hope (2006) and A Promised Land (2020). Rankings by scholars and historians, in which he has been featured since 2010, place him in the middle to upper tier of American presidents.\n", "\n", "Page: Family of Barack Obama\n", "Summary: The family of Barack Obama, the 44th president of the United States, is a prominent American family active in law, education, activism and politics. Obama's immediate family circle was the first family of the United States from 2009 to 2017, and are the first such family of African-American descent. His immediate family includes his wife Michelle Obama and daughters Malia and Sasha Obama.\n", "Obama's wider ancestry is made up of people of Kenyan (Luo), African-American, and Old Stock American (including originally English, Scots-Irish, Welsh, German, and Swiss) ancestry.\n", "\n", "\n", "\n", "Page: Barack Obama Sr.\n", "Summary: Barack Hussein Obama Sr. (; born Baraka Obama, 18 June 1934 – 24 November 1982) was a Kenyan senior governmental economist and the father of Barack Obama, the 44th president of the United States. He is a central figure of his son's memoir, Dreams from My Father (1995). Obama married in 1954 and had two children with his first wife, Kezia. He was selected for a special program to attend college in the United States and studied at the University of Hawaii where he met Stanley Ann Dunham, whom he married in 1961 following the conception of his son, Barack II. Dunham divorced Obama three years later. The elder Obama later went to Harvard University for graduate school, where he earned an M.A. in economics, and returned to Kenya in 1964. He saw his son Barack once more, when his son was about 10.\n", "In late 1964, Obama Sr. married Ruth Beatrice Baker, a Jewish-American woman he had met in Massachusetts. They had two sons together before separating in 1971 and divorcing in 1973. Obama first worked for an oil company, before beginning work as an economist with the Kenyan Ministry of Transport. He gained a promotion to senior economic analyst in the Ministry of Finance. He was among a cadre of young Kenyan men who had been educated in the West in a program supported by Tom Mboya. Obama Sr. had conflicts with Kenyan president Jomo Kenyatta, which adversely affected his career. He was fired and blacklisted in Kenya, finding it nearly impossible to get a job. Obama Sr. was involved in three serious car accidents during his final years; he died as a result of the last one in 1982.\n", "\n", "\u001b[0m\n", "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n", "Final Answer: Barack Obama was born on August 4, 1961, and was 61 years old in 2022.\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n" ] }, { "data": { "text/plain": [ "'Barack Obama was born on August 4, 1961, and was 61 years old in 2022.'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.agents import load_tools\n", "from langchain.agents import initialize_agent\n", "from langchain.agents import AgentType\n", "\n", "tools = load_tools([\"wikipedia\", \"llm-math\"], llm=llm)\n", "agent = initialize_agent(tools, \n", " llm, \n", " agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, \n", " verbose=True)\n", "\n", "\n", "agent.run(\"When was Barack Obama born? How old was he in 2022?\")" ] }, { "cell_type": "code", "execution_count": null, "id": "382c9344-3ac5-42f5-942f-2501fcd48bd4", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "availableInstances": [ { "_defaultOrder": 0, "_isFastLaunch": true, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 4, "name": "ml.t3.medium", "vcpuNum": 2 }, { "_defaultOrder": 1, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 8, "name": "ml.t3.large", "vcpuNum": 2 }, { "_defaultOrder": 2, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.t3.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 3, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.t3.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 4, "_isFastLaunch": true, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 8, "name": "ml.m5.large", "vcpuNum": 2 }, { "_defaultOrder": 5, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.m5.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 6, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.m5.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 7, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 64, "name": "ml.m5.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 8, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 128, "name": "ml.m5.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 9, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 192, "name": "ml.m5.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 10, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 256, "name": "ml.m5.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 11, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 384, "name": "ml.m5.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 12, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 8, "name": "ml.m5d.large", "vcpuNum": 2 }, { "_defaultOrder": 13, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.m5d.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 14, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.m5d.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 15, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 64, "name": "ml.m5d.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 16, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 128, "name": "ml.m5d.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 17, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 192, "name": "ml.m5d.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 18, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 256, "name": "ml.m5d.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 19, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 384, "name": "ml.m5d.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 20, "_isFastLaunch": false, "category": "General purpose", "gpuNum": 0, "hideHardwareSpecs": true, "memoryGiB": 0, "name": "ml.geospatial.interactive", "supportedImageNames": [ "sagemaker-geospatial-v1-0" ], "vcpuNum": 0 }, { "_defaultOrder": 21, "_isFastLaunch": true, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 4, "name": "ml.c5.large", "vcpuNum": 2 }, { "_defaultOrder": 22, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 8, "name": "ml.c5.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 23, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.c5.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 24, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.c5.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 25, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 72, "name": "ml.c5.9xlarge", "vcpuNum": 36 }, { "_defaultOrder": 26, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 96, "name": "ml.c5.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 27, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 144, "name": "ml.c5.18xlarge", "vcpuNum": 72 }, { "_defaultOrder": 28, "_isFastLaunch": false, "category": "Compute optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 192, "name": "ml.c5.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 29, "_isFastLaunch": true, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.g4dn.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 30, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.g4dn.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 31, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 64, "name": "ml.g4dn.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 32, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 128, "name": "ml.g4dn.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 33, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 4, "hideHardwareSpecs": false, "memoryGiB": 192, "name": "ml.g4dn.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 34, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 256, "name": "ml.g4dn.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 35, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 61, "name": "ml.p3.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 36, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 4, "hideHardwareSpecs": false, "memoryGiB": 244, "name": "ml.p3.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 37, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 8, "hideHardwareSpecs": false, "memoryGiB": 488, "name": "ml.p3.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 38, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 8, "hideHardwareSpecs": false, "memoryGiB": 768, "name": "ml.p3dn.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 39, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.r5.large", "vcpuNum": 2 }, { "_defaultOrder": 40, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.r5.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 41, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 64, "name": "ml.r5.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 42, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 128, "name": "ml.r5.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 43, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 256, "name": "ml.r5.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 44, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 384, "name": "ml.r5.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 45, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 512, "name": "ml.r5.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 46, "_isFastLaunch": false, "category": "Memory Optimized", "gpuNum": 0, "hideHardwareSpecs": false, "memoryGiB": 768, "name": "ml.r5.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 47, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 16, "name": "ml.g5.xlarge", "vcpuNum": 4 }, { "_defaultOrder": 48, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 32, "name": "ml.g5.2xlarge", "vcpuNum": 8 }, { "_defaultOrder": 49, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 64, "name": "ml.g5.4xlarge", "vcpuNum": 16 }, { "_defaultOrder": 50, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 128, "name": "ml.g5.8xlarge", "vcpuNum": 32 }, { "_defaultOrder": 51, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 1, "hideHardwareSpecs": false, "memoryGiB": 256, "name": "ml.g5.16xlarge", "vcpuNum": 64 }, { "_defaultOrder": 52, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 4, "hideHardwareSpecs": false, "memoryGiB": 192, "name": "ml.g5.12xlarge", "vcpuNum": 48 }, { "_defaultOrder": 53, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 4, "hideHardwareSpecs": false, "memoryGiB": 384, "name": "ml.g5.24xlarge", "vcpuNum": 96 }, { "_defaultOrder": 54, "_isFastLaunch": false, "category": "Accelerated computing", "gpuNum": 8, "hideHardwareSpecs": false, "memoryGiB": 768, "name": "ml.g5.48xlarge", "vcpuNum": 192 } ], "instance_type": "ml.m5.large", "kernelspec": { "display_name": "Python 3 (PyTorch 1.13 Python 3.9 CPU Optimized)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/pytorch-1.13-cpu-py39" }, "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.9.16" } }, "nbformat": 4, "nbformat_minor": 5 }