@lssm/lib.knowledge 0.0.0-canary-20251206160926
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/README.md +65 -0
- package/dist/access/guard.d.ts +20 -0
- package/dist/access/guard.js +1 -0
- package/dist/access/index.d.ts +2 -0
- package/dist/access/index.js +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -0
- package/dist/ingestion/document-processor.d.ts +24 -0
- package/dist/ingestion/document-processor.js +1 -0
- package/dist/ingestion/embedding-service.d.ts +12 -0
- package/dist/ingestion/embedding-service.js +1 -0
- package/dist/ingestion/gmail-adapter.d.ts +18 -0
- package/dist/ingestion/gmail-adapter.js +6 -0
- package/dist/ingestion/index.d.ts +6 -0
- package/dist/ingestion/index.js +1 -0
- package/dist/ingestion/storage-adapter.d.ts +15 -0
- package/dist/ingestion/storage-adapter.js +1 -0
- package/dist/ingestion/vector-indexer.d.ts +17 -0
- package/dist/ingestion/vector-indexer.js +1 -0
- package/dist/query/index.d.ts +2 -0
- package/dist/query/index.js +1 -0
- package/dist/query/service.d.ts +27 -0
- package/dist/query/service.js +3 -0
- package/dist/retriever/index.d.ts +4 -0
- package/dist/retriever/index.js +1 -0
- package/dist/retriever/interface.d.ts +55 -0
- package/dist/retriever/interface.js +0 -0
- package/dist/retriever/static-retriever.d.ts +34 -0
- package/dist/retriever/static-retriever.js +2 -0
- package/dist/retriever/vector-retriever.d.ts +42 -0
- package/dist/retriever/vector-retriever.js +1 -0
- package/dist/types.d.ts +55 -0
- package/dist/types.js +0 -0
- package/package.json +55 -0
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @lssm/lib.knowledge
|
|
2
|
+
|
|
3
|
+
Knowledge retrieval and management library for ContractSpec. Provides the runtime implementation for knowledge spaces, including:
|
|
4
|
+
|
|
5
|
+
- **Retriever Interface**: Unified interface for knowledge retrieval (vector, static, hybrid)
|
|
6
|
+
- **Query Service**: RAG-powered question answering over knowledge spaces
|
|
7
|
+
- **Ingestion Pipeline**: Document processing, embedding, and vector indexing
|
|
8
|
+
- **Access Guard**: Policy-based access control for knowledge spaces
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
bun add @lssm/lib.knowledge
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
### Basic Retriever
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { createVectorRetriever } from '@lssm/lib.knowledge/retriever';
|
|
22
|
+
|
|
23
|
+
const retriever = createVectorRetriever({
|
|
24
|
+
embeddings: embeddingProvider,
|
|
25
|
+
vectorStore: vectorStoreProvider,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const results = await retriever.retrieve('How do I reset my password?', {
|
|
29
|
+
spaceKey: 'support-faq',
|
|
30
|
+
topK: 5,
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Static Knowledge
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { createStaticRetriever } from '@lssm/lib.knowledge/retriever';
|
|
38
|
+
|
|
39
|
+
const retriever = createStaticRetriever({
|
|
40
|
+
'product-canon': 'Product specifications and documentation...',
|
|
41
|
+
'support-faq': 'Frequently asked questions...',
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const content = await retriever.getStatic('product-canon');
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Architecture
|
|
48
|
+
|
|
49
|
+
This package bridges `@lssm/lib.contracts` (specs/types) with `@lssm/lib.ai-agent` (AI SDK integration):
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
@lssm/lib.contracts (specs/types)
|
|
53
|
+
↓
|
|
54
|
+
@lssm/lib.knowledge (runtime)
|
|
55
|
+
↓
|
|
56
|
+
@lssm/lib.ai-agent (AI SDK)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { KnowledgeAccessContext, KnowledgeAccessResult } from "../types.js";
|
|
2
|
+
import { ResolvedAppConfig, ResolvedKnowledge } from "@lssm/lib.contracts/app-config";
|
|
3
|
+
import { KnowledgeCategory } from "@lssm/lib.contracts/knowledge";
|
|
4
|
+
|
|
5
|
+
//#region src/access/guard.d.ts
|
|
6
|
+
interface KnowledgeAccessGuardOptions {
|
|
7
|
+
disallowWriteCategories?: KnowledgeCategory[];
|
|
8
|
+
requireWorkflowBinding?: boolean;
|
|
9
|
+
requireAgentBinding?: boolean;
|
|
10
|
+
}
|
|
11
|
+
declare class KnowledgeAccessGuard {
|
|
12
|
+
private readonly disallowedWrite;
|
|
13
|
+
private readonly requireWorkflowBinding;
|
|
14
|
+
private readonly requireAgentBinding;
|
|
15
|
+
constructor(options?: KnowledgeAccessGuardOptions);
|
|
16
|
+
checkAccess(spaceBinding: ResolvedKnowledge, context: KnowledgeAccessContext, appConfig: ResolvedAppConfig): KnowledgeAccessResult;
|
|
17
|
+
private isSpaceBound;
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { KnowledgeAccessGuard, KnowledgeAccessGuardOptions };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=[`external`,`ephemeral`];var t=class{disallowedWrite;requireWorkflowBinding;requireAgentBinding;constructor(t={}){this.disallowedWrite=new Set(t.disallowWriteCategories??e),this.requireWorkflowBinding=t.requireWorkflowBinding??!0,this.requireAgentBinding=t.requireAgentBinding??!1}checkAccess(e,t,n){let{binding:r,space:i}=e;if(r.required!==!1&&!this.isSpaceBound(e,n))return{allowed:!1,reason:`Knowledge space "${i.meta.key}" is not bound in the resolved app config.`};if(t.operation===`write`&&this.disallowedWrite.has(i.meta.category))return{allowed:!1,reason:`Knowledge space "${i.meta.key}" is category "${i.meta.category}" and is read-only.`};if(this.requireWorkflowBinding&&t.workflowName){let e=r.scope?.workflows;if(e&&!e.includes(t.workflowName))return{allowed:!1,reason:`Workflow "${t.workflowName}" is not authorized to access knowledge space "${i.meta.key}".`}}if(this.requireAgentBinding&&t.agentName){let e=r.scope?.agents;if(e&&!e.includes(t.agentName))return{allowed:!1,reason:`Agent "${t.agentName}" is not authorized to access knowledge space "${i.meta.key}".`}}return i.meta.category===`ephemeral`?{allowed:!0,severity:`warning`,reason:`Knowledge space "${i.meta.key}" is ephemeral; results may be transient.`}:{allowed:!0}}isSpaceBound(e,t){return t.knowledge.some(t=>t.space.meta.key===e.space.meta.key&&(e.space.meta.version==null||t.space.meta.version===e.space.meta.version))}};export{t as KnowledgeAccessGuard};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{KnowledgeAccessGuard as e}from"./guard.js";export{e as KnowledgeAccessGuard};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { KnowledgeAccessContext, KnowledgeAccessResult, RetrievalOptions, RetrievalResult } from "./types.js";
|
|
2
|
+
import { KnowledgeAccessGuard, KnowledgeAccessGuardOptions } from "./access/guard.js";
|
|
3
|
+
import { KnowledgeRetriever, RetrieverConfig } from "./retriever/interface.js";
|
|
4
|
+
import { StaticRetriever, StaticRetrieverConfig, createStaticRetriever } from "./retriever/static-retriever.js";
|
|
5
|
+
import { VectorRetriever, VectorRetrieverConfig, createVectorRetriever } from "./retriever/vector-retriever.js";
|
|
6
|
+
import { KnowledgeAnswer, KnowledgeQueryConfig, KnowledgeQueryService } from "./query/service.js";
|
|
7
|
+
import { DocumentFragment, DocumentProcessor, RawDocument } from "./ingestion/document-processor.js";
|
|
8
|
+
import { EmbeddingService } from "./ingestion/embedding-service.js";
|
|
9
|
+
import { VectorIndexConfig, VectorIndexer } from "./ingestion/vector-indexer.js";
|
|
10
|
+
import { GmailIngestionAdapter } from "./ingestion/gmail-adapter.js";
|
|
11
|
+
import { StorageIngestionAdapter } from "./ingestion/storage-adapter.js";
|
|
12
|
+
export { DocumentFragment, DocumentProcessor, EmbeddingService, GmailIngestionAdapter, KnowledgeAccessContext, KnowledgeAccessGuard, KnowledgeAccessGuardOptions, KnowledgeAccessResult, KnowledgeAnswer, KnowledgeQueryConfig, KnowledgeQueryService, KnowledgeRetriever, RawDocument, RetrievalOptions, RetrievalResult, RetrieverConfig, StaticRetriever, StaticRetrieverConfig, StorageIngestionAdapter, VectorIndexConfig, VectorIndexer, VectorRetriever, VectorRetrieverConfig, createStaticRetriever, createVectorRetriever };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{StaticRetriever as e,createStaticRetriever as t}from"./retriever/static-retriever.js";import{VectorRetriever as n,createVectorRetriever as r}from"./retriever/vector-retriever.js";import{KnowledgeQueryService as i}from"./query/service.js";import{DocumentProcessor as a}from"./ingestion/document-processor.js";import{EmbeddingService as o}from"./ingestion/embedding-service.js";import{VectorIndexer as s}from"./ingestion/vector-indexer.js";import{GmailIngestionAdapter as c}from"./ingestion/gmail-adapter.js";import{StorageIngestionAdapter as l}from"./ingestion/storage-adapter.js";import"./ingestion/index.js";import{KnowledgeAccessGuard as u}from"./access/guard.js";export{a as DocumentProcessor,o as EmbeddingService,c as GmailIngestionAdapter,u as KnowledgeAccessGuard,i as KnowledgeQueryService,e as StaticRetriever,l as StorageIngestionAdapter,s as VectorIndexer,n as VectorRetriever,t as createStaticRetriever,r as createVectorRetriever};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/ingestion/document-processor.d.ts
|
|
2
|
+
interface RawDocument {
|
|
3
|
+
id: string;
|
|
4
|
+
mimeType: string;
|
|
5
|
+
data: Uint8Array;
|
|
6
|
+
metadata?: Record<string, string>;
|
|
7
|
+
}
|
|
8
|
+
interface DocumentFragment {
|
|
9
|
+
id: string;
|
|
10
|
+
documentId: string;
|
|
11
|
+
text: string;
|
|
12
|
+
metadata?: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
type Extractor = (input: RawDocument) => Promise<DocumentFragment[]>;
|
|
15
|
+
declare class DocumentProcessor {
|
|
16
|
+
private readonly extractors;
|
|
17
|
+
constructor();
|
|
18
|
+
registerExtractor(mimeType: string, extractor: Extractor): void;
|
|
19
|
+
process(document: RawDocument): Promise<DocumentFragment[]>;
|
|
20
|
+
private extractText;
|
|
21
|
+
private extractJson;
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
24
|
+
export { DocumentFragment, DocumentProcessor, RawDocument };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Buffer as e}from"node:buffer";var t=class{extractors=new Map;constructor(){this.registerExtractor(`text/plain`,this.extractText.bind(this)),this.registerExtractor(`application/json`,this.extractJson.bind(this))}registerExtractor(e,t){this.extractors.set(e.toLowerCase(),t)}async process(e){let t=this.extractors.get(e.mimeType.toLowerCase())??this.extractors.get(`*/*`);if(!t)throw Error(`No extractor registered for mime type ${e.mimeType}`);let n=await t(e);return n.length===0?[{id:`${e.id}:0`,documentId:e.id,text:``,metadata:e.metadata}]:n}async extractText(t){let n=e.from(t.data).toString(`utf-8`);return[{id:`${t.id}:0`,documentId:t.id,text:n,metadata:t.metadata}]}async extractJson(t){let n=e.from(t.data).toString(`utf-8`);try{let e=JSON.parse(n);return[{id:`${t.id}:0`,documentId:t.id,text:JSON.stringify(e,null,2),metadata:{...t.metadata,contentType:`application/json`}}]}catch{return this.extractText(t)}}};export{t as DocumentProcessor};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { DocumentFragment } from "./document-processor.js";
|
|
2
|
+
import { EmbeddingProvider, EmbeddingResult } from "@lssm/lib.contracts/integrations/providers";
|
|
3
|
+
|
|
4
|
+
//#region src/ingestion/embedding-service.d.ts
|
|
5
|
+
declare class EmbeddingService {
|
|
6
|
+
private readonly provider;
|
|
7
|
+
private readonly batchSize;
|
|
8
|
+
constructor(provider: EmbeddingProvider, batchSize?: number);
|
|
9
|
+
embedFragments(fragments: DocumentFragment[]): Promise<EmbeddingResult[]>;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { EmbeddingService };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class{provider;batchSize;constructor(e,t=16){this.provider=e,this.batchSize=t}async embedFragments(e){let t=[];for(let n=0;n<e.length;n+=this.batchSize){let r=e.slice(n,n+this.batchSize).map(e=>({id:e.id,text:e.text,metadata:e.metadata})),i=await this.provider.embedDocuments(r);t.push(...i)}return t}};export{e as EmbeddingService};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { DocumentProcessor } from "./document-processor.js";
|
|
2
|
+
import { EmbeddingService } from "./embedding-service.js";
|
|
3
|
+
import { VectorIndexer } from "./vector-indexer.js";
|
|
4
|
+
import { EmailInboundProvider, EmailThread } from "@lssm/lib.contracts/integrations/providers";
|
|
5
|
+
|
|
6
|
+
//#region src/ingestion/gmail-adapter.d.ts
|
|
7
|
+
declare class GmailIngestionAdapter {
|
|
8
|
+
private readonly gmail;
|
|
9
|
+
private readonly processor;
|
|
10
|
+
private readonly embeddings;
|
|
11
|
+
private readonly indexer;
|
|
12
|
+
constructor(gmail: EmailInboundProvider, processor: DocumentProcessor, embeddings: EmbeddingService, indexer: VectorIndexer);
|
|
13
|
+
syncThreads(query?: Parameters<EmailInboundProvider['listThreads']>[0]): Promise<void>;
|
|
14
|
+
ingestThread(thread: EmailThread): Promise<void>;
|
|
15
|
+
private toRawDocument;
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { GmailIngestionAdapter };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
var e=class{constructor(e,t,n,r){this.gmail=e,this.processor=t,this.embeddings=n,this.indexer=r}async syncThreads(e){let t=await this.gmail.listThreads(e);for(let e of t)await this.ingestThread(e)}async ingestThread(e){let t=this.toRawDocument(e),n=await this.processor.process(t),r=await this.embeddings.embedFragments(n);await this.indexer.upsert(n,r)}toRawDocument(e){let n=t(e);return{id:e.id,mimeType:`text/plain`,data:Buffer.from(n,`utf-8`),metadata:{subject:e.subject??``,participants:e.participants.map(e=>e.email).join(`, `),updatedAt:e.updatedAt.toISOString()}}}};function t(e){let t=[`Subject: ${e.subject??``}`,`Snippet: ${e.snippet??``}`],i=e.messages.map(e=>{let t=[`From: ${n(e.from)}`,`To: ${e.to.map(n).join(`, `)}`];e.sentAt&&t.push(`Date: ${e.sentAt.toISOString()}`);let i=e.textBody??r(e.htmlBody??``);return`${t.join(`
|
|
2
|
+
`)}\n\n${i??``}`});return[...t,...i].join(`
|
|
3
|
+
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
`)}function n(e){return e.name?`${e.name} <${e.email}>`:e.email}function r(e){return e.replace(/<[^>]+>/g,` `)}export{e as GmailIngestionAdapter};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DocumentFragment, DocumentProcessor, RawDocument } from "./document-processor.js";
|
|
2
|
+
import { EmbeddingService } from "./embedding-service.js";
|
|
3
|
+
import { VectorIndexConfig, VectorIndexer } from "./vector-indexer.js";
|
|
4
|
+
import { GmailIngestionAdapter } from "./gmail-adapter.js";
|
|
5
|
+
import { StorageIngestionAdapter } from "./storage-adapter.js";
|
|
6
|
+
export { DocumentFragment, DocumentProcessor, EmbeddingService, GmailIngestionAdapter, RawDocument, StorageIngestionAdapter, VectorIndexConfig, VectorIndexer };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DocumentProcessor as e}from"./document-processor.js";import{EmbeddingService as t}from"./embedding-service.js";import{VectorIndexer as n}from"./vector-indexer.js";import{GmailIngestionAdapter as r}from"./gmail-adapter.js";import{StorageIngestionAdapter as i}from"./storage-adapter.js";export{e as DocumentProcessor,t as EmbeddingService,r as GmailIngestionAdapter,i as StorageIngestionAdapter,n as VectorIndexer};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { DocumentProcessor } from "./document-processor.js";
|
|
2
|
+
import { EmbeddingService } from "./embedding-service.js";
|
|
3
|
+
import { VectorIndexer } from "./vector-indexer.js";
|
|
4
|
+
import { GetObjectResult } from "@lssm/lib.contracts/integrations/providers";
|
|
5
|
+
|
|
6
|
+
//#region src/ingestion/storage-adapter.d.ts
|
|
7
|
+
declare class StorageIngestionAdapter {
|
|
8
|
+
private readonly processor;
|
|
9
|
+
private readonly embeddings;
|
|
10
|
+
private readonly indexer;
|
|
11
|
+
constructor(processor: DocumentProcessor, embeddings: EmbeddingService, indexer: VectorIndexer);
|
|
12
|
+
ingestObject(object: GetObjectResult): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { StorageIngestionAdapter };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class{constructor(e,t,n){this.processor=e,this.embeddings=t,this.indexer=n}async ingestObject(e){if(!(`data`in e)||!e.data)throw Error(`Storage ingestion requires object data`);let t={id:e.key,mimeType:e.contentType??`application/octet-stream`,data:e.data,metadata:{bucket:e.bucket,checksum:e.checksum??``}},n=await this.processor.process(t),r=await this.embeddings.embedFragments(n);await this.indexer.upsert(n,r)}};export{e as StorageIngestionAdapter};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { DocumentFragment } from "./document-processor.js";
|
|
2
|
+
import { EmbeddingResult, VectorStoreProvider } from "@lssm/lib.contracts/integrations/providers";
|
|
3
|
+
|
|
4
|
+
//#region src/ingestion/vector-indexer.d.ts
|
|
5
|
+
interface VectorIndexConfig {
|
|
6
|
+
collection: string;
|
|
7
|
+
namespace?: string;
|
|
8
|
+
metadata?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
declare class VectorIndexer {
|
|
11
|
+
private readonly provider;
|
|
12
|
+
private readonly config;
|
|
13
|
+
constructor(provider: VectorStoreProvider, config: VectorIndexConfig);
|
|
14
|
+
upsert(fragments: DocumentFragment[], embeddings: EmbeddingResult[]): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { VectorIndexConfig, VectorIndexer };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class{provider;config;constructor(e,t){this.provider=e,this.config=t}async upsert(e,t){let n=t.map(t=>{let n=e.find(e=>e.id===t.id);return{id:t.id,vector:t.vector,payload:{...this.config.metadata,...n?.metadata??{},documentId:n?.documentId},namespace:this.config.namespace}}),r={collection:this.config.collection,documents:n};await this.provider.upsert(r)}};export{e as VectorIndexer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{KnowledgeQueryService as e}from"./service.js";export{e as KnowledgeQueryService};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { EmbeddingProvider, LLMProvider, LLMResponse, VectorSearchResult, VectorStoreProvider } from "@lssm/lib.contracts/integrations/providers";
|
|
2
|
+
|
|
3
|
+
//#region src/query/service.d.ts
|
|
4
|
+
interface KnowledgeQueryConfig {
|
|
5
|
+
collection: string;
|
|
6
|
+
namespace?: string;
|
|
7
|
+
topK?: number;
|
|
8
|
+
systemPrompt?: string;
|
|
9
|
+
}
|
|
10
|
+
interface KnowledgeAnswer {
|
|
11
|
+
answer: string;
|
|
12
|
+
references: (VectorSearchResult & {
|
|
13
|
+
text?: string;
|
|
14
|
+
})[];
|
|
15
|
+
usage?: LLMResponse['usage'];
|
|
16
|
+
}
|
|
17
|
+
declare class KnowledgeQueryService {
|
|
18
|
+
private readonly embeddings;
|
|
19
|
+
private readonly vectorStore;
|
|
20
|
+
private readonly llm;
|
|
21
|
+
private readonly config;
|
|
22
|
+
constructor(embeddings: EmbeddingProvider, vectorStore: VectorStoreProvider, llm: LLMProvider, config: KnowledgeQueryConfig);
|
|
23
|
+
query(question: string): Promise<KnowledgeAnswer>;
|
|
24
|
+
private buildMessages;
|
|
25
|
+
}
|
|
26
|
+
//#endregion
|
|
27
|
+
export { KnowledgeAnswer, KnowledgeQueryConfig, KnowledgeQueryService };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var e=class{embeddings;vectorStore;llm;config;constructor(e,t,n,r){this.embeddings=e,this.vectorStore=t,this.llm=n,this.config=r}async query(e){let r=await this.embeddings.embedQuery(e),i=await this.vectorStore.search({collection:this.config.collection,vector:r.vector,topK:this.config.topK??5,namespace:this.config.namespace,filter:void 0}),a=t(i),o=this.buildMessages(e,a),s=await this.llm.chat(o);return{answer:s.message.content.map(e=>`text`in e?e.text:``).join(``),references:i.map(e=>({...e,text:n(e)})),usage:s.usage}}buildMessages(e,t){return[{role:`system`,content:[{type:`text`,text:this.config.systemPrompt??`You are a knowledge assistant that answers questions using the provided context. Cite relevant sources if possible.`}]},{role:`user`,content:[{type:`text`,text:`Question:\n${e}\n\nContext:\n${t}`}]}]}};function t(e){return e.length===0?`No relevant documents found.`:e.map((e,t)=>{let r=n(e);return`Source ${t+1} (score: ${e.score.toFixed(3)}):\n${r}`}).join(`
|
|
2
|
+
|
|
3
|
+
`)}function n(e){let t=e.payload??{};return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:JSON.stringify(t)}export{e as KnowledgeQueryService};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { KnowledgeRetriever, RetrieverConfig } from "./interface.js";
|
|
2
|
+
import { StaticRetriever, StaticRetrieverConfig, createStaticRetriever } from "./static-retriever.js";
|
|
3
|
+
import { VectorRetriever, VectorRetrieverConfig, createVectorRetriever } from "./vector-retriever.js";
|
|
4
|
+
export { KnowledgeRetriever, RetrieverConfig, StaticRetriever, StaticRetrieverConfig, VectorRetriever, VectorRetrieverConfig, createStaticRetriever, createVectorRetriever };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{StaticRetriever as e,createStaticRetriever as t}from"./static-retriever.js";import{VectorRetriever as n,createVectorRetriever as r}from"./vector-retriever.js";export{e as StaticRetriever,n as VectorRetriever,t as createStaticRetriever,r as createVectorRetriever};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { RetrievalOptions, RetrievalResult } from "../types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/retriever/interface.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Unified interface for knowledge retrieval.
|
|
7
|
+
*
|
|
8
|
+
* Implementations can use vector stores, static content, or hybrid approaches.
|
|
9
|
+
* This interface is consumed by @lssm/lib.ai-agent for both static injection
|
|
10
|
+
* and dynamic RAG tool queries.
|
|
11
|
+
*/
|
|
12
|
+
interface KnowledgeRetriever {
|
|
13
|
+
/**
|
|
14
|
+
* Retrieve relevant content for a query using semantic search.
|
|
15
|
+
*
|
|
16
|
+
* @param query - The search query or question
|
|
17
|
+
* @param options - Retrieval options including space key and filters
|
|
18
|
+
* @returns Array of retrieval results sorted by relevance
|
|
19
|
+
*/
|
|
20
|
+
retrieve(query: string, options: RetrievalOptions): Promise<RetrievalResult[]>;
|
|
21
|
+
/**
|
|
22
|
+
* Get static content by space key (for required knowledge injection).
|
|
23
|
+
*
|
|
24
|
+
* Used for injecting required knowledge into agent system prompts
|
|
25
|
+
* without performing semantic search.
|
|
26
|
+
*
|
|
27
|
+
* @param spaceKey - The knowledge space key
|
|
28
|
+
* @returns The static content or null if not available
|
|
29
|
+
*/
|
|
30
|
+
getStatic(spaceKey: string): Promise<string | null>;
|
|
31
|
+
/**
|
|
32
|
+
* Check if this retriever supports a given knowledge space.
|
|
33
|
+
*
|
|
34
|
+
* @param spaceKey - The knowledge space key to check
|
|
35
|
+
* @returns True if the space is supported
|
|
36
|
+
*/
|
|
37
|
+
supportsSpace(spaceKey: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* List all supported knowledge space keys.
|
|
40
|
+
*
|
|
41
|
+
* @returns Array of supported space keys
|
|
42
|
+
*/
|
|
43
|
+
listSpaces(): string[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Configuration for creating a retriever.
|
|
47
|
+
*/
|
|
48
|
+
interface RetrieverConfig {
|
|
49
|
+
/** Default number of results to return */
|
|
50
|
+
defaultTopK?: number;
|
|
51
|
+
/** Default minimum score threshold */
|
|
52
|
+
defaultMinScore?: number;
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { KnowledgeRetriever, RetrieverConfig };
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { RetrievalOptions, RetrievalResult } from "../types.js";
|
|
2
|
+
import { KnowledgeRetriever, RetrieverConfig } from "./interface.js";
|
|
3
|
+
|
|
4
|
+
//#region src/retriever/static-retriever.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for the static retriever.
|
|
8
|
+
*/
|
|
9
|
+
interface StaticRetrieverConfig extends RetrieverConfig {
|
|
10
|
+
/** Map of space key to static content */
|
|
11
|
+
content: Map<string, string> | Record<string, string>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A simple in-memory retriever for static knowledge content.
|
|
15
|
+
*
|
|
16
|
+
* Useful for:
|
|
17
|
+
* - Required knowledge that doesn't need semantic search
|
|
18
|
+
* - Testing and development
|
|
19
|
+
* - Small knowledge bases that fit in memory
|
|
20
|
+
*/
|
|
21
|
+
declare class StaticRetriever implements KnowledgeRetriever {
|
|
22
|
+
private readonly content;
|
|
23
|
+
constructor(config: StaticRetrieverConfig);
|
|
24
|
+
retrieve(query: string, options: RetrievalOptions): Promise<RetrievalResult[]>;
|
|
25
|
+
getStatic(spaceKey: string): Promise<string | null>;
|
|
26
|
+
supportsSpace(spaceKey: string): boolean;
|
|
27
|
+
listSpaces(): string[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Create a static retriever from a content map.
|
|
31
|
+
*/
|
|
32
|
+
declare function createStaticRetriever(content: Record<string, string> | Map<string, string>): StaticRetriever;
|
|
33
|
+
//#endregion
|
|
34
|
+
export { StaticRetriever, StaticRetrieverConfig, createStaticRetriever };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class{content;constructor(e){this.content=e.content instanceof Map?e.content:new Map(Object.entries(e.content))}async retrieve(e,t){let n=this.content.get(t.spaceKey);if(!n)return[];let r=e.toLowerCase(),i=n.split(`
|
|
2
|
+
`).filter(e=>e.trim()),a=[];for(let e of i)e.toLowerCase().includes(r)&&a.push({content:e,source:t.spaceKey,score:1,metadata:{type:`static`}});return a.slice(0,t.topK??5)}async getStatic(e){return this.content.get(e)??null}supportsSpace(e){return this.content.has(e)}listSpaces(){return[...this.content.keys()]}};function t(t){return new e({content:t})}export{e as StaticRetriever,t as createStaticRetriever};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { RetrievalOptions, RetrievalResult } from "../types.js";
|
|
2
|
+
import { KnowledgeRetriever, RetrieverConfig } from "./interface.js";
|
|
3
|
+
import { EmbeddingProvider, VectorStoreProvider } from "@lssm/lib.contracts/integrations/providers";
|
|
4
|
+
|
|
5
|
+
//#region src/retriever/vector-retriever.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration for the vector retriever.
|
|
9
|
+
*/
|
|
10
|
+
interface VectorRetrieverConfig extends RetrieverConfig {
|
|
11
|
+
/** Embedding provider for query vectorization */
|
|
12
|
+
embeddings: EmbeddingProvider;
|
|
13
|
+
/** Vector store provider for similarity search */
|
|
14
|
+
vectorStore: VectorStoreProvider;
|
|
15
|
+
/** Map of space key to collection name */
|
|
16
|
+
spaceCollections: Map<string, string> | Record<string, string>;
|
|
17
|
+
/** Optional static content for getStatic() calls */
|
|
18
|
+
staticContent?: Map<string, string> | Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A retriever that uses vector similarity search.
|
|
22
|
+
*
|
|
23
|
+
* Uses embedding provider to vectorize queries and vector store
|
|
24
|
+
* provider to perform similarity search.
|
|
25
|
+
*/
|
|
26
|
+
declare class VectorRetriever implements KnowledgeRetriever {
|
|
27
|
+
private readonly config;
|
|
28
|
+
private readonly spaceCollections;
|
|
29
|
+
private readonly staticContent;
|
|
30
|
+
constructor(config: VectorRetrieverConfig);
|
|
31
|
+
retrieve(query: string, options: RetrievalOptions): Promise<RetrievalResult[]>;
|
|
32
|
+
getStatic(spaceKey: string): Promise<string | null>;
|
|
33
|
+
supportsSpace(spaceKey: string): boolean;
|
|
34
|
+
listSpaces(): string[];
|
|
35
|
+
private extractContent;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Create a vector retriever from configuration.
|
|
39
|
+
*/
|
|
40
|
+
declare function createVectorRetriever(config: VectorRetrieverConfig): VectorRetriever;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { VectorRetriever, VectorRetrieverConfig, createVectorRetriever };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class{config;spaceCollections;staticContent;constructor(e){this.config=e,this.spaceCollections=e.spaceCollections instanceof Map?e.spaceCollections:new Map(Object.entries(e.spaceCollections)),this.staticContent=e.staticContent?e.staticContent instanceof Map?e.staticContent:new Map(Object.entries(e.staticContent)):new Map}async retrieve(e,t){let n=this.spaceCollections.get(t.spaceKey);if(!n)return[];let r=await this.config.embeddings.embedQuery(e),i=await this.config.vectorStore.search({collection:n,vector:r.vector,topK:t.topK??this.config.defaultTopK??5,namespace:t.tenantId,filter:t.filter}),a=t.minScore??this.config.defaultMinScore??0;return i.filter(e=>e.score>=a).map(e=>({content:this.extractContent(e.payload),source:e.id,score:e.score,metadata:e.payload}))}async getStatic(e){return this.staticContent.get(e)??null}supportsSpace(e){return this.spaceCollections.has(e)}listSpaces(){return[...this.spaceCollections.keys()]}extractContent(e){return e?typeof e.text==`string`?e.text:typeof e.content==`string`?e.content:JSON.stringify(e):``}};function t(t){return new e(t)}export{e as VectorRetriever,t as createVectorRetriever};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { KnowledgeCategory } from "@lssm/lib.contracts/knowledge";
|
|
2
|
+
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Result from a knowledge retrieval operation.
|
|
7
|
+
*/
|
|
8
|
+
interface RetrievalResult {
|
|
9
|
+
/** The retrieved content/text */
|
|
10
|
+
content: string;
|
|
11
|
+
/** Source identifier (document ID, URL, etc.) */
|
|
12
|
+
source: string;
|
|
13
|
+
/** Relevance score (0-1, higher is more relevant) */
|
|
14
|
+
score: number;
|
|
15
|
+
/** Additional metadata about the result */
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Options for knowledge retrieval.
|
|
20
|
+
*/
|
|
21
|
+
interface RetrievalOptions {
|
|
22
|
+
/** Knowledge space key to query */
|
|
23
|
+
spaceKey: string;
|
|
24
|
+
/** Maximum number of results to return */
|
|
25
|
+
topK?: number;
|
|
26
|
+
/** Minimum relevance score threshold */
|
|
27
|
+
minScore?: number;
|
|
28
|
+
/** Filter by knowledge category */
|
|
29
|
+
category?: KnowledgeCategory;
|
|
30
|
+
/** Tenant-scoped retrieval */
|
|
31
|
+
tenantId?: string;
|
|
32
|
+
/** Additional filter criteria */
|
|
33
|
+
filter?: Record<string, unknown>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Context for knowledge access operations.
|
|
37
|
+
*/
|
|
38
|
+
interface KnowledgeAccessContext {
|
|
39
|
+
tenantId: string;
|
|
40
|
+
appId: string;
|
|
41
|
+
environment?: string;
|
|
42
|
+
workflowName?: string;
|
|
43
|
+
agentName?: string;
|
|
44
|
+
operation: 'read' | 'write' | 'search';
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Result of an access check.
|
|
48
|
+
*/
|
|
49
|
+
interface KnowledgeAccessResult {
|
|
50
|
+
allowed: boolean;
|
|
51
|
+
reason?: string;
|
|
52
|
+
severity?: 'error' | 'warning';
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
export { KnowledgeAccessContext, KnowledgeAccessResult, RetrievalOptions, RetrievalResult };
|
package/dist/types.js
ADDED
|
File without changes
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lssm/lib.knowledge",
|
|
3
|
+
"version": "0.0.0-canary-20251206160926",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"publish:pkg": "bun publish --tolerate-republish --ignore-scripts --verbose",
|
|
14
|
+
"build": "bun build:bundle && bun build:types",
|
|
15
|
+
"build:bundle": "tsdown",
|
|
16
|
+
"build:types": "tsc --noEmit",
|
|
17
|
+
"dev": "bun build:bundle --watch",
|
|
18
|
+
"clean": "rimraf dist .turbo",
|
|
19
|
+
"lint": "bun lint:fix",
|
|
20
|
+
"lint:fix": "eslint src --fix",
|
|
21
|
+
"lint:check": "eslint src",
|
|
22
|
+
"test": "bun test"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@lssm/lib.contracts": "workspace:*"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@lssm/tool.tsdown": "workspace:*",
|
|
29
|
+
"@lssm/tool.typescript": "workspace:*",
|
|
30
|
+
"tsdown": "^0.17.0",
|
|
31
|
+
"typescript": "^5.9.3"
|
|
32
|
+
},
|
|
33
|
+
"exports": {
|
|
34
|
+
".": "./dist/index.js",
|
|
35
|
+
"./access": "./dist/access/index.js",
|
|
36
|
+
"./access/guard": "./dist/access/guard.js",
|
|
37
|
+
"./ingestion": "./dist/ingestion/index.js",
|
|
38
|
+
"./ingestion/document-processor": "./dist/ingestion/document-processor.js",
|
|
39
|
+
"./ingestion/embedding-service": "./dist/ingestion/embedding-service.js",
|
|
40
|
+
"./ingestion/gmail-adapter": "./dist/ingestion/gmail-adapter.js",
|
|
41
|
+
"./ingestion/storage-adapter": "./dist/ingestion/storage-adapter.js",
|
|
42
|
+
"./ingestion/vector-indexer": "./dist/ingestion/vector-indexer.js",
|
|
43
|
+
"./query": "./dist/query/index.js",
|
|
44
|
+
"./query/service": "./dist/query/service.js",
|
|
45
|
+
"./retriever": "./dist/retriever/index.js",
|
|
46
|
+
"./retriever/interface": "./dist/retriever/interface.js",
|
|
47
|
+
"./retriever/static-retriever": "./dist/retriever/static-retriever.js",
|
|
48
|
+
"./retriever/vector-retriever": "./dist/retriever/vector-retriever.js",
|
|
49
|
+
"./types": "./dist/types.js",
|
|
50
|
+
"./*": "./*"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
}
|
|
55
|
+
}
|