LlamaIndex 支持模块(Supporting Modules)配置指南:Settings 全局配置与 StorageContext 存储定制
【免费下载链接】llama_indexLlamaIndex is the document processing platform for AI项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index
本文围绕 LlamaIndex 中的两个核心配置模块——全局Settings对象与StorageContext存储上下文——展开讲解。它们可以单独配置后传给各个索引,也可以作为全局默认值统一生效。读完本文,你将掌握如何配置 LLM、嵌入模型、节点解析器、回调、分词器等全局资源,如何将旧的ServiceContext迁移到Settings,以及如何通过StorageContext定制文档、向量与索引的存储位置。
什么是 Supporting Modules
在 LlamaIndex 的模块体系中,Supporting Modules(支持模块)是两大可独立配置、并可作为全局默认值使用的配置模块:
Settings:包含你正在使用的 LLM、嵌入模型、节点解析器(Node Parser)、回调管理器(Callback Manager)等常用资源。StorageContext:用于指定文档(Node对象)、向量嵌入和索引元数据的存储位置与存储方式,详见官方文档 customizing storage。
它们的特点是“可以分别配置后传给单个索引,也可以全局设置”。你可以在 module_guides/index.md 中查看整个模块指南的目录结构,Supporting Modules 位于 supporting_modules 目录下,包含三个文档:settings.mdx(配置 Settings)、service_context_migration.md(迁移指南)、supporting_modules.md(本页概览)。
Settings:应用全局的配置单例
Settings是索引与查询阶段常用资源的集合,可以在整个 LlamaIndex 工作流/应用中设置全局配置。它是一个贯穿应用生命周期的简单单例对象:当某个组件没有被显式提供时,Settings对象会作为全局默认值来提供它。
在源码层面,Settings实现在 llama-index-core/llama_index/core/settings.py 中,核心是一个带懒加载特性的_Settingsdataclass。从源码结构可以看到,各属性(_llm、_embed_model、_callback_manager、_tokenizer、_node_parser、_prompt_helper、_transformations等)默认均为None,只有在你首次访问对应属性时才通过resolve_llm("default")或resolve_embed_model("default")等函数解析出默认实现。这也解释了“参数懒加载”的行为:LLM 或嵌入模型只有在底层模块真正需要时才会被加载。
局部配置(transformations、LLM、嵌入模型)则可以直接传入使用它们的接口,实现覆盖全局默认值。
配置 LLM
LLM 用于响应提示与查询,负责生成自然语言回复。通过Settings.llm设置:
from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)设置后,所有未显式传入llm的索引、查询引擎、Agent 等组件都会使用该 LLM。从 settings.py 可以看到,llm属性在 setter 中会经过resolve_llm解析(支持直接传 LLM 实例或字符串形式的模型名),而在 getter 中会为 LLM 自动挂接全局callback_manager。
配置嵌入模型
嵌入模型用于将文本转换为数值表示,用于计算相似度与 top-k 检索。通过Settings.embed_model设置:
from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core import Settings Settings.embed_model = OpenAIEmbedding( model="text-embedding-3-small", embed_batch_size=100 )与 LLM 一样,embed_model的 getter/setter 在 settings.py 中实现了懒加载与回调管理器挂接。
配置节点解析器 / 文本分割器
节点解析器/文本分割器用于将文档解析为更小的块,称为节点(Node)。通过Settings.text_splitter设置:
from llama_index.core.node_parser import SentenceSplitter from llama_index.core import Settings Settings.text_splitter = SentenceSplitter(chunk_size=1024)如果只想改变 chunk_size 或 chunk_overlap,而不更换默认分割器,也可以直接设置这两个属性:
Settings.chunk_size = 512 Settings.chunk_overlap = 20在源码中,Settings还暴露了node_parser属性(settings.py中的_node_parser),用于在查询路径中解析/分割节点,二者配合可以灵活控制分块行为。
配置 Transformations(摄取期变换)
Transformations 在摄取(ingestion)阶段作用于Document。默认使用node_parser/text_splitter,但可以覆盖并进一步自定义:
from llama_index.core.node_parser import SentenceSplitter from llama_index.core import Settings Settings.transformations = [SentenceSplitter(chunk_size=1024)]从源码看,_transformations是List[TransformComponent]类型的字段,TransformComponent是 LlamaIndex 中变换组件的基类,因此你可以传入自定义的变换组件列表,而不仅是分割器。
配置 Tokenizer
Tokenizer 用于统计 token 数量,应设置为与你使用的 LLM 匹配的实现:
from llama_index.core import Settings # openai import tiktoken Settings.tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo").encode # open-source from transformers import AutoTokenizer Settings.tokenizer = AutoTokenizer.from_pretrained( "mistralai/Mixtral-8x7B-Instruct-v0.1" )注:原文档中开源示例的变量名存在笔误(Settings.tokenzier),实际属性名为Settings.tokenizer,上面已修正。tokenizer 用于 token 计数、上下文窗口计算与成本估算,选错会导致长度估算偏差。
配置 Callbacks
可以设置全局回调管理器(CallbackManager),用于观察和消费整个 llama-index 代码中产生的事件:
from llama_index.core.callbacks import TokenCountingHandler, CallbackManager from llama_index.core import Settings token_counter = TokenCountingHandler() Settings.callback_manager = CallbackManager([token_counter])设置后,Settings在解析 LLM 与嵌入模型时会把该callback_manager自动挂接到模型实例上(见 settings.py),从而实现全局事件追踪,例如统计 token 使用量。
配置 Prompt Helper 参数
查询期间会用到几个特定参数,以确保发送给 LLM 的提示词为生成指定数量的 token 留出足够空间。通常这些参数会根据 LLM 的属性自动配置,但在特殊情况下可以覆盖:
from llama_index.core import Settings # maximum input size to the LLM Settings.context_window = 4096 # number of tokens reserved for text generation. Settings.num_output = 256context_window:LLM 的最大输入大小;num_output:为文本生成预留的 token 数量。
从 settings.py 可以看到,Settings同时持有prompt_helper与chat_prompt_helper字段,这些参数会直接影响 PromptHelper 对提示词长度的规划。
局部配置(Local Configurations)
使用 Settings 特定部分的接口也可以接受局部覆盖,覆盖值优先于全局默认:
index = VectorStoreIndex.from_documents( documents, embed_model=embed_model, transformations=transformations ) query_engine = index.as_query_engine(llm=llm)这种“全局默认 + 局部覆盖”的设计使得同一应用中不同索引可以使用不同的 LLM 或嵌入模型,而不必反复修改全局状态。
从 ServiceContext 迁移到 Settings
自 v0.10.0 起,LlamaIndex 引入了新的全局Settings对象,用于取代旧的ServiceContext配置。
为什么要迁移?新的Settings是全局配置对象,参数采用懒加载方式实例化——LLM、嵌入模型等属性只在底层模块真正需要时才加载。而旧的 ServiceContext 时代,各个模块往往没有使用它,并且它会在运行时强制把每个组件都加载进内存(即使这些组件并未被使用)。可见Settings在内存占用与启动开销上更优。
全局配置的威力:配置全局 Settings 意味着改变 LlamaIndex 中每个模块的默认值。例如,如果你不使用 OpenAI,一个典型的配置如下:
from llama_index.llms.ollama import Ollama from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import Settings Settings.llm = Ollama(model="llama2", request_timeout=120.0) Settings.embed_model = HuggingFaceEmbedding( model_name="BAAI/bge-small-en-v1.5" )有了这组 Settings,可以确保框架内永远不会使用 OpenAI。Settings对象支持几乎与旧ServiceContext相同的全部属性,完整列表见 settings.mdx。
完整迁移示例
下面是从ServiceContext迁移到Settings的完整对照:
迁移前(Before)
from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.llms.openai import OpenAI from llama_index.core import ServiceContext, set_global_service_context service_context = ServiceContext.from_defaults( llm=OpenAI(model="gpt-3.5-turbo"), embed_model=OpenAIEmbedding(model="text-embedding-3-small"), node_parser=SentenceSplitter(chunk_size=512, chunk_overlap=20), num_output=512, context_window=3900, ) set_global_service_context(service_context)迁移后(After)
from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.llms.openai import OpenAI from llama_index.core import Settings Settings.llm = OpenAI(model="gpt-3.5-turbo") Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small") Settings.node_parser = SentenceSplitter(chunk_size=512, chunk_overlap=20) Settings.num_output = 512 Settings.context_window = 3900迁移要点:
- 删除
ServiceContext.from_defaults(...)与set_global_service_context(...)调用; - 改为直接对
Settings的各属性赋值; - 原来通过
node_parser传入的SentenceSplitter对应到Settings.node_parser; num_output、context_window等参数名保持不变。
按模块配置(Local Config)
以上介绍的是全局配置。若要按模块配置,所有模块接口都应支持接收所用对象的 kwargs(在 IDE 中可通过智能提示自动补全),示例如下:
# a vector store index only needs an embed model index = VectorStoreIndex.from_documents( documents, embed_model=embed_model, transformations=transformations ) # ... until you create a query engine query_engine = index.as_query_engine(llm=llm)# a document summary index needs both an llm and embed model # for the constructor index = DocumentSummaryIndex.from_documents( documents, embed_model=embed_model, llm=llm )值得注意的是:向量存储索引在构建时通常只需要嵌入模型(用于生成向量),而文档摘要索引(DocumentSummaryIndex)在构造时同时需要 LLM 与嵌入模型(LLM 用于生成摘要)。这种差异体现了按需注入局部配置的灵活性。
StorageContext:定制存储层
除了Settings之外,Supporting Modules 概览中提到的另一个配置模块是StorageContext。默认情况下,LlamaIndex 用 5 行以内的代码就能让你查询数据:
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader documents = SimpleDirectoryReader("data").load_data() index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() response = query_engine.query("Summarize the documents.")但底层,LlamaIndex 支持可替换的存储层(storage layer),允许你定制摄取后的文档(即Node对象)、嵌入向量和索引元数据的存储位置,详见 customizing storage。
低层 API 示例
使用低层 API 可以获得更细粒度的控制。以默认的简单存储实现为例:
from llama_index.core.storage.docstore import SimpleDocumentStore from llama_index.core.storage.index_store import SimpleIndexStore from llama_index.core.vector_stores import SimpleVectorStore from llama_index.core.node_parser import SentenceSplitter # create parser and parse document into nodes parser = SentenceSplitter() nodes = parser.get_nodes_from_documents(documents) # create storage context using default stores storage_context = StorageContext.from_defaults( docstore=SimpleDocumentStore(), vector_store=SimpleVectorStore(), index_store=SimpleIndexStore(), ) # create (or load) docstore and add nodes storage_context.docstore.add_documents(nodes) # build index index = VectorStoreIndex(nodes, storage_context=storage_context) # save index index.storage_context.persist(persist_dir="<persist_dir>") # can also set index_id to save multiple indexes to the same folder index.set_index_id("<index_id>") index.storage_context.persist(persist_dir="<persist_dir>") # to load index later, make sure you setup the storage context # this will load the persisted stores from persist_dir storage_context = StorageContext.from_defaults(persist_dir="<persist_dir>") # then load the index object from llama_index.core import load_index_from_storage loaded_index = load_index_from_storage(storage_context) # if loading an index from a persist_dir containing multiple indexes loaded_index = load_index_from_storage(storage_context, index_id="<index_id>") # if loading multiple indexes from a persist dir loaded_indices = load_index_from_storage( storage_context, index_ids=["<index_id>", ...] )要点说明:
StorageContext由三类存储组成:docstore(文档/节点存储)、vector_store(向量存储)、index_store(索引元数据存储);- 通过
StorageContext.from_defaults(...)可以用一行改动替换任意一种底层存储实现,例如换成 Redis、Pinecone、Chroma 等向量存储; persist_dir用于持久化目录;index_id/index_ids用于在同一目录下保存或加载多个索引。
向量存储集成与持久化
大多数向量存储集成会把整个索引(向量 + 文本)直接存在向量存储本身中。这样做的一大好处是无需像上面那样显式持久化索引——因为向量存储本身已经是托管服务,数据在索引中自动持久化。
支持该做法的向量存储包括:AzureAISearchVectorStore、ChatGPTRetrievalPluginClient、CassandraVectorStore、ChromaVectorStore、EpsillaVectorStore、DocArrayHnswVectorStore、DocArrayInMemoryVectorStore、JaguarVectorStore、LanceDBVectorStore、MetalVectorStore、MilvusVectorStore、MyScaleVectorStore、OpensearchVectorStore、PineconeVectorStore、QdrantVectorStore、TablestoreVectorStore、RedisVectorStore、UpstashVectorStore、WeaviateVectorStore。
以 Pinecone 为例:
import pinecone from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.vector_stores.pinecone import PineconeVectorStore # Creating a Pinecone index api_key = "api_key" pinecone.init(api_key=api_key, environment="us-west1-gcp") pinecone.create_index( "quickstart", dimension=1536, metric="euclidean", pod_type="p1" ) index = pinecone.Index("quickstart") # construct vector store vector_store = PineconeVectorStore(pinecone_index=index) # create storage context storage_context = StorageContext.from_defaults(vector_store=vector_store) # load documents documents = SimpleDirectoryReader("./data").load_data() # create index, which will insert documents/vectors to pinecone index = VectorStoreIndex.from_documents( documents, storage_context=storage_context )如果你已有加载好数据的向量存储,可以直接连接它并创建VectorStoreIndex:
index = pinecone.Index("quickstart") vector_store = PineconeVectorStore(pinecone_index=index) loaded_index = VectorStoreIndex.from_vector_store(vector_store=vector_store)小结与最佳实践
- 默认优先用
Settings:Settings是 v0.10.0 之后推荐的全局配置方式,取代了ServiceContext;它采用懒加载,内存开销更小。 - 全局默认 + 局部覆盖:将通用的 LLM、嵌入模型、分割器、回调管理器配置到
Settings,把特例通过接口 kwargs 传入单个索引/查询引擎。 - 存储按需定制:需要精细控制时用低层 API 组合 docstore、vector_store、index_store;追求省事时直接选择支持全量持久化的向量存储集成。
- 迁移时注意:
Settings支持几乎全部旧ServiceContext属性,迁移主要是把ServiceContext.from_defaults(...)改为逐个属性赋值。
如需深入了解,可继续阅读仓库内相关文档:settings.mdx、service_context_migration.md、customization.md,以及核心实现 settings.py。
【免费下载链接】llama_indexLlamaIndex is the document processing platform for AI项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考