如何使用DeepSeek配合LlamaIndex进行RAG(V4教程)
如何使用DeepSeek配合LlamaIndex进行RAG(V4教程)

您有一个PDF文件夹、一个DeepSeek API密钥和一个问题:如何让LlamaIndex使用DeepSeek而不是OpenAI来回答关于您的文档的问题?本教程将指导您在当前V4 API上从`pip install`开始,到构建一个可以检索片段、调用`deepseek-v4-flash`并流式传输答案的工作查询引擎的端到端过程。我们将涵盖官方`llama-index-llms-deepseek`包、更灵活的`OpenAILike`路径、在V4-Flash和V4-Pro之间的模型选择、思考模式、嵌入选择(因为DeepSeek不提供嵌入模型),以及传统的`deepseek-chat`/`deepseek-reasoner`迁移窗口。代码示例适用于Python 3.10+。
What you’ll build

一个最小但适合生产的检索增强生成管道:加载文档目录,将它们分块并嵌入到向量存储中,检索与用户查询最相关的段落,并通过LlamaIndex将它们传递给DeepSeek V4。最终,您将拥有一个可以回答您自己数据中问题的脚本,并清楚地了解如何选择DeepSeek模型层级以及在需要推理时如何开启思考模式。
存在两种集成路径。第一种使用专门的 llama-index-llms-deepseek 包,它 继承了 LlamaIndex 的 OpenAILike 类。第二种直接使用 OpenAILike 。两者都击中相同的端点—— POST /chat/completions, the OpenAI-compatible surface at https://api.deepseek.com ——所以选择主要取决于用户体验。以下是两者的代码片段。
Prerequisites
- Python 3.10 或更高版本,在虚拟环境中。
- 一个 DeepSeek API 密钥。如果您还没有,请参阅 get a DeepSeek API key.
- 一个嵌入模型提供者。DeepSeek目前不提供嵌入模型,因此您需要使用OpenAI的
text-embedding-3-small,一个本地模型(BGE、Jina或类似模型,通过Hugging Face获取),或Ollama-served嵌入。 - LlamaIndex安装需要约200MB的磁盘空间,如果使用本地嵌入则需要更多。
- 熟悉LlamaIndex的基本知识——如果不熟悉,请阅读 DeepSeek Python integration first.
选择一个模型:V4-Flash 或 V4-Pro
DeepSeek V4(发布于2026年4月24日)以两个MIT许可下的开放权重专家混合模型的形式发布: deepseek-v4-flash (总参数量284B / 活跃参数量13B)和 deepseek-v4-pro (总容量1.6T / 活跃容量49B)。两者共享一个100万个token的默认上下文窗口,并支持输出高达384,000个token。两者通过相同的参数支持思考模式——它不是一个单独的模型ID。
对于大多数RAG工作负载, deepseek-v4-flash 是正确的默认设置。每百万token的输出成本大约比V4-Pro便宜12倍,延迟更低,并且从上下文合成的任务很少能从前沿级别的推理中受益。当检索到的上下文包含代码、密集的财务表格或多文档推理链(在此情况下,Flash的表现不足)时,请选择V4-Pro。
| Model | Active params | 输入缺失($/M) | Output ($/M) | Best for |
|---|---|---|---|---|
deepseek-v4-flash |
13B | $0.14 | $0.28 | 默认RAG、聊天、摘要 |
deepseek-v4-pro |
49B | $0.435 promo / $1.74 list | $0.87 promo / $3.48 list | 编码代理、复杂的多文档推理 |
2026年4月的价格;请在官方网站上核实 DeepSeek API pricing page before committing.
一个注意事项:如果您正在维护一个仍然使用 deepseek-chat or deepseek-reasoner的旧脚本, deepseek-v4-flash. They retire on 2026-07-24 at 15:59 UTC; migrating is a one-line model= change. The base_url stays the same.
步骤 1:安装软件包
使用专门的DeepSeek包装器,加上一个向量存储和一个嵌入提供者。shell命令安装LlamaIndex核心、DeepSeek LLM包、OpenAI嵌入(在此处仅用于嵌入文本)和文件读取器:
pip install llama-index-core
pip install llama-index-llms-deepseek
pip install llama-index-embeddings-openai
pip install llama-index-readers-file
如果您希望完全避免使用OpenAI,可以将第三行替换为 llama-index-embeddings-huggingface 并使用本地模型,例如 BAAI/bge-small-en-v1.5。这将在您的硬件上保留嵌入,唯一的出站流量就是DeepSeek调用本身。
步骤 2:配置 DeepSeek LLM
专用包为您提供 DeepSeek 类 that 扩展 OpenAILike 并且接受一个 model plus api_key将设置设置为全局 设置s 对象,因此脚本中的每个检索器和查询引擎默认使用DeepSeek。Python:
import os
from llama_index.core import 设置s
from llama_index.llms.deepseek import DeepSeek
from llama_index.embeddings.openai import OpenAIEmbedding
设置s.llm = DeepSeek(
model="deepseek-v4-flash",
api_key=os.environ["DEEPSEEK_API_KEY"],
temperature=1.3, # general conversation default
max_tokens=2048,
)
设置s.embed_model = OpenAIEmbedding(
model="text-embedding-3-small",
api_key=os.environ["OPENAI_API_KEY"],
)
The temperature 数值遵循DeepSeek官方指南: 0.0 for code or maths, 1.0 for data analysis, 1.3 用于一般对话和翻译 1.5 用于创意写作。选择与您的检索任务相匹配的值;对于基于事实的RAG在技术文档上的应用, 0.0 减少漂移。参见更广泛的参数讨论。 DeepSeek prompt engineering.
替代方案:直接使用 OpenAI 进行配置
如果您不想使用第二个包,请指向 OpenAILike 在DeepSeek的基础URL上。这是专用包装器内部使用的相同代码路径:
from llama_index.llms.openai_like import OpenAILike
设置s.llm = OpenAILike(
model="deepseek-v4-flash",
api_base="https://api.deepseek.com/v1",
api_key=os.environ["DEEPSEEK_API_KEY"],
is_chat_model=True,
is_function_calling_model=True,
context_window=1_000_000,
max_tokens=2048,
)
设置 is_chat_model=True 事项 — 没有它,LlamaIndex 将通过遗留的完成路径路由,并且元数据推断会中断。 is_function_calling_model=True 启用工具调用功能,V4 支持在思维和非思维模式下进行。对于更底层的细节,参考文档是开始的地方。如果你更喜欢从 Anthropic SDK 驱动它,DeepSeek 还暴露了一个与 Anthropic 兼容的界面,该界面使用相同的基 URL。 DeepSeek OpenAI SDK compatibility ) 然后构建一个向量索引。API 是无状态的 — LlamaIndex 在每个请求时发送会话历史和检索到的上下文,因为 DeepSeek 不会在服务器端保留之前的回合。
步骤 3:构建索引
将源文件拖入一个 data/ 目录(PDF文件、Markdown、HTML、.txt、.docx文件均由对于更深入的chunking策略、混合检索和针对DeepSeek的重新排序的探讨,该文档读取) 对于更深入的chunking策略、混合检索和针对DeepSeek的重新排序的探讨,该文档将索引包装在查询引擎中并提出一个问题。检索器拉取 top-k 块,LlamaIndex 将它们放入提示中,DeepSeek 综合出一个答案。Python:
from llama_index.core import 对于更深入的chunking策略、混合检索和针对DeepSeek的重新排序的探讨,该文档, VectorStoreIndex
documents = 对于更深入的chunking策略、混合检索和针对DeepSeek的重新排序的探讨,该文档("data").load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="./storage")
介绍了架构选择。这里的最低路径足以实现一个工作原型。 DeepSeek RAG tutorial 流式传输只需更改一个标志——设置
步骤 4:查询索引

. 这提供了逐个标记的输出,使得面向用户的聊天 UI 感觉响应。对于更深入的流式参考,请参阅
query_engine = index.并迭代(similarity_top_k=4)
response = query_engine.query(
"Summarise the refund policy in three bullet points."
)
print(response)
并迭代 并迭代 on 并迭代 docs. docs.. DeepSeek API streaming docs.
步骤 5:开启思考模式(实际需要时)
V4中的思考模式是一个请求参数,而不是一个独立的模型ID。要通过LlamaIndex开启它,请传递 reasoning_effort and the thinking 将extra-body标志传递到底层客户端。 DeepSeek 使用专用包装器:
设置s.llm = DeepSeek(
model="deepseek-v4-pro",
api_key=os.environ["DEEPSEEK_API_KEY"],
additional_kwargs={
"reasoning_effort": "high",
"extra_body": {"thinking": {"type": "enabled"}},
},
)
With thinking enabled, the response returns reasoning_content alongside the final content. LlamaIndex在对于最高设置(您需要≥384,000以避免在非常长的跟踪上截断)。中呈现最终内容 对于最高设置(您需要≥384,000以避免在非常长的跟踪上截断)。;如果需要记录或显示推理跟踪,则可在底层消息对象上找到推理跟踪。使用 reasoning_effort="max" 假设一个面向客户支持的RAG应用每月运行100,000次查询 max_tokens 以确保缓存命中。
一个实用规则:对于涉及检索文档的多步推理查询(法律交叉引用、财务核对、多跳研究)启用思考模式,而对于检索和总结任务则关闭它。思考模式响应成本更高——您需要为推理令牌付费。对于更深入的比较,请参阅 DeepSeek R1 vs OpenAI o1.
步骤 6:成本计算示例
在您认为集成完成之前进行三项检查: deepseek-v4-flash。一个典型请求:1,500个令牌的系统提示(首次调用后缓存),400个令牌的检索上下文加上100个令牌的用户查询(未缓存),以及250个令牌的回答。在V4-Flash速率下列出所有三个桶:
Cached input : 1,500 × 100,000 = 150,000,000 × $0.0028/M = $4.20
Uncached input : 500 × 100,000 = 50,000,000 × $0.14/M = $7.00
Output : 250 × 100,000 = 25,000,000 × $0.28/M = $7.00
------
Total $18.20
在V4-Pro速率下(每百万$0.0145 / $1.74 / $3.48列表,有效$0.003625 / $0.435 / $0.87,通过2026-05-31的75%促销期间),同样的工作量约为$195——大约高11倍。选择与您质量阈值匹配的层级;对于基于事实的RAG,Flash通常在每可接受回答的价格上更具优势。The DeepSeek pricing calculator 自动处理任意令牌混合。请注意,只有当LlamaIndex实际重用前缀时,上下文缓存才会启动——请将系统提示和工具模式保持在系统提示的开头。 messages 确认请求击中DeepSeek。
Verify it worked
Three checks before you call the integration done:
- Confirm the request hits DeepSeek. Set
llama_index.core.set_global_handler("simple")或者使用HTTP调试代理包装,并确认URL是https://api.deepseek.com/v1/chat/completions. - 确认检索到的上下文在提示中。 打印
response.source_nodes——你应该看到为问题检索到的块。 - 确认思考模式(如果已启用)。 延迟明显增加,并且底层响应对象包含非空
reasoning_content.
Common errors and fixes
| Error | 原因 | Fix |
|---|---|---|
模型 `gpt-3.5-turbo` 不存在 |
您使用了纯 OpenAI 类 instead of OpenAILike or DeepSeek |
Switch to OpenAILike with is_chat_model=True |
| 401 Unauthorized | 错误的密钥或错误的环境变量 | 打印 os.environ["DEEPSEEK_API_KEY"][:6]; rotate if leaked |
Empty 对于最高设置(您需要≥384,000以避免在非常长的跟踪上截断)。 in JSON mode |
截断或缺失模式示例 | Raise max_tokens; 在提示中包含单词“json”以及一个小示例模式 |
| 第一次调用慢,后续调用快 | 上下文缓存预热中 | 预期 —— 系统提示前缀现在已缓存在更便宜的层级 |
model_not_found on deepseek-chat 2026年7月之后 |
旧版ID于2026-07-24 15:59 UTC退役 | Change model to deepseek-v4-flash |
Next steps

您有一个基于DeepSeek的RAG管道正在运行。合理的扩展:
- Swap
VectorStoreIndex对于托管向量数据库(Qdrant、Weaviate、Pinecone),一旦您的语料库超过内存。 - 在LLM调用之前添加跨编码的重排序 —— 它几乎总是优于提高
similarity_top_k. - 与LangChain的等效功能进行比较 DeepSeek with LangChain 如果您的团队已经标准化使用LangChain。
- 如果您希望将所有内容都从公共互联网上移除,请指向一个运行着开放DeepSeek权重的本地Ollama服务器——参见
OpenAILike浏览我们其他 running DeepSeek on Ollama. - 以获取端到端应用程序构建。 DeepSeek tutorials ,配置一个嵌入模型(DeepSeek不提供),并从您的文档中构建一个
DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentation and pricing page before committing to a production decision.
Frequently asked questions
我应该如何在 Python 中使用 DeepSeek 与 LlamaIndex?
Install llama-index-llms-deepseek, set 设置s.llm = DeepSeek(model="deepseek-v4-flash", api_key=...)。使用 VectorStoreIndex 进行查询。该包将LlamaIndex的 index.并迭代().query(...)类封装在DeepSeek的与OpenAI兼容的 OpenAILike 类 against DeepSeek’s OpenAI-compatible POST /chat/completions endpoint. Full walkthrough in this DeepSeek Python integration guide.
我应该使用哪个模型与 LlamaIndex 配合——V4-Flash 还是 V4-Pro?
Default to deepseek-v4-flash 用于检索增强生成、聊天和摘要。输出成本为每百万个令牌0.28美元,而促销价为0.87美元/列表价3.48美元。 deepseek-v4-pro,并且大多数RAG查询的瓶颈在于检索质量,而不是生成推理。当你在多文档推理或复杂编码任务上测量Flash失败时,请选择V4-Pro。在[2]详细了解各个级别。 DeepSeek V4 overview.
DeepSeek 为 LlamaIndex 提供嵌入模型吗?
不——DeepSeek目前不提供嵌入模型,因此您需要外部提供商。常见选择是OpenAI的[3] ,本地Hugging Face模型如BGE或Jina,或Ollama托管嵌入。如果您想将文档内容保留在第三方服务器之外,请选择本地托管嵌入。 text-embedding-3-small。用于多步推理查询,并在直接摘要时关闭。更多详情请参阅[4]。 DeepSeek API documentation 覆盖了聊天界面但不包括嵌入层。
我应该如何在 LlamaIndex 中启用 DeepSeek 思考模式?
思考是一个请求参数,在V4模型中,而不是一个单独的模型ID。传递即可。 reasoning_effort="high" and extra_body={"thinking": {"type": "enabled"}} through additional_kwargs on the DeepSeek or OpenAILike 客户端。然后响应返回 reasoning_content alongside the final content. Use it for multi-step reasoning queries and leave it off for straight summarisation. More detail in the DeepSeek API best practices.
为什么在使用 DeepSeek 与 LlamaIndex 配合时会出现“找不到模型”错误?
两个常见原因。首先,你可能正在使用LlamaIndex的普通 OpenAI 类, which restricts model names to GPT family — switch to OpenAILike 或专用的 DeepSeek 包装器。其次,在2026-07-24 15:59 UTC之后,旧版ID deepseek-chat and deepseek-reasoner 已被淘汰;更新 model to deepseek-v4-flash or deepseek-v4-pro. See the DeepSeek API error codes 参考以获取完整列表。
Sources & Methodology
Last source check: April 30, 2026
Primary sources
- OfficialDeepSeek API documentationEndpoints, request/response shape, model IDsLast checked: April 30, 2026
- PricingDeepSeek API pricing pagePer-1M-token rates, billing units, cache-hit pricingLast checked: April 30, 2026
- Model cardDeepSeek on Hugging FaceWeights, license, usage notes per modelLast checked: April 30, 2026
- RepositoryLlamaIndex DeepSeek LLM API 参考文档Confirms the DeepSeek 类 sub类es OpenAILikeLast checked: April 30, 2026
- RepositoryLlamaIndex DeepSeek 示例笔记本展示了教程中使用的模型 + api_key 构造函数签名Last checked: April 30, 2026
Technical references
- Technical reportDeepSeek-R1 paper (arXiv:2501.12948)R1 reasoning approach, distillation resultsLast checked: April 30, 2026
Methodology
本文信息已对照官方DeepSeek文档、文章引用的主要来源以及上述日期的deepseekai.guide定价数据集进行核对。对于引用的第三方数据,原始来源已在行内链接,以便读者验证和重新检查。
Data confidence
High for facts cited inline with primary-source links; medium for context narrative.
Editorial note
人工智能工具发展迅速。如果您发现过时的数字或损坏的链接,页脚中的联系链接是向编辑团队报告的最快方式。