Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(kb-tool): integrate BM25 search and docs_* read for inline documents (#14494)

Inneiad0da3753ea9
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
index f0ac12278ea..1c162ff7681 100644
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
@@ -62,7 +62,12 @@ interface RagService {
semanticSearchForChat: (
params: { knowledgeIds?: string[]; query: string; topK: number },
signal?: AbortSignal,
- ) => Promise<{ chunks: any[]; fileResults: any[] }>;
+ ) => Promise<{
+ chunks: any[];
+ documents?: any[];
+ errors?: { bm25?: string; vector?: string };
+ fileResults: any[];
+ }>;
}
interface KnowledgeBaseService {
@@ -252,18 +257,35 @@ export class KnowledgeBaseExecutionRuntime {
try {
const { query, topK = 20 } = args;
- const { chunks, fileResults } = await this.ragService.semanticSearchForChat(
+ const result = await this.ragService.semanticSearchForChat(
{ knowledgeIds: options?.knowledgeBaseIds, query, topK },
options?.signal,
);
-
- if (chunks.length === 0) {
- const state: SearchKnowledgeBaseState = { chunks: [], fileResults: [], totalResults: 0 };
+ const chunks = result.chunks ?? [];
+ const fileResults = result.fileResults ?? [];
+ const documents = result.documents ?? [];
+ const errors = result.errors;
+ const totalResults = chunks.length + documents.length;
+
+ if (totalResults === 0) {
+ const state: SearchKnowledgeBaseState = {
+ chunks: [],
+ documents: [],
+ errors,
+ fileResults: [],
+ totalResults: 0,
+ };
return { content: promptNoSearchResults(query), state, success: true };
}
- const formattedContent = formatSearchResults(fileResults, query);
- const state: SearchKnowledgeBaseState = { chunks, fileResults, totalResults: chunks.length };
+ const formattedContent = formatSearchResults(fileResults, query, documents, errors);
+ const state: SearchKnowledgeBaseState = {
+ chunks,
+ documents,
+ errors,
+ fileResults,
+ totalResults,
+ };
return { content: formattedContent, state, success: true };
} catch (e) {
diff --git a/packages/builtin-tool-knowledge-base/src/executor/index.ts b/packages/builtin-tool-knowledge-base/src/executor/index.ts
index 1287a497859..de23e7fe8d4 100644
--- a/packages/builtin-tool-knowledge-base/src/executor/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/executor/index.ts
@@ -159,18 +159,40 @@ class KnowledgeBaseExecutor extends BaseExecutor<typeof KnowledgeBaseApiName> {
const knowledgeIds = agentSelectors.currentKnowledgeIds(agentState);
const knowledgeBaseIds = knowledgeIds.knowledgeBaseIds;
- const { chunks, fileResults } = await ragService.semanticSearchForChat(
+ const result = await ragService.semanticSearchForChat(
{ knowledgeIds: knowledgeBaseIds, query, topK },
ctx.signal,
);
-
- if (chunks.length === 0) {
- const state: SearchKnowledgeBaseState = { chunks: [], fileResults: [], totalResults: 0 };
- return { content: promptNoSearchResults(query), state, success: true };
+ const chunks = result.chunks ?? [];
+ const fileResults = result.fileResults ?? [];
+ const documents = result.documents ?? [];
+ const errors = result.errors;
+ const totalResults = chunks.length + documents.length;
+
+ if (totalResults === 0) {
+ const state: SearchKnowledgeBaseState = {
+ chunks: [],
+ documents: [],
+ errors,
+ fileResults: [],
+ totalResults: 0,
+ };
+ // Use formatSearchResults when errors are present so failure details
+ // are surfaced instead of being silently dropped.
+ const content = errors
+ ? formatSearchResults(fileResults, query, documents, errors)
+ : promptNoSearchResults(query);
+ return { content, state, success: true };
}
- const formattedContent = formatSearchResults(fileResults, query);
- const state: SearchKnowledgeBaseState = { chunks, fileResults, totalResults: chunks.length };
+ const formattedContent = formatSearchResults(fileResults, query, documents, errors);
+ const state: SearchKnowledgeBaseState = {
+ chunks,
+ documents,
+ errors,
+ fileResults,
+ totalResults,
+ };
return { content: formattedContent, state, success: true };
} catch (e) {
diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.ts
index 70caf5f71c5..1d32a54ef31 100644
--- a/packages/builtin-tool-knowledge-base/src/manifest.ts
+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts
@@ -97,7 +97,7 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {
// ---- Search & Read ----
{
description:
- 'Search through knowledge base using semantic vector search to find relevant files and chunks. Returns a summary of matching files with their relevance scores and brief excerpts. Use this first to discover which files contain relevant information. IMPORTANT: Since this uses vector-based search, always resolve pronouns and references to concrete entities (e.g., use "authentication system" instead of "it").',
+ 'Search the knowledge base. Returns two result types: (1) <files> β€” uploaded files matched by semantic vector search at chunk-level (file_* IDs); (2) <documents> β€” inline notes/documents matched by full-text BM25 search at document-level (docs_* IDs). Use this to discover relevant content first, then call readKnowledge with the returned IDs to get full content. Resolve pronouns/references to concrete entities for best vector recall.',
name: KnowledgeBaseApiName.searchKnowledgeBase,
parameters: {
properties: {
@@ -121,13 +121,13 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {
},
{
description:
- 'Read the full content of specific files from the knowledge base. Use this after searchKnowledgeBase to get complete information from relevant files. You can read multiple files at once.',
+ 'Read the full content of specific resources from the knowledge base. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents created via createDocument. Use this after searchKnowledgeBase or viewKnowledgeBase to get complete content. You can read multiple resources at once.',
name: KnowledgeBaseApiName.readKnowledge,
parameters: {
properties: {
fileIds: {
description:
- 'Array of file IDs to read. Get these IDs from searchKnowledgeBase results.',
+ 'Array of resource IDs to read. Accepts file IDs (file_*) and document IDs (docs_*) returned by searchKnowledgeBase or viewKnowledgeBase.',
items: {
type: 'string',
},
diff --git a/packages/builtin-tool-knowledge-base/src/systemRole.ts b/packages/builtin-tool-knowledge-base/src/systemRole.ts
index 31905ccbb02..70274b74bc4 100644
--- a/packages/builtin-tool-knowledge-base/src/systemRole.ts
+++ b/packages/builtin-tool-knowledge-base/src/systemRole.ts
@@ -56,11 +56,11 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso
**Knowledge base search (use when user explicitly asks for KB or semantic search):**
- **listKnowledgeBases**: Discover available knowledge bases. Returns name, description, and ID for each.
- **viewKnowledgeBase**: See all files/documents in a specific knowledge base. Provides file IDs, types, and sizes.
-- **searchKnowledgeBase**: Semantic search across knowledge base content.
- - Uses vector search β€” always resolve pronouns to concrete entities
- - BAD: "What does it do?" β†’ GOOD: "What does the authentication system do?"
- - Adjust topK (5-100, default: 15) based on how many results you need
-- **readKnowledge**: Read complete file content by file IDs. Use after searching or browsing.
+- **searchKnowledgeBase**: Search across knowledge base content. Returns two result types:
+ - \`<files>\` β€” uploaded files matched by semantic vector search at chunk-level (file_* IDs). Resolve pronouns to concrete entities (BAD: "What does it do?" β†’ GOOD: "What does the authentication system do?").
+ - \`<documents>\` β€” inline notes/documents (created via createDocument) matched by full-text BM25 search at document-level (docs_* IDs). Works well with literal keyword queries.
+ - Adjust topK (5-100, default: 15) per result type.
+- **readKnowledge**: Read complete content by ID. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents. Use the IDs returned by searchKnowledgeBase or viewKnowledgeBase.
**Knowledge base management:**
- **createKnowledgeBase**: Create a new knowledge base with a name and optional description.
diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.ts
index 8a9b6c41a42..4e20f67c2cd 100644
--- a/packages/builtin-tool-knowledge-base/src/types.ts
+++ b/packages/builtin-tool-knowledge-base/src/types.ts
@@ -22,8 +22,25 @@ export interface SearchKnowledgeBaseArgs {
query: string;
topK?: number;
}
+
+/**
+ * BM25 hit on a custom/document inside a knowledge base.
+ * Mirrors database/repositories/search KnowledgeBaseDocumentHit; redeclared
+ * here to keep this package decoupled from server-only types.
+ */
+export interface KnowledgeBaseDocumentResult {
+ documentId: string;
+ knowledgeBaseId: string;
+ relevance: number;
+ snippet: string;
+ title: string;
+ updatedAt: Date | string;
+}
+
export interface SearchKnowledgeBaseState {
chunks: ChatSemanticSearchChunk[];
+ documents: KnowledgeBaseDocumentResult[];
+ errors?: { bm25?: string; vector?: string };
fileResults: FileSearchResult[];
totalResults: number;
}
diff --git a/packages/database/src/repositories/search/index.test.ts b/packages/database/src/repositories/search/index.test.ts
index de35015f793..9fd96b70c1d 100644
--- a/packages/database/src/repositories/search/index.test.ts
+++ b/packages/database/src/repositories/search/index.test.ts
@@ -6,7 +6,7 @@ import { documents } from '../../schemas';
import type { NewAgent } from '../../schemas/agent';
import { agents } from '../../schemas/agent';
import type { NewFile } from '../../schemas/file';
-import { files } from '../../schemas/file';
+import { files, knowledgeBases } from '../../schemas/file';
import { messages } from '../../schemas/message';
import type { NewTopic } from '../../schemas/topic';
import { topics } from '../../schemas/topic';
@@ -851,6 +851,124 @@ describe.skipIf(!isServerDB)('SearchRepo', () => {
});
});
+ describe('searchKnowledgeBaseDocuments', () => {
+ const kbA = 'kb-search-a';
+ const kbB = 'kb-search-b';
+
+ beforeEach(async () => {
+ // Create two KBs for the test user + one for the other user
+ await serverDB.insert(knowledgeBases).values([
+ { id: kbA, name: 'Knowledge Base A', userId },
+ { id: kbB, name: 'Knowledge Base B', userId },
+ { id: 'kb-other-1', name: 'Other User KB', userId: otherUserId },
+ ]);
+
+ // Documents in KB-A
+ await serverDB.insert(documents).values([
+ {
+ content:
+ 'Machine learning algorithms can be supervised, unsupervised, or reinforcement-based. ' +
+ 'Common supervised methods include linear regression, decision trees, and neural networks.',
+ fileType: 'custom/document',
+ filename: 'ml-overview.md',
+ knowledgeBaseId: kbA,
+ source: 'internal://document/placeholder',
+ sourceType: 'api',
+ title: 'Machine Learning Overview',
+ totalCharCount: 200,
+ totalLineCount: 5,
+ userId,
+ },
+ {
+ content: 'Documentation about cooking β€” completely unrelated topic.',
+ fileType: 'custom/document',
+ filename: 'cooking.md',
+ knowledgeBaseId: kbA,
+ source: 'internal://document/placeholder',
+ sourceType: 'api',
+ title: 'Cooking Notes',
+ totalCharCount: 50,
+ totalLineCount: 2,
+ userId,
+ },
+ // Document in KB-B (must NOT be returned when searching KB-A)
+ {
+ content:
+ 'This document is in a different knowledge base and should not match KB-A scope.',
+ fileType: 'custom/document',
+ filename: 'ml-other-kb.md',
+ knowledgeBaseId: kbB,
+ source: 'internal://document/placeholder',
+ sourceType: 'api',
+ title: 'Machine Learning in KB-B',
+ totalCharCount: 100,
+ totalLineCount: 3,
+ userId,
+ },
+ // Document for other user (cross-user isolation check)
+ {
+ content: 'Machine learning notes from another user.',
+ fileType: 'custom/document',
+ filename: 'ml-other-user.md',
+ knowledgeBaseId: 'kb-other-1',
+ source: 'internal://document/placeholder',
+ sourceType: 'api',
+ title: 'Other user ML notes',
+ totalCharCount: 50,
+ totalLineCount: 2,
+ userId: otherUserId,
+ },
+ ]);
+ });
+
+ it('should return [] for empty query', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('', [kbA]);
+ expect(results).toEqual([]);
+ });
+
+ it('should return [] when no knowledgeBaseIds provided', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', []);
+ expect(results).toEqual([]);
+ });
+
+ it('should match documents within KB scope by content', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ expect(results.length).toBeGreaterThan(0);
+ // Should hit ML overview, not cooking
+ expect(results.some((r) => r.title === 'Machine Learning Overview')).toBe(true);
+ expect(results.every((r) => r.knowledgeBaseId === kbA)).toBe(true);
+ });
+
+ it('should respect KB scope (KB-A query does not return KB-B docs)', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ expect(results.every((r) => r.title !== 'Machine Learning in KB-B')).toBe(true);
+ });
+
+ it('should isolate across users', async () => {
+ // Searching with otherUserId's KB should not leak to current user
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [
+ 'kb-other-1',
+ ]);
+ // Current user (`userId`) does not own kb-other-1, so query against it returns []
+ expect(results).toEqual([]);
+ });
+
+ it('should produce snippet ≀ 300 characters', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ results.forEach((r) => {
+ expect(r.snippet.length).toBeLessThanOrEqual(303); // 300 + '...' suffix
+ });
+ });
+
+ it('should produce relevance in [1, 3] range', async () => {
+ const results = await searchRepo.searchKnowledgeBaseDocuments('machine learning', [kbA]);
+ results.forEach((r) => {
+ expect(r.relevance).toBeGreaterThanOrEqual(1);
+ expect(r.relevance).toBeLessThanOrEqual(3);
+ });
+ });
+ });
+
describe('search - context types', () => {
beforeEach(async () => {
// Create test data for context testing
diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.ts
index bbc2becd8f1..b61bbc63b10 100644
--- a/packages/database/src/repositories/search/index.ts
+++ b/packages/database/src/repositories/search/index.ts
@@ -1,4 +1,4 @@
-import { and, eq, ne, sql } from 'drizzle-orm';
+import { and, eq, inArray, ne, sql } from 'drizzle-orm';
import {
agents,
@@ -133,6 +133,20 @@ export interface KnowledgeBaseSearchResult extends BaseSearchResult {
type: 'knowledgeBase';
}
+/**
+ * BM25 hit for KB-scoped documents (custom/document) used by chunkRouter.semanticSearchForChat.
+ * Distinct from PageSearchResult β€” this carries snippet + KB id for agent tool consumption.
+ * `relevance` is normalized to [1, 3] (lower = better, matches BaseSearchResult semantics).
+ */
+export interface KnowledgeBaseDocumentHit {
+ documentId: string;
+ knowledgeBaseId: string;
+ relevance: number;
+ snippet: string;
+ title: string;
+ updatedAt: Date;
+}
+
export interface AssistantSearchResult extends BaseSearchResult {
author: string;
avatar?: string | null;
@@ -649,6 +663,53 @@ export class SearchRepo {
});
}
+ /**
+ * KB-scoped BM25 search over custom/document documents.
+ * Used by chunkRouter.semanticSearchForChat to surface inline documents
+ * to the KB agent tool's searchKnowledgeBase API.
+ */
+ async searchKnowledgeBaseDocuments(
+ query: string,
+ knowledgeBaseIds: string[],
+ limit: number = 20,
+ ): Promise<KnowledgeBaseDocumentHit[]> {
+ if (!query || query.trim() === '') return [];
+ if (!knowledgeBaseIds || knowledgeBaseIds.length === 0) return [];
+
+ const bm25Query = sanitizeBm25Query(query);
+
+ const rows = await this.db
+ .select({
+ content: documents.content,
+ filename: documents.filename,
+ id: documents.id,
+ knowledgeBaseId: documents.knowledgeBaseId,
+ score: sql<number>`paradedb.score(${documents.id})`,
+ title: documents.title,
+ updatedAt: documents.updatedAt,
+ })
+ .from(documents)
+ .where(
+ and(
+ eq(documents.userId, this.userId),
+ eq(documents.fileType, 'custom/document'),
+ inArray(documents.knowledgeBaseId, knowledgeBaseIds),
+ sql`(${documents.title} @@@ ${bm25Query} OR ${documents.slug} @@@ ${bm25Query} OR ${documents.content} @@@ ${bm25Query})`,
+ ),
+ )
+ .orderBy(sql`paradedb.score(${documents.id}) DESC`)
+ .limit(limit);
+
+ return this.mapScoresToRelevance(rows).map((row) => ({
+ documentId: row.id,
+ knowledgeBaseId: row.knowledgeBaseId ?? '',
+ relevance: row.relevance,
+ snippet: this.truncate(row.content, 300) ?? '',
+ title: row.title || row.filename || 'Untitled',
+ updatedAt: row.updatedAt,
+ }));
+ }
+
/**
* Search memories by title, summary, details (BM25)
*/
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap
index 6beb1298fa3..88ec020992b 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap
@@ -1,26 +1,90 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+exports[`formatSearchResults > should annotate empty result with both errors 1`] = `
+"<knowledge_base_search_results query="test query" totalCount="0">
+<instruction>No relevant content found in the knowledge base for this query.
+Note: vector search unavailable (Invalid API key for embedding provider); only document results returned.
+Note: full-text document search unavailable (paradedb extension unavailable); only file chunk results returned.</instruction>
+</knowledge_base_search_results>"
+`;
+
+exports[`formatSearchResults > should annotate when BM25 fails but vector succeeds 1`] = `
+"<knowledge_base_search_results query="test query" totalCount="1">
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.
+Note: full-text document search unavailable (paradedb extension unavailable); only file chunk results returned.</instruction>
+<files totalCount="1">
+<file id="file_only" name="Sole Result.pdf" relevanceScore="0.8">
+<chunk fileId="file_only" fileName="Sole Result.pdf" similarity="0.82">partial info</chunk>
+</file>
+</files>
+</knowledge_base_search_results>"
+`;
+
+exports[`formatSearchResults > should annotate when vector search fails but BM25 succeeds 1`] = `
+"<knowledge_base_search_results query="test query" totalCount="1">
+<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.
+Note: vector search unavailable (Invalid API key for embedding provider); only document results returned.</instruction>
+<documents totalCount="1">
+<document id="docs_only" title="Fallback Note" relevance="1.1" knowledgeBaseId="kb_main">
+<snippet>fallback content via BM25</snippet>
+</document>
+</documents>
+</knowledge_base_search_results>"
+`;
+
+exports[`formatSearchResults > should format documents only (BM25 hits, no file chunks) 1`] = `
+"<knowledge_base_search_results query="machine learning" totalCount="1">
+<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<documents totalCount="1">
+<document id="docs_abc123" title="ML Notes" relevance="1.2" knowledgeBaseId="kb_main">
+<snippet>machine learning is a subset of artificial intelligence...</snippet>
+</document>
+</documents>
+</knowledge_base_search_results>"
+`;
+
exports[`formatSearchResults > should format file with special characters in name 1`] = `
"<knowledge_base_search_results query="password reset" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="special-123" name="FAQ: Common Questions & Answers (2024).md" relevanceScore="0.88">
<chunk fileId="special-123" fileName="FAQ: Common Questions & Answers (2024).md" similarity="0.9">Q: How do I reset my password? A: Click on the "Forgot Password" link on the login page.</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should format long text chunks without truncation 1`] = `
"<knowledge_base_search_results query="documentation details" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="long-doc" name="Detailed Documentation.md" relevanceScore="0.91">
<chunk fileId="long-doc" fileName="Detailed Documentation.md" similarity="0.93">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</chunk>
</file>
+</files>
+</knowledge_base_search_results>"
+`;
+
+exports[`formatSearchResults > should format mixed file chunks and documents 1`] = `
+"<knowledge_base_search_results query="neural networks" totalCount="2">
+<instruction>Search results from the knowledge base. Two source types: <files> (vector search, chunk-level) and <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
+<file id="file_pdf1" name="AI Handbook.pdf" relevanceScore="0.91">
+<chunk fileId="file_pdf1" fileName="AI Handbook.pdf" similarity="0.94">Neural networks are computational models...</chunk>
+</file>
+</files>
+<documents totalCount="1">
+<document id="docs_inline1" title="Deep Learning Cheatsheet" relevance="1.5" knowledgeBaseId="kb_research">
+<snippet>Deep learning architectures include CNNs, RNNs, and Transformers.</snippet>
+</document>
+</documents>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should format multiple files with varying relevance scores 1`] = `
"<knowledge_base_search_results query="API authentication security" totalCount="3">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="3">
<file id="doc-001" name="API Reference.md" relevanceScore="0.95">
<chunk fileId="doc-001" fileName="API Reference.md" similarity="0.98">The Authentication API provides endpoints for user login, logout, and token refresh. All endpoints require HTTPS and proper API keys.</chunk>
<chunk fileId="doc-001" fileName="API Reference.md" similarity="0.92">To authenticate a user, send a POST request to /api/auth/login with username and password in the request body.</chunk>
@@ -32,51 +96,60 @@ exports[`formatSearchResults > should format multiple files with varying relevan
<file id="doc-003" name="Troubleshooting Guide.md" relevanceScore="0.73">
<chunk fileId="doc-003" fileName="Troubleshooting Guide.md" similarity="0.75">If you encounter authentication errors, first verify that your API key is valid and has not expired.</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should format query with special characters 1`] = `
"<knowledge_base_search_results query="How to use fetchData<T> with async/await?" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="code-sample" name="Code Examples.md" relevanceScore="0.94">
<chunk fileId="code-sample" fileName="Code Examples.md" similarity="0.96">Use the following TypeScript code: const result = await fetchData<T>({ url, params });</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should format single file with multiple chunks 1`] = `
"<knowledge_base_search_results query="how to install the application" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="file-123" name="Getting Started Guide.md" relevanceScore="0.92">
<chunk fileId="file-123" fileName="Getting Started Guide.md" similarity="0.95">To get started with the application, first install all dependencies using npm install or yarn install. Make sure you have Node.js version 16 or higher installed on your system.</chunk>
<chunk fileId="file-123" fileName="Getting Started Guide.md" similarity="0.88">After installation, you can run the development server with npm run dev. The application will be available at http://localhost:3000 by default.</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should handle empty file results 1`] = `
"<knowledge_base_search_results query="no results query" totalCount="0">
-<instruction>No relevant files found in the knowledge base for this query.</instruction>
+<instruction>No relevant content found in the knowledge base for this query.</instruction>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should handle file with multiple high-similarity chunks 1`] = `
"<knowledge_base_search_results query="project setup steps" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="comprehensive-guide" name="Complete Tutorial.md" relevanceScore="0.96">
<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.98">Step 1: Initialize the project with the configuration file.</chunk>
<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.97">Step 2: Configure the environment variables for your deployment.</chunk>
<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.96">Step 3: Run the migration scripts to set up the database schema.</chunk>
<chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.95">Step 4: Start the development server and verify everything is working.</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
exports[`formatSearchResults > should handle files with low relevance scores 1`] = `
"<knowledge_base_search_results query="specific technical query" totalCount="1">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>
+<files totalCount="1">
<file id="low-relevance" name="Tangentially Related.md" relevanceScore="0.32">
<chunk fileId="low-relevance" fileName="Tangentially Related.md" similarity="0.35">This document contains some loosely related information that might be helpful.</chunk>
</file>
+</files>
</knowledge_base_search_results>"
`;
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts
index 90e9dad8855..c699c98ff99 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import type { FileSearchResult } from './formatSearchResults';
+import type { DocumentSearchResult, FileSearchResult } from './formatSearchResults';
import { formatSearchResults } from './formatSearchResults';
describe('formatSearchResults', () => {
@@ -188,4 +188,79 @@ describe('formatSearchResults', () => {
const result = formatSearchResults(fileResults, 'project setup steps');
expect(result).toMatchSnapshot();
});
+
+ it('should format documents only (BM25 hits, no file chunks)', () => {
+ const documents: DocumentSearchResult[] = [
+ {
+ documentId: 'docs_abc123',
+ knowledgeBaseId: 'kb_main',
+ relevance: 1.2,
+ snippet: 'machine learning is a subset of artificial intelligence...',
+ title: 'ML Notes',
+ },
+ ];
+ const result = formatSearchResults([], 'machine learning', documents);
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should format mixed file chunks and documents', () => {
+ const fileResults: FileSearchResult[] = [
+ {
+ fileId: 'file_pdf1',
+ fileName: 'AI Handbook.pdf',
+ relevanceScore: 0.91,
+ topChunks: [{ similarity: 0.94, text: 'Neural networks are computational models...' }],
+ },
+ ];
+ const documents: DocumentSearchResult[] = [
+ {
+ documentId: 'docs_inline1',
+ knowledgeBaseId: 'kb_research',
+ relevance: 1.5,
+ snippet: 'Deep learning architectures include CNNs, RNNs, and Transformers.',
+ title: 'Deep Learning Cheatsheet',
+ },
+ ];
+ const result = formatSearchResults(fileResults, 'neural networks', documents);
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should annotate when vector search fails but BM25 succeeds', () => {
+ const documents: DocumentSearchResult[] = [
+ {
+ documentId: 'docs_only',
+ knowledgeBaseId: 'kb_main',
+ relevance: 1.1,
+ snippet: 'fallback content via BM25',
+ title: 'Fallback Note',
+ },
+ ];
+ const result = formatSearchResults([], 'test query', documents, {
+ vector: 'Invalid API key for embedding provider',
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should annotate when BM25 fails but vector succeeds', () => {
+ const fileResults: FileSearchResult[] = [
+ {
+ fileId: 'file_only',
+ fileName: 'Sole Result.pdf',
+ relevanceScore: 0.8,
+ topChunks: [{ similarity: 0.82, text: 'partial info' }],
+ },
+ ];
+ const result = formatSearchResults(fileResults, 'test query', [], {
+ bm25: 'paradedb extension unavailable',
+ });
+ expect(result).toMatchSnapshot();
+ });
+
+ it('should annotate empty result with both errors', () => {
+ const result = formatSearchResults([], 'test query', [], {
+ bm25: 'paradedb extension unavailable',
+ vector: 'Invalid API key for embedding provider',
+ });
+ expect(result).toMatchSnapshot();
+ });
});
diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts
index e19cfd23c5f..1a467c3d4f3 100644
--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts
+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts
@@ -10,6 +10,19 @@ export interface FileSearchResult {
topChunks: FileSearchResultChunk[];
}
+export interface DocumentSearchResult {
+ documentId: string;
+ knowledgeBaseId: string;
+ relevance: number;
+ snippet: string;
+ title: string;
+}
+
+export interface SearchResultErrors {
+ bm25?: string;
+ vector?: string;
+}
+
/**
* Formats a single chunk with XML tags
*/
@@ -29,22 +42,75 @@ ${chunks.join('\n')}
};
/**
- * Formats knowledge base search results into an XML structure
- * @param fileResults - Array of file search results with relevance scores and chunks
- * @param query - The original search query
- * @returns Formatted XML string with search results
+ * Formats a single document search result (BM25 hit on custom/document) with XML tags.
+ * Documents return only a snippet β€” agent should call readKnowledge with the docs_* id
+ * to fetch the full content.
*/
-export const formatSearchResults = (fileResults: FileSearchResult[], query: string): string => {
- if (fileResults.length === 0) {
+const formatDocument = (doc: DocumentSearchResult): string => {
+ return `<document id="${doc.documentId}" title="${doc.title}" relevance="${doc.relevance}" knowledgeBaseId="${doc.knowledgeBaseId}">
+<snippet>${doc.snippet}</snippet>
+</document>`;
+};
+
+/**
+ * Formats knowledge base search results into an XML structure.
+ * Two source types:
+ * - <files>: uploaded files matched by semantic vector search (chunk-level)
+ * - <documents>: inline documents matched by full-text search (document-level)
+ */
+export const formatSearchResults = (
+ fileResults: FileSearchResult[],
+ query: string,
+ documentResults: DocumentSearchResult[] = [],
+ errors?: SearchResultErrors,
+): string => {
+ const totalCount = fileResults.length + documentResults.length;
+
+ const errorNotes: string[] = [];
+ if (errors?.vector) {
+ errorNotes.push(
+ `Note: vector search unavailable (${errors.vector}); only document results returned.`,
+ );
+ }
+ if (errors?.bm25) {
+ errorNotes.push(
+ `Note: full-text document search unavailable (${errors.bm25}); only file chunk results returned.`,
+ );
+ }
+ const errorNote = errorNotes.length > 0 ? '\n' + errorNotes.join('\n') : '';
+
+ if (totalCount === 0) {
return `<knowledge_base_search_results query="${query}" totalCount="0">
-<instruction>No relevant files found in the knowledge base for this query.</instruction>
+<instruction>No relevant content found in the knowledge base for this query.${errorNote}</instruction>
</knowledge_base_search_results>`;
}
- const filesXml = fileResults.map((file) => formatFile(file)).join('\n');
+ const sections: string[] = [];
- return `<knowledge_base_search_results query="${query}" totalCount="${fileResults.length}">
-<instruction>Here are the search results from the knowledge base. Use the readKnowledge tool with file IDs to get complete content.</instruction>
+ if (fileResults.length > 0) {
+ const filesXml = fileResults.map((file) => formatFile(file)).join('\n');
+ sections.push(`<files totalCount="${fileResults.length}">
${filesXml}
+</files>`);
+ }
+
+ if (documentResults.length > 0) {
+ const docsXml = documentResults.map((doc) => formatDocument(doc)).join('\n');
+ sections.push(`<documents totalCount="${documentResults.length}">
+${docsXml}
+</documents>`);
+ }
+
+ const instruction = `Search results from the knowledge base. ${
+ fileResults.length > 0 && documentResults.length > 0
+ ? 'Two source types: <files> (vector search, chunk-level) and <documents> (full-text search, document-level). '
+ : fileResults.length > 0
+ ? 'Source type: <files> (vector search, chunk-level). '
+ : 'Source type: <documents> (full-text search, document-level). '
+ }Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.${errorNote}`;
+
+ return `<knowledge_base_search_results query="${query}" totalCount="${totalCount}">
+<instruction>${instruction}</instruction>
+${sections.join('\n')}
</knowledge_base_search_results>`;
-};
\ No newline at end of file
+};
diff --git a/src/features/PageEditor/TitleSection.tsx b/src/features/PageEditor/TitleSection.tsx
index 8bad524220f..e6949843bf7 100644
--- a/src/features/PageEditor/TitleSection.tsx
+++ b/src/features/PageEditor/TitleSection.tsx
@@ -104,6 +104,7 @@ const TitleSection = memo(() => {
padding: 0,
resize: 'none',
width: '100%',
+ borderRadius: '0px',
}}
onChange={(e) => {
const truncated = truncateByWeightedLength(e.target.value, 100);
diff --git a/src/server/routers/lambda/__tests__/chunk.test.ts b/src/server/routers/lambda/__tests__/chunk.test.ts
new file mode 100644
index 00000000000..f2c02c42e8d
--- /dev/null
+++ b/src/server/routers/lambda/__tests__/chunk.test.ts
@@ -0,0 +1,158 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { ChunkModel } from '@/database/models/chunk';
+import { DocumentModel } from '@/database/models/document';
+import { EmbeddingModel } from '@/database/models/embedding';
+import { FileModel } from '@/database/models/file';
+import { MessageModel } from '@/database/models/message';
+import { SearchRepo } from '@/database/repositories/search';
+import { ChunkService } from '@/server/services/chunk';
+import { DocumentService } from '@/server/services/document';
+
+import { chunkRouter } from '../chunk';
+
+vi.mock('@/database/models/asyncTask', () => ({ AsyncTaskModel: vi.fn() }));
+vi.mock('@/database/models/chunk', () => ({ ChunkModel: vi.fn() }));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
+vi.mock('@/database/models/embedding', () => ({ EmbeddingModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/message', () => ({ MessageModel: vi.fn() }));
+vi.mock('@/database/repositories/search', () => ({ SearchRepo: vi.fn() }));
+vi.mock('@/server/services/chunk', () => ({ ChunkService: vi.fn() }));
+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));
+vi.mock('@/database/server', () => ({ getServerDB: vi.fn() }));
+
+describe('chunkRouter.getFileContents β€” ID branching', () => {
+ const userId = 'user_test';
+ let mockCtx: any;
+ let documentModelMock: any;
+ let fileModelMock: any;
+ let documentServiceMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ documentModelMock = { findById: vi.fn(), findByFileId: vi.fn() };
+ fileModelMock = { findById: vi.fn() };
+ documentServiceMock = { parseFile: vi.fn() };
+
+ vi.mocked(DocumentModel).mockImplementation(() => documentModelMock);
+ vi.mocked(FileModel).mockImplementation(() => fileModelMock);
+ vi.mocked(DocumentService).mockImplementation(() => documentServiceMock);
+ vi.mocked(AsyncTaskModel).mockImplementation(() => ({}) as any);
+ vi.mocked(ChunkModel).mockImplementation(() => ({}) as any);
+ vi.mocked(EmbeddingModel).mockImplementation(() => ({}) as any);
+ vi.mocked(MessageModel).mockImplementation(() => ({}) as any);
+ vi.mocked(SearchRepo).mockImplementation(() => ({}) as any);
+ vi.mocked(ChunkService).mockImplementation(() => ({}) as any);
+
+ mockCtx = {
+ userId,
+ asyncTaskModel: {},
+ chunkModel: {},
+ chunkService: {},
+ documentModel: documentModelMock,
+ documentService: documentServiceMock,
+ embeddingModel: {},
+ fileModel: fileModelMock,
+ messageModel: {},
+ searchRepo: {},
+ };
+ });
+
+ it('reads docs_* directly from documents table without touching files', async () => {
+ documentModelMock.findById.mockResolvedValue({
+ content: '# 推荐俑\n\nMain body text here.',
+ filename: '推荐俑.md',
+ id: 'docs_pPAXDRIqlgxrG0HV',
+ metadata: { tag: 'letter' },
+ title: '推荐俑',
+ });
+
+ const caller = chunkRouter.createCaller(mockCtx);
+ const result = await caller.getFileContents({ fileIds: ['docs_pPAXDRIqlgxrG0HV'] });
+
+ expect(documentModelMock.findById).toHaveBeenCalledWith('docs_pPAXDRIqlgxrG0HV');
+ expect(fileModelMock.findById).not.toHaveBeenCalled();
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({
+ content: '# 推荐俑\n\nMain body text here.',
+ fileId: 'docs_pPAXDRIqlgxrG0HV',
+ filename: '推荐俑',
+ metadata: { tag: 'letter' },
+ });
+ expect(result[0].error).toBeUndefined();
+ });
+
+ it('returns "Document not found" for missing docs_* id', async () => {
+ documentModelMock.findById.mockResolvedValue(undefined);
+
+ const caller = chunkRouter.createCaller(mockCtx);
+ const result = await caller.getFileContents({ fileIds: ['docs_missing'] });
+
+ expect(result[0]).toMatchObject({
+ content: '',
+ error: 'Document not found',
+ fileId: 'docs_missing',
+ });
+ expect(fileModelMock.findById).not.toHaveBeenCalled();
+ });
+
+ it('falls through to file lookup for file_* id', async () => {
+ fileModelMock.findById.mockResolvedValue({ id: 'file_xyz', name: 'doc.pdf' });
+ documentModelMock.findByFileId.mockResolvedValue({
+ content: 'parsed pdf content',
+ metadata: null,
+ });
+
+ const caller = chunkRouter.createCaller(mockCtx);
+ const result = await caller.getFileContents({ fileIds: ['file_xyz'] });
+
+ expect(fileModelMock.findById).toHaveBeenCalledWith('file_xyz');
+ expect(documentModelMock.findByFileId).toHaveBeenCalledWith('file_xyz');
+ expect(documentModelMock.findById).not.toHaveBeenCalled();
+ expect(result[0]).toMatchObject({
+ content: 'parsed pdf content',
+ fileId: 'file_xyz',
+ filename: 'doc.pdf',
+ });
+ });
+
+ it('returns "File not found" for missing file_* id', async () => {
+ fileModelMock.findById.mockResolvedValue(undefined);
+
+ const caller = chunkRouter.createCaller(mockCtx);
+ const result = await caller.getFileContents({ fileIds: ['file_missing'] });
+
+ expect(result[0]).toMatchObject({
+ content: '',
+ error: 'File not found',
+ fileId: 'file_missing',
+ });
+ });
+
+ it('handles mixed batch of docs_* and file_*', async () => {
+ documentModelMock.findById.mockResolvedValue({
+ content: 'doc content',
+ filename: 'note.md',
+ id: 'docs_a',
+ title: 'Note',
+ });
+ fileModelMock.findById.mockResolvedValue({ id: 'file_b', name: 'paper.pdf' });
+ documentModelMock.findByFileId.mockResolvedValue({
+ content: 'pdf content',
+ metadata: null,
+ });
+
+ const caller = chunkRouter.createCaller(mockCtx);
+ const result = await caller.getFileContents({ fileIds: ['docs_a', 'file_b'] });
+
+ expect(result).toHaveLength(2);
+ const docsResult = result.find((r) => r.fileId === 'docs_a');
+ const fileResult = result.find((r) => r.fileId === 'file_b');
+ expect(docsResult?.content).toBe('doc content');
+ expect(fileResult?.content).toBe('pdf content');
+ });
+});
diff --git a/src/server/routers/lambda/chunk.ts b/src/server/routers/lambda/chunk.ts
index f7fc403a60d..f156cccab37 100644
--- a/src/server/routers/lambda/chunk.ts
+++ b/src/server/routers/lambda/chunk.ts
@@ -12,6 +12,7 @@ import { DocumentModel } from '@/database/models/document';
import { EmbeddingModel } from '@/database/models/embedding';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
+import { type KnowledgeBaseDocumentHit, SearchRepo } from '@/database/repositories/search';
import { knowledgeBaseFiles } from '@/database/schemas';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -33,6 +34,7 @@ const chunkProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
embeddingModel: new EmbeddingModel(ctx.serverDB, ctx.userId),
fileModel: new FileModel(ctx.serverDB, ctx.userId),
messageModel: new MessageModel(ctx.serverDB, ctx.userId),
+ searchRepo: new SearchRepo(ctx.serverDB, ctx.userId),
},
});
});
@@ -124,21 +126,49 @@ export const chunkRouter = router({
getFileContents: chunkProcedure
.input(
z.object({
+ // Accepts both file IDs (file_*) and document IDs (docs_*).
+ // Name kept as `fileIds` for backward compatibility with existing callers.
fileIds: z.array(z.string()),
}),
)
.mutation(async ({ ctx, input }) => {
return await pMap(
input.fileIds,
- async (fileId) => {
+ async (id) => {
+ // ---- Branch A: docs_* β€” read documents.content directly ----
+ // Used by KB inline documents (custom/document) which have no S3 file.
+ if (id.startsWith('docs_')) {
+ const doc = await ctx.documentModel.findById(id);
+ if (!doc) {
+ return {
+ content: '',
+ error: 'Document not found',
+ fileId: id,
+ filename: `Unknown document ${id}`,
+ };
+ }
+ const content = doc.content ?? '';
+ const lines = content.split('\n');
+ return {
+ content,
+ fileId: id,
+ filename: doc.title || doc.filename || 'Untitled',
+ metadata: doc.metadata,
+ preview: lines.slice(0, 5).join('\n'),
+ totalCharCount: content.length,
+ totalLineCount: lines.length,
+ };
+ }
+
+ // ---- Branch B: file_* β€” original file/parse path ----
// 1. Find file information
- const file = await ctx.fileModel.findById(fileId);
+ const file = await ctx.fileModel.findById(id);
if (!file) {
return {
content: '',
error: 'File not found',
- fileId,
- filename: `Unknown file ${fileId}`,
+ fileId: id,
+ filename: `Unknown file ${id}`,
};
}
@@ -148,17 +178,17 @@ export const chunkRouter = router({
content: string | null;
metadata: Record<string, any> | null;
}
- | undefined = await ctx.documentModel.findByFileId(fileId);
+ | undefined = await ctx.documentModel.findByFileId(id);
// 3. If not exists, parse the file
if (!document) {
try {
- document = await ctx.documentService.parseFile(fileId);
+ document = await ctx.documentService.parseFile(id);
} catch (error) {
return {
content: '',
error: `Failed to parse file: ${(error as Error).message}`,
- fileId,
+ fileId: id,
filename: file.name,
};
}
@@ -174,7 +204,7 @@ export const chunkRouter = router({
// 5. Return content with details
return {
content,
- fileId,
+ fileId: id,
filename: file.name,
metadata: document.metadata,
preview,
@@ -240,10 +270,13 @@ export const chunkRouter = router({
semanticSearchForChat: chunkProcedure
.input(SemanticSearchSchema)
.mutation(async ({ ctx, input }) => {
- try {
+ const topK = input.topK ?? 20;
+ const knowledgeIds = input.knowledgeIds ?? [];
+
+ // Path 1: vector search over file chunks
+ const vectorPath = async (): Promise<ChatSemanticSearchChunk[]> => {
const { model, provider } =
getServerDefaultFilesConfig().embeddingModel || DEFAULT_FILE_EMBEDDING_MODEL_ITEM;
- // Read user's provider config from database
const modelRuntime = await initModelRuntimeFromDB(ctx.serverDB, ctx.userId, provider);
// slice content to make sure in the context window limit
@@ -261,54 +294,85 @@ export const chunkRouter = router({
const embedding = embeddings![0];
let finalFileIds = input.fileIds ?? [];
-
- if (input.knowledgeIds && input.knowledgeIds.length > 0) {
+ if (knowledgeIds.length > 0) {
const knowledgeFiles = await ctx.serverDB.query.knowledgeBaseFiles.findMany({
- where: inArray(knowledgeBaseFiles.knowledgeBaseId, input.knowledgeIds),
+ where: inArray(knowledgeBaseFiles.knowledgeBaseId, knowledgeIds),
});
-
finalFileIds = knowledgeFiles.map((f) => f.fileId).concat(finalFileIds);
}
- const chunks = await ctx.chunkModel.semanticSearchForChat({
+ return ctx.chunkModel.semanticSearchForChat({
embedding,
fileIds: finalFileIds,
query: input.query,
- topK: input.topK,
+ topK,
});
+ };
- // Group chunks by file and calculate relevance scores
- const fileResults = groupAndRankFiles(chunks, input.topK || 15);
+ // Path 2: BM25 search over KB-scoped custom/document documents
+ const bm25Path = async (): Promise<KnowledgeBaseDocumentHit[]> => {
+ if (knowledgeIds.length === 0) return [];
+ return ctx.searchRepo.searchKnowledgeBaseDocuments(input.query, knowledgeIds, topK);
+ };
- // TODO: need to rerank the chunks
+ const [vectorResult, bm25Result] = await Promise.allSettled([vectorPath(), bm25Path()]);
- return { chunks, fileResults };
- } catch (e) {
- console.error(e);
+ const chunks: ChatSemanticSearchChunk[] =
+ vectorResult.status === 'fulfilled' ? vectorResult.value : [];
+ const documents: KnowledgeBaseDocumentHit[] =
+ bm25Result.status === 'fulfilled' ? bm25Result.value : [];
- const error = e as any;
- const errorType = error.errorType;
+ const errors: { bm25?: string; vector?: string } = {};
+ if (vectorResult.status === 'rejected') {
+ const error = vectorResult.reason as any;
+ const errorType = error?.errorType;
+ const msg = error?.message || errorType || 'Vector search failed';
+ errors.vector = msg;
+ console.error('[semanticSearchForChat] vector path failed', error);
+ }
+ if (bm25Result.status === 'rejected') {
+ const error = bm25Result.reason as any;
+ errors.bm25 = error?.message || 'BM25 search failed';
+ console.error('[semanticSearchForChat] BM25 path failed', error);
+ }
- // Map business error types to appropriate HTTP status codes
+ // Backward compatibility: if BM25 was not attempted (no KB scope) AND
+ // vector failed, surface the original TRPCError so existing chat flows
+ // (which only use vector) get the same diagnostics they did before.
+ if (
+ vectorResult.status === 'rejected' &&
+ knowledgeIds.length === 0 &&
+ documents.length === 0
+ ) {
+ const error = vectorResult.reason as any;
+ const errorType = error?.errorType;
if (errorType === 'InvalidProviderAPIKey') {
throw new TRPCError({
code: 'METHOD_NOT_SUPPORTED',
message: error.message || 'Invalid API key for embedding provider',
});
}
-
if (errorType === 'ProviderBizError') {
throw new TRPCError({
code: 'BAD_REQUEST',
message: error.message || 'Provider service error',
});
}
-
- // For unknown errors, still return 500 but with proper message
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
- message: error.message || errorType || 'Failed to perform semantic search',
+ message: error?.message || errorType || 'Failed to perform semantic search',
});
}
+
+ const fileResults = groupAndRankFiles(chunks, input.topK || 15);
+
+ // TODO: need to rerank the chunks
+ return {
+ chunks,
+ documents,
+ errors: Object.keys(errors).length > 0 ? errors : undefined,
+ fileResults,
+ totalResults: chunks.length + documents.length,
+ };
}),
});