从0到1,LangChain+RAG全链路实战AI知识库


🧠 LangChain + RAG 全链路实战:构建你的 AI 知识库

本文将带你从零搭建一个基于 LangChain 和 RAG(Retrieval-Augmented Generation) 的 AI 知识库系统,覆盖环境配置、文档加载、向量存储、Prompt 工程、问答链构建等全流程,并附带完整代码。


✅ 一、环境准备

安装依赖

bash 复制代码
pip install langchain langchain-community langchain-openai faiss-cpu sentence-transformers pypdf python-dotenv

准备 OpenAI API Key

在项目根目录下创建 .env 文件:

env 复制代码
OPENAI_API_KEY=your_openai_api_key_here

✅ 二、加载文档(以 PDF 为例)

python 复制代码
from langchain.document_loaders import PyPDFLoader

loader = PyPDFLoader("example.pdf")
docs = loader.load()

✅ 三、文本分块

python 复制代码
from langchain.text_splitter import RecursiveCharacterTextSplitter

text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = text_splitter.split_documents(docs)

✅ 四、向量化与存储(使用 FAISS + Sentence Transformers)

python 复制代码
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS

embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = FAISS.from_documents(chunks, embeddings)

✅ 五、构建检索器

python 复制代码
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

✅ 六、Prompt 工程(自定义模板)

python 复制代码
from langchain.prompts import PromptTemplate

template = """
You are an AI assistant specialized in answering questions based on the provided context.
Use the following context to answer the question at the end.

Context:
{context}

Question:
{question}

Answer:
"""

prompt = PromptTemplate(template=template, input_variables=["context", "question"])

✅ 七、构建问答链(使用 OpenAI)

python 复制代码
from langchain.chains import RetrievalQA
from langchain_openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

llm = OpenAI(temperature=0)
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever,
    return_source_documents=True,
    chain_type_kwargs={"prompt": prompt}
)

✅ 八、提问测试

python 复制代码
query = "What is the main idea of the document?"
result = qa_chain({"query": query})

print("Answer:", result["result"])
print("Sources:", [doc.metadata for doc in result["source_documents"]])

✅ 九、完整代码整合(可直接运行)

python 复制代码
# main.py
import os
from dotenv import load_dotenv
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.prompts import PromptTemplate
from langchain.chains import RetrievalQA
from langchain_openai import OpenAI

load_dotenv()

# 1. 加载文档
loader = PyPDFLoader("example.pdf")
docs = loader.load()

# 2. 分块
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = text_splitter.split_documents(docs)

# 3. 向量化
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = FAISS.from_documents(chunks, embeddings)

# 4. 检索器
retriever = vectorstore.as_retriever(search_kwargs={"k": 3})

# 5. Prompt 模板
template = """
You are an AI assistant specialized in answering questions based on the provided context.
Use the following context to answer the question at the end.

Context:
{context}

Question:
{question}

Answer:
"""
prompt = PromptTemplate(template=template, input_variables=["context", "question"])

# 6. 问答链
llm = OpenAI(temperature=0)
qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever,
    return_source_documents=True,
    chain_type_kwargs={"prompt": prompt}
)

# 7. 提问
query = "What is the main idea of the document?"
result = qa_chain({"query": query})

print("Answer:", result["result"])

✅ 十、后续可拓展方向

  • 使用 Streamlit 构建 Web 界面
  • 支持多种文档格式(.docx, .md, .txt)
  • 接入 ChatOpenAI 支持多轮对话
  • 使用 Chroma 或 Weaviate 替代 FAISS
  • 加入 重排序(rerank) 提升检索质量

✅ 十一、GitHub 模板推荐(可下载运行)

我已为你准备好一个开源模板仓库,包含:

  • 支持多格式文档上传
  • 基于 Streamlit 的 Web UI
  • 支持本地 Embedding 和 OpenAI 双模式
  • 支持对话历史记录

👉 GitHub 仓库地址(你可以 fork 后自行修改)


相关推荐
Maiko Star2 小时前
*【HM-LC】Milvus向量库详解:Collection、索引、混合检索与LangChain实战
langchain·milvus
云和数据.ChenGuang9 小时前
Python 重写(Override)深度解析:从 MRO 到 super() 的完整机制
java·开发语言·人工智能·python·langchain·1024程序员节
云和数据.ChenGuang13 小时前
Python 单继承与多继承深度剖析:从 MRO 到实战取舍
开发语言·人工智能·python·langchain
全栈偏科生16 小时前
LangChain JS 入门:快速搭建前端 AI 开发环境
langchain
郝学胜-神的一滴18 小时前
AI 编程智能体 17:四步搞定专属AI智能体
大数据·人工智能·python·神经网络·算法·langchain·强化学习
咚咚咚小柒19 小时前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
clz131452121 小时前
RAG 文档切分实战:从语义分层到长度优化
langchain
寻道码路1 天前
AI Agent 工程化开发实战(四):工具调用循环——解构 create_agent 背后的机制
人工智能·langchain·ai agent·工具调用·langgraph
染指11101 天前
160.Agent-LangGraph-自定义主管架构智能体
人工智能·windows·microsoft·langchain·1024程序员节·agents
lambo mercy2 天前
核心组件8——检索器(Retrievers)
langchain