Introducción a LangChain

1

Desarrollo de aplicaciones con LLM utilizando LangChain

2

Estructura y módulos de LangChain

3

Uso de modelos Open Source de Hugging Face

4

Uso de modelos de OpenAI API

5

Prompt templates de LangChain

6

Cadenas en LangChain

7

Utility chains

8

RetrievalQA chain

9

Foundational chains

Quiz: Introducción a LangChain

Casos de uso de LangChain

10

Casos de uso de LangChain

11

¿Cómo utilizar LangChain en mi equipo?

Quiz: Casos de uso de LangChain

Manejo de documentos con índices

12

¿Cómo manejar documentos con índices en LangChain?

13

La clase Document

14

Document Loaders: PDF

15

Document Loaders: CSV con Pandas DataFrames

16

Document Loaders: JSONL

17

Document Transformers: TextSplitters

18

Proyecto de Chatbot: configuración de entorno para LangChain y obtención de datos

19

Proyecto de Chatbot: creación de documents de Hugging Face

Quiz: Manejo de documentos con índices

Embeddings y bases de datos vectoriales

20

Uso de embeddings y bases de datos vectoriales con LangChain

21

¿Cómo usar embeddings de OpenAI en LangChain?

22

¿Cómo usar embeddings de Hugging Face en LangChaing?

23

Chroma vector store en LangChain

24

Proyecto de Chatbot: ingesta de documents en Chroma

25

RetrievalQA: cadena para preguntar

26

Proyecto de Chatbot: cadena de conversación

27

Proyecto de Chatbot: RetrievalQA chain

Quiz: Embeddings y bases de datos vectoriales

Chats y memoria con LangChain

28

¿Para qué sirve la memoria en cadenas y chats?

29

Uso de modelos de chat con LangChain

30

Chat prompt templates

31

ConversationBufferMemory

32

ConversationBufferWindowMemory

33

ConversationSummaryMemory

34

ConversationSummaryBufferMemory

35

Entity memory

36

Proyecto de Chatbot: chat history con ConversationalRetrievalChain

Quiz: Chats y memoria con LangChain

Evolución del uso de LLM

37

LangChain y LLM en evolución constante

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
21 Min
4 Seg
Curso de LangChain

Curso de LangChain

Omar Espejel

Omar Espejel

Utility chains

7/37
Resources

How to work with strings in language processing?

Strings are fundamental in LangChain, since they allow to create workflows where each step is a different process. A text is entered at the beginning of the chain and is transformed through several links until a response is obtained using a language model. In this guide, we will focus on foundational and utility strings and how to load and process them with the help of essential tools.

How to load a PDF for processing with LangChain?

To handle unstructured documents as PDFs, you must install specialized libraries:

  1. OnStructure: allows LangChain to work with various types of unstructured documents.
  2. PyPDF: Used by LangChain to load and fit PDFs.
  3. ChromaDB: An efficient vector database for managing embeddings.

After installing these tools, use the requests library to download a PDF from a specific URL. When opened, save it locally for further processing.

import requests
 # Get PDF from URLurl = "URL_DEL_PDF"r = requests.get(url)with open("publickeycryptography.pdf", "wb") as f: f.write(r.content)

How to process a PDF with PyPDFLoader in LangChain?

To use LangChain, you need its DocumentLoaders module and specifically PyPDFLoader:

from langchain.document_loaders import PyPDFLoader
 # Load PDF in proper formatloader = PyPDFLoader("publickeycryptography.pdf")data = loader.load()

How are Embeddings integrated with OpenAI and ChromaDB?

Once the PDF is processed, OpenAI embeddings must be imported to convert the data to the required numeric format:

from langchain.embeddings import OpenAIEmbeddings
 # Conversion of the PDF into an embedded formatembeddings = OpenAIEmbeddings()embeddings_data = embeddings.embed_documents(data).

Finally, store these embeddings in ChromaDB for use with the utility strings:

from langchain.vectorstores import Chroma
 # Storing embeddings in ChromaDBvector_store = Chroma.from_embeddings(embeddings_data)

How to summarize a long text with LoadSummarizeChain?

LangChain allows to summarize long documents with appropriate tools, such as LoadSummarizeChain. This chain can handle long documents by splitting them into manageable parts and summarizing them individually, combining the individual summaries into a final one using a MapReduce approach:

from langchain.chains import load_summarize_chain
 # Configuration and execution of the summarizing chainsummary_chain = load_summarize_chain(  model=LLLM_DaVinci,  chain_type="MapReduce")summary = summary_chain.run(data)

What are the benefits of using prompts?

The use of custom prompts allows for better results in the generated summaries. You can define a Mexican-style prompt, for example:

from langchain.prompts import PromptTemplate
template_text = "Write a cool summary of the following roll: {text}.  Short summary with Mexican slang."prompt_template = PromptTemplate(template=template_text,  input_variables=["text"])

With the chain type Stuff, you use this prompt to generate more culturally adapted summaries:

informal_chain = load_summarize_chain(  model=LLLM_DaVinci,  chain_type="Stuff",  prompt_template=prompt_template, verbose=True)
 # Running the chain with an excerpt from the PDFsummary_mx = informal_chain.run(data[:2])

In essence, the Stuff type limits the context to the size of the prompt, which means that large documents must be shortened before entering the model. However, it allows the creation of culturally appropriate and specific recommendations.

In summary, LangChain opens the door to efficient navigation and processing of large amounts of text with a noticeable degree of customization, allowing users to create accurate and culturally sensitive workflows.

Contributions 11

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Buenas, no me parece tan grave que el codigo no este actualizado, en la vida profesional nos toca leer documentacion, es muy sencillo entrar a la documentacion y readaptar el codigo, no hay que ser genio para ello. Animos!
El código usado en este video ya está obsoleto (21-2-24). Por ejemplo el método run ya no se aplica. Hay prevista alguna actualización de los videos? Lo digo porque ahora mismo ya no sirve. Gracias.
Algo que me ha servido mucho para entender mejor este tema *(por que igual es complejo), es separar los procesos por pasos:* 1\. pasar el pdf a Document de Langchain 2\. hacer un resumen previo para cada pagina 3\. hacer el prompt-template 4\. hacer resumen en español mexicano. Creo que puede ser útil.
El `vectorstore` que se crea en esta clase no se uso para ninguno de los ejemplos...

Aqune algo complejo, veo mucho potencial en lo que podemos lograr con LangChain 🦜⛓

⛓️ Cadenas (Chains)

Utilizar un LLM de forma aislada está bien para aplicaciones sencillas, pero las aplicaciones más complejas requieren encadenar LLM, ya sea entre sí o con otros componentes.
.
LangChain proporciona la interfaz Chain para generar aplicaciones más específicas. Ya que la idea de componer componentes en cadena, simplifica drásticamente su especificación, haciendo más modular la implementación de aplicaciones complejas, lo que a su vez facilita mucho la depuración, el mantenimiento y la mejora de nuestras aplicaciones.
.

📝 Resumen (Summarization)

Se puede utilizar una cadena de resumen para resumir (summarize) múltiples documentos. Una forma es introducir múltiples documentos más pequeños, después de haberlos dividido en trozos, y operar sobre ellos con una MapReduceDocumentsChain. También puede elegir que la cadena que realiza el resumen sea una cadena StuffDocumentsChain o una cadena RefineDocumentsChain.
.
Supongamos una conversación en formato .txt:

Elena: Perfect, Carlos, Ana, Juan, thank you for your feedback. Regarding priorities, we continue to focus on completing the search functionality as it is essential for the launch. Carlos, can you talk to Ana later to review the design changes?

Carlos: Of course, Elena, I will be happy to do that.

Ana: Carlos, I will send you a meeting request for that.

Juan: Regarding the implementation of the search function, I have some doubts about the integration with the third-party API we discussed yesterday. Could we go over that before we start?

Elena: Certainly, Juan. What time would be convenient for you?

Juan: Could it be at 10:30? I would have time to review the documentation before the meeting.

Elena: Sure, lets schedule the meeting for 10:30 then. Also, remember that today at 3 PM, we will have our weekly project update meeting, so lets make sure we are prepared to update the whole team.

Ana: Understood, I will be ready for that meeting.

Carlos: Same here, I will be ready to provide a solid update.

Juan: I will be ready too and hope to have some answers about the integration by then.

Elena: Perfect, that sounds great. In summary, today we will focus on the search functionality, review the design changes, and clarify any doubts about the integration with the third-party API. Lets work with energy and efficiency, team!
import { PromptTemplate } from 'langchain/prompts'

const llm = new OpenAI({
	// code ...
})

const chain = loadSummarizationChain(llm, { type: 'map_reduce' })
const summarize = await chain.call({
    input_documents: docs,
})
console.log(summarize)
{
  text: "Elena, Carlos, Ana, and Juan discussed their ongoing project, focusing on the completion of the search functionality. Carlos agreed to review design changes with Ana, while Juan expressed concerns about integrating a third-party API. A meeting was scheduled for 10:30 to discuss this. Elena reminded the team about a project update meeting at 3 PM, and everyone confirmed their readiness to provide updates. The team agreed to focus on the search functionality, design changes, and API integration issues.",
  __run: undefined
}
Like ❤️ si lo leíste como chilango la cadena\_que\_resume\_con\_salng\_mx XD
Para los que quieren probar todo lo de la clase con PDFs distintos, pueden usar el siguiente sitio para que carguen los PDF de manera temporal y solo cambien la url <https://tmpfiles.org/>
Al final para que se usa estas líneas de código en el contexto de esta clase? porque yo veo que se usa es la variable "data" ```js embeddings = OpenAIEmbeddings() vectorstore = Chroma.from_documents(data, embeddings) ```embeddings = OpenAIEmbeddings()vectorstore = Chroma.from\_documents(data, embeddings)
La verdad muy mal que tengan código que NO es funcional, uno pierde más tiempo tratanto de arreglar cosas que realmente aprendiendo. Les recomiendo pagar la suscripción a Medium, que estar perdiendo el tiempo aquí.
![](https://static.platzi.com/media/user_upload/image-4764ec96-a0ef-4e87-a328-e2efe0f3fbdb.jpg)