WeKnora/internal/agent/tools/read_document.go

675 lines
22 KiB
Go
Raw Normal View History

refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
package tools
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const (
readDocumentDefaultLimit = 20
readDocumentMaxLimit = 100
readDocumentMaxContext = 5
readDocumentMaxMatches = 20
readDocumentScanPageSize = 100
// readDocumentChunkOverhead approximates the per-chunk tags and handles
// the model rendering adds around each chunk's content.
readDocumentChunkOverhead = 120
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
)
var readDocumentTool = BaseTool{
name: ToolReadDocument,
description: "Read a document from the knowledge bases in scope: its metadata plus chunks in document order.\n" +
"id is a dN document handle (reads a page of chunks starting at offset) or a cN chunk handle (reads that " +
"chunk; set context to include neighbouring chunks on each side).\n" +
"query finds passages inside the document: matching chunks come back with one chunk of context on each " +
"side. By default query is case-insensitive and split on whitespace: a chunk matches when it contains " +
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
"every word, in any order. Set regex=true to match query as one POSIX regular expression instead. " +
"When a query result is truncated, repeat it with offset=next_offset to get the following matches.\n" +
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
"Page through long documents with offset and limit: offset counts chunks in reading order from 0 and is " +
"not a chunk index, so continue with the returned next_offset, and use id=cN with context to read around " +
"a specific chunk. A page holds fewer than limit chunks when they would exceed the output size budget; " +
"next_offset always points at the first chunk not yet returned. Reading a long document end to end " +
"costs many calls, so prefer query or search_knowledge to locate the relevant part first.",
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
schema: json.RawMessage(`{
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "dN document handle or cN chunk handle from retrieval results or the runtime context",
"minLength": 1
},
"offset": {
"type": "integer",
"description": "Position in reading order to start from (default 0); continue with next_offset",
"minimum": 0
},
"limit": {
"type": "integer",
"description": "Chunks per page (default 20, max 100)",
"minimum": 1,
"maximum": 100
},
"query": {
"type": "string",
"description": "Words a chunk must all contain; returns matching chunks with context instead of a page"
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
},
"regex": {
"type": "boolean",
"description": "Match query as one POSIX regular expression (default false: each word matched literally)"
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
},
"context": {
"type": "integer",
"description": "Neighbouring chunks to include on each side of a cN chunk (default 0, max 5)",
"minimum": 0,
"maximum": 5
}
},
"required": ["id"]
}`),
}
// ReadDocumentInput defines the input parameters for read_document.
type ReadDocumentInput struct {
ID string `json:"id"`
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
Query string `json:"query,omitempty"`
Regex bool `json:"regex,omitempty"`
Context int `json:"context,omitempty"`
}
// ReadDocumentTool reads document metadata and chunks by page, by chunk
// handle, or by an in-document text search.
type ReadDocumentTool struct {
BaseTool
knowledgeService interfaces.KnowledgeService
chunkService interfaces.ChunkService
searchTargets types.SearchTargets
}
// NewReadDocumentTool creates a new read_document tool.
func NewReadDocumentTool(
knowledgeService interfaces.KnowledgeService,
chunkService interfaces.ChunkService,
searchTargets types.SearchTargets,
) *ReadDocumentTool {
return &ReadDocumentTool{
BaseTool: readDocumentTool,
knowledgeService: knowledgeService,
chunkService: chunkService,
searchTargets: searchTargets,
}
}
// readChunkRow is one chunk in the rendered result together with its role
// (page entry, search match, or context around a match).
type readChunkRow struct {
chunk *types.Chunk
role string // "", "match", "context_before", "context_after", "focus"
snippet string
}
// Execute resolves the id, then dispatches to page, chunk or query reading.
func (t *ReadDocumentTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var input ReadDocumentInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Failed to parse args: %v", err)}, err
}
id := strings.TrimSpace(input.ID)
if id == "" {
return &types.ToolResult{Success: false, Error: "id is required (a dN document handle or a cN chunk handle)"},
fmt.Errorf("missing id")
}
if t.knowledgeService == nil || t.chunkService == nil {
return &types.ToolResult{Success: false, Error: "document services are unavailable"},
fmt.Errorf("services unavailable")
}
limit := input.Limit
if limit <= 0 {
limit = readDocumentDefaultLimit
}
if limit > readDocumentMaxLimit {
limit = readDocumentMaxLimit
}
offset := input.Offset
if offset < 0 {
offset = 0
}
contextChunks := input.Context
if contextChunks < 0 {
contextChunks = 0
}
if contextChunks > readDocumentMaxContext {
contextChunks = readDocumentMaxContext
}
query := strings.TrimSpace(input.Query)
knowledge, chunk, err := t.resolveTarget(ctx, id)
if err != nil {
return &types.ToolResult{Success: false, Error: err.Error()}, err
}
var matchers []*regexp.Regexp
switch {
case query == "":
case input.Regex:
compiled, cerr := regexp.Compile("(?i)" + query)
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
if cerr != nil {
return &types.ToolResult{
Success: false, Error: fmt.Sprintf("invalid regex query %q: %v", query, cerr),
}, cerr
}
matchers = []*regexp.Regexp{compiled}
default:
// Models write keyword queries ("sunflower f(n,k)"), not exact
// phrases, so each word is matched on its own and all must appear.
for _, term := range strings.Fields(query) {
matchers = append(matchers, regexp.MustCompile("(?i)"+regexp.QuoteMeta(term)))
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
}
// A query always searches the owning document, even when id named a
// chunk: silently returning the single chunk would read as "no match".
switch {
case len(matchers) > 0:
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
return t.readByQuery(ctx, knowledge, query, matchers, offset)
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
case chunk != nil:
return t.readAroundChunk(ctx, knowledge, chunk, contextChunks)
default:
return t.readPage(ctx, knowledge, offset, limit)
}
}
// resolveTarget accepts either a document id or a chunk id. Documents are
// tried first because they are the common case; a chunk id falls through to
// the chunk lookup. Scope violations are reported as such rather than being
// masked as "not found".
func (t *ReadDocumentTool) resolveTarget(ctx context.Context, id string) (*types.Knowledge, *types.Chunk, error) {
if knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, id); err == nil && knowledge != nil {
authorized, authErr := authorizeLoadedKnowledge(ctx, t.searchTargets, knowledge, t.knowledgeService)
if authErr != nil {
return nil, nil, fmt.Errorf("document is not accessible: %w", authErr)
}
return authorized, nil, nil
}
chunk, err := t.chunkService.GetChunkByIDOnly(ctx, id)
if err != nil || chunk == nil {
return nil, nil, fmt.Errorf("id %s is neither a document (dN) nor a chunk (cN) in the current scope", id)
}
authorizedChunk, authErr := authorizeChunkInSearchTargets(
ctx, t.searchTargets, id, t.chunkService, t.knowledgeService,
)
if authErr != nil {
return nil, nil, fmt.Errorf("chunk is not accessible: %w", authErr)
}
knowledge, err := t.knowledgeService.GetKnowledgeByIDOnly(ctx, authorizedChunk.KnowledgeID)
if err != nil || knowledge == nil {
// The chunk is authorized; a missing parent row only costs the header.
knowledge = &types.Knowledge{
ID: authorizedChunk.KnowledgeID,
TenantID: authorizedChunk.TenantID,
KnowledgeBaseID: authorizedChunk.KnowledgeBaseID,
}
}
return knowledge, authorizedChunk, nil
}
func (t *ReadDocumentTool) tenantFor(knowledge *types.Knowledge) uint64 {
if knowledge.TenantID != 0 {
return knowledge.TenantID
}
return t.searchTargets.GetTenantIDForKB(knowledge.KnowledgeBaseID)
}
// listChunks fetches one page of text/FAQ chunks in document order.
func (t *ReadDocumentTool) listChunks(
ctx context.Context, knowledge *types.Knowledge, page, pageSize int,
) ([]*types.Chunk, int64, error) {
enabled := true
chunks, total, err := t.chunkService.GetRepository().ListPagedChunksByKnowledgeID(
ctx, t.tenantFor(knowledge), knowledge.ID,
&types.Pagination{Page: page, PageSize: pageSize},
[]types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ},
nil, "", "", "", "", &enabled,
)
if err != nil {
return nil, 0, fmt.Errorf("failed to list chunks: %w", err)
}
return chunks, total, nil
}
// countChunks returns the number of readable chunks without loading them.
func (t *ReadDocumentTool) countChunks(ctx context.Context, knowledge *types.Knowledge) int64 {
_, total, err := t.listChunks(ctx, knowledge, 1, 1)
if err != nil {
return 0
}
return total
}
// fetchWindow returns chunks [offset, offset+limit) in document order. The
// repository pages by page number, so a window that does not start on a page
// boundary is assembled from the two pages that cover it.
func (t *ReadDocumentTool) fetchWindow(
ctx context.Context, knowledge *types.Knowledge, offset, limit int,
) ([]*types.Chunk, int64, error) {
if limit <= 0 {
return nil, 0, nil
}
firstPage := offset/limit + 1
skip := offset % limit
chunks, total, err := t.listChunks(ctx, knowledge, firstPage, limit)
if err != nil {
return nil, 0, err
}
if skip > 0 {
if skip < len(chunks) {
chunks = chunks[skip:]
} else {
chunks = nil
}
// The next page exists whenever the first page did not already reach
// the end of the document, regardless of how far the window extends.
if int64(firstPage*limit) < total {
next, _, err := t.listChunks(ctx, knowledge, firstPage+1, limit)
if err != nil {
return nil, 0, err
}
chunks = append(chunks, next...)
}
}
if len(chunks) > limit {
chunks = chunks[:limit]
}
return chunks, total, nil
}
// readPage renders metadata plus chunks [offset, offset+limit).
func (t *ReadDocumentTool) readPage(
ctx context.Context, knowledge *types.Knowledge, offset, limit int,
) (*types.ToolResult, error) {
chunks, total, err := t.fetchWindow(ctx, knowledge, offset, limit)
if err != nil {
return &types.ToolResult{Success: false, Error: err.Error()}, err
}
if len(chunks) == 0 && total > 0 && int64(offset) >= total {
suggested := int(total) - limit
if suggested < 0 {
suggested = 0
}
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"offset %d is out of range: document has %d chunks (valid offsets 0..%d). Retry with offset=%d.",
offset, total, total-1, suggested),
Data: map[string]interface{}{
"knowledge_id": knowledge.ID,
"total_chunks": total,
"requested_offset": offset,
"requested_limit": limit,
"suggested_offset": suggested,
},
}, nil
}
chunks = fitChunksToBudget(chunks, OutputBudget(ctx)*4/5)
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
enrichChunkImageInfo(ctx, t.chunkService.GetRepository(), t.tenantFor(knowledge), chunks)
rows := make([]readChunkRow, 0, len(chunks))
for _, c := range chunks {
rows = append(rows, readChunkRow{chunk: c})
}
data := t.buildData(knowledge, total, rows)
data["offset"] = offset
data["page_size"] = limit
data["page"] = offset/limit + 1
if next := offset + len(chunks); int64(next) < total && len(chunks) > 0 {
data["next_offset"] = next
}
return &types.ToolResult{
Success: true,
Output: t.buildOutput(knowledge, total, rows, ""),
Data: data,
}, nil
}
// readAroundChunk renders a single chunk with optional neighbours.
func (t *ReadDocumentTool) readAroundChunk(
ctx context.Context, knowledge *types.Knowledge, focus *types.Chunk, contextChunks int,
) (*types.ToolResult, error) {
total := t.countChunks(ctx, knowledge)
rows := []readChunkRow{{chunk: focus, role: "focus"}}
if contextChunks > 0 && focus.ChunkType != types.ChunkTypeFAQ {
// Neighbours are resolved by chunk_index, not by list position:
// parent, summary and image chunks share the index sequence, so a
// position computed from ChunkIndex would drift away from the focus.
neighbours, err := t.chunkService.GetRepository().ListChunkNeighbors(
ctx, t.tenantFor(knowledge), knowledge.ID, focus.ChunkIndex, contextChunks, contextChunks,
[]types.ChunkType{types.ChunkTypeText, types.ChunkTypeFAQ},
)
if err != nil {
return &types.ToolResult{
Success: false, Error: fmt.Sprintf("failed to list neighbouring chunks: %v", err),
}, err
}
rows = rows[:0]
placed := false
for _, c := range neighbours {
if !placed && c.ChunkIndex > focus.ChunkIndex {
rows = append(rows, readChunkRow{chunk: focus, role: "focus"})
placed = true
}
role := "context_after"
if c.ChunkIndex < focus.ChunkIndex {
role = "context_before"
}
rows = append(rows, readChunkRow{chunk: c, role: role})
}
if !placed {
rows = append(rows, readChunkRow{chunk: focus, role: "focus"})
}
}
chunks := make([]*types.Chunk, 0, len(rows))
for _, r := range rows {
chunks = append(chunks, r.chunk)
}
enrichChunkImageInfo(ctx, t.chunkService.GetRepository(), t.tenantFor(knowledge), chunks)
data := t.buildData(knowledge, total, rows)
data["single_chunk"] = len(rows) == 1
data["focus_chunk_id"] = focus.ID
if q := faqStandardQuestion(focus); q != "" {
data["faq_id"] = focus.ID
data["faq_question"] = q
}
return &types.ToolResult{
Success: true,
Output: t.buildOutput(knowledge, total, rows, ""),
Data: data,
}, nil
}
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
// readByQuery scans the document in order from offset and returns chunks
// matched by every matcher, with one chunk of context on each side, capped at
// readDocumentMaxMatches and the output budget. A truncated result carries
// next_offset, the reading-order position of the first match it left out;
// without it matches past the cap could only be reached by paging the whole
// document.
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
func (t *ReadDocumentTool) readByQuery(
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
ctx context.Context, knowledge *types.Knowledge, query string, matchers []*regexp.Regexp, offset int,
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
) (*types.ToolResult, error) {
var rows []readChunkRow
emitted := make(map[string]bool)
matchCount := 0
truncated := false
var total int64
var prev *types.Chunk
forceNext := false
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
// Start one chunk before offset so a match at offset still gets its
// preceding context, also when offset is the first chunk of a page.
page := max(offset-1, 0)/readDocumentScanPageSize + 1
nextOffset := -1
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
tenantID := t.tenantFor(knowledge)
// Stop collecting before the registry's head/tail truncation would cut
// rows in the middle; the header and tags take the remaining share.
budget := OutputBudget(ctx) * 4 / 5
used := 0
emit := func(row readChunkRow) {
rows = append(rows, row)
emitted[row.chunk.ID] = true
used += utf8.RuneCountInString(row.chunk.Content) + readDocumentChunkOverhead
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
}
scan:
for {
chunks, pageTotal, err := t.listChunks(ctx, knowledge, page, readDocumentScanPageSize)
if err != nil {
return &types.ToolResult{Success: false, Error: err.Error()}, err
}
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
total = pageTotal
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
if len(chunks) == 0 {
break
}
enrichChunkImageInfo(ctx, t.chunkService.GetRepository(), tenantID, chunks)
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
for i, c := range chunks {
position := (page-1)*readDocumentScanPageSize + i
if position < offset {
// Before the requested start: only its text as context.
prev = c
continue
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
haystack := enrichChunkContent(c)
if q := faqStandardQuestion(c); q != "" {
haystack += "\n" + q
}
if matchesAll(matchers, haystack) {
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
if matchCount >= readDocumentMaxMatches || used >= budget {
truncated = true
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
nextOffset = position
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
break scan
}
matchCount++
if prev != nil && !emitted[prev.ID] {
emit(readChunkRow{chunk: prev, role: "context_before"})
}
if !emitted[c.ID] {
emit(readChunkRow{chunk: c, role: "match", snippet: extractChunkMatchSnippet(c, matchers)})
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
}
forceNext = true
} else if forceNext {
if !emitted[c.ID] && used < budget {
emit(readChunkRow{chunk: c, role: "context_after"})
}
forceNext = false
}
prev = c
}
if int64(page*readDocumentScanPageSize) >= total {
break
}
page++
}
data := t.buildData(knowledge, total, rows)
data["query"] = query
data["match_count"] = matchCount
data["truncated"] = truncated
fix(retrieval): fix recall correctness, score scales, cost and agent tools (#3687) * fix(retrieval): keep index writes and shared-KB lookups correct Index writes - Image OCR/caption chunks were indexed without IsEnabled, so every engine but Postgres stored them disabled and retrieval never returned them. The SQLite engine re-enables the affected rows at startup. - FAQ edits, similar-question additions and import merges re-index under the old SourceID and relied on the engine overwriting it. Postgres and SQLite kept the stale row (ON CONFLICT DO NOTHING); ES v8 and Qdrant mint a new document ID and kept both. FAQ re-indexing now deletes the old rows first, and Postgres/SQLite BatchSave upserts by (source_id, source_type). - Postgres: drop the GORM default tag on is_enabled, which replaced false with true on insert and indexed disabled chunks as enabled. - SQLite: BatchSave no longer attaches vectors and FTS rows to the wrong rows when part of a batch already exists, and vecTables is guarded against concurrent map writes. - CopyIndices: Postgres filters to the copied knowledge, pages by id and keeps is_enabled; SQLite copies every row of a chunk (generated questions included) with stable source IDs and enabled state. Shared knowledge bases - Chat merge: FAQ answer population and neighbor expansion look chunks up without the caller-tenant filter, like parent resolution (#3342). - Neighbor expansion never cuts the retrieval hit; the length budget goes to the text adjacent to it. - FAQ negative questions are applied whenever an FAQ KB is in scope and to chunks of shared FAQ KBs. - Search results get image_info for shared-KB chunks. - search_knowledge reads FAQ metadata from the search result instead of one tenant-scoped query per hit, so shared FAQs render their answers. * fix(retrieval): put every retrieval score on one scale Scores from different retrieval paths were ranked together while living on different scales, so ordering depended on which path produced a hit. Fusion - RRF ranked a chunk by its position in the concatenation of every vector (or keyword) list, appended in goroutine completion order. The second list's best hit ranked behind every hit of the first, and the order changed between identical requests. Each list is now ranked on its own by score and a chunk takes its best rank. - RRF is divided by its maximum, so hybrid scores land in [0, 1] like vector-only (cosine) and keyword-only (rescaled BM25) results. Raw RRF topped out near 0.016 and lost to any single-retriever hit it was ranked against across searches (document targets, model groups, FAQ calls); rerank's base-score term and MMR's relevance term had nothing to use. - Keyword-only BM25 is rescaled per list; engines' BM25 is not comparable. - FAQ iterative retrieval fuses each round like the first pass instead of sorting raw BM25 and cosine together, starts at twice the depth already searched, triggers when any single vector list is full (the old summed count never matched with more than one list) and replaces results per round. Rerank and chat pipeline - The FAQ boost is no longer capped at 1; capping made strong FAQs tie at 1.0 and fall to the tie-breaker. The composite score before boosts is kept as composite_score. - The FAQ direct-answer threshold is compared against that pre-boost score, and the FAQ that cleared it is the one marked match="exact" rather than the first FAQ. - Graph hits no longer carry a fabricated retrieval score of 1.0, which ranked them above every scored hit when rerank did not run; the composite score uses the model score in its place. Engines - OpenSearch and Weaviate return (1 + cos) / 2; their drivers now report cosine similarity and map thresholds onto the engine scale, so a threshold means the same on every engine. - Milvus L2 returned squared distance, ranked farthest-first downstream, and took the threshold as a radius; scores and radius are converted. - The multi-store normalizer no longer maps Milvus through (s + 1) / 2, which put it on a different scale from every other engine and from its own single-store results. Docs updated for fusion, normalization, FAQ boost and iterative recall. * perf(retrieval): bound rerank, agent and pipeline cost; stop failing on slow or missing models Rerank - Rerankers report the longest document a request can carry (max_document_chars / max_request_chars minus the query) and the rerank stage fits its own passages to it, trimming appended captions, OCR and generated questions first. One chunk with a large screenshot's OCR used to exceed the vendor limit and fail the whole batch, so every candidate lost its score and the threshold stopped applying. - Rerank HTTP requests default to a 60 s timeout; chat and agent contexts carry no deadline, so a stalled self-hosted rerank server held the turn open. - OCR and caption chunks no longer repeat their own text from image_info in the passage. - The chat pipeline and the agent tool rerank at most 200 candidates, best retrieval score first. - A rerank model that cannot be loaded degrades to retrieval order instead of failing every chat turn, as the search APIs already do; without rerank results the merge stage keeps only RerankTopK hits instead of enriching every one. Retrieval APIs - knowledge-search match_count and rerank.top_k are capped at 200 (unbounded values multiplied into tens of thousands of billed rerank passages); normalizedMatchCount clamps to the pool size so the over-retrieval arithmetic cannot overflow. - hybrid-search with rerank recalls at least rerank.top_k deep. Agent - search_knowledge fits its rendered output to four fifths of the tool output budget, dropping the lowest-ranked rows and telling the model how many it omitted; the model's view is rebuilt from Data, which registry truncation never reached. - Agent searches skip neighbor/parent/related enrichment rows, which were never retrieved yet tripled the rerank input. - ParallelToolCalls is enabled. The model was always told it may call tools in parallel while the engine ran them one by one; only read-only tools overlap, anything else stays a barrier. Chat pipeline - Query expansion searches keywords only (its variants are local rewrites whose embeddings repeat the main search) and is skipped when keyword matching is off. - Entity extraction, a second LLM call, is skipped for intents that need no KB retrieval and uses the rewritten query. - Partial-overlap dedup tokenizes each text once instead of per pair, and only compares token overlap between texts within 3x of each other's size. Storage - Migration 000112 adds btree indexes on embeddings(knowledge_id) and (chunk_id); document deletes, chunk re-index and enable/tag updates scanned the whole table. - Shared-KB knowledge rows are fetched in one query instead of one per ID. - Drop GORM Debug() from the ParadeDB keyword query and the knowledge batch lookup, which logged SQL and user queries on every search. Docs updated for the API limits, rerank timeout and passage fitting, agent parallel tools and output budget, and pipeline changes. * fix(retrieval): make agent tools and pipeline stages report what they did Agent tools - query_knowledge_graph now queries the graph store: entity names from the query are matched in each KB's graph, relations are returned (and shown to the model), and the entities' source chunks lead the results, with text search as a supplement. It used to run text search only, so a graph-only KB always answered "no relevant graph information". - search_knowledge reports failures instead of "no matching chunks": when every search fails the tool fails with the reason; partial failures are listed. A failed query embedding falls back to keyword search for hybrid KBs, as the chat pipeline does. - Keyword mode uses rerank to order hits, not to reject them (identifiers score low), and the empty-result hint no longer sends keyword mode back to keyword mode. - Dedup keeps siblings under one parent, no longer merges every image chunk of a document through chunk_index 0, and keeps the better-scored copy. - Search rows omit a <match> excerpt that only repeats the content; snippet terms are segmented for Chinese queries and skip stopwords, and FAQ matched questions are chosen by match strength. - read_document query mode returns next_offset when truncated and resumes from offset. - wiki_search over-fetches under document/tag scopes before filtering and says when every match was out of scope. - Prompts point to read_document(id=cN, context=k) for surrounding text. - The agent editor hides the retrieval-strategy section in agent mode, where search_knowledge uses the global retrieval settings. Chat pipeline - Intent labels are normalized; an unknown label retrieves instead of silently skipping the knowledge base, and web_search without web search enabled searches the knowledge bases. - Image turns get a 2048-token rewrite budget, and a reply cut off by the cap is salvaged field by field instead of being discarded. - History references are matched by how much of the query they cover; Jaccard against chunk-sized text never reached its threshold. - Entity search resolves chunks of org-shared KBs within the turn's KB scope, skips chunks whose document is gone (it used to panic) and caps graph chunks at 30. - Empty history is not fetched twice; fetched pages are cut on a rune boundary. Retrieval - A multi-KB search whose primary KB has no vectors embeds the query with a vector KB's model instead of failing on an empty model ID. - Rerank passages include the chunk's heading breadcrumb, which is part of what was embedded. - SQLite FTS searches the content column only and turns a lone Han character into a prefix query; TencentVectorDB ef follows TopK. Docs updated for the agent tools and pipeline stages. * fix(retrieval): address review findings on the retrieval fixes - Restore NeedsRetrieval for web_search without web search enabled: the intent prompt "web_search" is how the user learns web search is off, and running KB retrieval instead bypassed it. - query_knowledge_graph keeps the case of entity terms; Neo4j matches node names with case-sensitive CONTAINS, so lowercased terms never matched English entities. - An empty search_knowledge or query_knowledge_graph result states partial failures in its text, which is all the model sees for an empty result. - SQLite BatchSave replaces a source in one transaction, so a failed insert keeps the old rows instead of leaving the source unindexed. - Reuse stringSliceValue and an exported searchutil.ContainsChinese instead of new copies; drop an unused named return and the FAQ obsolete-source delete that the full per-chunk delete now covers. * fix(retrieval): address second review of the retrieval fixes - query_knowledge_graph: under a document/tag scope, keep only relations whose entities come from an in-scope evidence chunk (the graph namespace is the whole KB); drop chunks whose document no longer exists; report a graph or text search failure even when the other source returned hits. - search_knowledge: record the hybrid -> keyword fallback taken when the query embedding fails in mode_fallbacks, so an empty result is not read as "no semantic match". - query understanding salvage: take a cut-off value only for the image description; a truncated rewrite_query or intent is dropped instead of replacing the user's query. - Graph hits (no retrieval score) are kept past the no-rerank RerankTopK cut and the rerank candidate cap instead of always falling below them. - FAQ boost is capped at 1 again so scores stay on the [0, 1] scale; FAQs tied at the cap are ordered by their pre-boost score. - Negative-question filtering loads only candidates of FAQ knowledge bases. - read_document query continuation starts one chunk before offset so the first match keeps its preceding context at a page boundary. - graphSearchTerms and searchQueryTokens share one queryTerms splitter.
2026-09-25 02:48:18 +00:00
if nextOffset >= 0 {
data["next_offset"] = nextOffset
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
return &types.ToolResult{
Success: true,
Output: t.buildOutput(knowledge, total, rows, query),
Data: data,
}, nil
}
// fitChunksToBudget keeps the leading chunks whose rendered size fits in
// budget runes. The model sees the result rendered from Data, which the
// registry's Output truncation never reaches, so a page must be bounded here;
// the first chunk is always kept so paging makes progress.
func fitChunksToBudget(chunks []*types.Chunk, budget int) []*types.Chunk {
used := 0
for i, c := range chunks {
used += utf8.RuneCountInString(c.Content) + readDocumentChunkOverhead
if used > budget && i > 0 {
return chunks[:i]
}
}
return chunks
}
func matchesAll(matchers []*regexp.Regexp, s string) bool {
for _, m := range matchers {
if !m.MatchString(s) {
return false
}
}
return true
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
// documentInfo is the metadata header shared by every read mode.
func documentInfo(knowledge *types.Knowledge, total int64) map[string]interface{} {
info := map[string]interface{}{
"knowledge_id": knowledge.ID,
"title": knowledge.Title,
"type": knowledge.Type,
"source": formatSource(knowledge.Type, knowledge.Source),
"parse_status": knowledge.ParseStatus,
"chunk_count": total,
}
if knowledge.Description != "" {
info["description"] = knowledge.Description
}
if knowledge.FileName != "" {
info["file_name"] = knowledge.FileName
info["file_type"] = knowledge.FileType
info["file_size"] = formatFileSize(knowledge.FileSize)
}
if knowledge.Metadata != nil {
if metadata, err := knowledge.Metadata.Map(); err == nil && len(metadata) > 0 {
info["metadata"] = metadata
}
}
return info
}
func (t *ReadDocumentTool) buildData(
knowledge *types.Knowledge, total int64, rows []readChunkRow,
) map[string]interface{} {
formatted := make([]map[string]interface{}, 0, len(rows))
chunkIDs := make([]string, 0, len(rows))
sourceChunkID := ""
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
for i, r := range rows {
chunkIDs = append(chunkIDs, r.chunk.ID)
if sourceChunkID == "" && len(r.chunk.SourceLocators) > 0 {
sourceChunkID = r.chunk.ID
}
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
row := chunkDataMap(i+1, r.chunk)
if row["knowledge_id"] == "" {
row["knowledge_id"] = knowledge.ID
}
if r.role != "" {
row["role"] = r.role
}
if r.snippet != "" {
row["match_snippet"] = r.snippet
}
formatted = append(formatted, row)
}
return map[string]interface{}{
"display_type": "knowledge_chunks_list",
"knowledge_id": knowledge.ID,
"knowledge_base_id": knowledge.KnowledgeBaseID,
"knowledge_title": strings.TrimSpace(knowledge.Title),
// Keep citation identities when chunks are omitted from SSE/history.
"chunk_ids": chunkIDs,
"source_chunk_id": sourceChunkID,
refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
"total_chunks": total,
"fetched_chunks": len(formatted),
"chunks": formatted,
"document": documentInfo(knowledge, total),
}
}
func (t *ReadDocumentTool) buildOutput(
knowledge *types.Knowledge, total int64, rows []readChunkRow, query string,
) string {
var b strings.Builder
fmt.Fprintf(&b, "<document knowledge_id=\"%s\" title=\"%s\" total_chunks=\"%d\" fetched=\"%d\"",
xmlEscape(knowledge.ID), xmlEscape(strings.TrimSpace(knowledge.Title)), total, len(rows))
if knowledge.Type != "" {
fmt.Fprintf(&b, " source=\"%s\"", xmlEscape(formatSource(knowledge.Type, knowledge.Source)))
}
if knowledge.FileType != "" {
fmt.Fprintf(&b, " file_type=\"%s\"", xmlEscape(knowledge.FileType))
}
if knowledge.ParseStatus != "" {
fmt.Fprintf(&b, " parse_status=\"%s\"", xmlEscape(formatParseStatus(knowledge.ParseStatus)))
}
b.WriteString(">\n")
if knowledge.Description != "" {
fmt.Fprintf(&b, "<description>%s</description>\n", xmlEscape(knowledge.Description))
}
if knowledge.Metadata != nil {
if metadata, err := knowledge.Metadata.Map(); err == nil && len(metadata) > 0 {
b.WriteString("<metadata>")
first := true
for key, value := range metadata {
if !first {
b.WriteString("; ")
}
first = false
fmt.Fprintf(&b, "%s: %v", xmlEscape(key), value)
}
b.WriteString("</metadata>\n")
}
}
if query != "" {
fmt.Fprintf(&b, "<query>%s</query>\n", xmlEscape(query))
}
for _, r := range rows {
extra := ""
if r.role != "" {
extra = fmt.Sprintf(" role=\"%s\"", r.role)
}
if r.snippet != "" {
fmt.Fprintf(&b, "<match_snippet>%s</match_snippet>\n", xmlEscape(r.snippet))
}
writeChunkXML(&b, r.chunk, extra)
}
b.WriteString("</document>")
return b.String()
}
func formatSource(knowledgeType, source string) string {
switch knowledgeType {
case "file":
return "File Upload"
case "url":
return fmt.Sprintf("URL: %s", source)
case "passage":
return "Text Input"
default:
return knowledgeType
}
}
func formatFileSize(size int64) string {
if size == 0 {
return "Unknown"
}
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
}
func formatParseStatus(status string) string {
switch status {
case "pending":
return "Pending"
case "processing":
return "Processing"
case "completed", "success":
return "Completed"
case "failed":
return "Failed"
default:
return status
}
}