fix(ingest): stop hallucinating summaries from filenames on empty PDFs

Scanned PDFs without a successful OCR pass (e.g. when no VLM is configured
on the KB, or when the VLM returned a "no text content" reply that the
sanitizer discarded) reach the summary and wiki-ingest pipelines with
nothing but markdown image references for content. The downstream LLM
prompts used to receive the filename, file type, and title alongside that
empty content, and the generate_summary template explicitly forbade the
model from refusing — so the model would invent a topic from the filename
alone, producing e.g. a "Canon scanner manual" summary for an MX5280.pdf
that is actually a scanned legal letter.

Two changes shut this down:

1. Drop filename / title / file-type from every LLM prompt input. The
   wiki summary, knowledge extract, candidate slug, and chunk citation
   prompts now see only the document content. The knowledge summary
   path no longer prepends the "Document Type: X / File Name: Y" intro.

2. Add a content-sufficiency guard in front of the LLM call. A new
   helper strips markdown image references and HTML image tags and
   refuses to invoke the model when fewer than 50 real-text runes
   remain. getSummary returns a sentinel error in that case and the
   caller marks the knowledge as SummaryStatusFailed instead of
   surfacing the first chunk's bare image reference. Wiki ingest skips
   LLM extraction with a clear log message.

The generate_summary.yaml prompt is also updated: the "NEVER output
refusal phrases" clause is removed and replaced with an explicit
empty-content rule that returns a deterministic placeholder line.

Real OCR (Tesseract / PaddleOCR) and filename-pattern sanitisation are
intentionally left for separate PRs.
This commit is contained in:
Claude
2026-05-02 09:06:32 +00:00
committed by lyingbug
parent d3d433574f
commit 15550d14d4
7 changed files with 183 additions and 42 deletions
+37 -16
View File
@@ -2242,6 +2242,13 @@ func (s *knowledgeService) processChunks(ctx context.Context,
// defaultMaxInputChars is the default maximum characters used as input for summary generation.
const defaultMaxInputChars = 1024 * 24
// errInsufficientSummaryContent signals that getSummary refused to call the
// LLM because the document had no usable text after image markup was stripped
// (typical for scanned PDFs where VLM OCR yielded nothing). Callers should
// mark the knowledge's summary as failed instead of falling back to the first
// chunk's raw content (which would just be a bare image reference).
var errInsufficientSummaryContent = errors.New("insufficient text content for summary generation")
// getSummary generates a summary for knowledge content using an AI model
func (s *knowledgeService) getSummary(ctx context.Context,
summaryModel chat.Chat, knowledge *types.Knowledge, chunks []*types.Chunk,
@@ -2295,22 +2302,23 @@ func (s *knowledgeService) getSummary(ctx context.Context,
logger.GetLogger(ctx).Infof("getSummary: content length=%d chars (max=%d) for knowledge %s",
len([]rune(chunkContents)), maxInputChars, knowledge.ID)
// Prepare content with metadata for summary generation
contentWithMetadata := chunkContents
// Add knowledge metadata if available
if knowledge != nil {
metadataIntro := fmt.Sprintf("Document Type: %s\nFile Name: %s\n", knowledge.FileType, knowledge.FileName)
// Add additional metadata if available
if knowledge.Type != "" {
metadataIntro += fmt.Sprintf("Knowledge Type: %s\n", knowledge.Type)
}
// Prepend metadata to content
contentWithMetadata = metadataIntro + "\nContent:\n" + contentWithMetadata
// Bail out before the LLM call when there is not enough actual text to
// summarise. We deliberately do not pass filename/file-type metadata to the
// LLM: scanned PDFs frequently carry filenames like "MX5280.pdf" (the
// scanner model), and feeding that to the model would invite it to
// hallucinate a scanner manual instead of admitting the document had no
// extractable text.
if !hasSufficientTextContent(chunkContents) {
logger.GetLogger(ctx).Warnf(
"getSummary: content for knowledge %s has insufficient text after stripping image markup (len=%d); skipping LLM call",
knowledge.ID, len([]rune(strings.TrimSpace(stripImageMarkup(chunkContents)))),
)
return "", errInsufficientSummaryContent
}
// Pass the raw chunk text to the LLM with no filename / file-type framing.
contentWithMetadata := chunkContents
// Determine max output tokens from config
maxTokens := 2048
if s.config.Conversation.Summary != nil && s.config.Conversation.Summary.MaxCompletionTokens > 0 {
@@ -2482,11 +2490,24 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
summary, err := s.getSummary(ctx, chatModel, knowledge, textChunks)
if err != nil {
logger.Errorf(ctx, "Failed to generate summary for knowledge %s: %v", payload.KnowledgeID, err)
// Use first chunk content as fallback
// For the insufficient-content case (scanned PDF without OCR, etc.)
// we deliberately do NOT fall back to the first chunk's raw content,
// since that chunk is typically just a bare markdown image reference
// and surfacing it in the description is misleading.
if errors.Is(err, errInsufficientSummaryContent) {
knowledge.Description = ""
knowledge.SummaryStatus = types.SummaryStatusFailed
knowledge.UpdatedAt = time.Now()
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
logger.Errorf(ctx, "Failed to mark summary as failed: %v", updateErr)
return fmt.Errorf("failed to update knowledge: %w", updateErr)
}
return nil
}
// For other errors (LLM API issues etc.), fall back to the first chunk.
if len(textChunks) > 0 {
summary = textChunks[0].Content
if len(summary) > 500 {
// Use rune-based truncation to avoid cutting UTF-8 multi-byte characters
runes := []rune(summary)
if len(runes) > 500 {
summary = string(runes[:500])