How to use DeepSeek with LlamaIndex for RAG (V4 tutorial)

You have a folder of PDFs, a DeepSeek API key, and a question: how do I get LlamaIndex to answer questions over my documents using DeepSeek instead of OpenAI? This tutorial walks through wiring up DeepSeek with LlamaIndex end-to-end on the current API — from pip install to a working query engine that retrieves chunks, calls deepseek-flash, and streams an answer back. We’ll cover the official llama-index-llms-deepseek package, the more flexible OpenAILike route, model selection between deepseek-flash and deepseek-v4-pro, thinking mode, embedding choices (since DeepSeek does not ship an embedding model), and migrating from the retired deepseek-chat / deepseek-reasoner IDs. Code examples are Python 3.10+.
What you’ll build

A minimal but production-shaped Retrieval-Augmented Generation pipeline: load a directory of documents, chunk and embed them into a vector store, retrieve the most relevant passages for a user query, and pass them to deepseek-flash through LlamaIndex. By the end you’ll have a script that answers questions over your own data, plus a clear understanding of which DeepSeek model to pick and how to switch thinking mode on when a query genuinely needs reasoning.
Two integration paths exist. The first uses the dedicated llama-index-llms-deepseek package, whose DeepSeek class subclasses LlamaIndex’s OpenAILike class. The second uses OpenAILike directly. Both hit the same endpoint — POST /chat/completions, the OpenAI-compatible surface at https://api.deepseek.com — so the choice is mostly ergonomic. Snippets for both follow.
Prerequisites
- Python 3.10 or newer, in a virtualenv (the current LlamaIndex packages on PyPI require Python 3.10+).
- A DeepSeek API key, exported as the
DEEPSEEK_API_KEYenvironment variable. If you don’t have one yet, see get a DeepSeek API key. - An embedding provider. DeepSeek does not currently ship an embedding model, so you’ll need either OpenAI’s
text-embedding-3-small, a local model (BGE, Jina, or similar through Hugging Face), or Ollama-served embeddings. - Disk space for the LlamaIndex install, more if you go local-embedding.
- Familiarity with the LlamaIndex basics — if not, read DeepSeek Python integration first.
Pick a model: deepseek-flash or deepseek-v4-pro
DeepSeek’s API currently lists two models: deepseek-flash, served by DeepSeek-V4.1-Flash-1017 (released 17 October 2026), and deepseek-v4-pro, served by DeepSeek-V4-Pro-0813 (released 13 August 2026). Both have open weights under the MIT license on Hugging Face, a 1M-token context window and a maximum output of 384K tokens. Both support thinking and non-thinking mode through the same request parameter — it is not a separate model ID — and thinking is the default.
For most RAG workloads, deepseek-flash is the right default. Its output is 3.3× cheaper than V4-Pro per million tokens, and synthesis-from-context tasks rarely need the larger model. Reach for V4-Pro when the retrieved context contains code, dense financial tables, or multi-document reasoning chains where you’ve measured Flash falling short.
| Model | Served by | Input, cache miss ($/M, peak / off-peak) | Output ($/M, peak / off-peak) | Best for |
|---|---|---|---|---|
deepseek-flash |
DeepSeek-V4.1-Flash-1017 | $0.30 / $0.15 | $1.20 / $0.60 | Default RAG, chat, summarisation |
deepseek-v4-pro |
DeepSeek-V4-Pro-0813 | $1.32 / $0.66 | $3.96 / $1.98 | Coding agents, complex multi-doc reasoning |
Pricing as of November 2026 from the official DeepSeek pricing page. Off-peak rates are half the peak rates; peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays. Cache-hit input costs $0.006 / $0.003 on Flash and $0.044 / $0.022 on V4-Pro. See our DeepSeek API pricing guide for details.
One legacy note: if you’re maintaining an older script that still uses deepseek-chat or deepseek-reasoner, those IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC and are no longer listed in DeepSeek’s docs. The legacy name deepseek-v4-flash is still accepted but is served by DeepSeek-V4.1-Flash-1017 at the Flash price. Migrating is a one-line model="deepseek-flash" change; the base_url stays the same.
Step 1: Install the packages
Use the dedicated DeepSeek wrapper plus a vector store and an embedding provider. The shell commands install LlamaIndex core, the DeepSeek LLM package, OpenAI embeddings (used here only for embedding text), and the file readers:
pip install llama-index-core
pip install llama-index-llms-deepseek
pip install llama-index-embeddings-openai
pip install llama-index-readers-file
If you’d rather avoid OpenAI entirely, swap the third line for llama-index-embeddings-huggingface and use a local model such as BAAI/bge-small-en-v1.5. That keeps embeddings on your own hardware and the only outbound traffic is the DeepSeek call itself.
Step 2: Configure the DeepSeek LLM
The dedicated package gives you a DeepSeek class that extends OpenAILike and accepts a model plus api_key. Set it on the global Settings object so every retriever and query engine in the script uses DeepSeek by default. Python:
import os
from llama_index.core import Settings
from llama_index.llms.deepseek import DeepSeek
from llama_index.embeddings.openai import OpenAIEmbedding
Settings.llm = DeepSeek(
model="deepseek-flash",
api_key=os.environ["DEEPSEEK_API_KEY"],
context_window=1_000_000,
temperature=1.3, # general conversation default (non-thinking mode only)
max_tokens=2048,
additional_kwargs={
"extra_body": {"thinking": {"type": "disabled"}},
},
)
Settings.embed_model = OpenAIEmbedding(
model="text-embedding-3-small",
api_key=os.environ["OPENAI_API_KEY"],
)
Two settings need explaining. First, context_window: version 0.4.1 of llama-index-llms-deepseek (the current release on PyPI) only knows the old deepseek-chat / deepseek-reasoner names and falls back to 64,000 tokens for any other model, so pass the real 1M window yourself. Second, thinking: it is the API default, and this config switches it off with extra_body={"thinking": {"type": "disabled"}} because plain retrieve-and-summarise queries rarely need it (Step 5 shows how to turn it on).
The temperature values follow DeepSeek’s official guidance: 0.0 for code or maths, 1.0 for data analysis, 1.3 for general conversation and translation, 1.5 for creative writing. They apply in non-thinking mode only — thinking mode accepts temperature without error but ignores it. Choose the value that matches your retrieval task; for fact-grounded RAG over technical documents, 0.0 reduces drift. See the broader parameter discussion in DeepSeek prompt engineering.
Alternative: configure with OpenAILike directly
If you don’t want a second package, point OpenAILike (from llama-index-llms-openai-like) at DeepSeek’s base URL. This is the same code path the dedicated wrapper uses internally:
from llama_index.llms.openai_like import OpenAILike
Settings.llm = OpenAILike(
model="deepseek-flash",
api_base="https://api.deepseek.com",
api_key=os.environ["DEEPSEEK_API_KEY"],
is_chat_model=True,
is_function_calling_model=True,
context_window=1_000_000,
max_tokens=2048,
additional_kwargs={
"extra_body": {"thinking": {"type": "disabled"}},
},
)
Setting is_chat_model=True matters — without it, LlamaIndex routes through the legacy completion path and metadata inference breaks. is_function_calling_model=True enables tool calling, which both DeepSeek models support in thinking and non-thinking modes (the DeepSeek wrapper leaves it off for any model name other than deepseek-chat, so pass it explicitly there too if you need tools). One caveat: in thinking mode, requests that carry tools must pass every previous turn’s reasoning_content back to the API or it returns a 400 error, and the current llama-index-llms-openai release (0.8.4) drops reasoning blocks when it sends history back — so keep thinking disabled for tool-calling agents. For the lower-level details, the DeepSeek OpenAI SDK compatibility reference is the place to start. DeepSeek also exposes an Anthropic-compatible surface at https://api.deepseek.com/anthropic if you’d prefer to drive it from the Anthropic SDK.
Step 3: Build the index
Drop your source files into a data/ directory (PDFs, Markdown, HTML, .txt, .docx are all read by SimpleDirectoryReader). Then build a vector index. The API is stateless — LlamaIndex sends the conversation history and retrieved context on every request, since DeepSeek does not retain prior turns server-side.
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="./storage")
For a deeper look at chunking strategies, hybrid retrieval, and reranking against DeepSeek, the DeepSeek RAG tutorial covers the architectural choices. The minimal path here is enough for a working prototype.
Step 4: Query the index

Wrap the index in a query engine and ask a question. The retriever pulls the top-k chunks, LlamaIndex stuffs them into a prompt, and DeepSeek synthesises an answer. Python:
query_engine = index.as_query_engine(similarity_top_k=4)
response = query_engine.query(
"Summarise the refund policy in three bullet points."
)
print(response)
Streaming is a one-flag change — set streaming=True on as_query_engine and iterate response.response_gen. That gives token-by-token output, which makes user-facing chat UIs feel responsive. For a deeper streaming reference see the DeepSeek API streaming docs.
Step 5: Switch on thinking mode (when you actually need it)
Thinking mode is a request parameter, not a separate model ID, and it is on by default on DeepSeek’s API — the Step 2 config switched it off. To turn it back on through LlamaIndex, pass reasoning_effort and the thinking extra-body flag through additional_kwargs (the wrapper’s own reasoning_effort field is only forwarded for OpenAI’s own reasoning models). With the dedicated DeepSeek wrapper:
Settings.llm = DeepSeek(
model="deepseek-v4-pro",
api_key=os.environ["DEEPSEEK_API_KEY"],
context_window=1_000_000,
additional_kwargs={
"reasoning_effort": "high",
"extra_body": {"thinking": {"type": "enabled"}},
},
)
With thinking enabled, the API returns reasoning_content alongside the final content. LlamaIndex surfaces the final content in response.response and stores the reasoning trace as a ThinkingBlock in the chat message’s blocks if you want to log or display it. reasoning_effort accepts "low", "high" (the default) or "max"; use "max" for the most complex queries, and don’t set max_tokens so low that long answers are cut off (the maximum output on both models is 384K tokens).
A practical rule: enable thinking for queries that involve multi-step inference over retrieved documents (legal cross-references, financial reconciliation, multi-hop research) and leave it off for retrieval-and-summarise tasks. Thinking-mode responses cost more — you pay for the reasoning tokens as output. For a deeper comparison, see DeepSeek R1 vs OpenAI o1.
Step 6: Cost calculation worked example
Suppose a customer-support RAG application running 100,000 queries per month against deepseek-flash with thinking disabled. A typical request: a 1,500-token system prompt (cached after the first call), 400 tokens of retrieved context plus a 100-token user query (uncached), and a 250-token answer. Enumerating all three buckets at deepseek-flash rates (USD per 1M tokens, November 2026):
PEAK OFF-PEAK
Cached input : 1,500 × 100,000 = 150,000,000 × $0.006/M = $0.90 × $0.003/M = $0.45
Uncached input : 500 × 100,000 = 50,000,000 × $0.30/M = $15.00 × $0.15/M = $7.50
Output : 250 × 100,000 = 25,000,000 × $1.20/M = $30.00 × $0.60/M = $15.00
------ ------
Total $45.90 $22.95
The same workload at deepseek-v4-pro rates ($0.044 / $1.32 / $3.96 per million at peak; $0.022 / $0.66 / $1.98 off-peak) comes to $171.60 at peak ($6.60 + $66.00 + $99.00) or $85.80 off-peak ($3.30 + $33.00 + $49.50) — about 3.7× higher. A real month usually straddles both periods, so expect a total between the two figures. With thinking on, reasoning tokens are added to the output line. Pick the tier that matches your quality threshold; for grounded RAG, Flash usually wins on price-per-acceptable-answer. The DeepSeek pricing calculator automates this for arbitrary token mixes. Note that context caching kicks in only when LlamaIndex actually reuses a prefix — keep your system prompt and tool schemas at the start of messages for the cache to hit.
Verify it worked
Three checks before you call the integration done:
- Confirm the request hits DeepSeek. Set
llama_index.core.set_global_handler("simple")or wrap with an HTTP debug proxy and confirm the URL ishttps://api.deepseek.com/chat/completions. - Confirm retrieved context is in the prompt. Print
response.source_nodes— you should see the chunks that were retrieved for the question. - Confirm thinking mode (if enabled). Call
Settings.llm.chat(...)directly and check that the returned message’sblocksinclude aThinkingBlock— LlamaIndex’s copy of the API’sreasoning_content.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
The model `gpt-3.5-turbo` does not exist |
You used the plain OpenAI class instead of OpenAILike or DeepSeek |
Switch to OpenAILike with is_chat_model=True |
| 401 Unauthorized | Wrong key or wrong env var | Print os.environ["DEEPSEEK_API_KEY"][:6]; rotate if leaked |
Empty response.response in JSON mode |
Truncation or missing schema example | Raise max_tokens; include the word “json” plus a small example schema in the prompt |
| Slow first call, fast subsequent calls | Context cache warming up | Expected — the system-prompt prefix is now cached at the cheaper tier |
| 400 error in a tool-calling agent | Thinking mode is on and LlamaIndex did not pass reasoning_content back |
Disable thinking with extra_body={"thinking": {"type": "disabled"}} |
Model error on deepseek-chat or deepseek-reasoner |
Legacy IDs scheduled for retirement on 2026-07-24 15:59 UTC and no longer listed | Change model to deepseek-flash |
Next steps

You have a working DeepSeek-backed RAG pipeline. Reasonable extensions:
- Swap
VectorStoreIndexfor a hosted vector DB (Qdrant, Weaviate, Pinecone) once your corpus exceeds memory. - Add reranking with a cross-encoder before the LLM call — it is often more effective than raising
similarity_top_k. - Compare against the LangChain equivalent in DeepSeek with LangChain if your team already standardises on LangChain.
- If you want to keep everything off the public internet, point
OpenAILikeat a local Ollama server — note that Ollama’sdeepseek-v4.1-flashanddeepseek-v4-protags are cloud-only, so a fully local setup uses a smaller model such asdeepseek-r1:8b. See running DeepSeek on Ollama. - Browse the rest of our DeepSeek tutorials for end-to-end app builds.
Frequently asked questions
How do I use DeepSeek with LlamaIndex in Python?
Install llama-index-llms-deepseek, set Settings.llm = DeepSeek(model="deepseek-flash", api_key=os.environ["DEEPSEEK_API_KEY"], context_window=1_000_000), configure an embedding model (DeepSeek does not ship one), and build a VectorStoreIndex from your documents. Query it with index.as_query_engine().query(...). The package wraps LlamaIndex’s OpenAILike class against DeepSeek’s OpenAI-compatible POST /chat/completions endpoint. Full walkthrough in this DeepSeek Python integration guide.
What model should I use with LlamaIndex — deepseek-flash or deepseek-v4-pro?
Default to deepseek-flash for retrieval-augmented generation, chat, and summarisation. As of November 2026 its output costs $1.20 per million tokens at peak and $0.60 off-peak, versus $3.96 / $1.98 for deepseek-v4-pro, and most RAG queries are bottlenecked by retrieval quality, not generation reasoning. Reach for V4-Pro when you have measured Flash failing on multi-document reasoning or complex coding tasks. Compare the models in detail at the DeepSeek V4 overview.
Does DeepSeek provide an embedding model for LlamaIndex?
No — DeepSeek does not currently ship an embedding model, so you’ll need an external provider. Common choices are OpenAI’s text-embedding-3-small, a local Hugging Face model such as BGE or Jina, or Ollama-hosted embeddings. Pick locally hosted embeddings if you want to keep document content off third-party servers. The DeepSeek API documentation covers the chat surface but not embeddings.
How do I enable DeepSeek thinking mode in LlamaIndex?
Thinking is a request parameter on both deepseek-flash and deepseek-v4-pro, not a separate model ID, and DeepSeek’s API enables it by default. To set it explicitly, pass reasoning_effort="high" and extra_body={"thinking": {"type": "enabled"}} through additional_kwargs on the DeepSeek or OpenAILike client; use {"type": "disabled"} to turn it off. The response then returns reasoning_content alongside the final content. Use it for multi-step reasoning queries and leave it off for straight summarisation and tool-calling agents. More detail in the DeepSeek API best practices.
Why am I getting a “model not found” error when using DeepSeek with LlamaIndex?
Two common causes. First, you may be using LlamaIndex’s plain OpenAI class, which restricts model names to OpenAI’s own models — switch to OpenAILike or the dedicated DeepSeek wrapper. Second, the legacy IDs deepseek-chat and deepseek-reasoner were scheduled for retirement on 2026-07-24 15:59 UTC and are no longer listed in DeepSeek’s docs; update model to deepseek-flash or deepseek-v4-pro. See the DeepSeek API error codes reference for the full list.
Sources & Methodology
Primary sources
- OfficialDeepSeek API documentationEndpoints, request/response shape, model IDsLast checked: November 12, 2026
- Model cardDeepSeek on Hugging FaceWeights, license, usage notes per modelLast checked: November 12, 2026
- RepositoryLlamaIndex DeepSeek LLM API referenceConfirms the DeepSeek class subclasses OpenAILikeLast checked: November 12, 2026
- RepositoryLlamaIndex DeepSeek integration exampleShows the model + api_key constructor signature used in the tutorialLast checked: November 12, 2026
- Repositoryllama-index-llms-deepseek on PyPICurrent package version (0.4.1), Python 3.10+ requirement and the 64,000-token context fallback for unlisted model namesLast checked: November 12, 2026
Technical references
- Technical reportDeepSeek-R1 paper (arXiv:2501.12948)R1 reasoning approach, distillation resultsLast checked: November 12, 2026
- OfficialDeepSeek API — Models & PricingModel names, 1M context, 384K max output, peak and off-peak pricesLast checked: November 12, 2026
- OfficialDeepSeek API — Thinking Mode guideThinking on by default, enable/disable flag, reasoning_effort, ignored temperature, reasoning_content passback with toolsLast checked: November 12, 2026
Methodology
Information in this article was checked against the official DeepSeek documentation, the article's cited primary sources, and the deepseekai.guide pricing dataset on the date shown above. Where third-party numbers are quoted, the originating source is linked inline so the reader can verify and re-check.
Data confidence
High for facts cited inline with primary-source links; medium for context narrative.
Editorial note
AI tooling moves quickly. If you spot an outdated number or a broken link, the contact link in the footer is the fastest way to flag it for the editorial team.
