Howwise RSS
AI & Automation7 min read

LangChain Chroma Stops at 99 Documents: Causes and Fixes

Short answer

The langchain chroma 99 documents stop is not a built-in limit; it is a symptom of a hidden exception, such as an OpenAI 429 or quota error, a token limit, a Chroma batch limit, or a loop re-embedding every chunk. Capture the traceback first.

Key takeaways
  • The 99 figure is not a built-in limit of Chroma, LangChain or OpenAI; it is where an exception happened to hit.
  • Calling Chroma.from_documents inside a per-chunk loop re-embeds every chunk each pass, multiplying cost, rate-limit hits and duplicates.
  • Create the store once, then add_documents in batches of 50 to 100 with backoff, stable ids and a final count check.
  • Chroma's max batch size (often 5461 on SQLite builds) is separate from OpenAI's per-request input and token limits.
  • Editing the SQLite file by hand proves nothing, because Chroma also keeps HNSW and metadata segments in separate files.

Why does LangChain Chroma stop at 99 documents?

When the langchain chroma 99 documents problem appears, no component actually has a hard cap of 99 records. Chroma accepts many thousands per call, LangChain passes lists straight through, and OpenAI embeddings accept up to 2048 inputs per request. When a run dies near a round number, an exception interrupted it, often in a retry-less call that failed partway.

The usual pattern is a loop like `for i, chunk in enumerate(chunks): Chroma.from_documents(chunks, ...)`. Each iteration embeds all chunks again, so by iteration 99 you have sent roughly 99 times the intended tokens. That is exactly how a new or low-tier OpenAI account reaches a 429 or quota error and appears to hit a limit.

Start by wrapping the call and printing the full error rather than reading the last line of a scrolled terminal.

import traceback

try:
    db = Chroma.from_documents(chunks, embeddings, persist_directory="./chroma_db")
except Exception:
    traceback.print_exc()   # full chain, including the __cause__ from openai or chromadb
    raise
Tip: Look at the exception class and the chained 'The above exception was the direct cause' section. LangChain often wraps the real openai.RateLimitError or chromadb error underneath.

Which error maps to which cause?

Match the message you captured to this table. The fix column is the part to apply first.

Rows are ordered roughly by how often they appear in this scenario.

Error or symptomCauseFix
openai.RateLimitError 429 'Rate limit reached'Too many requests or tokens per minute, often from re-embedding in a loopRemove the loop, batch, add exponential backoff
429 with code insufficient_quotaNo credit or billing not set up on the account or projectAdd prepaid credit, check the correct project and API key
400 'maximum context length is 8192 tokens'A single chunk exceeds the embedding model's input limitReduce chunk_size in the splitter, check lengths with tiktoken
400 'max 300000 tokens per request' or too many inputsBatch has too many total tokens or more than 2048 inputsLower OpenAIEmbeddings chunk_size, use smaller batches
ValueError: Batch size N exceeds maximum batch size 5461Chroma's per-call limit, derived from the SQLite buildAdd documents in batches below the limit
Count lower than len(chunks), no errorEarlier run crashed, or ids collided and overwrote recordsUse unique stable ids, rerun, compare counts
Duplicates after rerunRandom uuid ids on each runUse deterministic ids and upsert
sqlite3 version error on importSystem SQLite older than Chroma requiresUse the pysqlite3-binary workaround

How do OpenAI limits and chunk size interact?

There are two separate OpenAI constraints. Each individual input must fit the model's context, which is 8192 tokens for text-embedding-3-small and text-embedding-3-large. Each request also has caps on input count (2048) and total tokens (about 300k), and your account has requests-per-minute and tokens-per-minute limits on top.

Chunks of 500 to 1000 tokens are far below the per-input limit, so the per-request total is what matters. 2048 inputs of 800 tokens is 1.6 million tokens, which breaks the request cap. LangChain's OpenAIEmbeddings splits inputs into sub-requests using its chunk_size parameter (its default is 1000 in older versions), so set it explicitly lower if you see token-limit errors.

To check your own limits, open the Limits page in the OpenAI platform settings and the Usage page for the correct project. Response headers such as x-ratelimit-remaining-tokens also show live headroom. A new or free-tier account can have very low limits and zero credit, which makes quota errors appear within minutes.

from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(
    model="text-embedding-3-small",
    chunk_size=100,      # inputs per underlying API request
    max_retries=6,       # built-in retry on 429 / transient errors
)

What is Chroma's maximum batch size and how do I stay under it?

Chroma rejects a single add call larger than its max batch size, which depends on the SQLite build's variable limit and is often 5461. Newer versions of langchain-chroma split large add_documents calls for you, while older langchain and chromadb combinations raise the ValueError 'Batch size ... exceeds maximum batch size'.

Do not rely on that behavior. Batching yourself works on every version and also keeps embedding requests small. You can read the limit from the client.

Since OpenAI limits usually bite first, a batch of 50 to 100 is safe for both.

import chromadb
client = chromadb.PersistentClient(path="./chroma_db")
print(client.get_max_batch_size())   # e.g. 5461

What is the reliable ingestion script?

This script creates the store once, uses deterministic ids so reruns overwrite instead of duplicating, retries with exponential backoff using tenacity, logs progress and verifies the count. Install with `pip install -U langchain-chroma langchain-openai langchain-text-splitters tenacity tiktoken`.

The retry predicate inspects each 429. Rate-limit errors and connection errors are retried, but an insufficient_quota error is re-raised immediately because waiting cannot fix a billing problem.

Chroma 0.4 and later persist automatically when you use a persistent client or persist_directory, so you do not call persist(). Import from langchain_chroma, not the deprecated langchain.vectorstores.

import hashlib, logging
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from tenacity import retry, wait_random_exponential, stop_after_attempt, retry_if_exception
import openai

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("ingest")

# max_retries=2 keeps the client's own retries short; tenacity below handles the long waits
embeddings = OpenAIEmbeddings(model="text-embedding-3-small", chunk_size=100, max_retries=2)
db = Chroma(
    collection_name="docs",
    embedding_function=embeddings,
    persist_directory="./chroma_db",
)

def make_id(doc, idx):
    key = f"{doc.metadata.get('source','')}|{idx}|{doc.page_content}"
    return hashlib.sha256(key.encode()).hexdigest()

def is_retryable(exc):
    if isinstance(exc, openai.RateLimitError):
        # quota exhaustion is also a 429 RateLimitError, but retrying cannot fix it
        code = getattr(exc, "code", None)
        return code != "insufficient_quota" and "insufficient_quota" not in str(exc)
    return isinstance(exc, (openai.APIConnectionError, openai.APITimeoutError))

@retry(
    retry=retry_if_exception(is_retryable),
    wait=wait_random_exponential(min=2, max=60),
    stop=stop_after_attempt(8),
    reraise=True,   # surface the original openai error, not tenacity's RetryError
)
def add_batch(docs, ids):
    db.add_documents(docs, ids=ids)

BATCH = 50
ids_all = [make_id(d, i) for i, d in enumerate(chunks)]
for start in range(0, len(chunks), BATCH):
    docs = chunks[start:start + BATCH]
    ids = ids_all[start:start + BATCH]
    try:
        add_batch(docs, ids)
    except Exception:
        log.exception("failed at batch starting %d", start)
        raise
    log.info("added %d/%d", min(start + BATCH, len(chunks)), len(chunks))

print(db._collection.count(), "stored of", len(chunks))
Warning: A 429 'rate limit' and a 429 'insufficient_quota' are both openai.RateLimitError, so filtering by class alone would retry quota failures up to 8 times with waits of up to 60 seconds each. The predicate above checks the error code and message and fails fast on quota errors; when that happens, stop and fix billing or the project's credit.

How do I avoid duplicates, wasted cost and a corrupt store?

Because ids derive from source, position and content, rerunning the script upserts the same records. If content changes, the id changes, so old versions linger. To rebuild cleanly, delete the collection or the directory before ingesting.

Deleting the persist directory destroys all stored vectors and cannot be undone, so confirm the path first and make sure no other process has the store open.

To cut cost, count tokens before embedding and skip chunks whose ids already exist. text-embedding-3-small is the cheaper model and is usually enough for RAG. Mixing models in one collection is a bug, because vector dimensions differ.

  1. Estimate tokens: use tiktoken.get_encoding('cl100k_base') and sum len(enc.encode(c.page_content)) across chunks.
  2. Fetch existing ids with db.get(ids=ids_all, include=[]) and keep only chunks whose id is missing.
  3. To start over, call db.delete_collection() or remove the directory with shutil.rmtree('./chroma_db').
  4. Recreate the Chroma object and rerun the script.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
total = sum(len(enc.encode(c.page_content)) for c in chunks)
print(total, "tokens")

existing = set(db.get(ids=ids_all, include=[])["ids"])
new = [(d, i) for d, i in zip(chunks, ids_all) if i not in existing]
print(len(new), "chunks need embedding")

How do I verify the data really was saved?

Compare db._collection.count() with len(chunks), then read a sample with db.get(limit=3). For a keyword check, run db.similarity_search('a phrase from your text', k=3).

You can also inspect chroma.sqlite3 with the sqlite3 CLI, for example `SELECT COUNT(*) FROM embeddings;`. That confirms metadata rows, but it is read-only evidence. Inserting rows by hand does not test anything, because Chroma keeps the vector index in separate HNSW files in a UUID-named folder and metadata and segment records in other tables. Rows added manually would have no vectors and would desynchronize the store.

If imports fail with an SQLite version error, install pysqlite3-binary and put `__import__('pysqlite3'); import sys; sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')` at the very top of your entry file. If a directory was created by a different Chroma version and raises schema errors, ingest into a fresh directory instead of reusing it.

sqlite3 chroma_db/chroma.sqlite3 "SELECT COUNT(*) FROM embeddings;"
sqlite3 chroma_db/chroma.sqlite3 "SELECT id, name FROM collections;"
Tip: Quick checklist for a LangChain Chroma 99 documents stall: 1) read the full traceback, 2) confirm no loop calls from_documents, 3) check OpenAI quota and limits, 4) lower batch and chunk_size, 5) compare count to len(chunks).

Common questions

Does Chroma.from_documents have a 99 document limit?

No. from_documents embeds and inserts whatever list you give it. A stop near 99 comes from an exception, typically an OpenAI 429 or a loop that re-embedded every chunk repeatedly.

Should I still call persist() after adding documents?

No. Chroma 0.4 and later write to disk automatically when you use a persistent client or persist_directory. The persist() method was removed from the current langchain-chroma wrapper.

Why is my collection count lower than len(chunks) without any error?

Duplicate ids silently overwrite one another, so identical or colliding ids shrink the count. Also check that an earlier crashed run did not write to a different collection name or directory.

Can I use from_documents for the first load and add_documents later?

Yes, as long as a first call receives a modest list and uses the same embedding model and collection name afterwards. For large sets, creating the Chroma object empty and batching add_documents is safer.

How big should chunks be for OpenAI embeddings?

Roughly 300 to 1000 tokens suits most RAG work and is well under the 8192-token input limit. Smaller chunks give more precise retrieval but increase record count and request volume.

Related topics:langchainchromadbopenai-embeddingsragpython