@radaros/core 0.3.4 → 0.3.6
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/index.d.ts +1407 -0
- package/dist/index.js +5269 -0
- package/package.json +6 -2
- package/src/a2a/a2a-remote-agent.ts +0 -270
- package/src/a2a/types.ts +0 -142
- package/src/agent/agent.ts +0 -417
- package/src/agent/llm-loop.ts +0 -290
- package/src/agent/run-context.ts +0 -35
- package/src/agent/types.ts +0 -89
- package/src/events/event-bus.ts +0 -45
- package/src/events/types.ts +0 -16
- package/src/guardrails/types.ts +0 -5
- package/src/hooks/types.ts +0 -6
- package/src/index.ts +0 -157
- package/src/knowledge/knowledge-base.ts +0 -146
- package/src/logger/logger.ts +0 -249
- package/src/mcp/mcp-client.ts +0 -264
- package/src/memory/memory.ts +0 -87
- package/src/memory/types.ts +0 -13
- package/src/memory/user-memory.ts +0 -211
- package/src/models/provider.ts +0 -22
- package/src/models/providers/anthropic.ts +0 -360
- package/src/models/providers/google.ts +0 -386
- package/src/models/providers/ollama.ts +0 -211
- package/src/models/providers/openai.ts +0 -345
- package/src/models/providers/vertex.ts +0 -427
- package/src/models/registry.ts +0 -107
- package/src/models/types.ts +0 -124
- package/src/session/session-manager.ts +0 -75
- package/src/session/types.ts +0 -10
- package/src/storage/driver.ts +0 -10
- package/src/storage/in-memory.ts +0 -44
- package/src/storage/mongodb.ts +0 -70
- package/src/storage/postgres.ts +0 -81
- package/src/storage/sqlite.ts +0 -81
- package/src/team/modes.ts +0 -1
- package/src/team/team.ts +0 -323
- package/src/team/types.ts +0 -26
- package/src/toolkits/base.ts +0 -15
- package/src/toolkits/duckduckgo.ts +0 -256
- package/src/toolkits/gmail.ts +0 -226
- package/src/toolkits/hackernews.ts +0 -121
- package/src/toolkits/websearch.ts +0 -158
- package/src/toolkits/whatsapp.ts +0 -209
- package/src/tools/define-tool.ts +0 -22
- package/src/tools/tool-executor.ts +0 -221
- package/src/tools/types.ts +0 -36
- package/src/utils/retry.ts +0 -56
- package/src/vector/base.ts +0 -44
- package/src/vector/embeddings/google.ts +0 -64
- package/src/vector/embeddings/openai.ts +0 -66
- package/src/vector/in-memory.ts +0 -115
- package/src/vector/mongodb.ts +0 -241
- package/src/vector/pgvector.ts +0 -169
- package/src/vector/qdrant.ts +0 -203
- package/src/vector/types.ts +0 -55
- package/src/workflow/step-runner.ts +0 -303
- package/src/workflow/types.ts +0 -55
- package/src/workflow/workflow.ts +0 -68
- package/tsconfig.json +0 -8
package/src/agent/run-context.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { v4 as uuidv4 } from "uuid";
|
|
2
|
-
import type { EventBus } from "../events/event-bus.js";
|
|
3
|
-
|
|
4
|
-
export class RunContext {
|
|
5
|
-
readonly runId: string;
|
|
6
|
-
readonly sessionId: string;
|
|
7
|
-
readonly userId?: string;
|
|
8
|
-
readonly metadata: Record<string, unknown>;
|
|
9
|
-
readonly eventBus: EventBus;
|
|
10
|
-
sessionState: Record<string, unknown>;
|
|
11
|
-
|
|
12
|
-
constructor(opts: {
|
|
13
|
-
sessionId: string;
|
|
14
|
-
userId?: string;
|
|
15
|
-
metadata?: Record<string, unknown>;
|
|
16
|
-
eventBus: EventBus;
|
|
17
|
-
sessionState?: Record<string, unknown>;
|
|
18
|
-
runId?: string;
|
|
19
|
-
}) {
|
|
20
|
-
this.runId = opts.runId ?? uuidv4();
|
|
21
|
-
this.sessionId = opts.sessionId;
|
|
22
|
-
this.userId = opts.userId;
|
|
23
|
-
this.metadata = opts.metadata ?? {};
|
|
24
|
-
this.eventBus = opts.eventBus;
|
|
25
|
-
this.sessionState = opts.sessionState ?? {};
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
getState<T>(key: string): T | undefined {
|
|
29
|
-
return this.sessionState[key] as T | undefined;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
setState(key: string, value: unknown): void {
|
|
33
|
-
this.sessionState[key] = value;
|
|
34
|
-
}
|
|
35
|
-
}
|
package/src/agent/types.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import type { z } from "zod";
|
|
2
|
-
import type { ModelProvider } from "../models/provider.js";
|
|
3
|
-
import type { ToolDef, ToolCallResult } from "../tools/types.js";
|
|
4
|
-
import type { Memory } from "../memory/memory.js";
|
|
5
|
-
import type { StorageDriver } from "../storage/driver.js";
|
|
6
|
-
import type { EventBus } from "../events/event-bus.js";
|
|
7
|
-
import type { TokenUsage, StreamChunk, MessageContent, ReasoningConfig } from "../models/types.js";
|
|
8
|
-
import type { RunContext } from "./run-context.js";
|
|
9
|
-
import type { LogLevel } from "../logger/logger.js";
|
|
10
|
-
import type { UserMemory } from "../memory/user-memory.js";
|
|
11
|
-
import type { RetryConfig } from "../utils/retry.js";
|
|
12
|
-
|
|
13
|
-
export interface AgentConfig {
|
|
14
|
-
name: string;
|
|
15
|
-
model: ModelProvider;
|
|
16
|
-
tools?: ToolDef[];
|
|
17
|
-
instructions?: string | ((ctx: RunContext) => string);
|
|
18
|
-
memory?: Memory;
|
|
19
|
-
storage?: StorageDriver;
|
|
20
|
-
sessionId?: string;
|
|
21
|
-
userId?: string;
|
|
22
|
-
addHistoryToMessages?: boolean;
|
|
23
|
-
numHistoryRuns?: number;
|
|
24
|
-
maxToolRoundtrips?: number;
|
|
25
|
-
temperature?: number;
|
|
26
|
-
structuredOutput?: z.ZodSchema;
|
|
27
|
-
hooks?: AgentHooks;
|
|
28
|
-
guardrails?: {
|
|
29
|
-
input?: InputGuardrail[];
|
|
30
|
-
output?: OutputGuardrail[];
|
|
31
|
-
};
|
|
32
|
-
eventBus?: EventBus;
|
|
33
|
-
/** Logging level. Set to "debug" for tool call details, "info" for summaries, "silent" to disable. Default: "silent". */
|
|
34
|
-
logLevel?: LogLevel;
|
|
35
|
-
/** Enable extended thinking / reasoning for the model. */
|
|
36
|
-
reasoning?: ReasoningConfig;
|
|
37
|
-
/** User-scoped memory for cross-session personalization. */
|
|
38
|
-
userMemory?: UserMemory;
|
|
39
|
-
/** Retry configuration for transient LLM API failures (429, 5xx, network errors). */
|
|
40
|
-
retry?: Partial<RetryConfig>;
|
|
41
|
-
/** Maximum context window tokens. History is auto-trimmed to fit. */
|
|
42
|
-
maxContextTokens?: number;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface RunOpts {
|
|
46
|
-
sessionId?: string;
|
|
47
|
-
userId?: string;
|
|
48
|
-
metadata?: Record<string, unknown>;
|
|
49
|
-
/** Per-request API key override passed to the model provider. */
|
|
50
|
-
apiKey?: string;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface RunOutput {
|
|
54
|
-
text: string;
|
|
55
|
-
toolCalls: ToolCallResult[];
|
|
56
|
-
usage: TokenUsage;
|
|
57
|
-
/** Parsed structured output if structuredOutput schema is set. */
|
|
58
|
-
structured?: unknown;
|
|
59
|
-
/** Model's internal reasoning / thinking content (when reasoning is enabled). */
|
|
60
|
-
thinking?: string;
|
|
61
|
-
durationMs?: number;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export interface AgentHooks {
|
|
65
|
-
beforeRun?: (ctx: RunContext) => Promise<void>;
|
|
66
|
-
afterRun?: (ctx: RunContext, output: RunOutput) => Promise<void>;
|
|
67
|
-
onToolCall?: (
|
|
68
|
-
ctx: RunContext,
|
|
69
|
-
toolName: string,
|
|
70
|
-
args: unknown
|
|
71
|
-
) => Promise<void>;
|
|
72
|
-
onError?: (ctx: RunContext, error: Error) => Promise<void>;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export type GuardrailResult =
|
|
76
|
-
| { pass: true }
|
|
77
|
-
| { pass: false; reason: string };
|
|
78
|
-
|
|
79
|
-
export interface InputGuardrail {
|
|
80
|
-
name: string;
|
|
81
|
-
validate: (input: MessageContent, ctx: RunContext) => Promise<GuardrailResult>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export interface OutputGuardrail {
|
|
85
|
-
name: string;
|
|
86
|
-
validate: (output: RunOutput, ctx: RunContext) => Promise<GuardrailResult>;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export type { StreamChunk };
|
package/src/events/event-bus.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from "node:events";
|
|
2
|
-
import type { AgentEventMap } from "./types.js";
|
|
3
|
-
|
|
4
|
-
type EventKey = keyof AgentEventMap;
|
|
5
|
-
|
|
6
|
-
export class EventBus {
|
|
7
|
-
private emitter = new EventEmitter();
|
|
8
|
-
|
|
9
|
-
constructor() {
|
|
10
|
-
this.emitter.setMaxListeners(100);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
on<K extends EventKey>(
|
|
14
|
-
event: K,
|
|
15
|
-
handler: (data: AgentEventMap[K]) => void
|
|
16
|
-
): this {
|
|
17
|
-
this.emitter.on(event, handler as (...args: unknown[]) => void);
|
|
18
|
-
return this;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
once<K extends EventKey>(
|
|
22
|
-
event: K,
|
|
23
|
-
handler: (data: AgentEventMap[K]) => void
|
|
24
|
-
): this {
|
|
25
|
-
this.emitter.once(event, handler as (...args: unknown[]) => void);
|
|
26
|
-
return this;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
off<K extends EventKey>(
|
|
30
|
-
event: K,
|
|
31
|
-
handler: (data: AgentEventMap[K]) => void
|
|
32
|
-
): this {
|
|
33
|
-
this.emitter.off(event, handler as (...args: unknown[]) => void);
|
|
34
|
-
return this;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
emit<K extends EventKey>(event: K, data: AgentEventMap[K]): boolean {
|
|
38
|
-
return this.emitter.emit(event, data);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
removeAllListeners(event?: EventKey): this {
|
|
42
|
-
this.emitter.removeAllListeners(event);
|
|
43
|
-
return this;
|
|
44
|
-
}
|
|
45
|
-
}
|
package/src/events/types.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { RunOutput } from "../agent/types.js";
|
|
2
|
-
|
|
3
|
-
export type AgentEventMap = {
|
|
4
|
-
"run.start": { runId: string; agentName: string; input: string };
|
|
5
|
-
"run.complete": { runId: string; output: RunOutput };
|
|
6
|
-
"run.error": { runId: string; error: Error };
|
|
7
|
-
"run.stream.chunk": { runId: string; chunk: string };
|
|
8
|
-
"tool.call": { runId: string; toolName: string; args: unknown };
|
|
9
|
-
"tool.result": { runId: string; toolName: string; result: unknown };
|
|
10
|
-
"team.delegate": { runId: string; memberId: string; task: string };
|
|
11
|
-
"workflow.step": {
|
|
12
|
-
runId: string;
|
|
13
|
-
stepName: string;
|
|
14
|
-
status: "start" | "done" | "error";
|
|
15
|
-
};
|
|
16
|
-
};
|
package/src/guardrails/types.ts
DELETED
package/src/hooks/types.ts
DELETED
package/src/index.ts
DELETED
|
@@ -1,157 +0,0 @@
|
|
|
1
|
-
// Agent
|
|
2
|
-
export { Agent } from "./agent/agent.js";
|
|
3
|
-
export { RunContext } from "./agent/run-context.js";
|
|
4
|
-
export { LLMLoop } from "./agent/llm-loop.js";
|
|
5
|
-
export type {
|
|
6
|
-
AgentConfig,
|
|
7
|
-
RunOpts,
|
|
8
|
-
RunOutput,
|
|
9
|
-
AgentHooks,
|
|
10
|
-
InputGuardrail,
|
|
11
|
-
OutputGuardrail,
|
|
12
|
-
GuardrailResult,
|
|
13
|
-
} from "./agent/types.js";
|
|
14
|
-
|
|
15
|
-
// Team
|
|
16
|
-
export { Team } from "./team/team.js";
|
|
17
|
-
export { TeamMode } from "./team/types.js";
|
|
18
|
-
export type { TeamConfig } from "./team/types.js";
|
|
19
|
-
|
|
20
|
-
// Workflow
|
|
21
|
-
export { Workflow } from "./workflow/workflow.js";
|
|
22
|
-
export type {
|
|
23
|
-
WorkflowConfig,
|
|
24
|
-
WorkflowResult,
|
|
25
|
-
StepDef,
|
|
26
|
-
StepResult,
|
|
27
|
-
AgentStep,
|
|
28
|
-
FunctionStep,
|
|
29
|
-
ConditionStep,
|
|
30
|
-
ParallelStep,
|
|
31
|
-
} from "./workflow/types.js";
|
|
32
|
-
|
|
33
|
-
// Models
|
|
34
|
-
export type { ModelProvider } from "./models/provider.js";
|
|
35
|
-
export type {
|
|
36
|
-
ChatMessage,
|
|
37
|
-
MessageRole,
|
|
38
|
-
MessageContent,
|
|
39
|
-
ContentPart,
|
|
40
|
-
TextPart,
|
|
41
|
-
ImagePart,
|
|
42
|
-
AudioPart,
|
|
43
|
-
FilePart,
|
|
44
|
-
ToolCall,
|
|
45
|
-
ToolDefinition,
|
|
46
|
-
TokenUsage,
|
|
47
|
-
ModelResponse,
|
|
48
|
-
StreamChunk,
|
|
49
|
-
ModelConfig,
|
|
50
|
-
ReasoningConfig,
|
|
51
|
-
} from "./models/types.js";
|
|
52
|
-
export { getTextContent, isMultiModal } from "./models/types.js";
|
|
53
|
-
export { ModelRegistry, registry, openai, anthropic, google, ollama, vertex } from "./models/registry.js";
|
|
54
|
-
export { OpenAIProvider } from "./models/providers/openai.js";
|
|
55
|
-
export { AnthropicProvider } from "./models/providers/anthropic.js";
|
|
56
|
-
export { GoogleProvider } from "./models/providers/google.js";
|
|
57
|
-
export { OllamaProvider } from "./models/providers/ollama.js";
|
|
58
|
-
export { VertexAIProvider } from "./models/providers/vertex.js";
|
|
59
|
-
export type { VertexAIConfig } from "./models/providers/vertex.js";
|
|
60
|
-
|
|
61
|
-
// Tools
|
|
62
|
-
export { defineTool } from "./tools/define-tool.js";
|
|
63
|
-
export { ToolExecutor } from "./tools/tool-executor.js";
|
|
64
|
-
export type { ToolDef, ToolResult, ToolCallResult, Artifact, ToolCacheConfig } from "./tools/types.js";
|
|
65
|
-
|
|
66
|
-
// Storage
|
|
67
|
-
export type { StorageDriver } from "./storage/driver.js";
|
|
68
|
-
export { InMemoryStorage } from "./storage/in-memory.js";
|
|
69
|
-
export { SqliteStorage } from "./storage/sqlite.js";
|
|
70
|
-
export { PostgresStorage } from "./storage/postgres.js";
|
|
71
|
-
export { MongoDBStorage } from "./storage/mongodb.js";
|
|
72
|
-
|
|
73
|
-
// Vector Stores
|
|
74
|
-
export type {
|
|
75
|
-
VectorStore,
|
|
76
|
-
VectorDocument,
|
|
77
|
-
VectorSearchResult,
|
|
78
|
-
VectorSearchOptions,
|
|
79
|
-
EmbeddingProvider,
|
|
80
|
-
} from "./vector/types.js";
|
|
81
|
-
export { BaseVectorStore } from "./vector/base.js";
|
|
82
|
-
export { InMemoryVectorStore } from "./vector/in-memory.js";
|
|
83
|
-
export { PgVectorStore } from "./vector/pgvector.js";
|
|
84
|
-
export type { PgVectorConfig } from "./vector/pgvector.js";
|
|
85
|
-
export { QdrantVectorStore } from "./vector/qdrant.js";
|
|
86
|
-
export type { QdrantConfig } from "./vector/qdrant.js";
|
|
87
|
-
export { MongoDBVectorStore } from "./vector/mongodb.js";
|
|
88
|
-
export type { MongoDBVectorConfig } from "./vector/mongodb.js";
|
|
89
|
-
|
|
90
|
-
// Embedding Providers
|
|
91
|
-
export { OpenAIEmbedding } from "./vector/embeddings/openai.js";
|
|
92
|
-
export type { OpenAIEmbeddingConfig } from "./vector/embeddings/openai.js";
|
|
93
|
-
export { GoogleEmbedding } from "./vector/embeddings/google.js";
|
|
94
|
-
export type { GoogleEmbeddingConfig } from "./vector/embeddings/google.js";
|
|
95
|
-
|
|
96
|
-
// Knowledge Base
|
|
97
|
-
export { KnowledgeBase } from "./knowledge/knowledge-base.js";
|
|
98
|
-
export type { KnowledgeBaseConfig, KnowledgeBaseToolConfig } from "./knowledge/knowledge-base.js";
|
|
99
|
-
|
|
100
|
-
// Session
|
|
101
|
-
export { SessionManager } from "./session/session-manager.js";
|
|
102
|
-
export type { Session } from "./session/types.js";
|
|
103
|
-
|
|
104
|
-
// Memory
|
|
105
|
-
export { Memory } from "./memory/memory.js";
|
|
106
|
-
export type { MemoryConfig, MemoryEntry } from "./memory/types.js";
|
|
107
|
-
export { UserMemory } from "./memory/user-memory.js";
|
|
108
|
-
export type { UserMemoryConfig, UserFact } from "./memory/user-memory.js";
|
|
109
|
-
|
|
110
|
-
// Events
|
|
111
|
-
export { EventBus } from "./events/event-bus.js";
|
|
112
|
-
export type { AgentEventMap } from "./events/types.js";
|
|
113
|
-
|
|
114
|
-
// Logger
|
|
115
|
-
export { Logger } from "./logger/logger.js";
|
|
116
|
-
export type { LogLevel, LoggerConfig } from "./logger/logger.js";
|
|
117
|
-
|
|
118
|
-
// Utils
|
|
119
|
-
export { withRetry } from "./utils/retry.js";
|
|
120
|
-
export type { RetryConfig } from "./utils/retry.js";
|
|
121
|
-
|
|
122
|
-
// MCP
|
|
123
|
-
export { MCPToolProvider } from "./mcp/mcp-client.js";
|
|
124
|
-
export type { MCPToolProviderConfig } from "./mcp/mcp-client.js";
|
|
125
|
-
|
|
126
|
-
// A2A
|
|
127
|
-
export { A2ARemoteAgent } from "./a2a/a2a-remote-agent.js";
|
|
128
|
-
export type { A2ARemoteAgentConfig } from "./a2a/a2a-remote-agent.js";
|
|
129
|
-
export type {
|
|
130
|
-
A2AAgentCard,
|
|
131
|
-
A2ASkill,
|
|
132
|
-
A2ATask,
|
|
133
|
-
A2ATaskState,
|
|
134
|
-
A2AMessage,
|
|
135
|
-
A2APart,
|
|
136
|
-
A2ATextPart,
|
|
137
|
-
A2AFilePart,
|
|
138
|
-
A2ADataPart,
|
|
139
|
-
A2AArtifact,
|
|
140
|
-
A2AJsonRpcRequest,
|
|
141
|
-
A2AJsonRpcResponse,
|
|
142
|
-
A2ASendParams,
|
|
143
|
-
A2ATaskQueryParams,
|
|
144
|
-
} from "./a2a/types.js";
|
|
145
|
-
|
|
146
|
-
// Toolkits
|
|
147
|
-
export { Toolkit } from "./toolkits/base.js";
|
|
148
|
-
export { WebSearchToolkit } from "./toolkits/websearch.js";
|
|
149
|
-
export type { WebSearchConfig } from "./toolkits/websearch.js";
|
|
150
|
-
export { GmailToolkit } from "./toolkits/gmail.js";
|
|
151
|
-
export type { GmailConfig } from "./toolkits/gmail.js";
|
|
152
|
-
export { WhatsAppToolkit } from "./toolkits/whatsapp.js";
|
|
153
|
-
export type { WhatsAppConfig } from "./toolkits/whatsapp.js";
|
|
154
|
-
export { HackerNewsToolkit } from "./toolkits/hackernews.js";
|
|
155
|
-
export type { HackerNewsConfig } from "./toolkits/hackernews.js";
|
|
156
|
-
export { DuckDuckGoToolkit } from "./toolkits/duckduckgo.js";
|
|
157
|
-
export type { DuckDuckGoConfig } from "./toolkits/duckduckgo.js";
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
import type { ToolDef } from "../tools/types.js";
|
|
3
|
-
import type {
|
|
4
|
-
VectorStore,
|
|
5
|
-
VectorDocument,
|
|
6
|
-
VectorSearchResult,
|
|
7
|
-
VectorSearchOptions,
|
|
8
|
-
} from "../vector/types.js";
|
|
9
|
-
|
|
10
|
-
export interface KnowledgeBaseConfig {
|
|
11
|
-
/** Display name used in tool description auto-generation. */
|
|
12
|
-
name: string;
|
|
13
|
-
/** The underlying vector store (any backend). */
|
|
14
|
-
vectorStore: VectorStore;
|
|
15
|
-
/** Collection/index name inside the vector store. */
|
|
16
|
-
collection?: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export interface KnowledgeBaseToolConfig {
|
|
20
|
-
/** Tool name exposed to the LLM. Defaults to `search_<collection>`. */
|
|
21
|
-
toolName?: string;
|
|
22
|
-
/** Custom tool description. A sensible default is generated from the KB name. */
|
|
23
|
-
description?: string;
|
|
24
|
-
/** Number of results to return per search. Default 5. */
|
|
25
|
-
topK?: number;
|
|
26
|
-
/** Minimum similarity score to include. */
|
|
27
|
-
minScore?: number;
|
|
28
|
-
/** Metadata filter applied to every search. */
|
|
29
|
-
filter?: Record<string, unknown>;
|
|
30
|
-
/** Custom formatter for search results. Defaults to numbered list with scores. */
|
|
31
|
-
formatResults?: (results: VectorSearchResult[]) => string;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export class KnowledgeBase {
|
|
35
|
-
readonly name: string;
|
|
36
|
-
readonly collection: string;
|
|
37
|
-
private store: VectorStore;
|
|
38
|
-
private initialized = false;
|
|
39
|
-
|
|
40
|
-
constructor(config: KnowledgeBaseConfig) {
|
|
41
|
-
this.name = config.name;
|
|
42
|
-
this.store = config.vectorStore;
|
|
43
|
-
this.collection = config.collection ?? config.name.toLowerCase().replace(/\s+/g, "_");
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async initialize(): Promise<void> {
|
|
47
|
-
if (this.initialized) return;
|
|
48
|
-
await this.store.initialize();
|
|
49
|
-
this.initialized = true;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
async add(doc: VectorDocument): Promise<void> {
|
|
53
|
-
await this.ensureInit();
|
|
54
|
-
await this.store.upsert(this.collection, doc);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async addDocuments(docs: VectorDocument[]): Promise<void> {
|
|
58
|
-
await this.ensureInit();
|
|
59
|
-
await this.store.upsertBatch(this.collection, docs);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async search(
|
|
63
|
-
query: string,
|
|
64
|
-
options?: VectorSearchOptions
|
|
65
|
-
): Promise<VectorSearchResult[]> {
|
|
66
|
-
await this.ensureInit();
|
|
67
|
-
return this.store.search(this.collection, query, options);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async get(id: string): Promise<VectorDocument | null> {
|
|
71
|
-
await this.ensureInit();
|
|
72
|
-
return this.store.get(this.collection, id);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async delete(id: string): Promise<void> {
|
|
76
|
-
await this.ensureInit();
|
|
77
|
-
await this.store.delete(this.collection, id);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async clear(): Promise<void> {
|
|
81
|
-
await this.store.dropCollection(this.collection);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async close(): Promise<void> {
|
|
85
|
-
await this.store.close();
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Returns a ToolDef that an Agent can use to search this knowledge base.
|
|
90
|
-
* Plug the result directly into `Agent({ tools: [kb.asTool()] })`.
|
|
91
|
-
*/
|
|
92
|
-
asTool(config: KnowledgeBaseToolConfig = {}): ToolDef {
|
|
93
|
-
const topK = config.topK ?? 5;
|
|
94
|
-
const minScore = config.minScore;
|
|
95
|
-
const filter = config.filter;
|
|
96
|
-
const toolName =
|
|
97
|
-
config.toolName ?? `search_${this.collection}`;
|
|
98
|
-
const description =
|
|
99
|
-
config.description ??
|
|
100
|
-
`Search the "${this.name}" knowledge base for relevant information. Use this before answering questions related to ${this.name}.`;
|
|
101
|
-
|
|
102
|
-
const formatResults =
|
|
103
|
-
config.formatResults ?? defaultFormatResults;
|
|
104
|
-
|
|
105
|
-
const kb = this;
|
|
106
|
-
|
|
107
|
-
return {
|
|
108
|
-
name: toolName,
|
|
109
|
-
description,
|
|
110
|
-
parameters: z.object({
|
|
111
|
-
query: z.string().describe("Search query to find relevant documents"),
|
|
112
|
-
}),
|
|
113
|
-
execute: async (args: Record<string, unknown>) => {
|
|
114
|
-
const results = await kb.search(args.query as string, {
|
|
115
|
-
topK,
|
|
116
|
-
minScore,
|
|
117
|
-
filter,
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
if (results.length === 0) {
|
|
121
|
-
return "No relevant documents found in the knowledge base.";
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
return formatResults(results);
|
|
125
|
-
},
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
private async ensureInit(): Promise<void> {
|
|
130
|
-
if (!this.initialized) await this.initialize();
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function defaultFormatResults(results: VectorSearchResult[]): string {
|
|
135
|
-
const lines = results.map((r, i) => {
|
|
136
|
-
const meta = r.metadata
|
|
137
|
-
? Object.entries(r.metadata)
|
|
138
|
-
.filter(([, v]) => v !== undefined)
|
|
139
|
-
.map(([k, v]) => `${k}: ${v}`)
|
|
140
|
-
.join(", ")
|
|
141
|
-
: "";
|
|
142
|
-
const metaStr = meta ? ` | ${meta}` : "";
|
|
143
|
-
return `[${i + 1}] (score: ${r.score.toFixed(3)}${metaStr})\n${r.content}`;
|
|
144
|
-
});
|
|
145
|
-
return `Found ${results.length} relevant document(s):\n\n${lines.join("\n\n")}`;
|
|
146
|
-
}
|