"""使用Qwen3-VL、通义文本向量和Qwen Plus构建可追溯的PDF RAG。""" from __future__ import annotations import argparse import base64 import hashlib import json import math import os import time from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable import pymupdf from jsonschema import validate from openai import OpenAI ROOT = Path(__file__).resolve().parent DEFAULT_INDEX = ROOT / "pdf-rag-index.json" BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1" VISION_MODEL = "qwen3-vl-plus" EMBEDDING_MODEL = "text-embedding-v4" ANSWER_MODEL = "qwen-plus" EMBEDDING_DIMENSIONS = 1024 MAX_PDF_BYTES = 30 * 1024 * 1024 MAX_PAGES = 100 ANSWER_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "answer": {"type": "string", "minLength": 1, "maxLength": 2000}, "citations": { "type": "array", "maxItems": 8, "items": { "type": "object", "properties": { "page": {"type": "integer", "minimum": 1}, "reason": {"type": "string", "minLength": 1, "maxLength": 200}, }, "required": ["page", "reason"], "additionalProperties": False, }, }, "insufficient_evidence": {"type": "boolean"}, }, "required": ["answer", "citations", "insufficient_evidence"], "additionalProperties": False, } @dataclass(frozen=True) class PageContent: page: int text: str visual_description: str def create_client() -> OpenAI: """创建百炼OpenAI兼容客户端,API Key只从环境变量读取。""" api_key = os.environ.get("DASHSCOPE_API_KEY", "").strip() if not api_key: raise RuntimeError("请先设置环境变量 DASHSCOPE_API_KEY") return OpenAI(api_key=api_key, base_url=BASE_URL, timeout=180) def usage_dict(response: Any) -> dict[str, int]: usage = getattr(response, "usage", None) return { "prompt_tokens": int(getattr(usage, "prompt_tokens", 0) or 0), "completion_tokens": int(getattr(usage, "completion_tokens", 0) or 0), "total_tokens": int(getattr(usage, "total_tokens", 0) or 0), } def parse_json_object(content: str) -> dict[str, Any]: """兼容模型偶尔返回的Markdown代码围栏,并限制顶层必须是对象。""" text = content.strip() if text.startswith("```"): lines = text.splitlines() text = "\n".join(lines[1:-1]).strip() value = json.loads(text) if not isinstance(value, dict): raise ValueError("模型输出的JSON顶层必须是对象") return value def normalize_pdf_path(pdf_path: str | Path) -> Path: path = Path(pdf_path).expanduser().resolve() if not path.is_file() or path.suffix.lower() != ".pdf": raise ValueError("请输入存在的PDF文件") if path.stat().st_size > MAX_PDF_BYTES: raise ValueError("示例项目限制PDF不能超过30MB") return path def image_data_url(png_bytes: bytes) -> str: return "data:image/png;base64," + base64.b64encode(png_bytes).decode("ascii") def describe_page_image(client: OpenAI, page: pymupdf.Page, page_number: int) -> tuple[str, dict[str, Any]]: """渲染PDF页面并让视觉模型描述表格、图表和版面中的关键事实。""" started = time.perf_counter() pixmap = page.get_pixmap(matrix=pymupdf.Matrix(1.5, 1.5), alpha=False) response = client.chat.completions.create( model=VISION_MODEL, temperature=0.1, messages=[ { "role": "system", "content": ( "你是PDF页面视觉解析器。只记录页面中可见的标题、表格、图表、流程、" "数值及其关系;不要补充页面之外的知识。输出简体中文纯文本,数值必须保留单位。" ), }, { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": image_data_url(pixmap.tobytes("png"))}}, {"type": "text", "text": f"这是PDF第{page_number}页。请提取可用于检索和问答的视觉信息。"}, ], }, ], ) return (response.choices[0].message.content or "").strip(), { "model": VISION_MODEL, "elapsed_seconds": round(time.perf_counter() - started, 3), "usage": usage_dict(response), } def extract_pages(client: OpenAI, pdf_path: str | Path, use_vision: bool = True) -> tuple[list[PageContent], list[dict[str, Any]]]: """按页保留文本和视觉描述,页码在整个RAG链路中不丢失。""" path = normalize_pdf_path(pdf_path) document = pymupdf.open(path) if document.page_count == 0 or document.page_count > MAX_PAGES: document.close() raise ValueError(f"PDF页数必须在1至{MAX_PAGES}页之间") pages: list[PageContent] = [] vision_runs: list[dict[str, Any]] = [] try: for index, page in enumerate(document): text = page.get_text("text", sort=True).strip() visual = "" if use_vision: visual, metadata = describe_page_image(client, page, index + 1) vision_runs.append({"page": index + 1, **metadata}) pages.append(PageContent(page=index + 1, text=text, visual_description=visual)) finally: document.close() return pages, vision_runs def chunk_text(text: str, max_characters: int = 1400, overlap: int = 180) -> list[str]: """以段落为边界分块;超长段落再按字符切分并保留重叠。""" normalized = "\n".join(line.strip() for line in text.splitlines() if line.strip()) if not normalized: return [] paragraphs = normalized.split("\n") chunks: list[str] = [] current = "" for paragraph in paragraphs: candidate = f"{current}\n{paragraph}".strip() if len(candidate) <= max_characters: current = candidate continue if current: chunks.append(current) current = "" if len(paragraph) <= max_characters: current = paragraph continue step = max_characters - overlap chunks.extend(paragraph[start:start + max_characters] for start in range(0, len(paragraph), step)) if current: chunks.append(current) return chunks def page_chunks(page: PageContent) -> list[dict[str, Any]]: """融合文字与视觉描述,并把页码作为不可变元数据写入每个分块。""" combined = f"页面文本:\n{page.text or '未提取到文字'}\n\n视觉描述:\n{page.visual_description or '未启用视觉解析'}" return [ {"page": page.page, "chunk_index": index, "content": content} for index, content in enumerate(chunk_text(combined)) ] def batches(values: list[str], size: int = 10) -> Iterable[list[str]]: for start in range(0, len(values), size): yield values[start:start + size] def embed_texts(client: OpenAI, texts: list[str]) -> tuple[list[list[float]], list[dict[str, Any]]]: """分批调用通义文本向量,避免长文档一次请求过大。""" if not texts or any(not value.strip() for value in texts): raise ValueError("待向量化文本不能为空") vectors: list[list[float]] = [] runs: list[dict[str, Any]] = [] for group in batches(texts): started = time.perf_counter() response = client.embeddings.create( model=EMBEDDING_MODEL, input=group, dimensions=EMBEDDING_DIMENSIONS, ) ordered = sorted(response.data, key=lambda item: item.index) vectors.extend([item.embedding for item in ordered]) runs.append({ "model": EMBEDDING_MODEL, "items": len(group), "elapsed_seconds": round(time.perf_counter() - started, 3), "usage": usage_dict(response), }) return vectors, runs def build_index( client: OpenAI, pdf_path: str | Path, index_path: str | Path = DEFAULT_INDEX, use_vision: bool = True, ) -> dict[str, Any]: """完成PDF解析、视觉补充、分块和向量化,并原子写入索引文件。""" path = normalize_pdf_path(pdf_path) pages, vision_runs = extract_pages(client, path, use_vision=use_vision) chunks = [chunk for page in pages for chunk in page_chunks(page)] vectors, embedding_runs = embed_texts(client, [chunk["content"] for chunk in chunks]) for chunk, vector in zip(chunks, vectors, strict=True): chunk["embedding"] = vector index = { "schema_version": 1, "source": { "name": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "pages": len(pages), }, "models": { "vision": VISION_MODEL if use_vision else None, "embedding": EMBEDDING_MODEL, "answer": ANSWER_MODEL, }, "chunks": chunks, "build_metadata": {"vision_runs": vision_runs, "embedding_runs": embedding_runs}, } destination = Path(index_path).resolve() destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_suffix(destination.suffix + ".tmp") temporary.write_text(json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8") temporary.replace(destination) return index def cosine_similarity(left: list[float], right: list[float]) -> float: if len(left) != len(right) or not left: raise ValueError("向量维度不一致或为空") numerator = sum(a * b for a, b in zip(left, right, strict=True)) left_norm = math.sqrt(sum(value * value for value in left)) right_norm = math.sqrt(sum(value * value for value in right)) if not left_norm or not right_norm: return 0.0 return numerator / (left_norm * right_norm) def load_index(index_path: str | Path = DEFAULT_INDEX) -> dict[str, Any]: path = Path(index_path).resolve() value = json.loads(path.read_text(encoding="utf-8")) if value.get("schema_version") != 1 or not value.get("chunks"): raise ValueError("索引文件格式不正确或没有分块") return value def retrieve(client: OpenAI, index: dict[str, Any], question: str, top_k: int = 4) -> tuple[list[dict[str, Any]], dict[str, Any]]: if not question.strip(): raise ValueError("问题不能为空") vectors, runs = embed_texts(client, [question.strip()]) scored = [ {**chunk, "score": cosine_similarity(vectors[0], chunk["embedding"])} for chunk in index["chunks"] ] scored.sort(key=lambda item: item["score"], reverse=True) evidence = [ {key: value for key, value in item.items() if key != "embedding"} for item in scored[:max(1, min(top_k, 8))] ] return evidence, runs[0] def answer_question( client: OpenAI, question: str, index_path: str | Path = DEFAULT_INDEX, top_k: int = 4, ) -> dict[str, Any]: """检索证据后生成结构化答案,并拒绝模型引用未检索到的页码。""" index = load_index(index_path) evidence, retrieval_run = retrieve(client, index, question, top_k=top_k) evidence_text = "\n\n".join( f"[证据{number}|第{item['page']}页|相似度{item['score']:.4f}]\n{item['content']}" for number, item in enumerate(evidence, start=1) ) started = time.perf_counter() response = client.chat.completions.create( model=ANSWER_MODEL, temperature=0.1, response_format={"type": "json_object"}, messages=[ { "role": "system", "content": ( "你是企业PDF问答助手。只能使用用户提供的检索证据回答。" "证据不足时明确说明,并将insufficient_evidence设为true。" "输出JSON对象,字段为answer、citations、insufficient_evidence;" "citations中的每项只含page和reason,禁止引用证据之外的页码。" ), }, {"role": "user", "content": f"问题:{question}\n\n可用证据:\n{evidence_text}"}, ], ) result = parse_json_object(response.choices[0].message.content or "") validate(instance=result, schema=ANSWER_SCHEMA) allowed_pages = {item["page"] for item in evidence} cited_pages = {item["page"] for item in result["citations"]} if not cited_pages.issubset(allowed_pages): raise ValueError("模型返回了未检索到的页码引用") return { **result, "source": index["source"]["name"], "evidence": evidence, "metadata": { "retrieval": retrieval_run, "answer": { "model": ANSWER_MODEL, "elapsed_seconds": round(time.perf_counter() - started, 3), "usage": usage_dict(response), }, }, } def main() -> None: parser = argparse.ArgumentParser(description="Qwen多模态PDF RAG示例") subparsers = parser.add_subparsers(dest="command", required=True) build_parser = subparsers.add_parser("build", help="解析PDF并建立本地JSON索引") build_parser.add_argument("pdf", help="待解析的PDF文件") build_parser.add_argument("--index", default=str(DEFAULT_INDEX), help="索引输出路径") build_parser.add_argument("--skip-vision", action="store_true", help="只解析文字,不调用视觉模型") ask_parser = subparsers.add_parser("ask", help="针对已建立的索引提问") ask_parser.add_argument("question", help="自然语言问题") ask_parser.add_argument("--index", default=str(DEFAULT_INDEX), help="索引文件路径") ask_parser.add_argument("--top-k", type=int, default=4, help="检索分块数量,范围1至8") arguments = parser.parse_args() client = create_client() if arguments.command == "build": result = build_index(client, arguments.pdf, arguments.index, use_vision=not arguments.skip_vision) print(json.dumps({"source": result["source"], "models": result["models"], "chunks": len(result["chunks"])}, ensure_ascii=False, indent=2)) else: result = answer_question(client, arguments.question, arguments.index, arguments.top_k) print(json.dumps(result, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()