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:

1 Días
5 Hrs
33 Min
44 Seg
Curso de LangChain

Curso de LangChain

Omar Espejel

Omar Espejel

RetrievalQA chain

8/37
Resources

How to build a utility string to answer questions?

The creation of utility chains, specifically designed to solve questions from documents, is an approach that combines artificial intelligence techniques with data manipulation. Using Python libraries, such as chains.retrieval.qa, we can build these chains that perform a "question answering" or QA process, taking advantage of information stored in specific databases.

What is retrieval.qa and how is it used?

retrieval.qa is a crucial feature of the string library that allows us to create a string for question answering from a language model and a database. Here, "retrieval" implies information retrieval, and "QA" refers to question resolution. With this tool, we can retrieve relevant information from a previously defined vector database, such as one stored with Chroma.

To use retrieval.qa, we follow these steps:

  1. Define the language model (LLM):

    • In the example, we use the gpt3-5 model, specifically OpenAI's gpt3.5 turbo.
    • This model is loaded and managed through model homogenization tools such as Langstan, which allow us to maintain a uniform class for different types of AI models, facilitating interconnectivity and substitutability without modifying the string.
  2. Define the chain type:

    • We use the ChainType Stuff string type, which allows us to process text that fits completely in the model prompt.
    • This approach avoids iterating through large volumes of text, as a MapReduce approach would do.
  3. Incorporation of a Retriever:

    • A Retriever is essential in this process as it acts as the database from which our string models will extract information.
    • In this case, our database is Chroma, and we use the VectorStore which stores documents, such as a PDF of a research paper.
from chains.retrieval.qa import RetrievalQA
 # Define language modelllm = 'gpt3-5'
 # Initialize stringstring_resolver = RetrievalQA.from_chain_type(  llm=llm,  chain_type='Stuff',  retriever=VectorStore)

What role does search and context play in query resolution?

The purpose of properly configuring search and context is to optimize the accuracy and relevance of the generated answers. As database storage and processing capabilities grow, these configurations allow the system to acquire greater knowledge and context when solving complex queries.

  • Search parameters (SearchQuarks):
    • These are important settings that determine which text fragments will be considered relevant when answering a question.
    • In the example provided, a setting that restricts to two text fragments is used. This number seeks to balance the context provided and the maximum prompt size accepted by the model.
  • Context balance:
    • By increasing the number of fragments, the model has more context to base its responses on, improving its accuracy.
    • However, the limitation remains the size of the prompt that the model can process, which is currently restricted but is expected to improve in the future.

How is the string executed to solve a question?

Once the string is properly initialized and configured with its parameters, we can perform specific queries. For example, to evaluate the relevance of public key cryptography, we simply run the string with the desired question and get not only the answer, but also the relevant context of the original content.

# execute questionanswer = string_resolver.run(  question='What is the relevance of public-key cryptography?')
print(answer)

With these tools and methodologies, we are well positioned to meet any challenge in the realm of question answering, and with the continued evolution of technology, the potential will only continue to grow. Stay tuned to these innovations and continue to explore the applications of machine learning and natural language processing.

Contributions 5

Questions 3

Sort by:

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

🚚 Recuperadores (Retrievers)

.

ℹ️ Summary

Esta guía proporciona un caso de uso sobre Recuperadores QA (Retrievers QA), sobre documentos combinados sobre cadenas en un almacenamiento vectorial local, HNSWLib.
.

🗂️ Background

Un recuperador es una interfaz que devuelve documentos a partir de una consulta no estructurada. Es más general que un almacén vectorial.
.
Un recuperador no necesita ser capaz de almacenar documentos, sólo de devolverlos (o recuperarlos). Los almacenes vectoriales pueden utilizarse como columna vertebral de un recuperador, pero también existen otros tipos de recuperadores.
.
Enlaces auxiliares:

.

🎯 Problem

Implementar una “Utility Chain” en LangChain utilizando TypeScript para implementar una tarea específica, por ejemplo, procesar y analizar datos textuales para extraer información QA.
.

🚧 Solution

LangChain permite incorporar prompts como parte de un flujo de procesamiento de una aplicación a un concentrado documental, para posteriormente la extracción específica información mediante RetrievalQAChain.

import { RetrievalQAChain } from 'langchain/chains'

Posteriormente, se genera una chain para efectuar un query sobre un nicho de información, por ejemplo una pregunta What time will the meeting be?.

const chain = RetrievalQAChain.fromLLM(llm, vectorStore.asRetriever({ k: 1 }))
const response = await chain.call({
    query: 'What time will the meeting be?',
})

Sin embargo, RetrievalQAChain emplea un VectorStore para poder mezclar y seccionar la información.
.
HNSWLib es un almacén de vectores en memoria, o local, que puede guardarse en un archivo. Instalable como dependencia mediante hnswlib-node.
.
Cada almacenamiento vectorial requiere de Incrustaciones (Embeddings), los cuales son un medio para representar información en un formato numérico.

import { OpenAIEmbeddings } from 'langchain/embeddings/openai'
import { HNSWLib } from 'langchain/vectorstores/hnswlib'

const embeddings = new OpenAIEmbeddings({
    openAIApiKey: API_TOKEN,
})
const vectorStore = await HNSWLib.fromDocuments(docs, embeddings)

🍻 Discussion

A distintos tipos de Embeddings, configurables para usarlos con LangChain. Dependiendo de caso de uso y la instalación, serán más ajustables para resolver los requerimientos de nuestro producto.
.
Cabe mencionar, que los Embeddings permiten procesar documentos, para permitirnos enfocar en la generación, refinamiento u optimización de nuestros prompts.

import { RetrievalQAChain } from 'langchain/chains'
import { OpenAIEmbeddings } from 'langchain/embeddings/openai'
import { OpenAI } from 'langchain/llms/openai'
import { TextLoader } from 'langchain/document_loaders/fs/text'
import { HNSWLib } from 'langchain/vectorstores/hnswlib'

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

const loader = new TextLoader('tmp/conversation.txt')
const docs = await loader.load()

const llm = new OpenAI({
    maxTokens: -1,
    modelName: 'gpt-4',
    temperature: 0,
    openAIApiKey: API_TOKEN,
})

const embeddings = new OpenAIEmbeddings({
    openAIApiKey: API_TOKEN,
})
const vectorStore = await HNSWLib.fromDocuments(docs, embeddings)

const chain = RetrievalQAChain.fromLLM(llm, vectorStore.asRetriever({ k: 1 }))
const response = await chain.call({
    query: 'What time will the meeting be?',
})
console.log(response)
Ya no es necesario utilizar `chain_type` porque RetrievalQA ya es una cadena completa en sí misma. La clase `RetrievalQA` combina un modelo de lenguaje y un recuperador de datos para generar respuestas basadas en la información recuperada. El uso de `chain_type` es más relevante cuando se trabaja con cadenas más complejas que involucran múltiples pasos o componentes. Por ejemplo, si deseas combinar RetrievalQA con otro tipo de cadena, como una cadena de generación de lenguaje, puedes utilizar `chain_type` para especificar cómo se conectan y se comunican entre sí.
No hablo español, pero he podido seguir el curso perfectamente por su didáctica y facilidad de comprensión en portugués. ¡Felicidades!
Hola, saben si hay forma de hacer esto con CSV? por ejemplo si tengo una columna con textos cortos (Tweets) y quiero que el modelo responda una pregunta para cada tweet de la columna determinada del CSV

Imprtante saber que podemos contar con funciones como esta.