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38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
{
 "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-HBcNcxp8X8oAKhSGT3BlbkFJ9sHkCuOITYjONfcc0Y3p\""
   ]
  },
  {
   "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
}