examples

Форк
0
/
11-langchain-expression-language.ipynb 
727 строк · 24.9 Кб
1
{
2
 "cells": [
3
  {
4
   "cell_type": "markdown",
5
   "metadata": {},
6
   "source": [
7
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pinecone-io/examples/blob/master/learn/generation/langchain/handbook/11-langchain-expression-language.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/pinecone-io/examples/blob/master/learn/generation/langchain/handbook/11-langchain-expression-language.ipynb)"
8
   ]
9
  },
10
  {
11
   "cell_type": "markdown",
12
   "metadata": {},
13
   "source": [
14
    "#### [LangChain Handbook](https://pinecone.io/learn/langchain)\n",
15
    "\n",
16
    "# LangChain Expression Language (LCEL)"
17
   ]
18
  },
19
  {
20
   "cell_type": "markdown",
21
   "metadata": {},
22
   "source": [
23
    "The **L**ang**C**hain **E**xpression **L**anguage (LCEL) is a abstraction of some interesting Python concepts into a format that enables a \"minimalist\" code layer for building chains of LangChain components.\n",
24
    "\n",
25
    "LCEL comes with strong support for:\n",
26
    "\n",
27
    "1. Superfast development of chains.\n",
28
    "2. Advanced features such as streaming, async, parallel execution, and more.\n",
29
    "3. Easy integration with LangSmith and LangServe."
30
   ]
31
  },
32
  {
33
   "cell_type": "code",
34
   "execution_count": null,
35
   "metadata": {},
36
   "outputs": [],
37
   "source": [
38
    "!pip install -qU \\\n",
39
    "    langchain==0.0.345 \\\n",
40
    "    anthropic==0.7.7 \\\n",
41
    "    cohere==4.37 \\\n",
42
    "    docarray==0.39.1"
43
   ]
44
  },
45
  {
46
   "cell_type": "markdown",
47
   "metadata": {},
48
   "source": [
49
    "## LCEL Syntax"
50
   ]
51
  },
52
  {
53
   "cell_type": "markdown",
54
   "metadata": {},
55
   "source": [
56
    "To understand LCEL syntax let's first build a simple chain in typical Python syntax."
57
   ]
58
  },
59
  {
60
   "cell_type": "code",
61
   "execution_count": 1,
62
   "metadata": {},
63
   "outputs": [],
64
   "source": [
65
    "from langchain.chat_models import ChatAnthropic\n",
66
    "from langchain.prompts import ChatPromptTemplate\n",
67
    "from langchain.schema.output_parser import StrOutputParser\n",
68
    "\n",
69
    "ANTHROPIC_API_KEY = \"<<YOUR_ANTHROPIC_API_KEY>>\"\n",
70
    "\n",
71
    "if ANTHROPIC_API_KEY == \"<<YOUR_ANTHROPIC_API_KEY>>\":\n",
72
    "    raise ValueError(\"Please set your ANTHROPIC_API_KEY\")\n",
73
    "\n",
74
    "prompt = ChatPromptTemplate.from_template(\n",
75
    "    \"Give me small report about {topic}\"\n",
76
    ")\n",
77
    "model = ChatAnthropic(\n",
78
    "    model=\"claude-2.1\",\n",
79
    "    max_tokens_to_sample=512,\n",
80
    "    anthropic_api_key=ANTHROPIC_API_KEY\n",
81
    ")  # swap Anthropic for OpenAI with `ChatOpenAI` and `openai_api_key`\n",
82
    "output_parser = StrOutputParser()"
83
   ]
84
  },
85
  {
86
   "cell_type": "markdown",
87
   "metadata": {},
88
   "source": [
89
    "In typical LangChain we would chain these together using an `LLMChain`:"
90
   ]
91
  },
92
  {
93
   "cell_type": "code",
94
   "execution_count": 2,
95
   "metadata": {},
96
   "outputs": [
97
    {
98
     "name": "stdout",
99
     "output_type": "stream",
100
     "text": [
101
      " Here is a brief report on some key aspects of artificial intelligence (AI):\n",
102
      "\n",
103
      "Introduction\n",
104
      "- AI refers to computer systems that are designed to perform tasks that would otherwise require human intelligence, such as visual perception, speech recognition, decision-making, and language translation. \n",
105
      "\n",
106
      "Major AI Techniques\n",
107
      "- Machine learning uses statistical techniques and neural networks to enable systems to improve at tasks with experience. Common techniques include deep learning, reinforcement learning, and supervised learning.\n",
108
      "- Computer vision focuses on extracting information from digital images and videos. It powers facial recognition, self-driving vehicles, and other visual AI tasks.\n",
109
      "- Natural language processing enables computers to understand, interpret, and generate human languages. Key applications include machine translation, search engines, and voice assistants like Siri.\n",
110
      "\n",
111
      "Current Capabilities\n",
112
      "- AI programs have matched or exceeded human capabilities in narrow or well-defined tasks like playing chess and Go, identifying objects in images, and transcribing speech. \n",
113
      "- However, general intelligence comparable to humans across different areas remains an unsolved challenge, often referred to as artificial general intelligence (AGI).\n",
114
      "\n",
115
      "Future Directions\n",
116
      "- Ongoing AI research is focused on developing stronger machine learning techniques, achievingexplainability and transparency in AI decision-making, and addressing potential ethical issues like bias.\n",
117
      "- If achieved, AGI could have significant societal and economic impacts, potentially enhancing and automating intellectual work. However safety, control and alignment with human values remain active research priorities.\n",
118
      "\n",
119
      "I hope this brief overview of some major aspects of the current state of AI technology and research provides useful context and information. Let me know if you would like me to elaborate on or clarify anything further.\n"
120
     ]
121
    }
122
   ],
123
   "source": [
124
    "from langchain.chains import LLMChain\n",
125
    "\n",
126
    "chain = LLMChain(\n",
127
    "    prompt=prompt,\n",
128
    "    llm=model,\n",
129
    "    output_parser=output_parser\n",
130
    ")\n",
131
    "\n",
132
    "# and run\n",
133
    "out = chain.run(topic=\"Artificial Intelligence\")\n",
134
    "print(out)"
135
   ]
136
  },
137
  {
138
   "cell_type": "markdown",
139
   "metadata": {},
140
   "source": [
141
    "Using LCEL the format is different, rather than relying on `Chains` we simple chain together each component using the pipe operator `|`:"
142
   ]
143
  },
144
  {
145
   "cell_type": "code",
146
   "execution_count": 3,
147
   "metadata": {},
148
   "outputs": [
149
    {
150
     "name": "stdout",
151
     "output_type": "stream",
152
     "text": [
153
      " Here is a brief report on artificial intelligence:\n",
154
      "\n",
155
      "Artificial intelligence (AI) refers to computer systems that can perform human-like cognitive functions such as learning, reasoning, and self-correction. AI has advanced significantly in recent years due to increases in computing power and the availability of large datasets and open source machine learning libraries.\n",
156
      "\n",
157
      "Some key highlights about the current state of AI:\n",
158
      "\n",
159
      "- Applications of AI - AI is being utilized in a wide variety of industries including finance, healthcare, transportation, criminal justice, and social media platforms. Use cases include personalized recommendations, predictive analytics, automated customer service agents, medical diagnosis, self-driving vehicles, and content moderation.\n",
160
      "\n",
161
      "- Machine Learning - The ability for AI systems to learn from data without explicit programming is driving much of the recent progress. Machine learning methods like deep learning neural networks have achieved new breakthroughs in areas like computer vision, speech recognition, and natural language processing. \n",
162
      "\n",
163
      "- Limitations - While AI has made great strides, current systems still have major limitations compared to human intelligence including lack of general world knowledge, difficulties dealing with novelty, bias issues from flawed datasets, and lack of skills for complex reasoning, empathy, creativity, etc. Ensuring the safety and controllability of AI systems remains an ongoing challenge.  \n",
164
      "\n",
165
      "- Future Outlook - Experts predict key areas for AI advancement to include gaining contextual understanding and reasoning skills, achieving more human-like communication abilities, algorithmic fairness and transparency, as well as advances in specialized fields like robotics, autonomous vehicles, and human-AI collaboration. Careful management of risks posed by more advanced AI systems remains crucial. Global competition for AI talent and computing resources continues to intensify.\n",
166
      "\n",
167
      "That covers some of the key trends, strengths and limitations, and future trajectories for artificial intelligence technology based on the current landscape. Please let me know if you would like me to elaborate on any part of this overview.\n"
168
     ]
169
    }
170
   ],
171
   "source": [
172
    "lcel_chain = prompt | model | output_parser\n",
173
    "\n",
174
    "# and run\n",
175
    "out = lcel_chain.invoke({\"topic\": \"Artificial Intelligence\"})\n",
176
    "print(out)"
177
   ]
178
  },
179
  {
180
   "cell_type": "markdown",
181
   "metadata": {},
182
   "source": [
183
    "Pretty cool, the way that this pipe operator is being used is that it is taking output from the function to the _left_ and feeding it into the function on the _right_."
184
   ]
185
  },
186
  {
187
   "cell_type": "markdown",
188
   "metadata": {},
189
   "source": [
190
    "## How the Pipe Operator Works"
191
   ]
192
  },
193
  {
194
   "cell_type": "markdown",
195
   "metadata": {},
196
   "source": [
197
    "To really understand LCEL we can take a look at how this pipe operation works. We know it takes output from the _right_ and feeds it to the _left_ — but this isn't typical Python, so how is this implemented? Let's try creating our own version of this with some simple functions.\n",
198
    "\n",
199
    "We will be using the `__or__` method within Python class objects. When we place two classes together like `chain = class_a | class_b` the Python interpreter will check if these classes contain this `__or__` method. If they do then our `|` code will be translated into `chain = class_a.__or__(class_b)`.\n",
200
    "\n",
201
    "That means both of these patterns will return the same thing:\n",
202
    "\n",
203
    "```python\n",
204
    "# object approach\n",
205
    "chain = class_a.__or__(class_b)\n",
206
    "chain(\"some input\")\n",
207
    "\n",
208
    "# pipe approach\n",
209
    "chain = class_a | class_b\n",
210
    "chain(\"some input\")\n",
211
    "\n",
212
    "```\n",
213
    "\n",
214
    "With that in mind, we can build a `Runnable` class that consumes a function and turns it into a function that can be chained with other functions using the pipe operator `|`."
215
   ]
216
  },
217
  {
218
   "cell_type": "code",
219
   "execution_count": 4,
220
   "metadata": {},
221
   "outputs": [],
222
   "source": [
223
    "class Runnable:\n",
224
    "    def __init__(self, func):\n",
225
    "        self.func = func\n",
226
    "\n",
227
    "    def __or__(self, other):\n",
228
    "        def chained_func(*args, **kwargs):\n",
229
    "            # the other func consumes the result of this func\n",
230
    "            return other(self.func(*args, **kwargs))\n",
231
    "        return Runnable(chained_func)\n",
232
    "\n",
233
    "    def __call__(self, *args, **kwargs):\n",
234
    "        return self.func(*args, **kwargs)"
235
   ]
236
  },
237
  {
238
   "cell_type": "markdown",
239
   "metadata": {},
240
   "source": [
241
    "Let's implement this to take the value `3`, add `5` (giving `8`), and multiply by `2` (giving `16`)."
242
   ]
243
  },
244
  {
245
   "cell_type": "code",
246
   "execution_count": 5,
247
   "metadata": {},
248
   "outputs": [
249
    {
250
     "data": {
251
      "text/plain": [
252
       "16"
253
      ]
254
     },
255
     "execution_count": 5,
256
     "metadata": {},
257
     "output_type": "execute_result"
258
    }
259
   ],
260
   "source": [
261
    "def add_five(x):\n",
262
    "    return x + 5\n",
263
    "\n",
264
    "def multiply_by_two(x):\n",
265
    "    return x * 2\n",
266
    "\n",
267
    "# wrap the functions with Runnable\n",
268
    "add_five = Runnable(add_five)\n",
269
    "multiply_by_two = Runnable(multiply_by_two)\n",
270
    "\n",
271
    "# run them using the object approach\n",
272
    "chain = add_five.__or__(multiply_by_two)\n",
273
    "chain(3)  # should return 16"
274
   ]
275
  },
276
  {
277
   "cell_type": "markdown",
278
   "metadata": {},
279
   "source": [
280
    "Using `__or__` directly we get the correct answer, now let's try using the pipe operator `|` to chain them together:"
281
   ]
282
  },
283
  {
284
   "cell_type": "code",
285
   "execution_count": 6,
286
   "metadata": {},
287
   "outputs": [
288
    {
289
     "data": {
290
      "text/plain": [
291
       "16"
292
      ]
293
     },
294
     "execution_count": 6,
295
     "metadata": {},
296
     "output_type": "execute_result"
297
    }
298
   ],
299
   "source": [
300
    "# chain the runnable functions together\n",
301
    "chain = add_five | multiply_by_two\n",
302
    "\n",
303
    "# invoke the chain\n",
304
    "chain(3)  # we should return 16"
305
   ]
306
  },
307
  {
308
   "cell_type": "markdown",
309
   "metadata": {},
310
   "source": [
311
    "Using either method we get the same response, at it's core this is what LCEL is doing, but there is more."
312
   ]
313
  },
314
  {
315
   "cell_type": "markdown",
316
   "metadata": {},
317
   "source": [
318
    "## LCEL Deep Dive"
319
   ]
320
  },
321
  {
322
   "cell_type": "markdown",
323
   "metadata": {},
324
   "source": [
325
    "Now that we understand what this syntax is doing under the hood, let's explore it within the context of LCEL and see a few of the additional methods that LangChain has provided to maximize flexibility when working with LCEL."
326
   ]
327
  },
328
  {
329
   "cell_type": "markdown",
330
   "metadata": {},
331
   "source": [
332
    "### Runnables"
333
   ]
334
  },
335
  {
336
   "cell_type": "markdown",
337
   "metadata": {},
338
   "source": [
339
    "When working with LCEL we may find that we need to modify the structure or values being passed between components — for this we can use _runnables_. Let's try:"
340
   ]
341
  },
342
  {
343
   "cell_type": "code",
344
   "execution_count": 9,
345
   "metadata": {},
346
   "outputs": [],
347
   "source": [
348
    "from langchain.embeddings import CohereEmbeddings\n",
349
    "from langchain.vectorstores import DocArrayInMemorySearch\n",
350
    "\n",
351
    "COHERE_API_KEY = \"<<COHERE_API_KEY>>\"\n",
352
    "if COHERE_API_KEY == \"<<COHERE_API_KEY>>\":\n",
353
    "    raise ValueError(\"Please set your COHERE_API_KEY\")\n",
354
    "\n",
355
    "embedding = CohereEmbeddings(\n",
356
    "    model=\"embed-english-light-v3.0\",\n",
357
    "    cohere_api_key=COHERE_API_KEY\n",
358
    ")\n",
359
    "\n",
360
    "vecstore_a = DocArrayInMemorySearch.from_texts(\n",
361
    "    [\"half the info will be here\", \"James' birthday is the 7th December\"],\n",
362
    "    embedding=embedding\n",
363
    ")\n",
364
    "vecstore_b = DocArrayInMemorySearch.from_texts(\n",
365
    "    [\"and half here\", \"James was born in 1994\"],\n",
366
    "    embedding=embedding\n",
367
    ")"
368
   ]
369
  },
370
  {
371
   "cell_type": "markdown",
372
   "metadata": {},
373
   "source": [
374
    "First let's try passing a question through to a single one of these `vecstore` objects:"
375
   ]
376
  },
377
  {
378
   "cell_type": "code",
379
   "execution_count": 17,
380
   "metadata": {},
381
   "outputs": [],
382
   "source": [
383
    "from langchain_core.runnables import (\n",
384
    "    RunnableParallel,\n",
385
    "    RunnablePassthrough\n",
386
    ")\n",
387
    "\n",
388
    "retriever_a = vecstore_a.as_retriever()\n",
389
    "retriever_b = vecstore_b.as_retriever()\n",
390
    "\n",
391
    "prompt_str = \"\"\"Answer the question below using the context:\n",
392
    "\n",
393
    "Context: {context}\n",
394
    "\n",
395
    "Question: {question}\n",
396
    "\n",
397
    "Answer: \"\"\"\n",
398
    "prompt = ChatPromptTemplate.from_template(prompt_str)\n",
399
    "\n",
400
    "retrieval = RunnableParallel(\n",
401
    "    {\"context\": retriever_a, \"question\": RunnablePassthrough()}\n",
402
    ")\n",
403
    "\n",
404
    "chain = retrieval | prompt | model | output_parser"
405
   ]
406
  },
407
  {
408
   "cell_type": "code",
409
   "execution_count": 16,
410
   "metadata": {},
411
   "outputs": [
412
    {
413
     "name": "stdout",
414
     "output_type": "stream",
415
     "text": [
416
      " Unfortunately I do not have enough context to definitively state when James was born. The only potentially relevant information is \"James' birthday is the 7th December\", but this does not specify the year he was born. To answer the question of when specifically James was born, I would need more details or context such as his current age or the year associated with his birthday.\n"
417
     ]
418
    }
419
   ],
420
   "source": [
421
    "out = chain.invoke(\"when was James born?\")\n",
422
    "print(out)"
423
   ]
424
  },
425
  {
426
   "cell_type": "markdown",
427
   "metadata": {},
428
   "source": [
429
    "Here we have used `RunnableParallel` to create two parallel streams of information, one for `\"context\"` that is information fed in from `retriever_a`, and another for `\"question\"` which is the _passthrough_ information, ie the information that is passed through from our `chain.invoke(\"when was James born?\")` call.\n",
430
    "\n",
431
    "Using this information the chain is close to answering the question but it doesn't have enough information, it is missing the information that we have stored in `retriever_b`. Fortunately, we can have multiple parallel information streams using the `RunnableParallel` object."
432
   ]
433
  },
434
  {
435
   "cell_type": "code",
436
   "execution_count": 18,
437
   "metadata": {},
438
   "outputs": [],
439
   "source": [
440
    "prompt_str = \"\"\"Answer the question below using the context:\n",
441
    "\n",
442
    "Context:\n",
443
    "{context_a}\n",
444
    "{context_b}\n",
445
    "\n",
446
    "Question: {question}\n",
447
    "\n",
448
    "Answer: \"\"\"\n",
449
    "prompt = ChatPromptTemplate.from_template(prompt_str)\n",
450
    "\n",
451
    "retrieval = RunnableParallel(\n",
452
    "    {\n",
453
    "        \"context_a\": retriever_a, \"context_b\": retriever_b,\n",
454
    "        \"question\": RunnablePassthrough()\n",
455
    "    }\n",
456
    ")\n",
457
    "\n",
458
    "chain = retrieval | prompt | model | output_parser"
459
   ]
460
  },
461
  {
462
   "cell_type": "code",
463
   "execution_count": 19,
464
   "metadata": {},
465
   "outputs": [
466
    {
467
     "name": "stdout",
468
     "output_type": "stream",
469
     "text": [
470
      " Based on the context provided, James was born in 1994. This is stated in the second document with the page content \"James was born in 1994\". Therefore, the answer to the question \"when was James born?\" is 1994.\n"
471
     ]
472
    }
473
   ],
474
   "source": [
475
    "out = chain.invoke(\"when was James born?\")\n",
476
    "print(out)"
477
   ]
478
  },
479
  {
480
   "cell_type": "markdown",
481
   "metadata": {},
482
   "source": [
483
    "Now the `RunnableParallel` object is allowing us to search with `retriever_a` _and_ `retriever_b` in parallel, ie at the same time."
484
   ]
485
  },
486
  {
487
   "cell_type": "markdown",
488
   "metadata": {},
489
   "source": [
490
    "## Runnable Lambdas"
491
   ]
492
  },
493
  {
494
   "cell_type": "markdown",
495
   "metadata": {},
496
   "source": [
497
    "The `RunnableLambda` is a LangChain abstraction that allows us to turn Python functions into pipe-compatible function, similar to the `Runnable` class we created near the beginning of this notebook.\n",
498
    "\n",
499
    "Let's try it out with our earlier `add_five` and `multiply_by_two` functions."
500
   ]
501
  },
502
  {
503
   "cell_type": "code",
504
   "execution_count": 23,
505
   "metadata": {},
506
   "outputs": [],
507
   "source": [
508
    "from langchain_core.runnables import RunnableLambda\n",
509
    "\n",
510
    "# wrap the functions with RunnableLambda\n",
511
    "add_five = RunnableLambda(add_five)\n",
512
    "multiply_by_two = RunnableLambda(multiply_by_two)"
513
   ]
514
  },
515
  {
516
   "cell_type": "markdown",
517
   "metadata": {},
518
   "source": [
519
    "As with our earlier `Runnable` abstraction, we can use `|` operators to chain together our `RunnableLambda` abstractions."
520
   ]
521
  },
522
  {
523
   "cell_type": "code",
524
   "execution_count": 26,
525
   "metadata": {},
526
   "outputs": [],
527
   "source": [
528
    "chain = add_five | multiply_by_two"
529
   ]
530
  },
531
  {
532
   "cell_type": "markdown",
533
   "metadata": {},
534
   "source": [
535
    "Unlike our `Runnable` abstraction, we cannot run the `RunnableLambda` chain by calling it directly, instead we must call `chain.invoke`:"
536
   ]
537
  },
538
  {
539
   "cell_type": "code",
540
   "execution_count": 25,
541
   "metadata": {},
542
   "outputs": [
543
    {
544
     "data": {
545
      "text/plain": [
546
       "16"
547
      ]
548
     },
549
     "execution_count": 25,
550
     "metadata": {},
551
     "output_type": "execute_result"
552
    }
553
   ],
554
   "source": [
555
    "chain.invoke(3)"
556
   ]
557
  },
558
  {
559
   "cell_type": "markdown",
560
   "metadata": {},
561
   "source": [
562
    "As before, we can see the same answer. Naturally we can feed custom functions into our chains using this approach. Let's try a short chain and see where we might want to insert a custom function:"
563
   ]
564
  },
565
  {
566
   "cell_type": "code",
567
   "execution_count": 32,
568
   "metadata": {},
569
   "outputs": [],
570
   "source": [
571
    "prompt_str = \"Tell me an short fact about {topic}\"\n",
572
    "prompt = ChatPromptTemplate.from_template(prompt_str)\n",
573
    "\n",
574
    "chain = prompt | model | output_parser"
575
   ]
576
  },
577
  {
578
   "cell_type": "code",
579
   "execution_count": 34,
580
   "metadata": {},
581
   "outputs": [
582
    {
583
     "data": {
584
      "text/plain": [
585
       "\" Here's a short fact about artificial intelligence:\\n\\nAI systems can analyze huge amounts of data and detect patterns that humans may miss. For example, AI is helping doctors diagnose diseases earlier by processing medical images and spotting subtle signs that a human might not notice.\""
586
      ]
587
     },
588
     "execution_count": 34,
589
     "metadata": {},
590
     "output_type": "execute_result"
591
    }
592
   ],
593
   "source": [
594
    "chain.invoke({\"topic\": \"Artificial Intelligence\"})"
595
   ]
596
  },
597
  {
598
   "cell_type": "code",
599
   "execution_count": 35,
600
   "metadata": {},
601
   "outputs": [
602
    {
603
     "data": {
604
      "text/plain": [
605
       "\" Here's a short fact about artificial intelligence:\\n\\nAI systems are able to teach themselves over time. Through machine learning, algorithms can analyze large amounts of data and improve their own processes and decision making without needing to be manually updated by humans. This self-learning ability is a key attribute enabling AI progress.\""
606
      ]
607
     },
608
     "execution_count": 35,
609
     "metadata": {},
610
     "output_type": "execute_result"
611
    }
612
   ],
613
   "source": [
614
    "chain.invoke({\"topic\": \"Artificial Intelligence\"})"
615
   ]
616
  },
617
  {
618
   "cell_type": "markdown",
619
   "metadata": {},
620
   "source": [
621
    "The returned text always includes the initial `\"Here's a short fact about ...\\n\\n\"` — let's add a function to split on double newlines `\"\\n\\n\"` and only return the fact itself."
622
   ]
623
  },
624
  {
625
   "cell_type": "code",
626
   "execution_count": 36,
627
   "metadata": {},
628
   "outputs": [],
629
   "source": [
630
    "def extract_fact(x):\n",
631
    "    if \"\\n\\n\" in x:\n",
632
    "        return \"\\n\".join(x.split(\"\\n\\n\")[1:])\n",
633
    "    else:\n",
634
    "        return x\n",
635
    "    \n",
636
    "get_fact = RunnableLambda(extract_fact)\n",
637
    "\n",
638
    "chain = prompt | model | output_parser | get_fact"
639
   ]
640
  },
641
  {
642
   "cell_type": "code",
643
   "execution_count": 37,
644
   "metadata": {},
645
   "outputs": [
646
    {
647
     "data": {
648
      "text/plain": [
649
       "'Most AI systems today are narrow AI, meaning they are focused on and trained for a specific task like computer vision, natural language processing or playing chess. General artificial intelligence that has human-level broad capabilities across many domains does not yet exist. AI has made tremendous progress in recent years thanks to advances in deep learning, big data and computing power, but still has limitations and scientists are working to make AI systems safer and more beneficial to humanity.'"
650
      ]
651
     },
652
     "execution_count": 37,
653
     "metadata": {},
654
     "output_type": "execute_result"
655
    }
656
   ],
657
   "source": [
658
    "chain.invoke({\"topic\": \"Artificial Intelligence\"})"
659
   ]
660
  },
661
  {
662
   "cell_type": "code",
663
   "execution_count": 38,
664
   "metadata": {},
665
   "outputs": [
666
    {
667
     "data": {
668
      "text/plain": [
669
       "'AI systems can analyze massive amounts of data and detect patterns that humans may miss. This ability to find insights in large datasets is one of the key strengths of AI and enables many practical applications like personalized recommendations, fraud detection, and medical diagnosis.'"
670
      ]
671
     },
672
     "execution_count": 38,
673
     "metadata": {},
674
     "output_type": "execute_result"
675
    }
676
   ],
677
   "source": [
678
    "chain.invoke({\"topic\": \"Artificial Intelligence\"})"
679
   ]
680
  },
681
  {
682
   "cell_type": "markdown",
683
   "metadata": {},
684
   "source": [
685
    "Now we're getting well formatted outputs using our final custom `get_fact` function.\n",
686
    "\n",
687
    "---\n",
688
    "\n",
689
    "That covers the essentials you need to getting started and building with the **L**ang**C**hain **E**xpression **L**anguage (LCEL). With it, we can put together chains very easily — and the current focus of the LangChain team is on further LCEL development and support.\n",
690
    "\n",
691
    "The pros and cons of LCEL are varied. Those that love it tend to focus on the minimalist code style, LCEL's support for streaming, parallel operations, and async, and LCEL's nice integration with LangChain's focus on chaining components together.\n",
692
    "\n",
693
    "There are also people that are less fond of LCEL. Typically people will point to it being yet another abstraction on top of an already very abstract library, that the syntax is confusing, against [the Zen of Python](https://peps.python.org/pep-0020/), and requires too much effort to learn new (or uncommon) syntax.\n",
694
    "\n",
695
    "Both viewpoints are entirely valid, LCEL is a very different approach — ofcourse there are major pros and major cons. In either case, if you're willing to spend some time learning the syntax, it allows us to develop very quickly, and with that in mind it's well worth learning."
696
   ]
697
  },
698
  {
699
   "cell_type": "markdown",
700
   "metadata": {},
701
   "source": [
702
    "---"
703
   ]
704
  }
705
 ],
706
 "metadata": {
707
  "kernelspec": {
708
   "display_name": "ml",
709
   "language": "python",
710
   "name": "python3"
711
  },
712
  "language_info": {
713
   "codemirror_mode": {
714
    "name": "ipython",
715
    "version": 3
716
   },
717
   "file_extension": ".py",
718
   "mimetype": "text/x-python",
719
   "name": "python",
720
   "nbconvert_exporter": "python",
721
   "pygments_lexer": "ipython3",
722
   "version": "3.9.12"
723
  }
724
 },
725
 "nbformat": 4,
726
 "nbformat_minor": 2
727
}
728

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.