chat-agent-toolkit 1.2.33 → 1.2.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/research-agent.cjs.js.map +1 -1
- package/dist/research-agent.es.js.map +1 -1
- package/package.json +1 -1
- package/src/config/config-manager.ts +295 -295
- package/src/config/config-types.ts +65 -65
- package/src/config/environment-variables.ts +16 -16
- package/src/config/index.ts +26 -26
- package/src/config/language-models-database.ts +1434 -1434
- package/src/config/mcp-server-registry.ts +24 -24
- package/src/config/model-registry.ts +271 -271
- package/src/config/model-tester.ts +211 -211
- package/src/config/model-utils.ts +193 -193
- package/src/config/provider-ui-config.ts +196 -196
- package/src/connectors/open-connector.json +130 -130
- package/src/index.ts +26 -26
- package/src/memory/ARCHITECTURE.md +302 -302
- package/src/memory/README.md +224 -224
- package/src/memory/agent-memory-manager.ts +416 -416
- package/src/memory/example.ts +343 -343
- package/src/memory/index.ts +47 -47
- package/src/memory/mastra-integration.ts +604 -604
- package/src/memory/storage/drizzle-storage.ts +236 -236
- package/src/memory/storage/in-memory-storage.ts +551 -551
- package/src/memory/storage/storage-interface.ts +68 -68
- package/src/memory/types.ts +125 -125
- package/src/models/types.ts +4 -4
- package/src/tools/index.ts +13 -13
- package/src/tools/open-connector-mastra.ts +270 -270
- package/src/tools/open-connector-mcp.ts +170 -170
- package/src/tools/qwksearch-api-tools.ts +326 -326
- package/src/tools/search/doc-utils.ts +139 -139
- package/src/tools/search/document.ts +47 -47
- package/src/tools/search/index.ts +14 -14
- package/src/tools/search/link-summarizer.ts +112 -112
- package/src/tools/search/meta-search-types.ts +62 -62
- package/src/tools/search/metaSearchAgent.ts +465 -465
- package/src/tools/search/search-handlers.ts +97 -97
- package/src/tools/search/suggestionGeneratorAgent.ts +56 -56
- package/src/types.d.ts +137 -137
- package/src/utils/index.ts +2 -2
- package/src/utils/markdown-to-html.ts +53 -53
- package/src/utils/outputParser.ts +73 -73
|
@@ -1,139 +1,139 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module research/search/doc-utils
|
|
3
|
-
* @description Document utilities: fallback docs, reranking, and formatting.
|
|
4
|
-
*/
|
|
5
|
-
import type { Document } from "./document";
|
|
6
|
-
|
|
7
|
-
export interface R2CredentialsInput {
|
|
8
|
-
accountId: string;
|
|
9
|
-
accessKeyId: string;
|
|
10
|
-
secretAccessKey: string;
|
|
11
|
-
bucket: string;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export function buildFallbackDocs(query: string): Document[] {
|
|
15
|
-
const trimmedQuery = (query || "").trim();
|
|
16
|
-
const searchQuery = trimmedQuery.length > 0 ? trimmedQuery : "web search";
|
|
17
|
-
const fallbackUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}`;
|
|
18
|
-
|
|
19
|
-
return [
|
|
20
|
-
{
|
|
21
|
-
pageContent:
|
|
22
|
-
"No indexed sources were returned by the configured search providers for this query.",
|
|
23
|
-
metadata: {
|
|
24
|
-
title: `Search results for: ${searchQuery}`,
|
|
25
|
-
url: fallbackUrl,
|
|
26
|
-
source: "Google Search",
|
|
27
|
-
},
|
|
28
|
-
},
|
|
29
|
-
];
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function normalizeSourcesOutput(output: unknown, query: string): Document[] {
|
|
33
|
-
if (Array.isArray(output) && output.length > 0) {
|
|
34
|
-
return output as Document[];
|
|
35
|
-
}
|
|
36
|
-
return buildFallbackDocs(query);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Resolves an uploaded fileId to its extracted `{ title, content }` payload.
|
|
41
|
-
* Hosts register a loader (e.g. reading the native R2 binding) so the search
|
|
42
|
-
* pipeline does not depend on filesystem or credential-based access.
|
|
43
|
-
*/
|
|
44
|
-
export type UploadFileLoader = (
|
|
45
|
-
fileId: string,
|
|
46
|
-
) => Promise<{ title: string; content: string } | null>;
|
|
47
|
-
|
|
48
|
-
let uploadFileLoader: UploadFileLoader | null = null;
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Registers the loader used by {@link rerankDocs} to resolve uploaded
|
|
52
|
-
* fileIds to extracted content. The registered loader takes precedence over
|
|
53
|
-
* the S3-credentials fallback.
|
|
54
|
-
*/
|
|
55
|
-
export function registerUploadFileLoader(loader: UploadFileLoader): void {
|
|
56
|
-
uploadFileLoader = loader;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async function downloadExtractedContent(fileId: string, r2Credentials: R2CredentialsInput): Promise<{ title: string; content: string } | null> {
|
|
60
|
-
try {
|
|
61
|
-
const { manageStorage } = await import("manage-storage");
|
|
62
|
-
const config = {
|
|
63
|
-
provider: "cloudflare" as const,
|
|
64
|
-
BUCKET_NAME: r2Credentials.bucket,
|
|
65
|
-
ACCESS_KEY_ID: r2Credentials.accessKeyId,
|
|
66
|
-
SECRET_ACCESS_KEY: r2Credentials.secretAccessKey,
|
|
67
|
-
BUCKET_URL: `https://${r2Credentials.accountId}.r2.cloudflarestorage.com`,
|
|
68
|
-
};
|
|
69
|
-
const extractedKey = `${fileId}-extracted.json`;
|
|
70
|
-
const data = await manageStorage("download", { ...config, key: extractedKey });
|
|
71
|
-
const parsed = JSON.parse(data);
|
|
72
|
-
return { title: parsed.title || "Uploaded Document", content: parsed.content || "" };
|
|
73
|
-
} catch (error) {
|
|
74
|
-
console.error(`[rerankDocs] Failed to download extracted content for fileId ${fileId}:`, error);
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export async function rerankDocs(
|
|
80
|
-
query: string,
|
|
81
|
-
docs: Document[],
|
|
82
|
-
fileIds: string[],
|
|
83
|
-
optimizationMode: "speed" | "balanced" | "quality",
|
|
84
|
-
r2Credentials?: R2CredentialsInput,
|
|
85
|
-
): Promise<Document[]> {
|
|
86
|
-
if (docs.length === 0 && fileIds.length === 0) {
|
|
87
|
-
return docs;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
let filesData: { title: string; content: string }[] = [];
|
|
91
|
-
|
|
92
|
-
if (fileIds.length > 0) {
|
|
93
|
-
const results = await Promise.all(
|
|
94
|
-
fileIds.map(async (fileId) => {
|
|
95
|
-
if (uploadFileLoader) {
|
|
96
|
-
try {
|
|
97
|
-
const loaded = await uploadFileLoader(fileId);
|
|
98
|
-
if (loaded) return loaded;
|
|
99
|
-
} catch (error) {
|
|
100
|
-
console.error(
|
|
101
|
-
`[rerankDocs] Registered upload loader failed for fileId ${fileId}:`,
|
|
102
|
-
error,
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
if (r2Credentials) {
|
|
107
|
-
return downloadExtractedContent(fileId, r2Credentials);
|
|
108
|
-
}
|
|
109
|
-
return null;
|
|
110
|
-
}),
|
|
111
|
-
);
|
|
112
|
-
filesData = results.filter((r) => r !== null);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
if (query.toLocaleLowerCase() === "summarize") {
|
|
116
|
-
return docs.slice(0, 15);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
const docsWithContent = docs.filter(
|
|
120
|
-
(doc) => doc.pageContent && doc.pageContent.length > 0,
|
|
121
|
-
);
|
|
122
|
-
|
|
123
|
-
const fileDocs: Document[] = filesData.map((fileData) => ({
|
|
124
|
-
pageContent: fileData.content,
|
|
125
|
-
metadata: { title: fileData.title, url: "File" },
|
|
126
|
-
}));
|
|
127
|
-
|
|
128
|
-
// Combine file docs with web results, cap at 15
|
|
129
|
-
return [...fileDocs, ...docsWithContent].slice(0, 15);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export function processDocs(docs: Document[]): string {
|
|
133
|
-
return docs
|
|
134
|
-
.map(
|
|
135
|
-
(_, index) =>
|
|
136
|
-
`${index + 1}. ${docs[index].metadata.title} ${docs[index].pageContent}`,
|
|
137
|
-
)
|
|
138
|
-
.join("\n");
|
|
139
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @module research/search/doc-utils
|
|
3
|
+
* @description Document utilities: fallback docs, reranking, and formatting.
|
|
4
|
+
*/
|
|
5
|
+
import type { Document } from "./document";
|
|
6
|
+
|
|
7
|
+
export interface R2CredentialsInput {
|
|
8
|
+
accountId: string;
|
|
9
|
+
accessKeyId: string;
|
|
10
|
+
secretAccessKey: string;
|
|
11
|
+
bucket: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function buildFallbackDocs(query: string): Document[] {
|
|
15
|
+
const trimmedQuery = (query || "").trim();
|
|
16
|
+
const searchQuery = trimmedQuery.length > 0 ? trimmedQuery : "web search";
|
|
17
|
+
const fallbackUrl = `https://www.google.com/search?q=${encodeURIComponent(searchQuery)}`;
|
|
18
|
+
|
|
19
|
+
return [
|
|
20
|
+
{
|
|
21
|
+
pageContent:
|
|
22
|
+
"No indexed sources were returned by the configured search providers for this query.",
|
|
23
|
+
metadata: {
|
|
24
|
+
title: `Search results for: ${searchQuery}`,
|
|
25
|
+
url: fallbackUrl,
|
|
26
|
+
source: "Google Search",
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function normalizeSourcesOutput(output: unknown, query: string): Document[] {
|
|
33
|
+
if (Array.isArray(output) && output.length > 0) {
|
|
34
|
+
return output as Document[];
|
|
35
|
+
}
|
|
36
|
+
return buildFallbackDocs(query);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Resolves an uploaded fileId to its extracted `{ title, content }` payload.
|
|
41
|
+
* Hosts register a loader (e.g. reading the native R2 binding) so the search
|
|
42
|
+
* pipeline does not depend on filesystem or credential-based access.
|
|
43
|
+
*/
|
|
44
|
+
export type UploadFileLoader = (
|
|
45
|
+
fileId: string,
|
|
46
|
+
) => Promise<{ title: string; content: string } | null>;
|
|
47
|
+
|
|
48
|
+
let uploadFileLoader: UploadFileLoader | null = null;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Registers the loader used by {@link rerankDocs} to resolve uploaded
|
|
52
|
+
* fileIds to extracted content. The registered loader takes precedence over
|
|
53
|
+
* the S3-credentials fallback.
|
|
54
|
+
*/
|
|
55
|
+
export function registerUploadFileLoader(loader: UploadFileLoader): void {
|
|
56
|
+
uploadFileLoader = loader;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function downloadExtractedContent(fileId: string, r2Credentials: R2CredentialsInput): Promise<{ title: string; content: string } | null> {
|
|
60
|
+
try {
|
|
61
|
+
const { manageStorage } = await import("manage-storage");
|
|
62
|
+
const config = {
|
|
63
|
+
provider: "cloudflare" as const,
|
|
64
|
+
BUCKET_NAME: r2Credentials.bucket,
|
|
65
|
+
ACCESS_KEY_ID: r2Credentials.accessKeyId,
|
|
66
|
+
SECRET_ACCESS_KEY: r2Credentials.secretAccessKey,
|
|
67
|
+
BUCKET_URL: `https://${r2Credentials.accountId}.r2.cloudflarestorage.com`,
|
|
68
|
+
};
|
|
69
|
+
const extractedKey = `${fileId}-extracted.json`;
|
|
70
|
+
const data = await manageStorage("download", { ...config, key: extractedKey });
|
|
71
|
+
const parsed = JSON.parse(data);
|
|
72
|
+
return { title: parsed.title || "Uploaded Document", content: parsed.content || "" };
|
|
73
|
+
} catch (error) {
|
|
74
|
+
console.error(`[rerankDocs] Failed to download extracted content for fileId ${fileId}:`, error);
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function rerankDocs(
|
|
80
|
+
query: string,
|
|
81
|
+
docs: Document[],
|
|
82
|
+
fileIds: string[],
|
|
83
|
+
optimizationMode: "speed" | "balanced" | "quality",
|
|
84
|
+
r2Credentials?: R2CredentialsInput,
|
|
85
|
+
): Promise<Document[]> {
|
|
86
|
+
if (docs.length === 0 && fileIds.length === 0) {
|
|
87
|
+
return docs;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let filesData: { title: string; content: string }[] = [];
|
|
91
|
+
|
|
92
|
+
if (fileIds.length > 0) {
|
|
93
|
+
const results = await Promise.all(
|
|
94
|
+
fileIds.map(async (fileId) => {
|
|
95
|
+
if (uploadFileLoader) {
|
|
96
|
+
try {
|
|
97
|
+
const loaded = await uploadFileLoader(fileId);
|
|
98
|
+
if (loaded) return loaded;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
console.error(
|
|
101
|
+
`[rerankDocs] Registered upload loader failed for fileId ${fileId}:`,
|
|
102
|
+
error,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (r2Credentials) {
|
|
107
|
+
return downloadExtractedContent(fileId, r2Credentials);
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}),
|
|
111
|
+
);
|
|
112
|
+
filesData = results.filter((r) => r !== null);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (query.toLocaleLowerCase() === "summarize") {
|
|
116
|
+
return docs.slice(0, 15);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const docsWithContent = docs.filter(
|
|
120
|
+
(doc) => doc.pageContent && doc.pageContent.length > 0,
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
const fileDocs: Document[] = filesData.map((fileData) => ({
|
|
124
|
+
pageContent: fileData.content,
|
|
125
|
+
metadata: { title: fileData.title, url: "File" },
|
|
126
|
+
}));
|
|
127
|
+
|
|
128
|
+
// Combine file docs with web results, cap at 15
|
|
129
|
+
return [...fileDocs, ...docsWithContent].slice(0, 15);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function processDocs(docs: Document[]): string {
|
|
133
|
+
return docs
|
|
134
|
+
.map(
|
|
135
|
+
(_, index) =>
|
|
136
|
+
`${index + 1}. ${docs[index].metadata.title} ${docs[index].pageContent}`,
|
|
137
|
+
)
|
|
138
|
+
.join("\n");
|
|
139
|
+
}
|
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module research/search/document
|
|
3
|
-
* @description Minimal document shape shared across the search pipeline.
|
|
4
|
-
* A document is a chunk of page content plus citation metadata (title, url, source, etc.).
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
export interface Document<
|
|
8
|
-
Metadata extends Record<string, any> = Record<string, any>,
|
|
9
|
-
> {
|
|
10
|
-
pageContent: string;
|
|
11
|
-
metadata: Metadata;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Splits text into overlapping chunks on whitespace boundaries.
|
|
16
|
-
* Default chunkSize 1000, chunkOverlap 200.
|
|
17
|
-
*/
|
|
18
|
-
export function splitTextIntoChunks(
|
|
19
|
-
text: string,
|
|
20
|
-
chunkSize = 1000,
|
|
21
|
-
chunkOverlap = 200,
|
|
22
|
-
): string[] {
|
|
23
|
-
const trimmed = (text || "").trim();
|
|
24
|
-
if (trimmed.length <= chunkSize) {
|
|
25
|
-
return trimmed.length > 0 ? [trimmed] : [];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
const chunks: string[] = [];
|
|
29
|
-
let start = 0;
|
|
30
|
-
|
|
31
|
-
while (start < trimmed.length) {
|
|
32
|
-
let end = Math.min(start + chunkSize, trimmed.length);
|
|
33
|
-
|
|
34
|
-
// Break on the last whitespace inside the window so words stay intact
|
|
35
|
-
if (end < trimmed.length) {
|
|
36
|
-
const lastSpace = trimmed.lastIndexOf(" ", end);
|
|
37
|
-
if (lastSpace > start) end = lastSpace;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
chunks.push(trimmed.slice(start, end).trim());
|
|
41
|
-
|
|
42
|
-
if (end >= trimmed.length) break;
|
|
43
|
-
start = Math.max(end - chunkOverlap, start + 1);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
return chunks.filter((chunk) => chunk.length > 0);
|
|
47
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @module research/search/document
|
|
3
|
+
* @description Minimal document shape shared across the search pipeline.
|
|
4
|
+
* A document is a chunk of page content plus citation metadata (title, url, source, etc.).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface Document<
|
|
8
|
+
Metadata extends Record<string, any> = Record<string, any>,
|
|
9
|
+
> {
|
|
10
|
+
pageContent: string;
|
|
11
|
+
metadata: Metadata;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Splits text into overlapping chunks on whitespace boundaries.
|
|
16
|
+
* Default chunkSize 1000, chunkOverlap 200.
|
|
17
|
+
*/
|
|
18
|
+
export function splitTextIntoChunks(
|
|
19
|
+
text: string,
|
|
20
|
+
chunkSize = 1000,
|
|
21
|
+
chunkOverlap = 200,
|
|
22
|
+
): string[] {
|
|
23
|
+
const trimmed = (text || "").trim();
|
|
24
|
+
if (trimmed.length <= chunkSize) {
|
|
25
|
+
return trimmed.length > 0 ? [trimmed] : [];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const chunks: string[] = [];
|
|
29
|
+
let start = 0;
|
|
30
|
+
|
|
31
|
+
while (start < trimmed.length) {
|
|
32
|
+
let end = Math.min(start + chunkSize, trimmed.length);
|
|
33
|
+
|
|
34
|
+
// Break on the last whitespace inside the window so words stay intact
|
|
35
|
+
if (end < trimmed.length) {
|
|
36
|
+
const lastSpace = trimmed.lastIndexOf(" ", end);
|
|
37
|
+
if (lastSpace > start) end = lastSpace;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
chunks.push(trimmed.slice(start, end).trim());
|
|
41
|
+
|
|
42
|
+
if (end >= trimmed.length) break;
|
|
43
|
+
start = Math.max(end - chunkOverlap, start + 1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return chunks.filter((chunk) => chunk.length > 0);
|
|
47
|
+
}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module agent-toolkit/tools/search
|
|
3
|
-
* @description Meta search agent tools for AI-powered web search and research
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
export { default as MetaSearchAgent } from "./metaSearchAgent";
|
|
7
|
-
export type { MetaSearchAgentType, Config, ChatTurnMessage, SearchingEvent, FewShotExample } from "./meta-search-types";
|
|
8
|
-
export { searchHandlers, createSearchHandlers } from "./search-handlers";
|
|
9
|
-
export { default as generateSuggestions } from "./suggestionGeneratorAgent";
|
|
10
|
-
export { groupAndSummarizeDocs } from "./link-summarizer";
|
|
11
|
-
export type { Document } from "./document";
|
|
12
|
-
export { splitTextIntoChunks } from "./document";
|
|
13
|
-
export { buildFallbackDocs, rerankDocs, processDocs, normalizeSourcesOutput, registerUploadFileLoader } from "./doc-utils";
|
|
14
|
-
export type { UploadFileLoader } from "./doc-utils";
|
|
1
|
+
/**
|
|
2
|
+
* @module agent-toolkit/tools/search
|
|
3
|
+
* @description Meta search agent tools for AI-powered web search and research
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { default as MetaSearchAgent } from "./metaSearchAgent";
|
|
7
|
+
export type { MetaSearchAgentType, Config, ChatTurnMessage, SearchingEvent, FewShotExample } from "./meta-search-types";
|
|
8
|
+
export { searchHandlers, createSearchHandlers } from "./search-handlers";
|
|
9
|
+
export { default as generateSuggestions } from "./suggestionGeneratorAgent";
|
|
10
|
+
export { groupAndSummarizeDocs } from "./link-summarizer";
|
|
11
|
+
export type { Document } from "./document";
|
|
12
|
+
export { splitTextIntoChunks } from "./document";
|
|
13
|
+
export { buildFallbackDocs, rerankDocs, processDocs, normalizeSourcesOutput, registerUploadFileLoader } from "./doc-utils";
|
|
14
|
+
export type { UploadFileLoader } from "./doc-utils";
|
|
@@ -1,112 +1,112 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module research/search/link-summarizer
|
|
3
|
-
* @description Groups link documents by URL then summarizes each group with an LLM.
|
|
4
|
-
*/
|
|
5
|
-
import { generateText, type LanguageModel } from "ai";
|
|
6
|
-
import type { Document } from "./document";
|
|
7
|
-
import { buildFallbackDocs } from "./doc-utils";
|
|
8
|
-
|
|
9
|
-
const SUMMARIZER_PROMPT = `You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the
|
|
10
|
-
text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.
|
|
11
|
-
If the query is "summarize", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.
|
|
12
|
-
|
|
13
|
-
- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.
|
|
14
|
-
- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.
|
|
15
|
-
- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.
|
|
16
|
-
|
|
17
|
-
The text will be shared inside the \`text\` XML tag, and the query inside the \`query\` XML tag.
|
|
18
|
-
|
|
19
|
-
<example>
|
|
20
|
-
1. \`<text>
|
|
21
|
-
Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers.
|
|
22
|
-
It was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications
|
|
23
|
-
by using containers.
|
|
24
|
-
</text>
|
|
25
|
-
|
|
26
|
-
<query>
|
|
27
|
-
What is Docker and how does it work?
|
|
28
|
-
</query>
|
|
29
|
-
|
|
30
|
-
Response:
|
|
31
|
-
Docker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application
|
|
32
|
-
deployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in
|
|
33
|
-
any environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed.
|
|
34
|
-
\`
|
|
35
|
-
2. \`<text>
|
|
36
|
-
The theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general
|
|
37
|
-
relativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based
|
|
38
|
-
on the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by
|
|
39
|
-
Albert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity.
|
|
40
|
-
General relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical
|
|
41
|
-
realm, including astronomy.
|
|
42
|
-
</text>
|
|
43
|
-
|
|
44
|
-
<query>
|
|
45
|
-
summarize
|
|
46
|
-
</query>
|
|
47
|
-
|
|
48
|
-
Response:
|
|
49
|
-
The theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special
|
|
50
|
-
relativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its
|
|
51
|
-
relation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in
|
|
52
|
-
1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe.
|
|
53
|
-
\`
|
|
54
|
-
</example>
|
|
55
|
-
|
|
56
|
-
Everything below is the actual data you will be working with. Good luck!
|
|
57
|
-
|
|
58
|
-
<query>
|
|
59
|
-
{question}
|
|
60
|
-
</query>
|
|
61
|
-
|
|
62
|
-
<text>
|
|
63
|
-
{content}
|
|
64
|
-
</text>
|
|
65
|
-
|
|
66
|
-
Make sure to answer the query in the summary.`;
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Groups fetched link documents by URL (max 10 chunks per URL), then
|
|
70
|
-
* summarizes each group with the LLM in parallel.
|
|
71
|
-
*/
|
|
72
|
-
export async function groupAndSummarizeDocs(
|
|
73
|
-
llm: LanguageModel,
|
|
74
|
-
linkDocs: Document[],
|
|
75
|
-
question: string,
|
|
76
|
-
): Promise<Document[]> {
|
|
77
|
-
// Group chunks by URL, capping at 10 chunks each
|
|
78
|
-
const docGroups: Document[] = [];
|
|
79
|
-
|
|
80
|
-
for (const doc of linkDocs) {
|
|
81
|
-
const existing = docGroups.find(
|
|
82
|
-
(d) => d.metadata.url === doc.metadata.url && d.metadata.totalDocs < 10,
|
|
83
|
-
);
|
|
84
|
-
|
|
85
|
-
if (!existing) {
|
|
86
|
-
docGroups.push({ ...doc, metadata: { ...doc.metadata, totalDocs: 1 } });
|
|
87
|
-
} else {
|
|
88
|
-
existing.pageContent += `\n\n${doc.pageContent}`;
|
|
89
|
-
existing.metadata.totalDocs += 1;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Summarize each group in parallel
|
|
94
|
-
const docs: Document[] = [];
|
|
95
|
-
|
|
96
|
-
await Promise.all(
|
|
97
|
-
docGroups.map(async (doc) => {
|
|
98
|
-
const prompt = SUMMARIZER_PROMPT.replace("{question}", question).replace(
|
|
99
|
-
"{content}",
|
|
100
|
-
doc.pageContent,
|
|
101
|
-
);
|
|
102
|
-
const { text } = await generateText({ model: llm, prompt });
|
|
103
|
-
|
|
104
|
-
docs.push({
|
|
105
|
-
pageContent: text,
|
|
106
|
-
metadata: { title: doc.metadata.title, url: doc.metadata.url },
|
|
107
|
-
});
|
|
108
|
-
}),
|
|
109
|
-
);
|
|
110
|
-
|
|
111
|
-
return docs.length > 0 ? docs : buildFallbackDocs(question);
|
|
112
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @module research/search/link-summarizer
|
|
3
|
+
* @description Groups link documents by URL then summarizes each group with an LLM.
|
|
4
|
+
*/
|
|
5
|
+
import { generateText, type LanguageModel } from "ai";
|
|
6
|
+
import type { Document } from "./document";
|
|
7
|
+
import { buildFallbackDocs } from "./doc-utils";
|
|
8
|
+
|
|
9
|
+
const SUMMARIZER_PROMPT = `You are a web search summarizer, tasked with summarizing a piece of text retrieved from a web search. Your job is to summarize the
|
|
10
|
+
text into a detailed, 2-4 paragraph explanation that captures the main ideas and provides a comprehensive answer to the query.
|
|
11
|
+
If the query is "summarize", you should provide a detailed summary of the text. If the query is a specific question, you should answer it in the summary.
|
|
12
|
+
|
|
13
|
+
- **Journalistic tone**: The summary should sound professional and journalistic, not too casual or vague.
|
|
14
|
+
- **Thorough and detailed**: Ensure that every key point from the text is captured and that the summary directly answers the query.
|
|
15
|
+
- **Not too lengthy, but detailed**: The summary should be informative but not excessively long. Focus on providing detailed information in a concise format.
|
|
16
|
+
|
|
17
|
+
The text will be shared inside the \`text\` XML tag, and the query inside the \`query\` XML tag.
|
|
18
|
+
|
|
19
|
+
<example>
|
|
20
|
+
1. \`<text>
|
|
21
|
+
Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers.
|
|
22
|
+
It was first released in 2013 and is developed by Docker, Inc. Docker is designed to make it easier to create, deploy, and run applications
|
|
23
|
+
by using containers.
|
|
24
|
+
</text>
|
|
25
|
+
|
|
26
|
+
<query>
|
|
27
|
+
What is Docker and how does it work?
|
|
28
|
+
</query>
|
|
29
|
+
|
|
30
|
+
Response:
|
|
31
|
+
Docker is a revolutionary platform-as-a-service product developed by Docker, Inc., that uses container technology to make application
|
|
32
|
+
deployment more efficient. It allows developers to package their software with all necessary dependencies, making it easier to run in
|
|
33
|
+
any environment. Released in 2013, Docker has transformed the way applications are built, deployed, and managed.
|
|
34
|
+
\`
|
|
35
|
+
2. \`<text>
|
|
36
|
+
The theory of relativity, or simply relativity, encompasses two interrelated theories of Albert Einstein: special relativity and general
|
|
37
|
+
relativity. However, the word "relativity" is sometimes used in reference to Galilean invariance. The term "theory of relativity" was based
|
|
38
|
+
on the expression "relative theory" used by Max Planck in 1906. The theory of relativity usually encompasses two interrelated theories by
|
|
39
|
+
Albert Einstein: special relativity and general relativity. Special relativity applies to all physical phenomena in the absence of gravity.
|
|
40
|
+
General relativity explains the law of gravitation and its relation to other forces of nature. It applies to the cosmological and astrophysical
|
|
41
|
+
realm, including astronomy.
|
|
42
|
+
</text>
|
|
43
|
+
|
|
44
|
+
<query>
|
|
45
|
+
summarize
|
|
46
|
+
</query>
|
|
47
|
+
|
|
48
|
+
Response:
|
|
49
|
+
The theory of relativity, developed by Albert Einstein, encompasses two main theories: special relativity and general relativity. Special
|
|
50
|
+
relativity applies to all physical phenomena in the absence of gravity, while general relativity explains the law of gravitation and its
|
|
51
|
+
relation to other forces of nature. The theory of relativity is based on the concept of "relative theory," as introduced by Max Planck in
|
|
52
|
+
1906. It is a fundamental theory in physics that has revolutionized our understanding of the universe.
|
|
53
|
+
\`
|
|
54
|
+
</example>
|
|
55
|
+
|
|
56
|
+
Everything below is the actual data you will be working with. Good luck!
|
|
57
|
+
|
|
58
|
+
<query>
|
|
59
|
+
{question}
|
|
60
|
+
</query>
|
|
61
|
+
|
|
62
|
+
<text>
|
|
63
|
+
{content}
|
|
64
|
+
</text>
|
|
65
|
+
|
|
66
|
+
Make sure to answer the query in the summary.`;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Groups fetched link documents by URL (max 10 chunks per URL), then
|
|
70
|
+
* summarizes each group with the LLM in parallel.
|
|
71
|
+
*/
|
|
72
|
+
export async function groupAndSummarizeDocs(
|
|
73
|
+
llm: LanguageModel,
|
|
74
|
+
linkDocs: Document[],
|
|
75
|
+
question: string,
|
|
76
|
+
): Promise<Document[]> {
|
|
77
|
+
// Group chunks by URL, capping at 10 chunks each
|
|
78
|
+
const docGroups: Document[] = [];
|
|
79
|
+
|
|
80
|
+
for (const doc of linkDocs) {
|
|
81
|
+
const existing = docGroups.find(
|
|
82
|
+
(d) => d.metadata.url === doc.metadata.url && d.metadata.totalDocs < 10,
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
if (!existing) {
|
|
86
|
+
docGroups.push({ ...doc, metadata: { ...doc.metadata, totalDocs: 1 } });
|
|
87
|
+
} else {
|
|
88
|
+
existing.pageContent += `\n\n${doc.pageContent}`;
|
|
89
|
+
existing.metadata.totalDocs += 1;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Summarize each group in parallel
|
|
94
|
+
const docs: Document[] = [];
|
|
95
|
+
|
|
96
|
+
await Promise.all(
|
|
97
|
+
docGroups.map(async (doc) => {
|
|
98
|
+
const prompt = SUMMARIZER_PROMPT.replace("{question}", question).replace(
|
|
99
|
+
"{content}",
|
|
100
|
+
doc.pageContent,
|
|
101
|
+
);
|
|
102
|
+
const { text } = await generateText({ model: llm, prompt });
|
|
103
|
+
|
|
104
|
+
docs.push({
|
|
105
|
+
pageContent: text,
|
|
106
|
+
metadata: { title: doc.metadata.title, url: doc.metadata.url },
|
|
107
|
+
});
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
return docs.length > 0 ? docs : buildFallbackDocs(question);
|
|
112
|
+
}
|