建立 LCEL 擷取鏈

使用 LangChain 的 Retrieval Augmented Generation(RAG)

Meri Nova

Machine Learning Engineer

為擷取準備資料

已儲存的文件區塊。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

使用者輸入。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

使用者輸入透過 RunnablePassthrough 進入鏈,並指定為「question」。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

以輸入查詢擷取器,並指定為「context」。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

將「context」與「question」帶入提示模板。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

將提示送入 LLM(模型)產生輸出。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

RAG 的 LCEL 入門

將模型輸出傳遞給剖析器。

使用 LangChain 的 Retrieval Augmented Generation(RAG)

建立擷取器實例

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


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

建立提示模板

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)
使用 LangChain 的 Retrieval Augmented Generation(RAG)

建立 LCEL 擷取鏈

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

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

呼叫擷取鏈

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 ...
使用 LangChain 的 Retrieval Augmented Generation(RAG)

一起來練習吧!

使用 LangChain 的 Retrieval Augmented Generation(RAG)

Preparing Video For Download...