Lightrag1.0.3代码解读
Lightrag1.0.3代码解读
文件链接:Release v1.0.3 · HKUDS/LightRAG
主要分初始化、插入、提问三部分
初始化
插入
插入:rag.insert()异步编程调用ainsert()
ainsert内的各步操作
- 文章处理
- 文本块处理
- 实体关系抽取
- 更新各存储区
文章处理
| |
文本块处理
| |
实体关系抽取
分为 外部 和 extract_entities函数内部
外部
| |
extract_entities函数内部
| |
_process_single_content函数内部
| |
更新各存储区
kv_store_doc_status.json
kv_store_full_docs.json
kv_store_Ilm_response_cache.json
kv_store_text_chunks.json
vdb_chunks.json
vdb_entities.json
vdb_relationships.json
chunk_overlap_token_size
chunk_overlap_token_size: int = 100 # vdb存储,以存实体数据为例
| |
entity_vdb 为 NanoVectorDBStorage类(storage.py) 的实例化
其 .upsert方法如下:
| |
提问(Query)
rag.query->self.aquery
aquery内 分四种模式,naive 和 local global hybrid
naive进入 naive_query 其他三种进入kg_query
| |
naive(朴素)
直接将query_vector和chunk_vector匹配。
- 将提问str转为vector,然后再chunks_vdb中匹配到“cosine_better_than_threshold”的前60十个chunk_id(如果能匹配到超过60个低于阈值的)
- 然后根据 chunk_id去 text_chunks_db里找到strs
- 最后将strs嵌入prompt输入LLM 也就是直接将与问句相似的chunks作为辅助数据让ai回答问题,相似性通过NanoVectorDB提供的向量邻近,本质上还是由embedding决定
| |
local、global and hybrid
(局部)(全局)(混合)
| |
-----Relationships-----
```csv
{relations_context}
```
-----Sources-----
```csv
{text_units_context}
```
"""
# 包含了实体、关系、相关chunks
context = await _build_query_context(
keywords,
knowledge_graph_inst,
entities_vdb,
relationships_vdb,
text_chunks_db,
query_param,
)
if query_param.only_need_context:
return context
if context is None:
return PROMPTS["fail_response"]
sys_prompt_temp = PROMPTS["rag_response"]
sys_prompt = sys_prompt_temp.format(
context_data=context, response_type=query_param.response_type
)
if query_param.only_need_prompt:
return sys_prompt
response = await use_model_func(
query,
system_prompt=sys_prompt,
)
if len(response) > len(sys_prompt):
response = (
response.replace(sys_prompt, "")
.replace("user", "")
.replace("model", "")
.replace(query, "")
.replace("<system>", "")
.replace("</system>", "")
.strip()
)
return response
最后更新于