{ "cells": [ { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "from langchain.llms import OpenAI\n" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"OPEN_API_KEY\"]=\"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\"" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "llm=OpenAI(openai_api_key=os.environ[\"OPEN_API_KEY\"],temperature=.5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 59, "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", "print(llm.predict(text))" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "os.environ[\"HUGGINGFACEHUB_API_TOKEN\"]=\"\"" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "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": 62, "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": 63, "metadata": {}, "outputs": [], "source": [ "### Prompt Templates And LLM Chain\n" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Tell me the capital of this India'" ] }, "execution_count": 64, "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": 65, "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": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "### Combining Multiple Chains Using Simple Sequential Chains" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "capital_prompt=PromptTemplate(input_variables=['country'],\n", " template=\"Please tellme the capital of the {country}\")\n", "\n", "capital_chain=LLMChain(llm=llm,prompt=capital_prompt)\n", "\n", "famous_template=PromptTemplate(input_variables=['capital'],\n", " template=\"Suggest to me some amazing places to visit in {capital}\")\n", "\n", "famous_chain=LLMChain(llm=llm,prompt=famous_template)\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Some amazing places to visit in Washington, D.C. include:\n", "\n", "1. The National Mall - This iconic stretch of green space is home to some of the most famous monuments and memorials, including the Lincoln Memorial, Washington Monument, and Vietnam Veterans Memorial.\n", "\n", "2. Smithsonian Museums - The Smithsonian Institution is made up of 19 museums and galleries, all of which are free to visit. Some must-see museums include the National Air and Space Museum, National Museum of Natural History, and National Museum of African American History and Culture.\n", "\n", "3. The White House - Take a tour of the official residence and workplace of the President of the United States. You can also visit the White House Visitor Center to learn more about its history and significance.\n", "\n", "4. Georgetown - This historic neighborhood is a charming mix of cobblestone streets, upscale shops and restaurants, and beautiful architecture. It's also home to Georgetown University and the famous Exorcist stairs.\n", "\n", "5. Arlington National Cemetery - Pay your respects to fallen soldiers at this somber and beautiful cemetery, which is also the final resting place of President John F. Kennedy and his family.\n", "\n", "6. National Zoo - Part of the Smithsonian Institution, the National Zoo is home to over 2,000 animals, including giant pandas, lions,\n" ] } ], "source": [ "from langchain.chains import SimpleSequentialChain\n", "chain=SimpleSequentialChain(chains=[capital_chain,famous_chain])\n", "print(chain.run(\"United States\"))" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "### Sequential Chain" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [], "source": [ "capital_prompt=PromptTemplate(input_variables=['country'],\n", " template=\"Please tellme the capital of the {country}\")\n", "\n", "capital_chain=LLMChain(llm=llm,prompt=capital_prompt,output_key=\"capital\")\n", "\n", "famous_template=PromptTemplate(input_variables=['capital'],\n", " template=\"Suggest to 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": 71, "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": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'country': 'India',\n", " 'capital': '\\n\\nThe capital of India is New Delhi.',\n", " 'places': \" It is a bustling metropolis with a rich history and culture. Some amazing places to visit in Delhi are:\\n\\n1. Red Fort: This iconic monument was built in the 17th century and served as the residence of the Mughal emperors. It is a UNESCO World Heritage Site and a must-visit for its stunning architecture and historical significance.\\n\\n2. India Gate: This war memorial is a popular spot for locals and tourists alike. It was built to honor the soldiers who lost their lives in World War I and the Third Anglo-Afghan War. The lush green lawns and the surrounding area make it a perfect spot for a picnic or a leisurely stroll.\\n\\n3. Qutub Minar: Another UNESCO World Heritage Site, the Qutub Minar is the tallest minaret in India. It was built in the 12th century and is a fine example of Indo-Islamic architecture. The complex also houses other historical structures and a lush garden.\\n\\n4. Lotus Temple: This beautiful temple is a symbol of unity and peace. Its unique lotus-shaped architecture and serene atmosphere make it a popular spot for meditation and reflection.\\n\\n5. Humayun's Tomb: This stunning mausoleum was built in the 16th century and is\"}" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chain({'country':\"India\"})" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "### Chatmodels WIth ChatOpenAI" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [], "source": [ "from langchain.chat_models import ChatOpenAI\n", "from langchain.schema import HumanMessage,SystemMessage,AIMessage" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "content=\"In California, regulatory reporting related to ESG (Environmental, Social, Governance) factors can vary depending on the industry and the specific regulations in place. However, there are some key reporting requirements that companies may need to adhere to:\\n\\n1. **California Transparency in Supply Chains Act (CTSCA)**: This law requires certain companies to disclose their efforts to eradicate slavery and human trafficking from their direct supply chains. Covered companies must disclose their efforts to verify and audit their supply chains, as well as their training programs for employees and management on human trafficking and slavery.\\n\\n2. **California Greenhouse Gas (GHG) Reporting Program**: California has its own GHG reporting program that requires facilities that emit over a certain threshold of greenhouse gases to report their emissions annually. This program is part of the state's efforts to reduce GHG emissions and combat climate change.\\n\\n3. **California Environmental Reporting System (CERS)**: Certain businesses in California are required to report their hazardous materials inventory and business activities that generate hazardous waste to the CERS database. This reporting helps regulators and emergency responders track and manage hazardous materials in the state.\\n\\n4. **California Sustainable Groundwater Management Act (SGMA)**: Under SGMA, local agencies in California are required to develop and implement sustainable groundwater management plans to ensure the long-term viability of groundwater resources. Reporting requirements may include monitoring groundwater levels, water quality, and implementation of sustainable management practices.\\n\\n5. **California Corporate Disclosure Act**: This proposed legislation would require publicly traded companies headquartered in California to disclose information related to their ESG practices, including greenhouse gas emissions, workforce diversity, and board diversity. While this bill has not been enacted as of my last update, it indicates a growing trend towards increased ESG reporting requirements in the state.\\n\\nIt's important for companies operating in California to stay informed about the latest regulatory requirements related to ESG reporting to ensure compliance and transparency in their operations.\" response_metadata={'token_usage': {'completion_tokens': 383, 'prompt_tokens': 34, 'total_tokens': 417}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None} id='run-1644211e-9ced-421a-9a12-46c6c1005ef7-0'\n" ] } ], "source": [ "from langchain.chat_models import ChatOpenAI\n", "from langchain.schema import HumanMessage,SystemMessage,AIMessage\n", "\n", "chatllm=ChatOpenAI(openai_api_key=os.environ[\"OPEN_API_KEY\"],temperature=.5,model='gpt-3.5-turbo')\n", "\n", "print(chatllm([\n", " SystemMessage(content=\"You are an expert in ESG (Environmental, Social, Governance) factual knowledge\"), \n", " HumanMessage(content=\"Please explain the regulatory reporting in California\") \n", "]))" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [], "source": [ "### Prompt Template + LLM + Output Parsers" ] }, { "cell_type": "code", "execution_count": 77, "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": 81, "metadata": {}, "outputs": [], "source": [ "class CommaSeperatedOutput(BaseOutputParser):\n", " def parse(self,text:str):\n", " return text.strip().split(\",\")\n", "\n" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [], "source": [ "template=\"You are a helpful assistant. When the user given any input, you should generate five synomonous words in a comma seperated list\"\n", "human_template=\"{text}\"\n", "chatprompt=ChatPromptTemplate.from_messages([\n", " (\"system\",template),\n", " (\"human\",human_template)\n", "])" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [], "source": [ "chain=chatprompt|chatllm|CommaSeperatedOutput()" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['smart', ' clever', ' bright', ' astute', ' sharp']" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chain.invoke({\"text\":\"intelligent\"})" ] } ], "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.12.4" } }, "nbformat": 4, "nbformat_minor": 2 }