SurfSense icon indicating copy to clipboard operation
SurfSense copied to clipboard

[BUG] RAG not working as expected

Open rweisse opened this issue 9 months ago • 7 comments

Bug Description

When you ask a question about a document, the LLM is sent the question along with all chunks of the document, rather than just the relevant chunks.

Deployment Type

  • Self-hosted version (Docker)
  • EMBEDDING_MODEL: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
  • Summary LLM: Ministral 3 14B (provider is Mistral)

Steps to Reproduce

  1. Self-host an Agent LLM of your choice for debugging purposes and connect it to SurfSense as a custom provider (I took Ministral 3 3B, hosted with LM Studio)
  2. Upload ideally a very large PDF document of your choice (around 50 pages or more).
  3. Ask a specific question that should not be too complicated to answer, as the solution can be found somewhere in the document.
  4. Have a look at the logs of prompt preprocessing on your LLM host. You will see a very large n_token size.
  5. If you analyze the chunks of your uploaded document and add up their tokens, you will find that, when added to the usual prompt overhead of Surfsense with over 14k tokens (system prompt + tools), they result in a similarly high value. Therefore, I assume that all chunks of selected documents are always sent.

Expected Behavior

Surfsense should identify all relevant chunks of selected documents from the question and send them to the LLM along with the question.

Actual Behavior

All chunks of selected documents are always sent.

This makes it impossible to use LLMs with a limited context window when documents are very large. This is a big problem, because the whole point of RAG is that you don't have to send the entire document due to a limited context window. Using LLMs with large context windows (such as Gemini 3 Pro) is also not a solution, as queries take longer and quickly become very expensive.

rweisse avatar Feb 13 '26 10:02 rweisse

Just found the corresponding code. There is no chunk filtering happening as described in this closed issue or the main readme.

Get all document objects from database... https://github.com/MODSetter/SurfSense/blob/0e96e4492b8f00c0cfc9a007f65a43845223286d/surfsense_backend/app/tasks/chat/stream_new_chat.py#L329-L341

Provide documents to context generation function https://github.com/MODSetter/SurfSense/blob/0e96e4492b8f00c0cfc9a007f65a43845223286d/surfsense_backend/app/tasks/chat/stream_new_chat.py#L352-L355

Line 138-142: For each chunk in document append chunk to context https://github.com/MODSetter/SurfSense/blob/0e96e4492b8f00c0cfc9a007f65a43845223286d/surfsense_backend/app/tasks/chat/stream_new_chat.py#L108-L154

rweisse avatar Feb 13 '26 12:02 rweisse

Unfortunately I just discovered that reranking doesn't work either. The RerankerService is never called anywhere in the code.

The following code reads the environment variables RERANKERS_ENABLED, RERANKERS_MODEL_NAME and RERANKERS_MODEL_TYPE and initializes the reranker instance. https://github.com/MODSetter/SurfSense/blob/0e96e4492b8f00c0cfc9a007f65a43845223286d/surfsense_backend/app/config/init.py#L337-L347

The function get_reranker_instance() which should provide the reranker service by processing the upper reranker instance gets never called and appears to be a dead end. https://github.com/MODSetter/SurfSense/blob/0e96e4492b8f00c0cfc9a007f65a43845223286d/surfsense_backend/app/services/reranker_service.py#L112-L124

In the meantime you might consider going into more detail about the current implementation status of RAG in README.md.

📊 Advanced RAG Techniques

:white_check_mark: Supports 100+ LLM's :warning: Supports 6000+ Embedding Models. (At the moment just used for chunking) :x: Supports all major Rerankers (Pinecone, Cohere, Flashrank etc) :x: Uses Hierarchical Indices (2 tiered RAG setup). :x: Utilizes Hybrid Search (Semantic + Full Text Search combined with Reciprocal Rank Fusion).

I think the project is great! I know that a lot of work goes into developing SurfSense and you do a great job! I am aware that this is a non-productive beta version and that some features (such as RAG) are still proof of concept. However, I would like to see you prioritise core features such as RAG over less important features in further development, as the success of SurfSense ultimately depends on a functioning RAG. I hope that you will release a successful stable version soon.

Best regards, Robert

rweisse avatar Feb 16 '26 08:02 rweisse

Bug Description

When you ask a question about a document, the LLM is sent the question along with all chunks of the document, rather than just the relevant chunks.

Deployment Type

  • Self-hosted version (Docker)
  • EMBEDDING_MODEL: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
  • Summary LLM: Ministral 3 14B (provider is Mistral)

Steps to Reproduce

  1. Self-host an Agent LLM of your choice for debugging purposes and connect it to SurfSense as a custom provider (I took Ministral 3 3B, hosted with LM Studio)
  2. Upload ideally a very large PDF document of your choice (around 50 pages or more).
  3. Ask a specific question that should not be too complicated to answer, as the solution can be found somewhere in the document.
  4. Have a look at the logs of prompt preprocessing on your LLM host. You will see a very large n_token size.
  5. If you analyze the chunks of your uploaded document and add up their tokens, you will find that, when added to the usual prompt overhead of Surfsense with over 14k tokens (system prompt + tools), they result in a similarly high value. Therefore, I assume that all chunks of selected documents are always sent.

Expected Behavior

Surfsense should identify all relevant chunks of selected documents from the question and send them to the LLM along with the question.

Actual Behavior

All chunks of selected documents are always sent.

This makes it impossible to use LLMs with a limited context window when documents are very large. This is a big problem, because the whole point of RAG is that you don't have to send the entire document due to a limited context window. Using LLMs with large context windows (such as Gemini 3 Pro) is also not a solution, as queries take longer and quickly become very expensive.

This is expected behavior. We had a limited chunk mode before in the old agent, but people never used it, and passing full document context always gave better results than passing fragmented information. We will look into adding this mode back when we add local LLM optimizations.

In my opinion, the whole point of RAG is to always send the most relevant, rather than compressed, information.

MODSetter avatar Feb 16 '26 08:02 MODSetter

Just found the corresponding code. There is no chunk filtering happening as described in this closed issue or the main readme.

Get all document objects from database...

SurfSense/surfsense_backend/app/tasks/chat/stream_new_chat.py

Lines 329 to 341 in 0e96e44

Fetch mentioned SurfSense docs if any

mentioned_surfsense_docs: list[SurfsenseDocsDocument] = [] if mentioned_surfsense_doc_ids: from sqlalchemy.orm import selectinload

 result = await session.execute( 
     select(SurfsenseDocsDocument) 
     .options(selectinload(SurfsenseDocsDocument.chunks)) 
     .filter( 
         SurfsenseDocsDocument.id.in_(mentioned_surfsense_doc_ids), 
     ) 
 ) 
 mentioned_surfsense_docs = list(result.scalars().all()) 

Provide documents to context generation function

SurfSense/surfsense_backend/app/tasks/chat/stream_new_chat.py

Lines 352 to 355 in 0e96e44

if mentioned_surfsense_docs: context_parts.append( format_mentioned_surfsense_docs_as_context(mentioned_surfsense_docs) ) Line 138-142: For each chunk in document append chunk to context

SurfSense/surfsense_backend/app/tasks/chat/stream_new_chat.py

Lines 108 to 154 in 0e96e44

def format_mentioned_surfsense_docs_as_context( documents: list[SurfsenseDocsDocument], ) -> str: """Format mentioned SurfSense documentation as context for the agent.""" if not documents: return ""

 context_parts = ["<mentioned_surfsense_docs>"] 
 context_parts.append( 
     "The user has explicitly mentioned the following SurfSense documentation pages. " 
     "These are official documentation about how to use SurfSense and should be used to answer questions about the application. " 
     "Use [citation:CHUNK_ID] format for citations (e.g., [citation:doc-123])." 
 ) 

 for doc in documents: 
     metadata_json = json.dumps({"source": doc.source}, ensure_ascii=False) 

     context_parts.append("<document>") 
     context_parts.append("<document_metadata>") 
     context_parts.append(f"  <document_id>doc-{doc.id}</document_id>") 
     context_parts.append("  <document_type>SURFSENSE_DOCS</document_type>") 
     context_parts.append(f"  <title><![CDATA[{doc.title}]]></title>") 
     context_parts.append(f"  <url><![CDATA[{doc.source}]]></url>") 
     context_parts.append( 
         f"  <metadata_json><![CDATA[{metadata_json}]]></metadata_json>" 
     ) 
     context_parts.append("</document_metadata>") 
     context_parts.append("") 
     context_parts.append("<document_content>") 

     if hasattr(doc, "chunks") and doc.chunks: 
         for chunk in doc.chunks: 
             context_parts.append( 
                 f"  <chunk id='doc-{chunk.id}'><![CDATA[{chunk.content}]]></chunk>" 
             ) 
     else: 
         context_parts.append( 
             f"  <chunk id='doc-0'><![CDATA[{doc.content}]]></chunk>" 
         ) 

     context_parts.append("</document_content>") 
     context_parts.append("</document>") 
     context_parts.append("") 

 context_parts.append("</mentioned_surfsense_docs>") 

 return "\n".join(context_parts)

Okay, so what is the issue here?

MODSetter avatar Feb 16 '26 08:02 MODSetter

Unfortunately I just discovered that reranking doesn't work either. The RerankerService is never called anywhere in the code.

The following code reads the environment variables RERANKERS_ENABLED, RERANKERS_MODEL_NAME and RERANKERS_MODEL_TYPE and initializes the reranker instance.

SurfSense/surfsense_backend/app/config/init.py

Lines 337 to 347 in 0e96e44

Reranker's Configuration | Pinecone, Cohere etc. Read more at https://github.com/AnswerDotAI/rerankers?tab=readme-ov-file#usage

RERANKERS_ENABLED = os.getenv("RERANKERS_ENABLED", "FALSE").upper() == "TRUE" if RERANKERS_ENABLED: RERANKERS_MODEL_NAME = os.getenv("RERANKERS_MODEL_NAME") RERANKERS_MODEL_TYPE = os.getenv("RERANKERS_MODEL_TYPE") reranker_instance = Reranker( model_name=RERANKERS_MODEL_NAME, model_type=RERANKERS_MODEL_TYPE, ) else: reranker_instance = None The function get_reranker_instance() which should provide the reranker service by processing the upper reranker instance gets never called and appears to be a dead end.

SurfSense/surfsense_backend/app/services/reranker_service.py

Lines 112 to 124 in 0e96e44

 @staticmethod 
 def get_reranker_instance() -> Optional["RerankerService"]: 
     """ 
     Get a reranker service instance from the global configuration. 

     Returns: 
         Optional[RerankerService]: A reranker service instance if configured, None otherwise 
     """ 
     from app.config import config 

     if hasattr(config, "reranker_instance") and config.reranker_instance: 
         return RerankerService(config.reranker_instance) 
     return None 

In the meantime you might consider going into more detail about the current implementation status of RAG in README.md.

📊 Advanced RAG Techniques

✅ Supports 100+ LLM's ⚠️ Supports 6000+ Embedding Models. (At the moment just used for chunking) ❌ Supports all major Rerankers (Pinecone, Cohere, Flashrank etc) ❌ Uses Hierarchical Indices (2 tiered RAG setup). ❌ Utilizes Hybrid Search (Semantic + Full Text Search combined with Reciprocal Rank Fusion).

I think the project is great! I know that a lot of work goes into developing SurfSense and you do a great job! I am aware that this is a non-productive beta version and that some features (such as RAG) are still proof of concept. However, I would like to see you prioritise core features such as RAG over less important features in further development, as the success of SurfSense ultimately depends on a functioning RAG. I hope that you will release a successful stable version soon.

Best regards, Robert

Thanks for pointing this out. We just need to add this back. We used it in the old agent, and it slipped my mind while moving to the new agent. It should be done by EOD tomorrow; it is an easy fix. Will update readme soon.

MODSetter avatar Feb 16 '26 08:02 MODSetter

We will look into adding this mode back when we add local LLM optimizations.

Thank you, that sounds great!

Okay, so what is the issue here?

There is no real issue with the code. It served more as proof of my issue description.

Thanks for pointing this out. We just need to add this back. We used it in the old agent, and it slipped my mind while moving to the new agent. It should be done by EOD tomorrow; it is an easy fix. Will update readme soon.

These are great news. If you get reranking working again it could be a kind of workaround in the meantime. If it were possible to pass a top_k parameter to the reranking model it would be possible to pass all chunks of a document to the reranking model and get back only k chunks. This would dramatically decrease the amount of chunks passed to the LLM.

rweisse avatar Feb 16 '26 09:02 rweisse

Bug Description

When you ask a question about a document, the LLM is sent the question along with all chunks of the document, rather than just the relevant chunks.

Deployment Type

  • Self-hosted version (Docker)
  • EMBEDDING_MODEL: sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2
  • Summary LLM: Ministral 3 14B (provider is Mistral)

Steps to Reproduce

  1. Self-host an Agent LLM of your choice for debugging purposes and connect it to SurfSense as a custom provider (I took Ministral 3 3B, hosted with LM Studio)
  2. Upload ideally a very large PDF document of your choice (around 50 pages or more).
  3. Ask a specific question that should not be too complicated to answer, as the solution can be found somewhere in the document.
  4. Have a look at the logs of prompt preprocessing on your LLM host. You will see a very large n_token size.
  5. If you analyze the chunks of your uploaded document and add up their tokens, you will find that, when added to the usual prompt overhead of Surfsense with over 14k tokens (system prompt + tools), they result in a similarly high value. Therefore, I assume that all chunks of selected documents are always sent.

Expected Behavior

Surfsense should identify all relevant chunks of selected documents from the question and send them to the LLM along with the question.

Actual Behavior

All chunks of selected documents are always sent. This makes it impossible to use LLMs with a limited context window when documents are very large. This is a big problem, because the whole point of RAG is that you don't have to send the entire document due to a limited context window. Using LLMs with large context windows (such as Gemini 3 Pro) is also not a solution, as queries take longer and quickly become very expensive.

This is expected behavior. We had a limited chunk mode before in the old agent, but people never used it, and passing full document context always gave better results than passing fragmented information. We will look into adding this mode back when we add local LLM optimizations.

In my opinion, the whole point of RAG is to always send the most relevant, rather than compressed, information.

Hi! Thanks for the amazing work on SurfSense. I've been doing a PoC with it and I ran into this exact same issue.

Since the system currently retrieves the entire parent document instead of just the most relevant chunks, the LLM's context window gets overwhelmed very quickly.

I think it would be a great idea to implement a setting to limit the number of chunks retrieved per query (e.g., a Top-K parameter) or shift towards chunk-level retrieval rather than document-level.

This feature would be incredibly useful because it would allow users to use smaller, more cost-effective LLMs with tighter context windows without running into token limit errors.

Would love to hear your thoughts on this approach!

rubengonlab avatar Feb 23 '26 12:02 rubengonlab