Repository navigation
Expand file tree
/
Copy pathknowledge-search.ts
More file actions
72 lines (71 loc) · 2.19 KB
/
Copy pathknowledge-search.ts
File metadata and controls
72 lines (71 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { DB } from "@db/index.js";
import { fail } from "@core/shared/errors.js";
import { createContent } from "@core/workflows/resources.js";
import { searchIntent } from "@core/modules/discovery/search-intent.js";
import {
aiSearchHit,
checkScope,
type ToolContext,
} from "@core/workflows/ai-documents.js";
export async function searchKnowledge(
db: DB,
ctx: ToolContext,
input: {
query: string;
mode?: "auto" | "keyword" | "ai";
libraryId?: string;
offset?: number;
},
search?: (actor: any, query: any) => Promise<any>,
) {
if (input.libraryId) await checkScope(db, ctx, input.libraryId);
let matchedIds: string[] | undefined;
// Narrow before retrieval and pagination, not after the first page of global results.
if (ctx.allowedResources !== undefined) {
matchedIds = ctx.allowedResources.length
? (
await db
.selectFrom("resources")
.select("id")
.where((eb) =>
eb.or([
eb("id", "in", ctx.allowedResources!),
...(!ctx.exactResources
? [eb("library_id", "in", ctx.allowedResources!)]
: []),
]),
)
.execute()
).map((r) => r.id)
: [];
}
if (!search && input.mode === "ai")
fail(503, "AI 搜索尚未配置,请使用关键词搜索");
const topic = searchIntent(input.query).topic || input.query;
const query = {
q: search ? input.query : topic,
kind: "document",
mode: input.mode ?? "auto",
libraryIds: input.libraryId ? [input.libraryId] : undefined,
offset: input.offset ?? 0,
matchedIds,
};
const page = await (search ?? createContent(db).list)(ctx.actor, query);
const items = [];
for (const r of page.items) {
try {
items.push(await aiSearchHit(db, ctx, r.id, topic));
} catch (error) {
if (![403, 404].includes((error as { status?: number }).status ?? 0))
throw error;
}
}
return {
items,
nextOffset: page.nextOffset,
engine: page.engine ?? "database",
mode: page.mode ?? "keyword",
notice:
page.notice ?? (!search ? "未配置搜索服务,已使用关键词搜索" : undefined),
};
}