You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

llama_index中ServiceContext缓存文件夹位置及Docker挂载咨询

LlamaIndex ServiceContext 缓存文件夹定位与持久化方案

缓存位置说明

当你用local:前缀加载HuggingFace嵌入模型时,LlamaIndex不会使用HuggingFace默认的~/.cache/huggingface目录,而是将模型缓存到自身专属的缓存路径,可通过以下方式定位和配置:

1. 代码直接获取缓存路径

在Jupyter Notebook中运行代码,打印当前嵌入模型的缓存目录:

from llama_index import ServiceContext
from llama_index.embeddings import HuggingFaceEmbedding
from llama_index.llms import OpenAI

llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)
# 初始化嵌入模型并查看缓存路径
embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
print("模型缓存路径:", embed_model.cache_folder)

# 或通过ServiceContext查看
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)
print("ServiceContext关联的缓存路径:", service_context.embed_model.cache_folder)

2. 环境变量指定缓存路径

通过LLAMA_INDEX_CACHE_DIR环境变量自定义缓存目录,启动Docker容器时同时挂载主机目录到容器内对应路径:

docker run -d \
  -e LLAMA_INDEX_CACHE_DIR=/app/llama_cache \
  -v /主机本地路径/llama_cache:/app/llama_cache \
  -p 8888:8888 \
  你的Jupyter镜像名称

设置后,LlamaIndex的所有缓存文件(包括嵌入模型、索引缓存等)都会存在指定目录,容器重启后不会丢失。

3. 代码显式指定缓存路径

初始化嵌入模型时直接设置cache_folder参数,再传入ServiceContext:

from llama_index import ServiceContext
from llama_index.embeddings import HuggingFaceEmbedding
from llama_index.llms import OpenAI

llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)
# 显式指定缓存目录
embed_model = HuggingFaceEmbedding(
    model_name="BAAI/bge-small-en-v1.5",
    cache_folder="/app/llama_cache"
)
service_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)

需确保容器内的/app/llama_cache已挂载到主机本地路径。

为什么HuggingFace默认缓存里找不到模型?

使用local:前缀时,LlamaIndex通过自身封装逻辑加载模型,而非直接调用HuggingFace的transformers库默认缓存机制,因此模型文件不会出现在~/.cache/huggingface目录下,而是存储在LlamaIndex专属缓存路径中。

内容的提问来源于stack exchange,提问作者Alexander Borochkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:27:19