Creare una catena di retrieval con LCEL

Retrieval Augmented Generation (RAG) con LangChain

Meri Nova

Machine Learning Engineer

Preparare i dati per il retrieval

I chunk di documento vengono archiviati.

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

Un input dell'utente.

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

Un input entra nella catena tramite RunnablePassthrough e viene assegnato a "question".

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

L'input viene usato per interrogare il retriever e assegnato a "context".

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

"context" e "question" vengono inseriti nel prompt template.

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

Il prompt viene passato all'LLM, o modello, per generare un output.

Retrieval Augmented Generation (RAG) con LangChain

Introduzione a LCEL per RAG

L'output del modello viene passato a un parser.

Retrieval Augmented Generation (RAG) con LangChain

Istanziamento di un retriever

vector_store = Chroma.from_documents(
    documents=chunks, 
    embedding=embedding_model
)


retriever = vector_store.as_retriever( search_type="similarity", search_kwargs={"k": 2} )
Retrieval Augmented Generation (RAG) con LangChain

Creare un prompt template

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template(""" Use the following pieces of context to answer the question at the end. If you don't know the answer, say that you don't know. Context: {context} Question: {question} """)
llm = ChatOpenAI(model="gpt-4o-mini", api_key="...", temperature=0)
Retrieval Augmented Generation (RAG) con LangChain

Creare una catena di retrieval con LCEL

from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
Retrieval Augmented Generation (RAG) con LangChain

Invocare la catena di retrieval

result = chain.invoke({"question": "What are the key findings or results presented in the paper?"})
print(result)
- Top Performance: RAG models set new records on open-domain question answering tasks...
- Better Generation: RAG models produce more specific, diverse, and factual language...
- Dynamic Knowledge Use: The non-parametric memory allows RAG models to access and ...
Retrieval Augmented Generation (RAG) con LangChain

Esercitiamoci!

Retrieval Augmented Generation (RAG) con LangChain

Preparing Video For Download...