langchain Chroma 构建本地向量数据库

langchain Chroma 构建本地向量数据库

python 复制代码
# import
from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings.sentence_transformer import (
    SentenceTransformerEmbeddings,
)
from langchain_community.embeddings import HuggingFaceEmbeddings 
from langchain_community.vectorstores import Chroma
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders.word_document import Docx2txtLoader

import glob
import os

# 数据库路径
db_dir = "./db"
# 文档路径
source_directory = "./docs"
# 文件后缀
file_ext = '*.docx'

# create the open-source embedding function
# embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
# 使用中文嵌入层编码器
ebd_function = HuggingFaceEmbeddings(model_name="shibing624/text2vec-base-chinese")

def add_files_to_db(filepath:str="",file_ext:str=""):
    docx_files = glob.glob(os.path.join(source_directory, file_ext))
    text_list=[]
    for file_name in docx_files:
        print(file_name)
        loader = Docx2txtLoader(file_name)
        documents = loader.load()
        text_list.extend(documents)

    # split it into chunks
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
    docs = text_splitter.split_documents(text_list)

    # load it into Chroma
    db = Chroma.from_documents(docs, ebd_function, persist_directory=db_dir)
    # save db to disk
    db.persist()


def query_db(db:Chroma,query:str=""):

    # query it
    docs = db.similarity_search(query)

    # print results
    print(docs[0].page_content)
    print("-----------------------------------------")


    
 
if __name__=="__main__":

    # 只需执行一次
    # add_files_to_db(source_directory,file_ext)

    db = Chroma(persist_directory=db_dir,embedding_function=ebd_function)
    query = "怎么治疗骨质疏松症?"
    query_db(db,query)
    query = "怎么治疗鼻炎?"
    query_db(db,query)
    db = None
    pass

文档在当前代码目录下

./docs/第十六章-感染性疾病.docx

./docs/第八章-骨骼关节和肌肉疾病.docx

./docs/第十九章-耳鼻咽喉疾病.docx

相关推荐
夏玉林的学习之路32 分钟前
正则表达式
数据库·c++·qt·mysql·正则表达式
JIngJaneIL1 小时前
财务管理|基于SprinBoot+vue的个人财务管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·财务管理系统
JIngJaneIL2 小时前
口腔健康系统|口腔医疗|基于java和小程序的口腔健康系统小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·口腔医疗小程序
白帽子黑客罗哥2 小时前
常见Web安全漏洞全解析:从原理到防御的实战指南
数据库·web安全·渗透测试·漏洞利用·权限提升
寒山李白4 小时前
IDEA连接MySQL服务器数据库指南
java·数据库·mysql·intellij-idea·idea·database
亿坊电商7 小时前
PHP后端项目中多环境配置管理:开发、测试、生产的优雅解决方案!
服务器·数据库·php
韩立学长7 小时前
基于Springboot的影视评论网站的设计与实现58py6238(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
未来之窗软件服务7 小时前
未来之窗昭和仙君(四十七)开发商品进销存——东方仙盟筑基期
数据库·进销存·仙盟创梦ide·东方仙盟·昭和仙君·东方仙盟架构
IDOlaoluo8 小时前
TinyRDM 1.2.3 Windows版安装教程(附Redis客户端下载及详细步骤)
数据库·redis·缓存
小光学长9 小时前
基于微信小程序的背单词系统x1o5sz72(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·微信小程序·小程序