当前位置: 首页 > news >正文

《AI大模型应知应会100篇》第66篇:用大模型 + 向量数据库构建你的个性化知识库系统(附实战代码)

第66篇:用大模型 + 向量数据库构建你的个性化知识库系统(附实战代码)

🎯 摘要:本文将手把手教你如何利用大语言模型(LLM)和向量数据库构建一套个性化的知识管理系统。你可以轻松实现知识的自动归类、快速检索与智能总结,打造属于你自己的“数字大脑”。文章包含完整代码实战、部署指南、可视化界面设计,并提供多个行业案例参考。


在这里插入图片描述

一、知识库架构设计概览

我们采用如下五层结构来构建整个知识库系统:

数据源 → 数据采集与清洗 → 向量化 → 存入向量数据库
→ 用户提问 → 向量匹配检索 → LLM生成解释/摘要 → 知识卡片展示

整体流程图如下:

+-----------------+     +---------------+     +---------------------+
| 数据采集        | --> | 向量化处理    | --> | 向量数据库存储       |
+-----------------+     +---------------+     +---------------------+|v+-------------------------+| 用户提问 -> 检索相关知识 |+-------------------------+|v+-----------------------------+| LLM生成摘要或详细解释       |+-----------------------------+|v+-----------------------------+| 可视化展示(知识卡片)      |+-----------------------------+

二、数据采集与清洗【实战部分】

我们要从多种渠道获取原始知识,包括 RSS 订阅、微信公众号抓取和 Markdown 文件导入。

✅ 安装依赖包

pip install feedparser requests beautifulsoup4 langchain pinecone-client openai streamlit

1. RSS 抓取示例

import feedparserdef fetch_rss_feed(url):feed = feedparser.parse(url)articles = []for entry in feed.entries:title = entry.titlelink = entry.linksummary = entry.summary if hasattr(entry, 'summary') else ''articles.append({"title": title, "link": link, "content": summary})return articles

使用示例:

rss_url = "https://realpython.com/feed.xml"
articles = fetch_rss_feed(rss_url)
print(articles[0])

输出:

{"title": "Python Tricks: Magic Methods","link": "https://realpython.com/python-magic-methods/","content": "Magic methods are the special methods..."
}

2. 微信公众号内容提取(需配合爬虫工具)

以 WeChatSogou 为例:

pip install wechatsogou
import wechatsogouws_api = wechatsogou.WechatSogouAPI()# 搜索某公众号历史文章
articles = ws_api.get_gzh_article_by_keyword("机器之心", "AI伦理")for a in articles:print(a['title'], a['url'])

3. Markdown 文件导入

import osdef read_md_files(directory):documents = []for fname in os.listdir(directory):if fname.endswith(".md"):with open(os.path.join(directory, fname), "r", encoding="utf-8") as f:content = f.read()documents.append({"title": fname,"source": fname,"content": content})return documents

三、向量化与存储【实战部分】

我们将使用 LangChain 构建向量数据库,支持 Pinecone 或 Milvus 等后端。

1. 初始化 OpenAI Embedding 模型

from langchain.embeddings.openai import OpenAIEmbeddingsembeddings = OpenAIEmbeddings(openai_api_key="YOUR_OPENAI_API_KEY")

2. 使用 Pinecone 创建向量数据库

import pineconepinecone.init(api_key="YOUR_PINECONE_API_KEY", environment="us-west1-gcp")
index_name = "knowledge-base"if index_name not in pinecone.list_indexes():pinecone.create_index(name=index_name, dimension=1536)index = pinecone.Index(index_name)

3. 插入知识向量到 Pinecone

from uuid import uuid4all_knowledge = []  # 假设你已经从多个来源收集了知识列表for doc in all_knowledge:text = doc["content"]vector = embeddings.embed_query(text)index.upsert([(str(uuid4()), vector, {"text": text, "title": doc["title"], "source": doc["source"]})])

四、知识检索与生成【实战部分】

1. 向量相似度搜索

query = "什么是Transformer?"
query_vector = embeddings.embed_query(query)result = index.query(queries=[query_vector], top_k=3, include_metadata=True)
print(result)

输出示例:

{"matches": [{"id": "abc123","score": 0.92,"metadata": {"text": "Transformer 是一种基于自注意力机制的深度学习模型...","title": "NLP核心技术之Transformer详解","source": "知乎"}},...]
}

2. 使用 LLM 生成解释或摘要

from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplatellm = ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_key="YOUR_API_KEY")prompt_template = """
请根据以下知识片段回答问题。如果有多条信息,请综合给出简明扼要的回答。知识片段:
{context}问题:
{question}回答:
"""prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])context = "\n".join([match["metadata"]["text"] for match in result["matches"]])
final_prompt = prompt.format(context=context, question=query)response = llm.predict(final_prompt)
print(response)

输出示例:

Transformer 是一种基于自注意力机制的深度学习模型,广泛应用于自然语言处理领域...

五、可视化与交互设计

1. 使用 Streamlit 构建前端界面

# frontend.py
import streamlit as st
import requestsst.set_page_config(page_title="我的知识库助手")
st.title("📚 我的知识库问答系统")question = st.text_input("请输入你要查询的问题:")
if st.button("🔍 查询"):payload = {"question": question}res = requests.post("http://localhost:8000/query", json=payload)answer = res.json().get("answer", "抱歉,没有找到相关信息。")sources = res.json().get("sources", [])st.markdown("### 💡 回答:")st.write(answer)st.markdown("### 📚 来源参考:")for src in sources:st.markdown(f"- [{src['title']}]({src['source']})")

运行前端:

streamlit run frontend.py

效果如下:

输入框:[请输入你要查询的问题]
按钮:[查询]
输出区域:显示答案 + 引用来源链接(点击可跳转)

六、实战案例研究


✅ 案例一:程序员专属知识库

1. 项目目标

打造一个属于程序员的知识管理系统,支持:

  • RSS 技术博客抓取(如 RealPython、掘金)
  • Markdown 笔记导入
  • 向量化存储 + Pinecone 检索
  • 基于 GPT 的问答与摘要生成
  • Streamlit 可视化界面

2. 项目结构
coder-knowledge-base/
│
├── data/                   # 存放抓取的文章和笔记
│   ├── rss_articles.json   # RSS 文章缓存
│   └── notes/              # 用户上传的 Markdown 文件
│
├── src/
│   ├── config.py           # 配置文件(API Key 等)
│   ├── fetchers/           # 数据采集模块
│   │   ├── rss_fetcher.py  # RSS 抓取
│   │   └── md_reader.py    # Markdown 导入
│   │
│   ├── vectorstore/        # 向量数据库操作
│   │   ├── pinecone_ops.py
│   │   └── embeddings.py
│   │
│   ├── llm/                # 大模型问答逻辑
│   │   └── qa_engine.py
│   │
│   └── app.py              # FastAPI 后端接口
│
├── frontend/               # Streamlit 前端
│   └── main.py
│
├── requirements.txt
└── README.md

3. 核心代码示例
📁 src/fetchers/rss_fetcher.py
import feedparser
import json
from datetime import datetimedef fetch_rss_feed(url, limit=5):feed = feedparser.parse(url)articles = []for entry in feed.entries[:limit]:article = {"title": entry.title,"source": url,"content": entry.summary,"timestamp": datetime.now().isoformat()}articles.append(article)return articles
📁 src/vectorstore/embeddings.py
from langchain.embeddings.openai import OpenAIEmbeddingsdef get_embeddings():return OpenAIEmbeddings(openai_api_key="YOUR_OPENAI_API_KEY")
📁 src/vectorstore/pinecone_ops.py
import pinecone
from uuid import uuid4def init_pinecone(index_name="coder-kb"):pinecone.init(api_key="YOUR_PINECONE_API_KEY", environment="us-west1-gcp")if index_name not in pinecone.list_indexes():pinecone.create_index(name=index_name, dimension=1536)return pinecone.Index(index_name)def insert_knowledge(index, knowledge_list, embeddings):vectors = []for doc in knowledge_list:vector = embeddings.embed_query(doc["content"])vectors.append((str(uuid4()),vector,{"text": doc["content"], "title": doc["title"], "source": doc["source"]}))index.upsert(vectors=vectors)
📁 src/llm/qa_engine.py
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplatedef answer_question(query, context):llm = ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_key="YOUR_OPENAI_API_KEY")prompt = PromptTemplate.from_template("""
请根据以下知识片段回答问题。如果有多条信息,请综合给出简明扼要的回答。知识片段:
{context}问题:
{question}回答:""")final_prompt = prompt.format(context=context, question=query)response = llm.predict(final_prompt)return response
📁 src/app.py (FastAPI 接口)
from fastapi import FastAPI
from pydantic import BaseModel
from src.vectorstore.pinecone_ops import init_pinecone, insert_knowledge
from src.vectorstore.embeddings import get_embeddings
from src.llm.qa_engine import answer_question
from src.fetchers.rss_fetcher import fetch_rss_feedapp = FastAPI()class QueryRequest(BaseModel):question: str@app.post("/query")
def query_knowledge(req: QueryRequest):index = init_pinecone()embeddings = get_embeddings()query_vector = embeddings.embed_query(req.question)result = index.query(queries=[query_vector], top_k=3, include_metadata=True)context = "\n".join([match['metadata']['text'] for match in result['matches']])answer = answer_question(req.question, context)sources = [match['metadata'] for match in result['matches']]return {"answer": answer, "sources": sources}
📁 frontend/main.py(Streamlit 前端)
import streamlit as st
import requestsst.set_page_config(page_title="程序员知识库助手")
st.title("🧠 程序员知识库问答系统")question = st.text_input("请输入你要查询的问题:")
if st.button("🔍 查询"):payload = {"question": question}res = requests.post("http://localhost:8000/query", json=payload)answer = res.json().get("answer", "抱歉,没有找到相关信息。")sources = res.json().get("sources", [])st.markdown("### 💡 回答:")st.write(answer)st.markdown("### 📚 来源参考:")for src in sources:st.markdown(f"- [{src['title']}]({src['source']})")

4. 部署说明
步骤 1:安装依赖
pip install -r requirements.txt
步骤 2:启动 FastAPI 后端
uvicorn src.app:app --reload

访问:http://localhost:8000/docs 查看 API 接口文档。

步骤 3:启动 Streamlit 前端

streamlit run frontend/main.py

✅ 案例二:医疗知识管理助手

1. 项目目标

为医生或研究人员打造一个医学知识管理系统,支持:

  • 微信公众号医学文章抓取
  • PDF 病历 OCR 提取
  • 医学术语词典匹配
  • LLM 自动分析症状与药物关系
  • Streamlit 展示卡片式病历摘要

2. 项目结构
medical-knowledge-base/
│
├── data/
│   ├── wx_gzh_data.json
│   └── patient_records/
│       └── *.pdf
│
├── src/
│   ├── config.py
│   ├── fetchers/
│   │   ├── wechat_fetcher.py
│   │   └── pdf_ocr_extractor.py
│   │
│   ├── vectorstore/
│   │   ├── pinecone_ops.py
│   │   └── embeddings.py
│   │
│   ├── llm/
│   │   └── medical_qa.py
│   │
│   └── app.py
│
├── frontend/
│   └── dashboard.py
│
├── requirements.txt
└── README.md

3. 核心代码示例
📁 src/fetchers/wechat_fetcher.py
import wechatsogou
from datetime import datetimedef fetch_wechat_medical(keyword):ws_api = wechatsogou.WechatSogouAPI()results = ws_api.get_gzh_article_by_keyword("丁香医生", keyword, number=5)articles = []for item in results:articles.append({"title": item["title"],"source": item["url"],"content": item["abstract"],"timestamp": datetime.now().isoformat()})return articles
📁 src/fetchers/pdf_ocr_extractor.py
from PIL import Image
import pytesseractdef extract_text_from_pdf(pdf_path):image = Image.open(pdf_path)text = pytesseract.image_to_string(image)return text
📁 src/llm/medical_qa.py
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplatedef analyze_medical_query(query, context):llm = ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_key="YOUR_OPENAI_API_KEY")prompt = PromptTemplate.from_template("""
你是一个医学助手,请基于以下资料回答问题:知识片段:
{context}问题:
{question}回答(请用中文):""")final_prompt = prompt.format(context=context, question=query)response = llm.predict(final_prompt)return response

4. 部署说明
安装依赖
pip install wechatsogou pytesseract langchain openai pinecone-client streamlit

注意:需要安装 Tesseract OCR 并配置环境变量(官网)

启动后端服务
uvicorn src.app:app --reload
启动前端界面
streamlit run frontend/dashboard.py

🧩 总结
功能程序员知识库医疗知识库
数据源RSS / Markdown微信公众号 / PDF
向量化LangChain + Pinecone同上
问答引擎GPT 生成解释GPT 医学推理
前端展示Streamlit 卡片Streamlit 病历摘要

📌 这两个案例展示了如何使用大模型和向量数据库构建个性化知识库,分别面向程序员和技术爱好者、医生和医学研究者。你可以根据自己的需求选择适合的数据源、模型和交互方式。


七、总结与扩展建议

当前系统优势:

✅ 多源数据采集能力
✅ 支持向量化存储与语义检索
✅ 利用 LLM 实现智能问答
✅ 支持知识卡片与来源引用展示

可扩展方向:

  1. 知识图谱构建思路

    • 使用 LLM 提取实体与关系;
    • 构建图数据库(Neo4j)关联知识点;
    • 支持推理路径(如:A引起B,B导致C);
  2. 自动化笔记整理与更新

    • 结合时间戳排序;
    • 设置定时任务自动拉取新内容;
    • 使用 Tag 分类 + 推荐系统;
  3. 本地模型替代方案

    • 替换为本地 embedding 模型(如 BERT、ChatGLM);
    • 使用 FAISS 替代 Pinecone 实现离线检索;
  4. 权限控制与协作功能

    • 不同用户组访问不同知识域;
    • 支持多人协作添加知识条目;
  5. 移动端适配

    • 构建 PWA 或小程序版本;
    • 支持语音输入提问;

📌 附录:推荐工具与资源

功能模块推荐工具/库
数据采集feedparser, WeChatSogou, requests
向量化LangChain + OpenAI / Sentence Transformers
向量数据库Pinecone, Milvus, FAISS
大模型问答OpenAI GPT, HuggingFace Transformers
前端展示Streamlit, React
数据展示Plotly, ECharts

📌 结语:通过本文的学习,你应该能够掌握如何搭建一个完整的个人知识库系统,涵盖数据采集、向量化、存储、检索与生成等关键环节。这套系统可以成为你终身学习的“外脑”,帮助你高效整理、检索与理解海量知识。

如果你喜欢这篇文章,欢迎点赞、收藏、转发,也欢迎关注我的专栏《AI大模型应知应会100篇》持续更新中 👇


如有疑问或需要定制开发,请留言或私信我,我们将持续为你提供高质量的人工智能内容。

相关文章:

  • Java 21 + Spring Boot 3.5:AI驱动的高性能框架实战
  • 【漫话机器学习系列】262.交叉项(Interaction Term)
  • 机器学习-特征工程
  • GD32 GPIO失控的解决方案
  • 【动态导通电阻】GaN HEMT动态导通电阻的精确测量
  • 每日Prompt:迷你 3D 建筑
  • 【leetcode】94. 二叉树的中序遍历
  • 【技术原理】ELK技术栈的历史沿革与技术演进
  • 《Elasticsearch 源码解析与优化实战》笔记
  • 前端面经 9 JS中的继承
  • FC7300 WDG MCAL 配置引导
  • kubernetes的service与服务发现
  • 矩阵转置的LATEX写法
  • Spring Cloud深度实践:从服务发现到弹性智能API网关全景解析
  • import pywinauto后tkinter.filedialog.askdirectory()无法调用,直接卡死,应如何解决
  • 基于Matlab实现图像透明叠加程序
  • LED接口设计
  • 物联网设备远程管理:基于代理IP的安全固件更新通道方案
  • ChatGPT到Claude全适配:跨模型Prompt高级设计规范与迁移技巧
  • Python连接redis
  • 篮球培训机构东方启明星被指停摆,家长称已登记未退费用超百万
  • 中国物流集团等10家央企11名领导人员职务任免
  • 英德宣布开发射程超2000公里导弹,以防务合作加强安全、促进经济
  • 宜昌谱写新叙事:长江大保护与高质量发展如何相互成就
  • 博柏利上财年营收下降17%,计划裁员1700人助推股价涨超18%
  • 中欧金融工作组第二次会议在比利时布鲁塞尔举行