使用 NVIDIA NeMo Retriever、託管 NIM、LanceDB、重新排序與基於事實生成建立多模態 RAG 管線
In this tutorial, we build an advanced multimodal retrieval-augmented generation pipeline with NVIDIA NeMo Retriever.We begin by configuring a Python 3.12 environment, installing the required packages, and performing offline PDF text extraction without relying on a GPU or external API key.
We then extend the workflow with hosted NVIDIA NIM endpoints to detect page elements, extract tables, charts, and infographics, generate dense vector embeddings, and store the processed content in LanceDB.
Finally, we implement dense retrieval, vision-language reranking, metadata-filtered search, grounded response generation with inline citations, and a lightweight recall-at-k evaluation to validate retrieval quality across multimodal document content.
Copy CodeCopiedUse a different Browserimport sys, os, subprocess, textwrap, json, time, warnings warnings.filterwarnings("ignore") assert sys.versioninfo[:2] == (3, 12), ( f"nemo-retriever requires Python 3.12.x (found {sys.version.split()[0]})." "Colab's default runtime is 3.
12; if you changed it, switch back." ) def sh(cmd): print(f"$ {cmd}") subprocess.
run(cmd, shell=True, check=False) try: import nemoretriever print("nemo-retriever already installed") except ImportError: sh("pip install -q --ignore-installed PyJWT nemo-retriever openai") import nemoretriever print("nemo-retriever version:", nemoretriever.
version) from nemoretriever import createingestor try: from nemoretriever.io import tomarkdown, tomarkdownbypage except ImportError: from nemoretriever.common.io import tomarkdown, tomarkdownbypage try: from nemoretriever.retriever import Retriever except ImportError: from nemoretriever.graph.
retriever import Retriever import pandas as pd pd.setoption("display.maxcolwidth", 160) DOC = "multimodaltest.pdf" if not os.path.exists(DOC): sh(f"curl -sL -o {DOC} " "https://raw.githubusercontent.com/NVIDIA/NeMo-Retriever/main/data/multimodaltest.pdf") print("document:", DOC, os.path.
getsize(DOC), "bytes") DOCS = [DOC] print("\n=== STAGE 1: offline text extraction (no API key) ===") offline = ( createingestor(runmode="inprocess", allownogpu=True) .files(DOCS) .
extract( extracttext=True, extracttables=False, extractcharts=False, extractimages=False, extractinfographics=False, usepageelements=False, extractpageasimage=False, method="pdfium", ) ) dfoffline = offline.ingest() print("rows:", dfoffline.shape, "\ncolumns:", list(dfoffline.
columns)) print("\npage 1 text preview:\n", dfoffline.iloc[0]["text"][:400]) We configure the Python 3.12 environment, install NVIDIA NeMo Retriever, and import the required ingestion and retrieval components.We download the sample multimodal PDF and define it as the input document for the pipeline.
We then perform CPU-based offline text extraction with PDFium and inspect the extracted rows, columns, and page content.Copy CodeCopiedUse a different Browserfrom getpass import getpass if not os.environ.get("NVIDIAAPIKEY"): try: from google.colab import userdata os.
environ["NVIDIAAPIKEY"] = userdata.get("NVIDIAAPIKEY") except Exception: os.environ["NVIDIAAPIKEY"] = getpass("NVIDIAAPIKEY (nvapi-...): ").strip() APIKEY = os.environ.get("NVIDIAAPIKEY", "").strip() HAVEKEY = APIKEY.
startswith("nvapi-") print("API key present:", HAVEKEY) PAGEELEMENTSURL = "https://ai.api.nvidia.com/v1/cv/nvidia/nemotron-page-elements-v3" OCRURL = "https://ai.api.nvidia.com/v1/cv/nvidia/nemotron-ocr-v1" TABLESTRUCTURL = "https://ai.api.nvidia.
com/v1/cv/nvidia/nemotron-table-structure-v1" GRAPHICELEMURL = "https://ai.api.nvidia.com/v1/cv/nvidia/nemotron-graphic-elements-v1" EMBEDURL = "https://integrate.api.nvidia.com/v1/embeddings" RERANKURL = "https://ai.api.nvidia.
com/v1/retrieval/nvidia/llama-nemotron-rerank-vl-1b-v2/reranking" CHATURL = "https://integrate.api.nvidia.com/v1" EMBEDMODEL = "nvidia/llama-nemotron-embed-1b-v2" RERANKMODEL = "nvidia/llama-nemotron-rerank-vl-1b-v2" LLMMODEL = "nvidia/llama-3.3-nemotron-super-49b-v1.5" LANCEDBURI, TABLE = ".
/lancedb", "colabdemo" df = dfoffline if HAVEKEY: print("\n=== STAGE 2: multimodal ingest via hosted NIMs ===") ing = ( createingestor( runmode="inprocess", allownogpu=True, errorpolicy="collect", ) .files(DOCS) .
extract( extracttext=True, extracttables=True, extractcharts=True, extractinfographics=True, extractimages=False, method="pdfium", dpi=200, tableoutputformat="markdown", pageelementsinvokeurl=PAGEELEMENTSURL, ocrinvokeurl=OCRURL, tablestructureinvokeurl=TABLESTRUCTURL, graphicelementsinvokeurl=GRAPHICELEMURL, apikey=APIKEY, requesttimeouts=120.
0, splitconfig={"text": {"maxtokens": 512, "overlaptokens": 64}}, ) .dedup(contenthash=True, bboxiou=True, iouthreshold=0.45) .embed( embeddingendpoint=EMBEDURL, modelname=EMBEDMODEL, embedmodelname=EMBEDMODEL, apikey=APIKEY, inputtype="passage", inferencebatchsize=16, nimhttpmaxconcurrent=8, ) .
vdbupload( vdbop="lancedb", vdbkwargs={ "uri": LANCEDBURI, "tablename": TABLE, "overwrite": True, "createindex": True, "indextype": "IVFHNSWSQ", "metric": "l2", }, ) ) t0 = time.time() df = ing.ingest(showprogress=True) print(f"ingested in {time.time()-t0:.1f}s -> {df.
shape}") We securely load the NVIDIA API key and define the hosted NIM endpoints for layout detection, OCR, table extraction, graphic analysis, embedding, reranking, and generation.
We create a multimodal ingestion pipeline that extracts text, tables, charts, and infographics while applying token-aware chunking and content deduplication.We generate embeddings for the extracted content and upload the resulting vectors and metadata to a LanceDB table.
Copy CodeCopiedUse a different Browserprint("\n=== Extraction inspection ===") for col in ["tables", "charts", "infographics", "images"]: if col in df.columns: n = int(df[col].apply(lambda v: len(v) if isinstance(v, (list, tuple)) else 0).
sum()) print(f" {col:<14} {n}") pages = tomarkdownbypage(df) print("\npages rendered to markdown:", list(pages.keys())) print("\n--- page 1 markdown (first 900 chars) ---\n", pages[min(pages)][:900]) fullmd = tomarkdown(df) if fullmd: with open("extracted.md", "w") as f: f.
write(fullmd) print("\nfull document markdown -> extracted.
md") if HAVEKEY: print("\n=== STAGE 3: dense retrieval ===") retriever = Retriever( runmode="service", topk=5, rerank=False, vdbkwargs={"uri": LANCEDBURI, "tablename": TABLE}, embedkwargs={ "embeddingendpoint": EMBEDURL, "modelname": EMBEDMODEL, "embedmodelname": EMBEDMODEL, "apikey": APIKEY, "inputtype": "query", }, ) QUERIES = [ "Given their activities, which animal is responsible for the typos in my documents?
", "What is the most expensive gadget and how much does it cost?", "Which animal is at the beach?", ] def show(hits, label=""): print(f"\n--- {label} ---") for i, h in enumerate(hits, 1): meta = h.get("metadata") if isinstance(meta, str): try: meta = json.
loads(meta) except Exception: meta = {} page = (meta or {}).get("pagenumber", "?") score = h.get("distance", h.get("rerankscore", "")) body = " ".join(str(h.get("text", "")).split())[:180] print(f" {i}.p{page} score={score} {body}") show(retriever.
query(QUERIES[0]), "single query") for q, hits in zip(QUERIES, retriever.queries(QUERIES, topk=3)): show(hits, q[:60]) We inspect the extracted multimodal elements and convert the processed document into page-level and full-document Markdown.
We configure a dense retriever that embeds user queries and searches the LanceDB vector index for the most relevant document chunks.We test both individual and batched queries while displaying page numbers, similarity scores, and retrieved text previews.
Copy CodeCopiedUse a different Browserif HAVEKEY: print("\n=== STAGE 4: retrieve + VL rerank ===") reranking = Retriever( runmode="service", topk=5, rerank=True, vdbkwargs={"uri": LANCEDBURI, "tablename": TABLE}, embedkwargs={ "embeddingendpoint": EMBEDURL, "modelname": EMBED_MODEL, "emb
Related
相關文章

阿里研究員透露Qwen4.5後模型將擴展至5-10T參數
阿里巴巴在雲棲大會上宣布新一代架構的Qwen4模型已開始訓練,未來Qwen4.5、Qwen5等版本參數規模將擴展至5至10兆。大會同時展示大模型遞歸自我改進技術已應用於訓練與推理,並推出多款影像、音樂、語音及全模態模型新版本。阿里也宣布下代視頻生成模型預計11月發布,並將語音模型落地於手機、AI眼鏡等終端裝置。

阿里公佈全模態模型新進展,Qwen4和下代視頻模型均在訓練中
阿里巴巴在2026雲棲大會上公布多項大模型進展,包括基於新架構的Qwen4已開始訓練,未來參數規模將擴展至5到10萬億。多模態方面,影片生成模型Wan3.0在評測中取得雙榜第一,下一代影片模型預計11月發布;語音、影像、音樂及世界模型等也同步升級。此外,Qwen3.8-Max透過自我進化技術,在零人工參與下持續迭代,整體下載量已超過30億次。

華為雲碼道全面升級:全球首個鴻蒙專屬AI編碼智能體登場,從想法到上架一條龍
官方給它的定位很硬:這是全球首個、也是目前唯一一個專為鴻蒙生態打造的AI編碼智能體,等於給鴻蒙開發者配了一位從頭跟到尾的數字搭檔。扛大樑的是鴻蒙編碼大模型。它依託鴻蒙增強訓練體系,在訓練數據、代碼生成、編譯通過率和Token消耗這幾個開發者最在意的維度上都佔著優勢,目前已經上線可調用。

蘋果零售先驅質疑AI代理購物:消費者不會完全交給機器
現年66歲的約翰遜曾於2000年加入蘋果,負責搭建零售業務,並參與建立後來成為蘋果產品銷售與用戶服務核心的實體門店網絡。谷歌正通過Universal Commerce Protocol推動AI代理覆蓋商品發現、比較和結賬流程,OpenAI也在將ChatGPT打造為購物平臺。

阿里 Qwen4 和下代視頻模型訓練中,Qwen4.5 後模型將擴展至 5-10T 參數
作者:汪淼 責編:汪淼 評論: 9 月 22 日消息,今日從 2026 年雲棲大會現場獲悉,阿里巴巴公佈了大模型一系列進展,大模型遞歸自我改進(RSI)已初步進入模型訓練、推理及芯模協同等環節中,基於新一代架構的 Qwen4 已在訓練中,未來 Qwen4.

阿里平頭哥發佈AI芯片真武V900,算力達M890三倍
基於真武V900構建的單一集群可擴展至50萬卡,可為前沿AI模型訓練與推理提供大規模算力支持。阿里表示,隨著平頭哥芯片產品線逐步成熟並獲得廣泛客戶應用,預計芯片年出貨量將大幅提升。阿里集團CEO吳泳銘透露,阿里自研M890AI超節點目前已具備支撐2萬億參數大模型推理的能力,並已於本季度規模化上架阿里雲數據中心。