ctransformers: Number of Tokens Exceeded Maximum Context Length
The ctransformers context length warning usually means the model loaded with a 512-token window, most often from an old GGML .bin file with no context metadata. Set context_length=4096 in the config dict, or as a keyword argument in the native API, and reload.
- The ctransformers default for context_length is -1, meaning use the value stored in the model file, so a persistent 512 usually points to an old GGML .bin file or a setting that never reached the library.
- A Llama 2 GGUF file stores a 4096-token context, while old GGML .bin files carry no context metadata and fall back to 512.
- In LangChain, context_length and max_new_tokens must go inside the config dict, not as top-level keyword arguments.
- The window holds prompt, retrieved context, chat history and output together, so prompt tokens + max_new_tokens must stay at or below context_length.
- Larger windows cost RAM through the KV cache and slow generation, so size the window to what the app needs.
The one-line fix: set context_length inside config
The warning 'Number of tokens (513) exceeded maximum context length (512)' points to the ctransformers context length the model was loaded with, not to a limit of Llama 2. The library's own default is -1, which means 'use the model's value'. A Llama 2 GGUF file stores 4096, so a 512 limit usually comes from an old GGML .bin file with no context metadata, where the llama.cpp fallback is 512.
The fix is the same in every case: set the value explicitly. In LangChain, pass it inside the config dictionary. This is the full working version:
from langchain_community.llms import CTransformers
llm = CTransformers(
model="TheBloke/Llama-2-7B-Chat-GGUF",
model_file="llama-2-7b-chat.Q4_K_M.gguf",
model_type="llama",
config={
"max_new_tokens": 512,
"context_length": 4096,
"temperature": 0.2,
"repetition_penalty": 1.1,
},
)
print(llm.invoke("Summarise the plot of Hamlet in five sentences."))Why is the ctransformers context length only 512?
In current ctransformers, the Config default for context_length is -1. That value tells the library to use the context length stored in the model file's metadata. A Llama 2 GGUF stores 4096, so a correctly loaded GGUF should not report 512.
The usual culprit is an old GGML .bin file. These files have no context metadata, so the llama.cpp fallback of 512 applies. Check the file extension first: a .bin from a 2023 download is the most common source of the 512 limit.
The second cause is a setting that never arrived. In LangChain, a context_length passed as a top-level keyword argument is ignored, so the model loads with whatever the file or fallback provides. Third, an explicit context_length=512 copied from an old tutorial will of course be honored.
The context window is one shared budget. It covers the system prompt, your instructions, retrieved documents, chat history, the user question and the generated answer. The warning fires when the running total goes past the limit.
It is a warning, not an exception. Generation continues, but the library has no room left, so answers get cut off, repeat themselves, or drift into garbled text. Treat it as a real defect.
The default max_new_tokens is 256, which is a separate limit on the answer length only.
How do I set context_length with the native ctransformers API?
Without LangChain, pass the values straight to from_pretrained as keyword arguments. Here they are top-level arguments, which is the opposite of the LangChain wrapper.
from ctransformers import AutoModelForCausalLM
llm = AutoModelForCausalLM.from_pretrained(
"TheBloke/Llama-2-7B-Chat-GGUF",
model_file="llama-2-7b-chat.Q4_K_M.gguf",
model_type="llama",
context_length=4096,
max_new_tokens=512,
)
text = llm("Explain the KV cache in two paragraphs.")
print(text)context_length vs max_new_tokens: how to budget tokens
context_length is the total window. max_new_tokens only caps the answer. The rule is: prompt tokens + max_new_tokens <= context_length.
Setting max_new_tokens equal to context_length leaves zero room for the prompt, which recreates the warning immediately.
Worked example with context_length=4096 and max_new_tokens=512: the prompt can use at most 3584 tokens. If the system prompt takes 150 and the question 50, 3384 tokens remain for retrieved context and history. At roughly 0.75 words per token, that is about 2500 words.
Count tokens before sending. With the native API, tokenize the text and take the length. These are the main config keys:
| Config key | Controls | Default | Typical Llama 2 value |
|---|---|---|---|
| context_length | Total window: prompt + history + output | -1 (use the model file's value; 512 fallback for old .bin files) | 4096 |
| max_new_tokens | Maximum generated tokens per call | 256 | 256 to 1024 |
| temperature | Sampling randomness | 0.8 | 0.1 to 0.7 |
| repetition_penalty | Discourages loops | 1.1 | 1.1 |
| threads | CPU threads used | auto | physical core count |
| gpu_layers | Layers offloaded to GPU | 0 | as VRAM allows |
prompt = "...your assembled prompt..."
n_prompt = len(llm.client.tokenize(prompt)) # LangChain wrapper
# native API: n_prompt = len(llm.tokenize(prompt))
budget = 4096 - 512
if n_prompt > budget:
print(f"Prompt too long: {n_prompt} > {budget}")Why do RAG apps and chat memory hit the limit?
Retrieval chains stuff documents into the prompt. With k=6 and chunk_size=1000 characters (about 250 tokens each), retrieval alone adds roughly 1500 tokens. Raise chunk_size to 2000 and k to 8 and you pass 4000 before the question.
ConversationBufferMemory makes it worse, because it appends every turn forever. Each reply of 300 tokens adds up, so a chat that works for five turns fails at the sixth.
Pick the fix by cause:
| Symptom | Cause | Fix |
|---|---|---|
| Warning on first question, limit shows 512 | Old GGML .bin file with no context metadata (512 fallback), or an explicit 512 in your code | Set context_length=4096 in config, or switch to a GGUF file |
| Warning only with retriever | k too high or large chunks | retriever k of 2 to 4, chunk_size 500 to 800 |
| Warning after several turns | Unbounded chat history | ConversationBufferWindowMemory(k=3) or summary memory |
| Long history needed | Window too small for transcript | ConversationSummaryMemory to compress older turns |
| Setting seems ignored | Value passed as kwarg to LangChain | Move it inside config={...} |
from langchain.memory import ConversationBufferWindowMemory
memory = ConversationBufferWindowMemory(k=3, memory_key="chat_history")
retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) What are the limits and costs of a bigger context window?
Do not exceed the length the model was trained on. Original LLaMA 1 supports 2048, Llama 2 supports 4096, and Code Llama variants were trained for 16k or more. Beyond that, quality drops even if the loader accepts the number.
Memory also grows with context. For a 7B Llama 2 model, the fp16 KV cache is about 0.5 MB per token, so 4096 tokens is roughly 2 GB on top of the model weights (a Q4 7B file is about 4 GB). Attention cost also rises with length, so latency increases on CPU-only machines.
Size the window to what the app needs. If prompts never exceed 1500 tokens, 2048 saves RAM and time. If the machine starts swapping, lower the window or use a smaller quantization.
How do I verify the fix, and what if the setting is ignored?
Verification is quick and should use the prompt that originally failed.
- Check whether your model file ends in .bin or .gguf; a .bin file explains a 512 fallback.
- Restart the Python process so the model reloads with the new config; the window is fixed at load time.
- Re-run the long prompt or full RAG chain that produced the warning.
- Confirm the 'exceeded maximum context length' message no longer appears.
- Check that the answer ends cleanly in a full sentence. If it stops mid-sentence, raise max_new_tokens while keeping prompt + max_new_tokens <= context_length.
- Log len(llm.client.tokenize(prompt)) in your app to catch regressions early.
What is the equivalent setting in llama-cpp-python?
LangChain's LlamaCpp wrapper and llama-cpp-python use different names for the same ideas. Its default n_ctx is also small (512 in older releases), so set it explicitly there too.
| Concept | ctransformers | llama-cpp-python / LlamaCpp |
|---|---|---|
| Total window | context_length | n_ctx |
| Output cap | max_new_tokens | max_tokens |
| CPU threads | threads | n_threads |
| GPU offload | gpu_layers | n_gpu_layers |
| Where set (LangChain) | inside config={} | top-level argument |
from langchain_community.llms import LlamaCpp
llm = LlamaCpp(
model_path="./llama-2-7b-chat.Q4_K_M.gguf",
n_ctx=4096,
max_tokens=512,
temperature=0.2,
) Common questions
Is the ctransformers tokens exceeded warning an error?
No, it is a warning and generation continues. Output can be truncated, repetitive or garbled once the window is full, so fix the configuration rather than ignoring it.
Can I set context_length higher than 4096 for Llama 2?
The loader may accept it, but Llama 2 was trained on 4096 tokens, so quality degrades beyond that. Use a model trained or fine-tuned for longer contexts if you need more.
What is the default max_new_tokens in ctransformers?
The default is 256 tokens. Answers longer than that are cut off even when the context window has space, so raise it to 512 or more for long answers.
Why is my context_length ignored in LangChain?
Most often it was passed as a top-level keyword argument instead of inside config={...}. Move it into the config dictionary and restart the process so the model reloads.
How many words fit in 4096 tokens?
About 3000 English words at roughly 0.75 words per token, shared between prompt and output. Code, numbers and non-English text use more tokens per word, so fewer words fit.