Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | /**
* AgentKits — RAG Pipeline
*
* End-to-end Retrieval-Augmented Generation in one function call.
* embed → search → rerank → LLM answer
*
* Usage:
* import { createRAG } from 'agentkits/rag';
* const rag = createRAG({
* embeddingProvider: 'gemini', embeddingApiKey: '...',
* llmProvider: 'gemini', llmApiKey: '...',
* });
* await rag.ingest(['doc1 text', 'doc2 text']);
* const answer = await rag.query('what is doc1 about?');
*/
import { createEmbedding, type EmbeddingConfig } from '../embedding/index.js';
import { createChat, type ChatConfig } from '../llm/index.js';
// ── Types ──────────────────────────────────────────────────────────
export interface RAGConfig {
/** Embedding config */
embeddingProvider?: EmbeddingConfig['provider'];
embeddingModel?: string;
embeddingApiKey?: string;
embeddingBaseUrl?: string;
/** LLM config */
llmProvider?: ChatConfig['provider'];
llmModel?: string;
llmApiKey?: string;
llmBaseUrl?: string;
/** Retrieval settings */
topK?: number; // default 5
minScore?: number; // default 0.3
chunkSize?: number; // default 500 chars
chunkOverlap?: number; // default 50 chars
/** Custom system prompt for answer generation */
systemPrompt?: string;
}
export interface RAGDocument {
id: string;
text: string;
metadata?: Record<string, any>;
embedding?: number[] | Float32Array;
}
export interface RAGResult {
answer: string;
sources: Array<{ id: string; text: string; score: number; metadata?: Record<string, any> }>;
model: string;
}
export interface RAGClient {
/** Ingest documents (auto chunks + embeds) */
ingest(texts: string[], metadata?: Record<string, any>[]): Promise<number>;
/** Ingest pre-chunked documents */
ingestDocuments(docs: RAGDocument[]): Promise<number>;
/** Query with RAG */
query(question: string, options?: { topK?: number; systemPrompt?: string }): Promise<RAGResult>;
/** Retrieve without generating answer */
retrieve(question: string, topK?: number): Promise<Array<{ id: string; text: string; score: number; metadata?: Record<string, any> }>>;
/** Get document count */
readonly count: number;
/** Clear all documents */
clear(): void;
}
// ── Chunking ──────────────────────────────────────────────────────
function chunkText(text: string, size: number, overlap: number): string[] {
if (text.length <= size) return [text];
const chunks: string[] = [];
let start = 0;
while (start < text.length) {
let end = start + size;
// Try to break at paragraph
if (end < text.length) {
const para = text.lastIndexOf('\n\n', end);
if (para > start + size * 0.5) end = para;
else {
const line = text.lastIndexOf('\n', end);
if (line > start + size * 0.5) end = line;
else {
const space = text.lastIndexOf(' ', end);
if (space > start + size * 0.5) end = space;
}
}
}
chunks.push(text.slice(start, end).trim());
start = end - overlap;
}
return chunks.filter(c => c.length > 0);
}
// ── Cosine Similarity ─────────────────────────────────────────────
function cosineSimilarity(a: number[] | Float32Array, b: number[] | Float32Array): number {
let dot = 0, normA = 0, normB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
// ── Main ──────────────────────────────────────────────────────────
export function createRAG(config: RAGConfig = {}): RAGClient {
const {
embeddingProvider = 'gemini',
embeddingModel,
embeddingApiKey,
embeddingBaseUrl,
llmProvider = 'gemini',
llmModel,
llmApiKey,
llmBaseUrl,
topK = 5,
minScore = 0.3,
chunkSize = 500,
chunkOverlap = 50,
systemPrompt,
} = config;
const embedder = createEmbedding({
provider: embeddingProvider,
model: embeddingModel,
apiKey: embeddingApiKey,
baseUrl: embeddingBaseUrl,
} as any);
const chat = createChat({
provider: llmProvider,
model: llmModel,
apiKey: llmApiKey,
baseUrl: llmBaseUrl,
} as any);
const store: RAGDocument[] = [];
let docCounter = 0;
const defaultSystemPrompt = systemPrompt ?? `You are a helpful assistant that answers questions based on the provided context.
Use ONLY the information from the context below to answer. If the context doesn't contain enough information, say so.
Be concise and accurate.`;
const client: RAGClient = {
async ingest(texts, metadata) {
let totalChunks = 0;
for (let i = 0; i < texts.length; i++) {
const chunks = chunkText(texts[i], chunkSize, chunkOverlap);
const embeddings = await embedder.embedBatch(chunks);
for (let j = 0; j < chunks.length; j++) {
store.push({
id: `doc-${docCounter++}`,
text: chunks[j],
metadata: metadata?.[i],
embedding: embeddings[j],
});
totalChunks++;
}
}
return totalChunks;
},
async ingestDocuments(docs) {
const textsToEmbed = docs.filter(d => !d.embedding).map(d => d.text);
const embeddings = textsToEmbed.length > 0 ? await embedder.embedBatch(textsToEmbed) : [];
let embedIdx = 0;
for (const doc of docs) {
store.push({
...doc,
embedding: doc.embedding ?? embeddings[embedIdx++],
});
}
return docs.length;
},
async retrieve(question, k = topK) {
if (store.length === 0) return [];
const queryEmbedding = await embedder.embed(question);
const scored = store
.map(doc => ({
id: doc.id,
text: doc.text,
score: cosineSimilarity(queryEmbedding, doc.embedding!),
metadata: doc.metadata,
}))
.filter(d => d.score >= minScore)
.sort((a, b) => b.score - a.score)
.slice(0, k);
return scored;
},
async query(question, options = {}) {
const k = options.topK ?? topK;
const sources = await client.retrieve(question, k);
if (sources.length === 0) {
return {
answer: 'I could not find relevant information to answer this question.',
sources: [],
model: llmModel ?? 'default',
};
}
const context = sources.map((s, i) => `[${i + 1}] ${s.text}`).join('\n\n');
const prompt = `Context:\n${context}\n\nQuestion: ${question}`;
const sysPrompt = options.systemPrompt ?? defaultSystemPrompt;
const answer = await chat.complete(prompt, { system: sysPrompt });
return {
answer,
sources,
model: llmModel ?? 'default',
};
},
get count() { return store.length; },
clear() { store.length = 0; docCounter = 0; },
};
return client;
}
|