Eine LCEL-Retrieval-Chain erstellen

Retrieval Augmented Generation (RAG) mit LangChain

Meri Nova

Machine Learning Engineer

Daten für Retrieval vorbereiten

Dokument-Chunks werden gespeichert.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

Eine Nutzereingabe.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

Eine Nutzereingabe gelangt über RunnablePassthrough in die Chain und wird „question“ zugewiesen.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

Die Eingabe wird für den Retriever genutzt und „context“ zugewiesen.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

„context“ und „question“ werden in die Prompt-Vorlage eingesetzt.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

Der Prompt wird ins LLM (Modell) integriert, um eine Ausgabe zu erzeugen.

Retrieval Augmented Generation (RAG) mit LangChain

Einführung in LCEL für RAG

Die Modell-Ausgabe wird an einen Parser übergeben.

Retrieval Augmented Generation (RAG) mit LangChain

Einen Retriever instanziieren

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) mit LangChain

Eine Prompt-Vorlage erstellen

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) mit LangChain

Eine LCEL-Retrieval-Chain bauen

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) mit LangChain

Die Retrieval-Chain ausführen

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) mit LangChain

Lass uns üben!

Retrieval Augmented Generation (RAG) mit LangChain

Preparing Video For Download...