用LangChain搭建语义搜索引擎

该教程介绍从PDF构建文档对象、生成嵌入、切分并索引到向量库,再以检索器封装实现相似度查询的完整流程,并列出文档结构、切分策略与向量检索等核心概念。

## 概览 以 PDF 和 LangChain 搭建语义搜索引擎 [嵌入点](<https://docs.langchain.com/oss/python/integrations/embeddings>) 财务报告和财务报告 [向量存储](<https://docs.langchain.com/oss/python/integrations/vectorstores>)。用它来检索类似查询的段落,然后插入检索器 [检索增强生成( RAG )](<https://docs.langchain.com/oss/python/deepagents/retrieval>) 或其他 LLM 工作流程。此教程覆盖 : 1. 创建 `Document` 来自 PDF 的对象。 2. 生成嵌入. 3. 装入并拆分一个PDF. 4. 向量存储和查询中的索引块。 5. 将店铺包装为回收商. 该指南还包括了搜索引擎上方一个最低限度的RAG执行. ### 概念 该教程侧重于文本检索,并涵盖以下概念: - [`Document`](<https://reference.langchain.com/python/langchain-core/documents/base/Document>) - [文本分割符](<https://docs.langchain.com/oss/python/integrations/splitters>) 财务报告和财务报告 [块块战略](<https://docs.langchain.com/oss/python/langchain/chunking>) - [嵌入层](<https://docs.langchain.com/oss/python/integrations/embeddings>) - [向量储存](<https://docs.langchain.com/oss/python/integrations/vectorstores>) 财务报告和财务报告 [检索器](<https://docs.langchain.com/oss/python/integrations/retrievers>) ## 设置 ### 安装依赖关系 此教程使用 PDF 读取 `pypdf` 软件包 : ``` pip install pypdf ``` ``` conda install pypdf -c conda-forge ``` ``` uv add pypdf ``` 详细情况见: [安装指南](<https://docs.langchain.com/oss/python/langchain/install>). ### 配置 LangSmith 您使用 LangChain 构建的许多应用程序将包含多个步骤, 并多次引用 LLM 的调用。 随着这些应用程序变得越来越复杂, 检查链条或代理中究竟发生了什么变得至关重要 。 这样做的最好方法是使用 [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langchain-knowledge-base>)。在您在上面的链接上签名后,请确定设置环境变量开始记录痕迹 : ``` export LANGSMITH_TRACING="true" export LANGSMITH_API_KEY="..." ``` 在笔记本中,你可以设置它们: ``` import getpass import os os.environ["LANGSMITH_TRACING"] = "true" os.environ["LANGSMITH_API_KEY"] = getpass.getpass() ``` ## 创建文档 LangChain 执行一个 [`Document`](<https://reference.langchain.com/python/langchain-core/documents/base/Document>) 文本和相关元数据单位的抽象。 它有三个属性 : - `page_content`: 代表内容的字符串。 - `metadata`: 包含任意元数据的命令。 - `id`: (可选)文档的字符串标识符。 `metadata` 可以捕捉文档的来源、其与其他文档的关系以及其他信息。 [`Document`](<https://reference.langchain.com/python/langchain-core/documents/base/Document>) 通常代表一个较大文档的块。以下代码创建样本文档: ``` from langchain_core.documents import Document documents = [ Document( page_content="Dogs are great companions, known for their loyalty and friendliness.", metadata={"source": "mammal-pets-doc"}, ), Document( page_content="Cats are independent pets that often enjoy their own space.", metadata={"source": "mammal-pets-doc"}, ), ] ``` ## 生成嵌入 矢量搜索存储与文本相关的数字向量。 将查询作为相同维度的向量嵌入, 然后使用相似度度量( 如 余弦相似度) 来查找相关的文本。 LangChain 支持嵌入来自 [许多供应商](<https://docs.langchain.com/oss/python/integrations/embeddings/>)中选择一个模式,以指定文本应如何转换成数字矢量: - OpenAI - 阿苏雷 - 谷歌双子座 - 双子企业代理平台 - AWS - HuggingFace - 奥拉玛 - 领带 - MistralAI - 杂音 - NVIDIA - 蒸发机 AI - IBM 华特森克斯 - 假话 - 以撒岛 ``` pip install -U "langchain-openai" ``` ``` import getpass import os if not os.environ.get("OPENAI_API_KEY"): os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ") from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings(model="text-embedding-3-large") ``` ``` pip install -U "langchain-openai" ``` ``` import getpass import os if not os.environ.get("AZURE_OPENAI_API_KEY"): os.environ["AZURE_OPENAI_API_KEY"] = getpass.getpass("Enter API key for Azure: ") from langchain_openai import AzureOpenAIEmbeddings embeddings = AzureOpenAIEmbeddings( azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"], azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"], openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"], ) ``` ``` pip install -qU langchain-google-genai ``` ``` import getpass import os if not os.environ.get("GOOGLE_API_KEY"): os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter API key for Google Gemini: ") from langchain_google_genai import GoogleGenerativeAIEmbeddings embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001") ``` ``` pip install -qU langchain-google-vertexai ``` ``` from langchain_google_vertexai import VertexAIEmbeddings embeddings = VertexAIEmbeddings(model="text-embedding-005") ``` ``` pip install -qU langchain-aws ``` ``` from langchain_aws import BedrockEmbeddings embeddings = BedrockEmbeddings(model_id="amazon.titan-embed-text-v2:0") ``` ``` pip install -qU langchain-huggingface ``` ``` from langchain_huggingface import HuggingFaceEmbeddings embeddings = HuggingFaceEmbeddings( model_name="sentence-transformers/all-mpnet-base-v2", encode_kwargs={"normalize_embeddings": True}, ) ``` ``` pip install -qU langchain-ollama ``` ``` from langchain_ollama import OllamaEmbeddings embeddings = OllamaEmbeddings(model="llama3") ``` ``` pip install -qU langchain-cohere ``` ``` import getpass import os if not os.environ.get("COHERE_API_KEY"): os.environ["COHERE_API_KEY"] = getpass.getpass("Enter API key for Cohere: ") from langchain_cohere import CohereEmbeddings embeddings = CohereEmbeddings(model="embed-english-v3.0") ``` ``` pip install -qU langchain-mistralai ``` ``` import getpass import os if not os.environ.get("MISTRALAI_API_KEY"): os.environ["MISTRALAI_API_KEY"] = getpass.getpass("Enter API key for MistralAI: ") from langchain_mistralai import MistralAIEmbeddings embeddings = MistralAIEmbeddings(model="mistral-embed") ``` ``` pip install -qU langchain-nomic ``` ``` import getpass import os if not os.environ.get("NOMIC_API_KEY"): os.environ["NOMIC_API_KEY"] = getpass.getpass("Enter API key for Nomic: ") from langchain_nomic import NomicEmbeddings embeddings = NomicEmbeddings(model="nomic-embed-text-v1.5") ``` ``` pip install -qU langchain-nvidia-ai-endpoints ``` ``` import getpass import os if not os.environ.get("NVIDIA_API_KEY"): os.environ["NVIDIA_API_KEY"] = getpass.getpass("Enter API key for NVIDIA: ") from langchain_nvidia_ai_endpoints import NVIDIAEmbeddings embeddings = NVIDIAEmbeddings(model="NV-Embed-QA") ``` ``` pip install -qU langchain-voyageai ``` ``` import getpass import os if not os.environ.get("VOYAGE_API_KEY"): os.environ["VOYAGE_API_KEY"] = getpass.getpass("Enter API key for Voyage AI: ") from langchain_voyageai import VoyageAIEmbeddings embeddings = VoyageAIEmbeddings(model="voyage-3") ``` ``` pip install -qU langchain-ibm ``` ``` import getpass import os if not os.environ.get("WATSONX_APIKEY"): os.environ["WATSONX_APIKEY"] = getpass.getpass("Enter API key for IBM watsonx: ") from langchain_ibm import WatsonxEmbeddings embeddings = WatsonxEmbeddings( model_id="ibm/slate-125m-english-rtrvr", url="https://us-south.ml.cloud.ibm.com", project_id="<WATSONX PROJECT_ID>", ) ``` ``` pip install -qU langchain-core ``` ``` from langchain_core.embeddings import DeterministicFakeEmbedding embeddings = DeterministicFakeEmbedding(size=4096) ``` ``` pip install -qU langchain-isaacus ``` ``` import getpass import os if not os.environ.get("ISAACUS_API_KEY"): os.environ["ISAACUS_API_KEY"] = getpass.getpass("Enter API key for Isaacus: ") from langchain_isaacus import IsaacusEmbeddings embeddings = IsaacusEmbeddings(model="kanon-2-embedder") ``` ``` vector_1 = embeddings.embed_query(documents[0].page_content) vector_2 = embeddings.embed_query(documents[1].page_content) assert len(vector_1) == len(vector_2) print(f"Generated vectors of length {len(vector_1)}\n") print(vector_1[:10]) ``` ``` Generated vectors of length 1536 [-0.008586574345827103, -0.03341241180896759, -0.008936782367527485, -0.0036674530711025, 0.010564599186182022, 0.009598285891115665, -0.028587326407432556, -0.015824200585484505, 0.0030416189692914486, -0.012899317778646946] ``` 接下来,存储嵌入到支持高效相似性搜索的矢量存储中. ## 选择一个向量存储 LangChain [`VectorStore`](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore>) 对象添加文本和 [`Document`](<https://reference.langchain.com/python/langchain-core/documents/base/Document>) 对象到存储并用相似的度量标准查询它们。它们往往初始化为 [嵌入](<https://docs.langchain.com/oss/python/integrations/embeddings>) 将文本翻译为数值向量的模型。 LangChain 包括 [一体化](<https://docs.langchain.com/oss/python/integrations/vectorstores>) 具有许多向量存储技术。有些是主机,需要资质,有些是单独运行的基础设施(本地或第三方),有些是用于轻量级工作量的模拟。选择向量存储 : - 记忆 - 亚马逊 OpenSearch - AstraDB - 色玛 - 米尔武斯 - MongoDB - PG 调试器 - PGVectorStore - 皮内酮 - 质子 ``` pip install -U "langchain-core" ``` ``` from langchain_core.vectorstores import InMemoryVectorStore vector_store = InMemoryVectorStore(embeddings) ``` ``` pip install -qU boto3 ``` ``` from opensearchpy import RequestsHttpConnection service = "es" # must set the service as 'es' region = "us-east-2" credentials = boto3.Session( aws_access_key_id="xxxxxx", aws_secret_access_key="xxxxx" ).get_credentials() awsauth = AWS4Auth("xxxxx", "xxxxxx", region, service, session_token=credentials.token) vector_store = OpenSearchVectorSearch.from_documents( docs, embeddings, opensearch_url="host url", http_auth=awsauth, timeout=300, use_ssl=True, verify_certs=True, connection_class=RequestsHttpConnection, index_name="test-index", ) ``` ``` pip install -U "langchain-astradb" ``` ``` from langchain_astradb import AstraDBVectorStore vector_store = AstraDBVectorStore( embedding=embeddings, api_endpoint=ASTRA_DB_API_ENDPOINT, collection_name="astra_vector_langchain", token=ASTRA_DB_APPLICATION_TOKEN, namespace=ASTRA_DB_NAMESPACE, ) ``` ``` pip install -qU langchain-chroma ``` ``` from langchain_chroma import Chroma vector_store = Chroma( collection_name="example_collection", embedding_function=embeddings, persist_directory="./chroma_langchain_db", # Where to save data locally, remove if not necessary ) ``` ``` pip install -qU langchain-milvus ``` ``` from langchain_milvus import Milvus URI = "./milvus_example.db" vector_store = Milvus( embedding_function=embeddings, connection_args={"uri": URI}, index_params={"index_type": "FLAT", "metric_type": "L2"}, ) ``` ``` pip install -qU langchain-mongodb ``` ``` from langchain_mongodb import MongoDBAtlasVectorSearch vector_store = MongoDBAtlasVectorSearch( embedding=embeddings, collection=MONGODB_COLLECTION, index_name=ATLAS_VECTOR_SEARCH_INDEX_NAME, relevance_score_fn="cosine", ) ``` ``` pip install -qU langchain-postgres ``` ``` from langchain_postgres import PGVector vector_store = PGVector( embeddings=embeddings, collection_name="my_docs", connection="postgresql+psycopg://...", ) ``` ``` pip install -qU langchain-postgres ``` ``` from langchain_postgres import PGEngine, PGVectorStore pg_engine = PGEngine.from_connection_string( url="postgresql+psycopg://..." ) vector_store = PGVectorStore.create_sync( engine=pg_engine, table_name='test_table', embedding_service=embeddings ) ``` ``` pip install -qU langchain-pinecone ``` ``` from langchain_pinecone import PineconeVectorStore from pinecone import Pinecone pc = Pinecone(api_key=...) index = pc.Index(index_name) vector_store = PineconeVectorStore(embedding=embeddings, index=index) ``` ``` pip install -qU langchain-qdrant ``` ``` from qdrant_client.models import Distance, VectorParams from langchain_qdrant import QdrantVectorStore from qdrant_client import QdrantClient client = QdrantClient(":memory:") vector_size = len(embeddings.embed_query("sample text")) if not client.collection_exists("test"): client.create_collection( collection_name="test", vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE) ) vector_store = QdrantVectorStore( client=client, collection_name="test", embedding=embeddings, ) ``` ## 装入并拆分一个 PDF 从 PDF 中装入内容,然后在索引编制前将其分割成小块。 [一个来自 2023 的 Nike 10 - K 文件样本](<https://github.com/langchain-ai/langchain/blob/v0.3/docs/docs/example_data/nke-10k-2023.pdf>),在运行示例前下载样本 PDF。设置 `file_path` (P)或 `filePath` ( JavaScript ) 到下载文件的绝对路径, 或使用相对于您工作目录的路径。 对于专用的 PDF 文件加载器( 包括 `PyPDFLoader` 和伙伴软件包),见 [PDF 文档加载器](<https://docs.langchain.com/oss/python/integrations/document_loaders#pdfs>). ``` import pypdf from langchain_core.documents import Document # Below is a minimal helper for demonstration purposes. def load_pdf_pages(file_path: str) -> list[Document]: reader = pypdf.PdfReader(file_path) return [ Document( page_content=page.extract_text() or "", metadata={"source": file_path, "page": i}, ) for i, page in enumerate(reader.pages) ] file_path = "../example_data/nke-10k-2023.pdf" docs = load_pdf_pages(file_path) print(len(docs)) ``` ``` 107 ``` 页面往往过于粗糙,无法检索。将页面分拆,这样相关的段落就不会被周围的文本稀释。 [`RecursiveCharacterTextSplitter`](<https://reference.langchain.com/python/langchain-text-splitters/character/RecursiveCharacterTextSplitter>) 在普通分隔符(如新线)上进行递归分割,直到每个块成为目标大小。这是通用文本使用例推荐的文本分割符。关于选择块大小、重叠和其他策略的指导意见,参见 [用于检索的块文档](<https://docs.langchain.com/oss/python/langchain/chunking>)设置 `add_start_index=True` 因此,每个拆分都保留一个 `start_index` 其字符的元数据字段在原始文档中被抵消。 ``` from langchain_text_splitters import RecursiveCharacterTextSplitter text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, add_start_index=True ) all_splits = text_splitter.split_documents(docs) print(len(all_splits)) ``` ``` 516 ``` ## 索引文档 将块索引到向量存储 : ``` ids = vector_store.add_documents(documents=all_splits) ``` 大多数向量存储集成也支持连接到已有的存储( 例如, 使用客户端或索引名称) 。 请参见特定文件 [融合](<https://docs.langchain.com/oss/python/integrations/vectorstores>) 详细情况。 ## 查询向量存储 在您将文件添加到 [`VectorStore`](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore>),您可以查询它: - 同步和同步 - 通过字符串查询和矢量 - 有和没有相似的分数 - 以相似性和 [最大边际关联性](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore/max_marginal_relevance_search>) (在相似性和多样性之间取得平衡) 这些方法一般会返回一份清单,列出 [`Document`](<https://reference.langchain.com/python/langchain-core/documents/base/Document>) 对象。 ### 按字符串搜索 嵌入到密集向量的地图文本中, 如此相似的含义在几何上是接近的。 这意味着您可以通过一个自然语言问题来获取相关的段落 : ``` results = vector_store.similarity_search( "How many distribution centers does Nike have in the US?" ) print(results[0]) ``` ``` page_content='direct to consumer operations sell products through the following number of retail stores in the United States: U.S. RETAIL STORES NUMBER NIKE Brand factory stores 213 NIKE Brand in-line stores (including employee-only stores) 74 Converse stores (including factory stores) 82 TOTAL 369 In the United States, NIKE has eight significant distribution centers. Refer to Item 2. Properties for further information. 2023 FORM 10-K 2' metadata={'page': 4, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 3125} ``` Async 查询 : ``` results = await vector_store.asimilarity_search("When was Nike incorporated?") print(results[0]) ``` ``` page_content='Table of Contents PART I ITEM 1. BUSINESS GENERAL NIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this "Annual Report"), the terms "we," "us," "our," "NIKE" and the "Company" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise. Our principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is the largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores and sales through our digital platforms (also referred to as "NIKE Brand Digital"), to retail accounts and to a mix of independent distributors, licensees and sales' metadata={'page': 3, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 0} ``` ### 返回分数 您可以返回与文档的相似性分数。 分数的含义因提供者而异。 在这种情况下, 分数是一个距离度量, 以相似性反向变化 : ``` # Note that providers implement different scores; the score here # is a distance metric that varies inversely with similarity. results = vector_store.similarity_search_with_score("What was Nike's revenue in 2023?") doc, score = results[0] print(f"Score: {score}\n") print(doc) ``` ``` Score: 0.23699893057346344 page_content='Table of Contents FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTS The following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line: FISCAL 2023 COMPARED TO FISCAL 2022 •NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively. The increase was due to higher revenues in North America, Europe, Middle East & Africa ("EMEA"), APLA and Greater China, which contributed approximately 7, 6, 2 and 1 percentage points to NIKE, Inc. Revenues, respectively. •NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale equivalent basis.' metadata={'page': 35, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 0} ``` ### 按矢量搜索 嵌入到查询中, 然后用生成的矢量搜索 : ``` embedding = embeddings.embed_query("How were Nike's margins impacted in 2023?") results = vector_store.similarity_search_by_vector(embedding) print(results[0]) ``` ``` page_content='Table of Contents GROSS MARGIN FISCAL 2023 COMPARED TO FISCAL 2022 For fiscal 2023, our consolidated gross profit increased 4% to $22,292 million compared to $21,479 million for fiscal 2022. Gross margin decreased 250 basis points to 43.5% for fiscal 2023 compared to 46.0% for fiscal 2022 due to the following: *Wholesale equivalent The decrease in gross margin for fiscal 2023 was primarily due to: •Higher NIKE Brand product costs, on a wholesale equivalent basis, primarily due to higher input costs and elevated inbound freight and logistics costs as well as product mix; •Lower margin in our NIKE Direct business, driven by higher promotional activity to liquidate inventory in the current period compared to lower promotional activity in the prior period resulting from lower available inventory supply; •Unfavorable changes in net foreign currency exchange rates, including hedges; and •Lower off-price margin, on a wholesale equivalent basis. This was partially offset by:' metadata={'page': 36, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 0} ``` 学习更多: - [API 参考文献](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore>) - [与整合有关的文件](<https://docs.langchain.com/oss/python/integrations/vectorstores>) ## 使用检索器 LangChain [`VectorStore`](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStore>) 对象没有子类 [`Runnable`](<https://reference.langchain.com/python/langchain-core/runnables/base/Runnable>). [检索器](<https://reference.langchain.com/python/langchain-core/retrievers/BaseRetriever>) 是 Runnables,所以它们支持同步和sync 等标准方法 `invoke` 财务报告和财务报告 `batch`。您也可以从矢量仓库建立检索器,而检索器也可以包装非矢量源(如外部 API) 。在这种情况下,创建简单的检索器而不进行子分类 `Retriever` 通过包装 `similarity_search`: ``` from typing import List from langchain_core.documents import Document from langchain_core.runnables import chain @chain def retriever(query: str) -> List[Document]: return vector_store.similarity_search(query, k=1) retriever.batch( [ "How many distribution centers does Nike have in the US?", "When was Nike incorporated?", ], ) ``` ``` [[Document(metadata={'page': 4, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 3125}, page_content='direct to consumer operations sell products through the following number of retail stores in the United States:\nU.S. RETAIL STORES NUMBER\nNIKE Brand factory stores 213 \nNIKE Brand in-line stores (including employee-only stores) 74 \nConverse stores (including factory stores) 82 \nTOTAL 369 \nIn the United States, NIKE has eight significant distribution centers. Refer to Item 2. Properties for further information.\n2023 FORM 10-K 2')], [Document(metadata={'page': 3, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 0}, page_content='Table of Contents\nPART I\nITEM 1. BUSINESS\nGENERAL\nNIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this "Annual Report"), the terms "we," "us," "our,"\n"NIKE" and the "Company" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\nOur principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\nthe largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\nand sales through our digital platforms (also referred to as "NIKE Brand Digital"), to retail accounts and to a mix of independent distributors, licensees and sales')]] ``` 向量存储器执行 `as_retriever` 返回 a 的方法 [`VectorStoreRetriever`](<https://reference.langchain.com/python/langchain-core/vectorstores/base/VectorStoreRetriever>)。这些检索者暴露 `search_type` 财务报告和财务报告 `search_kwargs` 来选择基本的存储方法并将其参数化。将上面的例子复制到: ``` retriever = vector_store.as_retriever( search_type="similarity", search_kwargs={"k": 1}, ) retriever.batch( [ "How many distribution centers does Nike have in the US?", "When was Nike incorporated?", ], ) ``` ``` [[Document(metadata={'page': 4, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 3125}, page_content='direct to consumer operations sell products through the following number of retail stores in the United States:\nU.S. RETAIL STORES NUMBER\nNIKE Brand factory stores 213 \nNIKE Brand in-line stores (including employee-only stores) 74 \nConverse stores (including factory stores) 82 \nTOTAL 369 \nIn the United States, NIKE has eight significant distribution centers. Refer to Item 2. Properties for further information.\n2023 FORM 10-K 2')], [Document(metadata={'page': 3, 'source': '../example_data/nke-10k-2023.pdf', 'start_index': 0}, page_content='Table of Contents\nPART I\nITEM 1. BUSINESS\nGENERAL\nNIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this "Annual Report"), the terms "we," "us," "our,"\n"NIKE" and the "Company" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\nOur principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\nthe largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\nand sales through our digital platforms (also referred to as "NIKE Brand Digital"), to retail accounts and to a mix of independent distributors, licensees and sales')]] ``` `VectorStoreRetriever` 支持搜索类型 `"similarity"` (违约), `"mmr"` (最大程度的边际相关性),和 `"similarity_score_threshold"`。使用最后一个选项来通过相似性分数过滤文档。您可以在更复杂的应用程序中使用检索器,例如 [检索增强生成( RAG )](<https://docs.langchain.com/oss/python/deepagents/retrieval>)它将一个问题和检索到的上下文结合起来,以启动一个 LLM 。为了更多地了解如何构建这样一个应用程序,请检查 [RAG 教程](<https://docs.langchain.com/oss/python/deepagents/rag>) 教学。 ## 今后的步骤 您现在已看到如何在 PDF 文档上构建语义搜索引擎。 更多信息见: - [可用的嵌入集成](<https://docs.langchain.com/oss/python/integrations/embeddings>) - [可用的矢量存储集成](<https://docs.langchain.com/oss/python/integrations/vectorstores>) 更多关于RAG: - [检索概览](<https://docs.langchain.com/oss/python/deepagents/retrieval>) - [深层特工的RAG](<https://docs.langchain.com/oss/python/deepagents/rag>) - [用于检索的块文档](<https://docs.langchain.com/oss/python/langchain/chunking>) - [提高检索质量](<https://docs.langchain.com/oss/python/langchain/retrieval-optimization>) - [评估 RAG 应用程序](<https://docs.langchain.com/langsmith/evaluate-rag-tutorial>) --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/knowledge-base.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?

查看原始来源