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

相关推荐
whcyhhh2 分钟前
头歌实践教学平台:大数据存储2023(六)
大数据·数据库·python
Elastic 中国社区官方博客1 小时前
让大模型思考,让小模型执行:在 Elastic Workflows 中拆分 LLM 成本
大数据·运维·数据库·人工智能·elasticsearch·ai
Faith_xzc2 小时前
一条 SQL 顶一条 Flink 链路?Doris Streaming Job 持续导入全景解析
大数据·数据库·sql·flink
这个DBA有点耶4 小时前
多模数据库深度解读:从“多库拼装”到“一库多能”的架构演进
数据库·mysql·dba
程序员夏洛5 小时前
MySQL 默认的事务隔离级别是什么?为什么选择这个级别?
数据库·mysql
艺术留白5 小时前
MokaTest使用篇-SQL接口
数据库·sql
艾醒(AiXing-w)5 小时前
LangChain 1.0 入门(三):稳定性双核心——重试机制+速率限速器参数详解与实战
开发语言·langchain·php
( •̀∀•́ )9206 小时前
MySQL 自动备份与恢复方案
数据库·mysql·oracle
未若君雅裁6 小时前
从函数到工具,LangChain Tools 与 Tool Calling 完整入门
langchain
这个DBA有点耶6 小时前
大事务的“事前预防”:监控、拦截、Kill,四层防线一次讲透
数据库·mysql·代码规范