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
1 Hrs
40 Min
22 Seg
Curso de LangChain

Curso de LangChain

Omar Espejel

Omar Espejel

Document Transformers: TextSplitters

17/37
Resources

How are documents fragmented to facilitate indexing?

In the world of natural language processing, structuring and breaking documents into smaller fragments is key to creating efficient and manageable indexes. Learning how to use TextSplitters, specifically the Recursive Character TextSplitter, is a critical step. Defining the right size for these text fragments can significantly improve the way documents are parsed and indexed. In the following, we will explore this approach and highlight how to convert multiple documents into smaller fragments for analysis.

What are TextSplitters and how to use them?

TextSplitters are tools that transform documents into more manageable fragments. The goal is to divide a large document into chapters and subchapters. To get started, the Recursive Character TextSplitter from the Langsteam library is used.

from langsteam import TextSplitter
text_splitter = TextSplitter()

The first step is to define the text size. Instead of measuring it by characters or words, a measurement in tokens is used.

What are tokens and how are they used in TextSplitter?

A token is a basic unit of data in natural language processing. To determine the size of fragments, functions that count the length in tokens are used. It is possible to use advanced methods such as OpenAI tokenizers or Jogging Face, although a simple length function is usually sufficient.

Importance of overlap in fragments

Overlap is essential to ensure that continuity is not lost between consecutive fragments. A text may contain important parts right at the beginning and end of a fragment, so introducing a 200-character overlap ensures that relevant information is not cut off abruptly.

Key features of the Recursive Character TextSplitter

This splitter has the feature of taking into account the ends of sentences and paragraphs, making sure not to cut sentences in half. This improves readability and comprehension of the text.

Why is chunk size and overlap important?

Chunk size and overlap are essential parameters when chunking documents:

  1. Chunk Size: To be effective, a Chunk Size must be consistent with the Embedding model employed.
    • Models such as Cohere handle between 500 to 600 tokens.
    • Sentence Transformers from Jogging Face accept around 250 tokens.
    • OpenAI - offers a margin of up to 8000 tokens.
  2. Chunk Overlap: It is recommended that the overlap be between 10% to 20% of the total chunk. This allows the chunks to maintain their connection without being overly repetitive.

Practical exploration

Once the documents are split, a much more extensive and detailed list of chunks is obtained. Originally, 18 documents were transformed into 142 more manageable snippets, ready to be indexed more accurately.

documents = text_splitter.splitDocuments(data)

With this methodology, indexing is facilitated and access to information is optimized by breaking down large documents into more precise and concise fragments.

Tips for advanced practices

  • When adjusting Chunk Size and Overlap values, experimenting with different settings can reveal which one is best suited to a specific task.
  • Keeping up to date with advances in Embedding models can allow you to handle larger chunks as technology capabilities increase.
  • Using libraries such as Langteam and Jogging Face for advanced tokenization can provide more accurate size measurement in tokens.

Learning to work with TextSplitters not only improves how information is indexed, but also transforms the way natural language is processed for data and knowledge retrieval. We encourage you to continue exploring and experimenting with these tools to maximize their potential.

Contributions 2

Questions 1

Sort by:

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

⚠️ Una advertencia para que sí usen la data del PDF de crypto.

Antes de cargar documents con el text_splitter recuerden correr nuevamente el código que carga el archivo public_key_cryptography.pdf que se aprende en la Clase 14 Document Loaders: PDF, de lo contrario van cargar la data del JSON o del CSV y no resolverán las queries que indica el profe. 🤓

from langchain.document_loaders import PyPDFLoader

loader = PyPDFLoader("./public_key_cryptography.pdf")
data = loader.load()

🔩 Divisores de Texto (Text Splitters)

.

ℹ️ Summary

Esta guía proporciona un caso de uso sobre “Text Splitters”, cuando se desea dividir un documento largo en trozos que puedan ajustarse a la ventaja contextual de un modelo.
.

🗂️ Background

Una vez cargados los documentos, a menudo querrá transformarlos para adaptarlos mejor a su aplicación. El ejemplo más sencillo es que quieras dividir un documento largo en trozos más pequeños que quepan en la ventana contextual de tu modelo. LangChain tiene una serie de transformadores de documentos incorporados que facilitan la división, combinación, filtrado y manipulación de documentos.
.
En alto nivel, los divisores de texto funcionan de la siguiente manera:
.

  1. Divida el texto en pequeños fragmentos semánticamente significativos (a menudo frases).
  2. Se empieza a combinar estos trozos pequeños en un trozo más grande hasta que alcances un cierto tamaño (medido por alguna función).
  3. Una vez alcanzado ese tamaño, haga de ese trozo su propio fragmento de texto y empiece a crear un nuevo trozo de texto con cierto solapamiento (para mantener el contexto entre los trozos).

.
Enalces auxiliares:

.

🎯 Problem

Implementar un “Text Splitter” utilizando TypeScript para dividir un repositorio de información manejable por el model GPT-4 de OpenAI.
.

🚧 Solution

LongChain recomienda la funcionalidad RecursiveCharacterTextSplitter, ya que posee la versatilidad de dividir, recursivamente, mediante caracteres distintivos en una oración y párrafos en un documento de texto.

import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'

const splitter = new RecursiveCharacterTextSplitter({
	chunkSize: 1000,
	chunkOverlap: 200,
})

const docsOutput = await splitter.splitDocuments(docs)

Podemos destacar los parámetros chunkSize y chunkOverlap, los cuales definen la división semántica del contenido en función del tamaño y la ampliación del mismo, respectivamente.
.

🍻 Discussion

En la definición del TextSplitter definimos un chunk de 1000 caracteres y un overlap de 200 caracteres, pero, ¿Cómo se cuál es valor correcto para estos parámetros?
.
Sobre el chunk, la cantidad de tokens o caracteres debe ser la misma que la que se definirá en el embedding, por lo que si se entregan más tokens que el modelo de embedding puede soportar, el modelo colapsará o procesará información incompleta. Los diferentes modelos aceptan diferentes límites, donde ada de OpenAI acepta hasta 8k de caracteres, mientras otros más modestos aceptan 500 (que es el valor estándar por ahora).
.
Con respecto al overlap es importante mantener un porcentaje de 10 a 20% para que pueda comprender contexto anterior sin que se repitan conceptos exageradamente, si bien este es un valor de prueba y error, se ha demostrado que estos valores son funcionales.

import { HNSWLib } from 'langchain/vectorstores/hnswlib'
import { OpenAIEmbeddings } from 'langchain/embeddings/openai'
import { RecursiveCharacterTextSplitter } from 'langchain/text_splitter'
import { TextLoader } from 'langchain/document_loaders/fs/text'

const API_TOKEN = // 👈 Enter the API Token from OpenAI

const textLoader = new TextLoader('tmp/meeting.txt')
const docs = await textLoader.load()

const splitter = new RecursiveCharacterTextSplitter({
	chunkSize: 1000,
	chunkOverlap: 200,
})
const docsOutput = await splitter.splitDocuments(docs)

const embeddings = new OpenAIEmbeddings({
	openAIApiKey: API_TOKEN,
})

const vectorStore = await HNSWLib.fromDocuments(docsOutput, embeddings)
console.log(vectorStore)