lyf-modular-rag 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ """lyf-modular-rag:模块化 RAG 工具包(读取 → 切分 → 检索 → 拼提示词 + FastAPI 封装)。
2
+
3
+ 课程作业打包版本,安装后可直接复用:
4
+ pip install lyf-modular-rag
5
+ """
6
+
7
+ from .utils import build_prompt, read_document, retrieve_answer, split_document
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = [
11
+ "read_document",
12
+ "split_document",
13
+ "retrieve_answer",
14
+ "build_prompt",
15
+ "create_app",
16
+ ]
17
+
18
+
19
+ def create_app(*args, **kwargs):
20
+ """延迟导入 FastAPI 应用工厂,避免未装 web 依赖时 import 失败。"""
21
+ from .app import create_app as _create_app
22
+
23
+ return _create_app(*args, **kwargs)
lyf_modular_rag/app.py ADDED
@@ -0,0 +1,107 @@
1
+ """可复用的 FastAPI 应用:离线建库 + 在线问答。
2
+
3
+ 对应课程 rag/main.py,改成工厂函数 create_app():
4
+ - API Key、模型名、持久化目录全部走环境变量,绝不写死在代码里
5
+ - 依赖在函数内部导入,未装 fastapi / chroma 时不影响包的其他部分
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ import uuid
13
+
14
+ from .utils import build_prompt, read_document, retrieve_answer, split_document
15
+
16
+
17
+ def create_app(
18
+ collection_name: str = "my_knowledge_base",
19
+ persist_directory: str = "./chroma_db",
20
+ embedding_model: str = "text-embedding-v4",
21
+ chat_model: str = "qwen-plus",
22
+ upload_temp_dir: str = "./temp_upload",
23
+ ):
24
+ """创建并返回一个 FastAPI 应用实例。
25
+
26
+ :param collection_name: Chroma 集合名(一个知识库一个集合)
27
+ :param persist_directory: 向量库持久化目录
28
+ :param embedding_model: 向量模型名
29
+ :param chat_model: 对话模型名
30
+ :param upload_temp_dir: 上传文件的临时目录
31
+ """
32
+ from fastapi import Body, FastAPI, File, UploadFile
33
+ from fastapi.openapi.docs import get_swagger_ui_html
34
+ from langchain_chroma import Chroma
35
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
36
+
37
+ api_key = os.getenv("DASHSCOPE_API_KEY")
38
+ if not api_key:
39
+ raise RuntimeError("请先设置环境变量 DASHSCOPE_API_KEY")
40
+ base_url = os.getenv("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
41
+
42
+ embeddings = OpenAIEmbeddings(
43
+ model=embedding_model,
44
+ api_key=api_key,
45
+ base_url=base_url,
46
+ dimensions=1024,
47
+ check_embedding_ctx_length=False,
48
+ )
49
+ db = Chroma(
50
+ collection_name=collection_name,
51
+ embedding_function=embeddings,
52
+ persist_directory=persist_directory,
53
+ )
54
+ retriever = db.as_retriever(
55
+ search_type="similarity_score_threshold",
56
+ search_kwargs={"score_threshold": 0.4, "k": 4},
57
+ )
58
+ llm = ChatOpenAI(model=chat_model, api_key=api_key, base_url=base_url, temperature=0.3)
59
+
60
+ app = FastAPI(docs_url=None)
61
+
62
+ @app.get("/docs", include_in_schema=False)
63
+ async def custom_swagger_ui_html():
64
+ return get_swagger_ui_html(
65
+ openapi_url=app.openapi_url,
66
+ title=app.title + " - Swagger UI",
67
+ swagger_js_url="https://cdn.staticfile.org/swagger-ui/5.11.0/swagger-ui-bundle.min.js",
68
+ swagger_css_url="https://cdn.staticfile.org/swagger-ui/5.11.0/swagger-ui.min.css",
69
+ )
70
+
71
+ @app.post("/get_vec")
72
+ async def get_vec(file: UploadFile = File(...)):
73
+ os.makedirs(upload_temp_dir, exist_ok=True)
74
+ file_path = os.path.join(upload_temp_dir, file.filename)
75
+ with open(file_path, "wb") as buffer:
76
+ shutil.copyfileobj(file.file, buffer)
77
+ try:
78
+ documents = read_document(file_path)
79
+ chunks = split_document(documents)
80
+ ids = [str(uuid.uuid4()) for _ in range(len(chunks))]
81
+ db.add_documents(documents=chunks, ids=ids)
82
+ return {"code": 200, "message": f"成功入库 {len(chunks)} 个文档片段"}
83
+ except Exception as exc:
84
+ return {"code": 500, "message": f"入库失败: {exc}"}
85
+ finally:
86
+ if os.path.exists(file_path):
87
+ os.remove(file_path)
88
+
89
+ @app.post("/get_answer")
90
+ async def get_answer(question: str = Body(..., embed=True, description="用户问题")):
91
+ try:
92
+ docs_with_scores = retrieve_answer(question, retriever)
93
+ final_prompt = build_prompt(docs_with_scores, question)
94
+ response = llm.invoke(final_prompt)
95
+ return {
96
+ "code": 200,
97
+ "question": question,
98
+ "answer": response.content,
99
+ "retrieved_chunks": [
100
+ {"content": doc.page_content, "score": round(score, 4)}
101
+ for doc, score in docs_with_scores
102
+ ],
103
+ }
104
+ except Exception as exc:
105
+ return {"code": 500, "message": f"回答失败: {exc}"}
106
+
107
+ return app
File without changes
@@ -0,0 +1,82 @@
1
+ """模块化 RAG 工具函数:读取、切分、检索、拼提示词。
2
+
3
+ 对应课程 rag/utils.py,改成可发布的包内模块:
4
+ 所有第三方依赖都在函数内部延迟导入,未装 langchain 时也能 import 本包。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, List, Tuple
10
+
11
+
12
+ def read_document(file_path: str) -> List[Any]:
13
+ """读取 PDF 或 TXT 文档,返回 Document 列表。
14
+
15
+ :param file_path: 文件路径,支持 .pdf / .txt
16
+ """
17
+ if file_path.endswith(".pdf"):
18
+ from langchain_community.document_loaders import PyPDFLoader
19
+
20
+ loader = PyPDFLoader(file_path)
21
+ elif file_path.endswith(".txt"):
22
+ from langchain_community.document_loaders import TextLoader
23
+
24
+ loader = TextLoader(file_path, encoding="utf-8")
25
+ else:
26
+ raise ValueError("只支持 PDF 或 TXT 文件")
27
+ return loader.load()
28
+
29
+
30
+ def split_document(documents: List[Any], chunk_size: int = 500, chunk_overlap: int = 50) -> List[Any]:
31
+ """把长文档切分成适合放进大模型上下文的小块。
32
+
33
+ :param documents: read_document 返回的 Document 列表
34
+ :param chunk_size: 每块最大长度
35
+ :param chunk_overlap: 相邻块的重叠长度,防止语义被截断
36
+ """
37
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
38
+
39
+ splitter = RecursiveCharacterTextSplitter(
40
+ chunk_size=chunk_size,
41
+ chunk_overlap=chunk_overlap,
42
+ length_function=len,
43
+ )
44
+ return splitter.split_documents(documents)
45
+
46
+
47
+ def retrieve_answer(query: str, retriever: Any, k: int = 4) -> List[Tuple[Any, float]]:
48
+ """调用检索器,返回 (Document, 相关性分数) 的元组列表。
49
+
50
+ :param query: 用户问题
51
+ :param retriever: 带分数的检索器(similarity_score_threshold)
52
+ :param k: 召回条数
53
+ """
54
+ return retriever.vectorstore.similarity_search_with_relevance_scores(query, k=k)
55
+
56
+
57
+ def build_prompt(
58
+ docs_with_scores: List[Tuple[Any, float]],
59
+ query: str,
60
+ score_threshold: float = 0.4,
61
+ system_tip: str = "你是一个智能导购助手。请根据以下参考资料回答用户的问题。如果参考资料中没有相关信息,请如实告知,不要编造。",
62
+ ) -> str:
63
+ """把检索结果拼成最终提示词;无命中时直接返回原问题。
64
+
65
+ :param docs_with_scores: retrieve_answer 的返回值
66
+ :param query: 用户问题
67
+ :param score_threshold: 低于该分数视为不相关
68
+ :param system_tip: 系统提示语
69
+ """
70
+ filtered_docs = [doc.page_content for doc, score in docs_with_scores if score >= score_threshold]
71
+
72
+ if not filtered_docs:
73
+ return query
74
+
75
+ context = "\n\n".join(filtered_docs)
76
+ return f"""{system_tip}
77
+
78
+ 参考资料:
79
+ {context}
80
+
81
+ 用户问题:{query}
82
+ """
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: lyf-modular-rag
3
+ Version: 0.1.0
4
+ Summary: 模块化 RAG 工具包:文档读取、切分、检索、提示词拼接与 FastAPI 封装
5
+ Author: linyifan
6
+ License: MIT
7
+ Project-URL: Homepage, https://pypi.org/project/lyf-modular-rag/
8
+ Project-URL: Repository, https://pypi.org/project/lyf-modular-rag/
9
+ Keywords: rag,llm,langchain,chroma,fastapi,knowledge-base
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: langchain-community>=0.3
20
+ Requires-Dist: langchain-text-splitters>=0.3
21
+ Requires-Dist: langchain-core>=0.3
22
+ Requires-Dist: langchain-openai>=0.2
23
+ Requires-Dist: langchain-chroma>=0.2
24
+ Requires-Dist: chromadb>=0.5
25
+ Requires-Dist: fastapi>=0.110
26
+ Requires-Dist: uvicorn>=0.29
27
+ Dynamic: license-file
28
+
29
+ # lyf-modular-rag
30
+
31
+ 模块化 RAG 工具包:**读取 → 切分 → 检索 → 拼提示词**,并提供一套可直接复用的 FastAPI 接口(离线建库 / 在线问答)。
32
+
33
+ 把《大模型应用 RAG》课程里的 `utils.py` + `main.py` 拆成标准 pip 包,任何项目 `pip install` 后即可复用,不用再复制粘贴代码。
34
+
35
+ ## 安装
36
+
37
+ ```bash
38
+ pip install lyf-modular-rag
39
+ ```
40
+
41
+ ## 快速开始
42
+
43
+ ```python
44
+ from lyf_modular_rag import read_document, split_document, retrieve_answer, build_prompt
45
+
46
+ docs = read_document("./data/课程讲义.pdf") # 支持 pdf / txt
47
+ chunks = split_document(docs, chunk_size=500, chunk_overlap=50)
48
+ ```
49
+
50
+ 四步串起来(离线存储 → 在线检索):
51
+
52
+ ```python
53
+ import os, uuid
54
+ from langchain_chroma import Chroma
55
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
56
+ from lyf_modular_rag import read_document, split_document, retrieve_answer, build_prompt
57
+
58
+ os.environ["DASHSCOPE_API_KEY"] = "你的 key" # 不要写进代码仓库
59
+
60
+ emb = OpenAIEmbeddings(
61
+ model="text-embedding-v4",
62
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
63
+ dimensions=1024,
64
+ check_embedding_ctx_length=False,
65
+ )
66
+ db = Chroma(collection_name="my_knowledge_base", embedding_function=emb, persist_directory="./chroma_db")
67
+
68
+ # 1 离线:读取 → 切分 → 入库
69
+ chunks = split_document(read_document("./data/讲义.pdf"))
70
+ db.add_documents(documents=chunks, ids=[str(uuid.uuid4()) for _ in chunks])
71
+
72
+ # 2 在线:召回 → 拼提示词 → 生成
73
+ retriever = db.as_retriever(search_type="similarity_score_threshold",
74
+ search_kwargs={"score_threshold": 0.4, "k": 4})
75
+ docs_with_scores = retrieve_answer("课程讲了什么?", retriever)
76
+ prompt = build_prompt(docs_with_scores, "课程讲了什么?")
77
+ llm = ChatOpenAI(model="qwen-plus", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", temperature=0.3)
78
+ print(llm.invoke(prompt).content)
79
+ ```
80
+
81
+ ## 起一套接口
82
+
83
+ ```python
84
+ from lyf_modular_rag import create_app
85
+ app = create_app(collection_name="my_knowledge_base", persist_directory="./chroma_db")
86
+ ```
87
+
88
+ ```bash
89
+ export DASHSCOPE_API_KEY=你的key
90
+ uvicorn your_module:app --reload --port 8000
91
+ ```
92
+
93
+ | 接口 | 方法 | 说明 |
94
+ | --- | --- | --- |
95
+ | `/get_vec` | POST | 上传 pdf/txt,读取 → 切分 → 向量入库 |
96
+ | `/get_answer` | POST | 传 `{"question": "..."}`,召回 → 拼提示词 → 大模型回答 |
97
+ | `/docs` | GET | 自定义 Swagger UI(国内 CDN) |
98
+
99
+ ## 接口与函数一览
100
+
101
+ | 函数 | 作用 | 关键参数 |
102
+ | --- | --- | --- |
103
+ | `read_document` | 读取 PDF / TXT | `file_path` |
104
+ | `split_document` | 递归字符切分 | `chunk_size`、`chunk_overlap` |
105
+ | `retrieve_answer` | 带分数的相似度召回 | `query`、`retriever`、`k` |
106
+ | `build_prompt` | 过滤低分片段并拼提示词 | `score_threshold`、`system_tip` |
107
+ | `create_app` | 生成 FastAPI 应用 | `collection_name`、`persist_directory` |
108
+
109
+ ## 说明
110
+
111
+ - 所有第三方依赖都在函数内部延迟导入,未装 langchain 时 `import lyf_modular_rag` 也不会报错。
112
+ - API Key 一律通过环境变量 `DASHSCOPE_API_KEY` 读取,代码中没有硬编码密钥。
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,9 @@
1
+ lyf_modular_rag/__init__.py,sha256=TYWoTeYS0YJK0eS4nmu3X-kh9hbR92D0kRorW8UITTc,643
2
+ lyf_modular_rag/app.py,sha256=lIW6Knl5UMec8TvIK3x7zju7IQ-8MhdI6zdbvvBxy-A,4099
3
+ lyf_modular_rag/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ lyf_modular_rag/utils.py,sha256=rxPB_30aSQmjd0jEelwRkdj6j6RoFyHKlOGdi7Tuy8Q,2786
5
+ lyf_modular_rag-0.1.0.dist-info/licenses/LICENSE,sha256=hWSLaTqhoGl3OOXufeK5FqQ6-_oM9K1QJMHh7d1sdGM,1065
6
+ lyf_modular_rag-0.1.0.dist-info/METADATA,sha256=1Sa7CUEWtGMY26yrpPz1hFU3TrJKE1AaJM96bLLPy14,4362
7
+ lyf_modular_rag-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ lyf_modular_rag-0.1.0.dist-info/top_level.txt,sha256=L-g2NbnU5JLu9oNLUB1gj6Ja7mLAfoMjjRLNNH0BKz8,16
9
+ lyf_modular_rag-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 linyifan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ lyf_modular_rag