建立 RAG 鏈
現在要把你在 RAG 工作流程中的所有元件串起來!你已經整理好文件,並將它們匯入 Chroma 資料庫以供擷取。你也建立了一個提示樣板,會把從學術論文擷取出的區塊納入其中,用來回答問題。
你在上一個練習建立的提示樣板已可用,變數為 prompt_template;一個 OpenAI 模型已初始化為 llm;而重建 retriever 的程式碼也已包含在指令碼中。
本練習屬於課程
使用 LangChain 開發 LLM 應用
練習說明
- 使用管道運算子(
|)建立一個 LCEL 鏈,依序連接retriever、prompt_template和llm。 - 鏈中應將 retriever 對應到
"context",並將使用者輸入對應到"question"。 - 使用
.invoke()方法,對提供的問題呼叫這個鏈。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
vectorstore = Chroma.from_documents(
docs,
embedding=OpenAIEmbeddings(api_key='', model='text-embedding-3-small'),
persist_directory=os.getcwd()
)
retriever = vectorstore.as_retriever(
search_type="similarity",
search_kwargs={"k": 3}
)
# Create a chain to link retriever, prompt_template, and llm
rag_chain = ({"context": ____, "question": ____}
| prompt_template
| llm)
# Invoke the chain
response = rag_chain.____("Which popular LLMs were considered in the paper?")
print(response.content)