Langchain-Chatchat icon indicating copy to clipboard operation
Langchain-Chatchat copied to clipboard

现在在上传文件到知识库的时候想对文件进行标记,该如何做呢?

Open 302658980 opened this issue 1 year ago • 2 comments

想法是:对于同一个知识库,团队A 只能访问 标记为A的文件,团队B只能访问标记为B的文件。知识库回答部分

302658980 avatar Mar 27 '24 08:03 302658980

嘿,@302658980!很高兴再次见到你。看来你又有新的挑战需要克服了呢!🚀

在Langchain-Chatchat中,文件标记功能是通过文件的元数据来实现的。具体来说,当你上传一个文件到知识库时,可以通过add_doc方法来添加文件的元数据,这可以被视为一种标记。这个方法在KBService类中定义,负责将文档添加到知识库,并处理文档的元数据。如果提供了文档列表(docs),则不再将文本向量化,并将数据库对应条目标为custom_docs=True。如果没有提供docs,则将文件内容转换为文本并处理。此外,它还会调整metadata["source"]以存储源文件的相对路径,这可以被视为一种通过指示文档来源的标记。

相关代码片段如下:

def add_doc(self, kb_file: KnowledgeFile, docs: List[Document] = [], **kwargs):
    """
    向知识库添加文件
    如果指定了docs,则不再将文本向量化,并将数据库对应条目标为custom_docs=True
    """
    if docs:
        custom_docs = True
        for doc in docs:
            doc.metadata.setdefault("source", kb_file.filename)
    else:
        docs = kb_file.file2text()
        custom_docs = False
    if docs:
        # 将 metadata["source"] 改为相对路径
        for doc in docs:
            try:
                source = doc.metadata.get("source", "")
                if os.path.isabs(source):
                    rel_path = Path(source).relative_to(self.doc_path)
                    doc.metadata["source"] = str(rel_path.as_posix().strip("/"))
            except Exception as e:
                print(f"cannot convert absolute path ({source}) to relative path. error is : {e}")
        self.delete_doc(kb_file)
        doc_infos = self.do_add_doc(docs, **kwargs)
        status = add_file_to_db(kb_file,
                                custom_docs=custom_docs,
                                docs_count=len(docs),
                                doc_infos=doc_infos)
    else:
        status = False
    return status

源代码链接:server/knowledge_base/kb_service/base.py

关于基于元数据的访问限制,list_summary_from_db方法可以根据提供的元数据字典过滤数据库中的摘要。过滤过程是通过以下循环完成的:

for k, v in metadata.items():
    docs = docs.filter(SummaryChunkModel.meta_data[k].as_string() == str(v))

源代码链接:server/db/repository/knowledge_metadata_repository.py

因此,你可以通过在上传文件时添加元数据来标记文件,然后通过元数据来限制对文件的访问。例如,你可以为团队A的文件添加元数据{"team": "A"},然后在查询时只返回元数据中包含{"team": "A"}的文件。

Sources

About Dosu

This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

If you want to continue the conversation, start your reply with @dosu-bot.

dosubot[bot] avatar Mar 27 '24 08:03 dosubot[bot]

这个问题已经被标记为 stale ,因为它已经超过 30 天没有任何活动。

github-actions[bot] avatar Apr 26 '24 21:04 github-actions[bot]

没有做这个功能

zRzRzRzRzRzRzR avatar May 07 '24 02:05 zRzRzRzRzRzRzR

可以自己封装一层api做权限控制

804e avatar May 16 '24 06:05 804e