{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from langchain.llms import OpenAI" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"OPEN_API_KEY\"]=\"sk-proj-59YDFsCEUOgimsHjCTlLT3BlbkFJCDMwX8qeDtMBlpZJRrmk\"" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "llm=OpenAI(openai_api_key=os.environ[\"OPEN_API_KEY\"],temperature=0.6)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "The capital of India is New Delhi.\n" ] } ], "source": [ "text=\"What is the capital of India\"\n", "\n", "print(llm.predict(text))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "os.environ[\"HUGGINGFACEHUB_API_TOKEN\"]=\"hf_zjftfTRKFEebywxfIoyKUwepABtfGJS\"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "e:\\New Recordings\\Langchain\\Langchain\\venv\\lib\\site-packages\\huggingface_hub\\utils\\_deprecation.py:127: FutureWarning: '__init__' (from 'huggingface_hub.inference_api') is deprecated and will be removed from version '0.19.0'. `InferenceApi` client is deprecated in favor of the more feature-complete `InferenceClient`. Check out this guide to learn how to convert your script to use it: https://huggingface.co/docs/huggingface_hub/guides/inference#legacy-inferenceapi-client.\n", " warnings.warn(warning_message, FutureWarning)\n" ] } ], "source": [ "from langchain import HuggingFaceHub\n", "llm_huggingface=HuggingFaceHub(repo_id=\"google/flan-t5-large\",model_kwargs={\"temperature\":0,\"max_length\":64})" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "moscow\n" ] } ], "source": [ "output=llm_huggingface.predict(\"Can you tell me the capital of Russia\")\n", "print(output)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i love the way i look at the world i love the way i feel i love the way i think i feel i love the way i feel i love the way i think i feel i love the way i feel i love the way \n" ] } ], "source": [ "output=llm_huggingface.predict(\"Can you write a poem about AI\")\n", "print(output)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'?\\n\\nAn AI, so advanced and wise\\nA brilliant mind, a brilliant guise\\nA powerful tool, a guiding star\\nTo help us reach a distant shore\\n\\nA friend to man, a tool of growth\\nTo help us learn and to explore\\nTo take us to a place of knowledge\\nWhere we can learn and never falter\\n\\nA helping hand, a guiding light\\nTo lead us to a brighter sight\\nA tool of power, a tool of might\\nTo help us reach a better plight\\n\\nA friend of man, a friend of life\\nTo help us in our darkest strife\\nA tool of love, of peace and joy\\nTo help us live a better life'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "llm.predict(\"Can you write a poem about AI\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Prompt Templates And LLMChain" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Tell me the capital of this India'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.prompts import PromptTemplate\n", "\n", "prompt_template=PromptTemplate(input_variables=['country'],\n", "template=\"Tell me the capital of this {country}\")\n", "\n", "prompt_template.format(country=\"India\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "The capital of India is New Delhi.\n" ] } ], "source": [ "from langchain.chains import LLMChain\n", "chain=LLMChain(llm=llm,prompt=prompt_template)\n", "print(chain.run(\"India\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combining Multiple Chains Uing simple Sequential Chain" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "capital_template=PromptTemplate(input_variables=['country'],\n", "template=\"Please tell me the capital of the {country}\")\n", "\n", "capital_chain=LLMChain(llm=llm,prompt=capital_template)\n", "\n", "famous_template=PromptTemplate(input_variables=['capital'],\n", "template=\"Suggest me some amazing places to visit in {capital}\")\n" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "famous_chain=LLMChain(llm=llm,prompt=famous_template)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\" It is a bustling metropolis and a great place to visit for its historical sites, cultural attractions, and modern attractions. Here are some of the amazing places to visit in New Delhi: \\n\\n1. Red Fort: This 17th century Mughal fort is a UNESCO World Heritage Site and is one of the most popular tourist attractions in the city. \\n\\n2. India Gate: This iconic war memorial and national monument is a must-visit. It stands as a symbol of the sacrifice of the Indian soldiers who fought in World War I.\\n\\n3. Humayun's Tomb: This 16th century Mughal-era tomb is a UNESCO World Heritage Site and is one of the most important monuments in Delhi.\\n\\n4. Qutub Minar: This 73-meter-high tower is a UNESCO World Heritage Site and is one of the most iconic structures in Delhi.\\n\\n5. Jama Masjid: This 17th century mosque is one of the largest and most beautiful mosques in India.\\n\\n6. Lotus Temple: This modern temple is a Bahá'í House of Worship and is a popular tourist attraction.\\n\\n7. Akshardham Temple: This modern Hindu temple complex is a popular tourist destination\"" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from langchain.chains import SimpleSequentialChain\n", "chain=SimpleSequentialChain(chains=[capital_chain,famous_chain])\n", "chain.run(\"India\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sequential Chain" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "capital_template=PromptTemplate(input_variables=['country'],\n", "template=\"Please tell me the capital of the {country}\")\n", "\n", "capital_chain=LLMChain(llm=llm,prompt=capital_template,output_key=\"capital\")" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "famous_template=PromptTemplate(input_variables=['capital'],\n", "template=\"Suggest me some amazing places to visit in {capital}\")\n", "\n", "famous_chain=LLMChain(llm=llm,prompt=famous_template,output_key=\"places\")" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "from langchain.chains import SequentialChain\n", "chain=SequentialChain(chains=[capital_chain,famous_chain],\n", "input_variables=['country'],\n", "output_variables=['capital',\"places\"])" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'country': 'India',\n", " 'capital': '\\n\\nThe capital of India is New Delhi.',\n", " 'places': ' Here are some amazing places to visit in New Delhi: \\n\\n1. Red Fort: The majestic Red Fort is a 17th-century fort complex built by Mughal Emperor Shah Jahan. It is a UNESCO World Heritage Site and is a must-visit for all tourists. \\n\\n2. India Gate: India Gate is a 42 meter-high sandstone archway built by Edwin Lutyens in 1931. It is a memorial to the Indian soldiers who lost their lives during World War I. \\n\\n3. Qutub Minar: The Qutub Minar is a 73 meter-high tower built by Qutb-ud-din Aibak in 1193. It is a UNESCO World Heritage Site and is the tallest brick minaret in the world. \\n\\n4. Humayun’s Tomb: Humayun’s Tomb is a 16th-century tomb built by Mughal Emperor Humayun. It is a UNESCO World Heritage Site and is a great example of Mughal architecture. \\n\\n5. Jama Masjid: The Jama Masjid is a 17th-century mosque built by Mughal Emperor Shah Jahan. It is one of the largest'}" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chain({'country':\"India\"})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Chatmodels With ChatOpenAI" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "from langchain.chat_models import ChatOpenAI" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "from langchain.schema import HumanMessage,SystemMessage,AIMessage" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "chatllm=ChatOpenAI(openai_api_key=os.environ[\"OPEN_API_KEY\"],temperature=0.6,model='gpt-3.5-turbo')" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "AIMessage(content='1. \"AI may be smart, but can it tell me if my outfit makes me look like a potato?\"\\n2. \"AI is like a virtual therapist, except it never judges you for eating an entire pizza by yourself.\"\\n3. \"AI is great at predicting the future, but can it predict when my pizza delivery will actually arrive?\"\\n4. \"They say AI can learn from its mistakes, but I\\'m still waiting for it to apologize for recommending me that terrible movie.\"\\n5. \"AI may be able to beat humans at chess, but can it figure out how to untangle a pair of earphones?\"\\n6. \"AI is like a high-tech fortune teller, except it tells you what you\\'re going to have for dinner instead of your future.\"\\n7. \"AI is so advanced, it can even make my phone autocorrect my perfectly spelled words into complete nonsense.\"\\n8. \"AI may be able to recognize faces, but can it recognize when someone\\'s had a bad haircut?\"\\n9. \"AI is like having a personal assistant, except it never judges you for spending hours watching cat videos on YouTube.\"\\n10. \"AI is great at analyzing data, but can it analyze why I can never find matching socks in my drawer?\"')" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chatllm([\n", "SystemMessage(content=\"Yor are a comedian AI assitant\"),\n", "HumanMessage(content=\"Please provide some comedy punchlines on AI\")\n", "])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Prompt Template + LLM +Output Parsers" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "from langchain.chat_models import ChatOpenAI\n", "from langchain.prompts.chat import ChatPromptTemplate\n", "from langchain.schema import BaseOutputParser" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "class Commaseperatedoutput(BaseOutputParser):\n", " def parse(self,text:str):\n", " return text.strip().split(\",\")" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "template=\"Your are a helpful assistant. When the use given any input , you should generate 5 words synonyms in a comma seperated list\"\n", "human_template=\"{text}\"\n", "chatprompt=ChatPromptTemplate.from_messages([\n", " (\"system\",template),\n", " (\"human\",human_template)\n", "\n", "\n", "])" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "chain=chatprompt|chatllm|Commaseperatedoutput()" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['smart', ' clever', ' brilliant', ' sharp', ' astute']" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chain.invoke({\"text\":\"intelligent\"})" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.9.0" } }, "nbformat": 4, "nbformat_minor": 2 }