diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.ts index f97bae3a..2a96dba4 100644 --- a/frontend/src/i18n/embed.ts +++ b/frontend/src/i18n/embed.ts @@ -468,7 +468,10 @@ const messages = { }, "knowledgeChunksList": { "chunkRange": "已加载 {fetched} / {total} 个分块", - "page": "第 {page} 页,每页 {pageSize} 个" + "page": "第 {page} 页,每页 {pageSize} 个", + "offsetRange": "第 {from}–{to} 块", + "queryMatches": "文档内搜索「{query}」命中 {count} 处", + "queryNoMatch": "文档内搜索「{query}」无匹配" }, "attachmentParsing": { "parsedSummary": "已解析 {count} 个附件", @@ -1050,7 +1053,10 @@ const messages = { }, "knowledgeChunksList": { "chunkRange": "{total}件中{fetched}件のチャンクを読み込みました", - "page": "{page}ページ目、1ページ{pageSize}件" + "page": "{page}ページ目、1ページ{pageSize}件", + "offsetRange": "チャンク {from}–{to}", + "queryMatches": "文書内検索「{query}」: {count}件一致", + "queryNoMatch": "文書内検索「{query}」: 一致なし" }, "attachmentParsing": { "parsedSummary": "{count}件の添付ファイルを解析しました", @@ -1632,7 +1638,10 @@ const messages = { }, "knowledgeChunksList": { "chunkRange": "Loaded {fetched} / {total} chunks", - "page": "Page {page}, {pageSize} per page" + "page": "Page {page}, {pageSize} per page", + "offsetRange": "Chunks {from}–{to}", + "queryMatches": "{count} matches for \"{query}\" in this document", + "queryNoMatch": "No matches for \"{query}\" in this document" }, "attachmentParsing": { "parsedSummary": "Parsed {count} attachment(s)", diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 7bfb0397..08cc6e1e 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -5930,7 +5930,10 @@ export default { }, knowledgeChunksList: { chunkRange: 'Loaded {fetched} / {total} chunks', - page: 'Page {page}, {pageSize} per page' + page: 'Page {page}, {pageSize} per page', + offsetRange: 'Chunks {from}–{to}', + queryMatches: '{count} matches for "{query}" in this document', + queryNoMatch: 'No matches for "{query}" in this document' }, attachmentParsing: { parsedSummary: 'Parsed {count} attachment(s)', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index 0f7acefc..a4a36538 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -5930,7 +5930,10 @@ export default { }, knowledgeChunksList: { chunkRange: '{fetched} / {total}チャンクを読み込みました', - page: '{page}ページ目、1ページあたり{pageSize}件' + page: '{page}ページ目、1ページあたり{pageSize}件', + offsetRange: 'チャンク {from}–{to}', + queryMatches: '文書内検索「{query}」: {count}件一致', + queryNoMatch: '文書内検索「{query}」: 一致なし' }, attachmentParsing: { parsedSummary: '{count}件の添付ファイルを解析しました', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 75f4bdb3..cd082a28 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1557,7 +1557,10 @@ export default { }, knowledgeChunksList: { chunkRange: '{fetched} / {total} 청크 로드됨', - page: '{page}페이지, 페이지당 {pageSize}개' + page: '{page}페이지, 페이지당 {pageSize}개', + offsetRange: '청크 {from}–{to}', + queryMatches: '문서 내 검색 "{query}": {count}건 일치', + queryNoMatch: '문서 내 검색 "{query}": 일치 없음' }, grepResults: { chunkHits: '청크 {count}개', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 149ce280..350308e9 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1557,7 +1557,10 @@ export default { }, knowledgeChunksList: { chunkRange: 'Загружено {fetched} / {total} фрагментов', - page: 'Стр. {page}, по {pageSize} на странице' + page: 'Стр. {page}, по {pageSize} на странице', + offsetRange: 'Фрагменты {from}–{to}', + queryMatches: 'Поиск «{query}» в документе: совпадений {count}', + queryNoMatch: 'Поиск «{query}» в документе: совпадений нет' }, grepResults: { chunkHits: '{count} фрагм.', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index ae7c21eb..94e8fa11 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1559,7 +1559,10 @@ export default { }, knowledgeChunksList: { chunkRange: '已加载 {fetched} / {total} 个分块', - page: '第 {page} 页,每页 {pageSize} 个' + page: '第 {page} 页,每页 {pageSize} 个', + offsetRange: '第 {from}–{to} 块', + queryMatches: '文档内搜索「{query}」命中 {count} 处', + queryNoMatch: '文档内搜索「{query}」无匹配' }, grepResults: { chunkHits: '{count} 片段', diff --git a/frontend/src/utils/knowledgeChunksDisplay.test.mjs b/frontend/src/utils/knowledgeChunksDisplay.test.mjs index cb0c15f5..1dc64bf8 100644 --- a/frontend/src/utils/knowledgeChunksDisplay.test.mjs +++ b/frontend/src/utils/knowledgeChunksDisplay.test.mjs @@ -10,6 +10,15 @@ const t = (key, params) => { if (key === 'agentStream.knowledgeChunksList.page') { return `page ${params?.page}/${params?.pageSize}` } + if (key === 'agentStream.knowledgeChunksList.offsetRange') { + return `chunks ${params?.from}-${params?.to}` + } + if (key === 'agentStream.knowledgeChunksList.queryMatches') { + return `found ${params?.count} for ${params?.query}` + } + if (key === 'agentStream.knowledgeChunksList.queryNoMatch') { + return `none for ${params?.query}` + } return key } @@ -24,3 +33,36 @@ test('getKnowledgeChunksSummaryHtml joins chunk range and page', () => { assert.match(html, /loaded 20<\/strong>\/282<\/strong>/) assert.match(html, /page 3\/20/) }) + +test('getKnowledgeChunksSummaryHtml reports in-document search results, not a chunk range', () => { + const none = getKnowledgeChunksSummaryHtml(t, { + display_type: 'knowledge_chunks_list', + fetched_chunks: 0, + total_chunks: 708, + query: 'sunflower ', + match_count: 0, + }) + assert.equal(none, 'none for sunflower <f>') + + const some = getKnowledgeChunksSummaryHtml(t, { + display_type: 'knowledge_chunks_list', + fetched_chunks: 9, + total_chunks: 708, + query: 'sunflower', + match_count: 20, + truncated: true, + }) + assert.equal(some, 'found 20+ for sunflower') +}) + +test('getKnowledgeChunksSummaryHtml shows the chunk range for offset paging', () => { + const html = getKnowledgeChunksSummaryHtml(t, { + display_type: 'knowledge_chunks_list', + fetched_chunks: 37, + total_chunks: 708, + offset: 100, + page: 2, + page_size: 100, + }) + assert.equal(html, 'loaded 37/708 · chunks 101-137') +}) diff --git a/frontend/src/utils/knowledgeChunksDisplay.ts b/frontend/src/utils/knowledgeChunksDisplay.ts index 11fb24c5..d166c1a2 100644 --- a/frontend/src/utils/knowledgeChunksDisplay.ts +++ b/frontend/src/utils/knowledgeChunksDisplay.ts @@ -10,6 +10,18 @@ export function getKnowledgeChunksSummaryHtml( return '' } + const query = toolData.query?.trim() + if (query) { + const count = Number(toolData.match_count ?? 0) + const params = { + query: escapeHtml(query), + count: `${count}${toolData.truncated ? '+' : ''}`, + } + return count > 0 + ? t('agentStream.knowledgeChunksList.queryMatches', params) + : t('agentStream.knowledgeChunksList.queryNoMatch', params) + } + const parts: string[] = [ t('agentStream.knowledgeChunksList.chunkRange', { fetched: `${toolData.fetched_chunks ?? 0}`, @@ -18,6 +30,19 @@ export function getKnowledgeChunksSummaryHtml( ] const total = Number(toolData.total_chunks ?? 0) + const fetched = Number(toolData.fetched_chunks ?? 0) + // read_document pages by offset and may return fewer than page_size chunks + // to stay within the output budget, so a page number would be misleading. + if (toolData.offset !== undefined) { + if (fetched > 0 && fetched < total) { + const from = Number(toolData.offset) + 1 + parts.push( + t('agentStream.knowledgeChunksList.offsetRange', { from, to: from + fetched - 1 }), + ) + } + return parts.join(' · ') + } + const pageSize = Number(toolData.page_size ?? 0) if (total > pageSize && pageSize > 0) { parts.push( @@ -30,3 +55,11 @@ export function getKnowledgeChunksSummaryHtml( return parts.join(' · ') } + +function escapeHtml(s: string): string { + return s + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} diff --git a/internal/agent/tools/read_document.go b/internal/agent/tools/read_document.go index 50d43f22..8b9f9af8 100644 --- a/internal/agent/tools/read_document.go +++ b/internal/agent/tools/read_document.go @@ -18,6 +18,9 @@ const ( 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 ) var readDocumentTool = BaseTool{ @@ -26,10 +29,13 @@ var readDocumentTool = BaseTool{ "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. query is a case-insensitive literal by default; set regex=true for a POSIX regular expression.\n" + + "side. By default query is case-insensitive and split on whitespace: a chunk matches when it contains " + + "every word, in any order. Set regex=true to match query as one POSIX regular expression instead.\n" + "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. Use search_knowledge first when you do not yet know which document holds the answer.", + "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.", schema: json.RawMessage(`{ "type": "object", "properties": { @@ -51,11 +57,11 @@ var readDocumentTool = BaseTool{ }, "query": { "type": "string", - "description": "Text to find inside the document; returns matching chunks with context instead of a page" + "description": "Words a chunk must all contain; returns matching chunks with context instead of a page" }, "regex": { "type": "boolean", - "description": "Interpret query as a POSIX regular expression (default false: literal match)" + "description": "Match query as one POSIX regular expression (default false: each word matched literally)" }, "context": { "type": "integer", @@ -150,26 +156,30 @@ func (t *ReadDocumentTool) Execute(ctx context.Context, args json.RawMessage) (* return &types.ToolResult{Success: false, Error: err.Error()}, err } - var matcher *regexp.Regexp - if query != "" { - pattern := query - if !input.Regex { - pattern = regexp.QuoteMeta(query) - } - compiled, cerr := regexp.Compile("(?i)" + pattern) + var matchers []*regexp.Regexp + switch { + case query == "": + case input.Regex: + compiled, cerr := regexp.Compile("(?i)" + query) if cerr != nil { return &types.ToolResult{ Success: false, Error: fmt.Sprintf("invalid regex query %q: %v", query, cerr), }, cerr } - matcher = compiled + 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))) + } } // 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 matcher != nil: - return t.readByQuery(ctx, knowledge, query, matcher) + case len(matchers) > 0: + return t.readByQuery(ctx, knowledge, query, matchers) case chunk != nil: return t.readAroundChunk(ctx, knowledge, chunk, contextChunks) default: @@ -308,6 +318,7 @@ func (t *ReadDocumentTool) readPage( }, }, nil } + chunks = fitChunksToBudget(chunks, OutputBudget(ctx)*4/5) enrichChunkImageInfo(ctx, t.chunkService.GetRepository(), t.tenantFor(knowledge), chunks) rows := make([]readChunkRow, 0, len(chunks)) @@ -384,10 +395,11 @@ func (t *ReadDocumentTool) readAroundChunk( }, nil } -// readByQuery scans the document in order and returns matching chunks with -// one chunk of context on each side, capped at readDocumentMaxMatches. +// readByQuery scans the document in order and returns chunks matched by +// every matcher, with one chunk of context on each side, capped at +// readDocumentMaxMatches. func (t *ReadDocumentTool) readByQuery( - ctx context.Context, knowledge *types.Knowledge, query string, matcher *regexp.Regexp, + ctx context.Context, knowledge *types.Knowledge, query string, matchers []*regexp.Regexp, ) (*types.ToolResult, error) { var rows []readChunkRow emitted := make(map[string]bool) @@ -398,7 +410,6 @@ func (t *ReadDocumentTool) readByQuery( forceNext := false page := 1 tenantID := t.tenantFor(knowledge) - compiled := []*regexp.Regexp{matcher} // 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 @@ -406,7 +417,7 @@ func (t *ReadDocumentTool) readByQuery( emit := func(row readChunkRow) { rows = append(rows, row) emitted[row.chunk.ID] = true - used += utf8.RuneCountInString(row.chunk.Content) + used += utf8.RuneCountInString(row.chunk.Content) + readDocumentChunkOverhead } scan: @@ -427,7 +438,7 @@ scan: if q := faqStandardQuestion(c); q != "" { haystack += "\n" + q } - if matcher.MatchString(haystack) { + if matchesAll(matchers, haystack) { if matchCount >= readDocumentMaxMatches || used >= budget { truncated = true break scan @@ -437,7 +448,7 @@ scan: emit(readChunkRow{chunk: prev, role: "context_before"}) } if !emitted[c.ID] { - emit(readChunkRow{chunk: c, role: "match", snippet: extractChunkMatchSnippet(c, compiled)}) + emit(readChunkRow{chunk: c, role: "match", snippet: extractChunkMatchSnippet(c, matchers)}) } forceNext = true } else if forceNext { @@ -465,6 +476,30 @@ scan: }, 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 +} + // documentInfo is the metadata header shared by every read mode. func documentInfo(knowledge *types.Knowledge, total int64) map[string]interface{} { info := map[string]interface{}{ diff --git a/internal/agent/tools/read_document_test.go b/internal/agent/tools/read_document_test.go index d6ff8579..42c7872f 100644 --- a/internal/agent/tools/read_document_test.go +++ b/internal/agent/tools/read_document_test.go @@ -329,6 +329,33 @@ func TestReadDocumentQueryStopsAtOutputBudget(t *testing.T) { } } +func TestReadDocumentPageStopsAtOutputBudget(t *testing.T) { + tool, repo := newReadDocumentFixture(12) + for _, c := range repo.ordered { + c.Content = strings.Repeat("x", 400) + } + ctx := WithOutputBudget(context.Background(), 2000) + res, err := tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","offset":2,"limit":10}`)) + if err != nil || !res.Success { + t.Fatalf("res=%+v err=%v", res, err) + } + got := chunkIDsFromData(t, res.Data) + if len(got) == 0 || len(got) >= 10 { + t.Fatalf("expected a partial, budget-bound page, got %v", got) + } + if res.Data["next_offset"] != 2+len(got) { + t.Fatalf("next_offset must resume after the last returned chunk: %+v", res.Data) + } + + // A single chunk larger than the budget is still returned so paging + // always advances. + repo.ordered[0].Content = strings.Repeat("y", 5000) + res, err = tool.Execute(ctx, json.RawMessage(`{"id":"doc-1","limit":10}`)) + if err != nil || !res.Success || res.Data["next_offset"] != 1 { + t.Fatalf("oversized first chunk: res=%+v err=%v", res, err) + } +} + func TestReadDocumentLastPageHasNoNextOffset(t *testing.T) { tool, _ := newReadDocumentFixture(5) res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","offset":0,"limit":20}`)) @@ -427,6 +454,20 @@ func TestReadDocumentQueryIsLiteralUnlessRegex(t *testing.T) { } } +func TestReadDocumentQueryMatchesEveryWordInAnyOrder(t *testing.T) { + tool, repo := newReadDocumentFixture(4) + repo.ordered[1].Content = "Let f(n,k) be the least size forcing a sunflower." + repo.ordered[2].Content = "A sunflower alone." + res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"Sunflower f(n,k)"}`)) + if err != nil || !res.Success || res.Data["match_count"] != 1 { + t.Fatalf("words should match in any order, and only together: res=%+v err=%v", res, err) + } + rows := res.Data["chunks"].([]map[string]interface{}) + if rows[1]["chunk_id"] != "chunk-1" || rows[1]["role"] != "match" { + t.Fatalf("rows = %+v", rows) + } +} + func TestReadDocumentQueryWithoutMatchesKeepsHeader(t *testing.T) { tool, _ := newReadDocumentFixture(3) res, err := tool.Execute(context.Background(), json.RawMessage(`{"id":"doc-1","query":"absent"}`)) diff --git a/internal/modelcontext/model_output.go b/internal/modelcontext/model_output.go index a07b8046..84e369d5 100644 --- a/internal/modelcontext/model_output.go +++ b/internal/modelcontext/model_output.go @@ -330,6 +330,9 @@ func (r *sourceRegistry) modelKnowledgeChunksOutput(data map[string]interface{}, writeDocumentInfo(&b, info) if query := stringValue(data, "query"); query != "" { fmt.Fprintf(&b, " \n", escapeAttr(query)) + b.WriteString(" No chunk contains every word of the query. Retry with fewer or different " + + "words (the document's own language and terms), or read a chunk from search_knowledge " + + "results with id=cN and context.\n") } b.WriteString(" \n") return b.String() diff --git a/internal/modelcontext/registry_test.go b/internal/modelcontext/registry_test.go index 3527f3a6..cede3127 100644 --- a/internal/modelcontext/registry_test.go +++ b/internal/modelcontext/registry_test.go @@ -617,6 +617,7 @@ func TestModelOutputRendersReadDocumentHeaderAndNavigation(t *testing.T) { }}) require.Contains(t, empty, ``) require.Contains(t, empty, ``) + require.Contains(t, empty, "No chunk contains every word of the query.") } func TestModelOutputRendersDocumentListWithPagination(t *testing.T) {