Skip to content

feat: implement POST /api/v1/searchbots/ask — streaming RAG with citations and think-tag processing - #5

Closed
xugangqiang wants to merge 4 commits into
mainfrom
feat/searchbots-ask
Closed

xugangqiang wants to merge 4 commits into
mainfrom
feat/searchbots-ask

Conversation

@xugangqiang

Copy link
Copy Markdown
Owner

What this PR solves

Implements POST /api/v1/searchbots/ask in Go — retrieves chunks, builds a prompt, streams the LLM answer with citations and think-tag processing via SSE. Matches Python bot_api.py:ask_about_embedded.

Changes (23 files, ~3100+ lines)

New endpoint

  • POST /api/v1/searchbots/ask — streaming SSE with think-tag markers and [ID:n] citations

New service components

Component File
AskService service/ask_service.go
InsertCitations service/citation.go
ThinkStreamState / StreamThinkTagDelta service/think_tag.go
KbPrompt / ChunksFormat service/kb_prompt.go
SourcedChunk service/chunk_types.go
hydrateChunkVectors service/chunk/chunk.go

Architecture

  • Extract AskService from handler (~170 → 25 lines)
  • SSEWriter DI interface replaces mutable global var
  • Move chunk infrastructure to service/chunk/ (ChunkService, FetchChunkVectors)
  • PtrString extracted to common/format.go
  • NumTokensFromString unified to C++ tokenizer with fallback
  • StreamingLLM interface with context-aware cancellation

Testing (>90 unit tests)

  • service/citation_test.go — 23 tests
  • service/kb_prompt_test.go — 11 tests
  • service/chunk_types_test.go — 12 tests
  • service/think_tag_test.go — 17 tests
  • service/ask_service_test.go — 12 tests
  • service/chunk/chunk_test.go — 7 tests
  • internal/handler/searchbot_test.go — 7 Ask handler tests

Type

  • New Feature

🤖 Generated with Claude Code

xugangqiang and others added 4 commits June 8, 2026 17:28
- Add RetrievalTest handler to SearchBotHandler with full field mapping
- Add common.StringSlice for flexible JSON binding (accepts string or array)
- Add applyRetrievalDefaults matching Python bot_api.py endpoint defaults
- Extract toRetrievalServiceRequest to centralize handler→service DTO mapping
- Rename ChunkServiceIface → ChunkRetriever (Go idiom, -er suffix)
- Move regex to package-level var in parseRelatedQuestions (compile once)
- Secure error handling: generic messages + common.Warn() instead of err.Error()
- Add "data": nil to error responses for consistent response shape
- Filter empty/whitespace-only KbIDs before validation
- Unify chunkHandler error codes to common constants (CodeArgumentError/CodeServerError)
- Change service.RetrievalTestRequest.Datasets type to common.StringSlice
- Update struct doc comment to list all SearchBotHandler endpoints
- Add comprehensive unit tests: defaults, empty/whitespace KbID, message assertions
- Resolve rebase conflicts with upstream difyRetrievalHandler
- Add docEngine param to NewDifyRetrievalHandler (upstream signature change)
- Add Swagger annotations to RetrievalTest, Get, List
- Update PR description to match template

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ions, and think-tag processing

Core features:
- AskService: retrieval-augmented Q&A pipeline with streaming output
- InsertCitations: vector similarity-based citation insertion ([ID:n] markers)
- StreamThinkTagDelta: <think> tag streaming state machine (matches Python)
- KbPrompt + ChunksFormat: typed chunk-to-prompt and chunk-to-response formatting
- SourcedChunk: typed normalization layer over raw retrieval chunks
- hydrateChunkVectors: zero-vector hydration for ES via FetchChunkVectors

Architecture:
- Extract AskService from handler (170→25 lines) — testable pipeline
- SSEWriter interface (DI) replaces package-level mutable var
- ExtractChunkVectors moved to service package
- NumTokensFromString unified via C++ tokenizer with fallback
- StreamingLLM interface with context-aware cancellation

Testing:
- 85+ unit tests across 6 test files
- Pure function coverage 90%+ (citation, think-tag, kb-prompt, chunk-view)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Move ChunkService + RetrievalTest + hydrateChunkVectors to service/chunk/
- Move FetchChunkVectors to service/chunk/vector.go
- Move PtrString to common/format.go (generic utility)
- Merge chunk_view.go into chunk_types.go (type definitions)
- Rename chunk_view_test.go → chunk_types_test.go
- Split KbPrompt tests → kb_prompt_test.go
- Move hydrate/isZero tests to service/chunk/chunk_test.go
- Remove duplicate chunk_vector files from service/
- service/chunk/ imports service/ only (no circular dependency)

Co-Authored-By: Claude Code <[email protected]>
@xugangqiang xugangqiang closed this Jun 9, 2026
xugangqiang added a commit that referenced this pull request Jul 28, 2026
- Scope temperature to 0.2 only for keyword/question extraction; the
  generic field-extraction path now leaves Temperature unset to use the
  model default, matching Python's generic Extractor (generator.py).
- Merge runAutoKeywords/runAutoQuestions with their *Locked duplicates
  into single functions taking a *sync.Mutex (nil = sequential); map
  access stays race-safe under concurrency.
- retryInvoker.Invoke now returns a nil response on failure instead of
  the last partial response.
- RetryWithBackoff gains an optional shouldRetry predicate; the extractor
  chat call uses a lightweight classifier so non-transient errors
  (auth/4xx/config) stop retrying immediately. The greedy </think> strip
  already matched Python's re.sub behavior, so no change there.

Addresses review items #3, #5, #6, #7 on PR infiniflow#17470.
xugangqiang added a commit that referenced this pull request Aug 14, 2026
Align three Go DLA / PDF post-processing behaviors with the Python
deepdoc reference so the Go pipeline converges on real documents.

1. DLA annotation tie-break (#4): when a text box overlaps multiple
   same-type regions with equal box-coverage, prefer the region with the
   higher region-coverage ratio. Mirrors Python's (ov, _ov) tuple
   comparison in LayoutRecognizer.__call__.

2. header/footer filtering (#5): match header|footer|number as a
   substring (regex (?i)header|footer|number) instead of the anchored
   ^(header|footer|number)$, so composite labels such as "page-footer"
   and page numbers are stripped, matching Python's filterPDFHeaderFooter.

3. per-class NMS (#6): apply greedy per-class non-maximum suppression
   (IoU 0.45, +1 overlap convention) to DLA regions before annotation,
   matching Python's layout post-process and removing duplicate
   same-type detections.

Tests:
- table/table_annotate_parity_test.go: new unit tests for #4 tie-break
  and #6 NMS (RED -> GREEN).
- parser/pdf_postprocess_test.go: substring header/footer match test (#5).
- table/table_annotate_test.go: adjust TestAnnotateBoxLayouts_SyntheticFigure
  expected coordinates for the corrected Y-sort order.
- tool/compare_test.go: fix missing `common` import so the golden
  comparator test compiles.

Validated with the golden comparison harness (TestBatchCompareWithPython)
against the Python reference on a real PDF: DLA region counts and text
content converge.
xugangqiang added a commit that referenced this pull request Aug 17, 2026
- Pad only the header row (not every row) to the furthest merged column,
  and cap that width at maxMergeExtentCols, so a pathological far merge
  (e.g. A1:XFD1) cannot exhaust parser memory or flood data rows with
  empty <td> cells (review comment #5).
- Add tests for padRowToWidth, mergeExtentCol, decodeChunkRows, multi-sheet
  output, empty-sheet handling, and a far-merge no-bloat regression guard.
- Check all Excelize fixture errors in tests (errcheck, review comment #1).
xugangqiang added a commit that referenced this pull request Aug 18, 2026
Python's table path fills cells only from page-level/region-level OCR boxes
matched via construct_table; it never crops individual empty cells for
recognition. Go additionally ran ocrTableCells, which cropped each empty TSR
cell and recognized it, producing cell text that Python leaves blank. This
divergence broke the Go/Python OCR alignment target.

Remove ocrTableCells and its two call sites in processOneTable
(table_extract.go). Cell text now comes solely from FillCellTextFromBoxes
(page-level OCR box matching), matching Python. Delete the now-dead function
and its dedicated test, and update the inferOCRRecognize doc comment.

Add TestProcessOneTable_NoPerCellOCR as a regression guard: an empty TSR cell
with no overlapping page-level box must stay empty for both the rotated
(bestAngle != 0) and non-rotated (bestAngle == 0) paths, even when the OCR
engine would return text for a cropped cell.

Refs: alignment note #5 (Per-cell OCR, Go-only behavioral difference).
xugangqiang added a commit that referenced this pull request Aug 18, 2026
Python's table path fills cells only from page-level/region-level OCR boxes
matched via construct_table; it never crops individual empty cells for
recognition. Go additionally ran ocrTableCells, which cropped each empty TSR
cell and recognized it, producing cell text that Python leaves blank. This
divergence broke the Go/Python OCR alignment target.

Remove ocrTableCells and its two call sites in processOneTable
(table_extract.go). Cell text now comes solely from FillCellTextFromBoxes
(page-level OCR box matching), matching Python. Delete the now-dead function
and its dedicated test, and update the inferOCRRecognize doc comment.

Add TestProcessOneTable_NoPerCellOCR as a regression guard: an empty TSR cell
with no overlapping page-level box must stay empty for both the rotated
(bestAngle != 0) and non-rotated (bestAngle == 0) paths, even when the OCR
engine would return text for a cropped cell.

Refs: alignment note #5 (Per-cell OCR, Go-only behavioral difference).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant