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95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
{
 "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
}