|
| 1 | +import { UUID } from "crypto"; |
| 2 | + |
| 3 | +import { AgentRuntime } from "./runtime.ts"; |
| 4 | +import { embed } from "./embedding.ts"; |
| 5 | +import { Content, ModelClass, type Memory } from "./types.ts"; |
| 6 | +import { stringToUuid } from "./uuid.ts"; |
| 7 | +import { embeddingZeroVector } from "./memory.ts"; |
| 8 | +import { splitChunks } from "./generation.ts"; |
| 9 | +import { models } from "./models.ts"; |
| 10 | +import elizaLogger from "./logger.ts"; |
| 11 | + |
| 12 | +async function get(runtime: AgentRuntime, message: Memory): Promise<string[]> { |
| 13 | + const processed = preprocess(message.content.text); |
| 14 | + elizaLogger.log(`Querying knowledge for: ${processed}`); |
| 15 | + const embedding = await embed(runtime, processed); |
| 16 | + const fragments = await runtime.knowledgeManager.searchMemoriesByEmbedding( |
| 17 | + embedding, |
| 18 | + { |
| 19 | + roomId: message.agentId, |
| 20 | + agentId: message.agentId, |
| 21 | + count: 3, |
| 22 | + match_threshold: 0.1, |
| 23 | + } |
| 24 | + ); |
| 25 | + |
| 26 | + const uniqueSources = [ |
| 27 | + ...new Set( |
| 28 | + fragments.map((memory) => { |
| 29 | + elizaLogger.log( |
| 30 | + `Matched fragment: ${memory.content.text} with similarity: ${message.similarity}` |
| 31 | + ); |
| 32 | + return memory.content.source; |
| 33 | + }) |
| 34 | + ), |
| 35 | + ]; |
| 36 | + |
| 37 | + const knowledgeDocuments = await Promise.all( |
| 38 | + uniqueSources.map((source) => |
| 39 | + runtime.documentsManager.getMemoryById(source as UUID) |
| 40 | + ) |
| 41 | + ); |
| 42 | + |
| 43 | + const knowledge = knowledgeDocuments |
| 44 | + .filter((memory) => memory !== null) |
| 45 | + .map((memory) => memory.content.text); |
| 46 | + return knowledge; |
| 47 | +} |
| 48 | + |
| 49 | +export type KnowledgeItem = { |
| 50 | + id: UUID; |
| 51 | + content: Content; |
| 52 | +}; |
| 53 | + |
| 54 | +async function set(runtime: AgentRuntime, item: KnowledgeItem) { |
| 55 | + await runtime.documentsManager.createMemory({ |
| 56 | + embedding: embeddingZeroVector, |
| 57 | + id: item.id, |
| 58 | + agentId: runtime.agentId, |
| 59 | + roomId: runtime.agentId, |
| 60 | + userId: runtime.agentId, |
| 61 | + createdAt: Date.now(), |
| 62 | + content: item.content, |
| 63 | + }); |
| 64 | + |
| 65 | + const preprocessed = preprocess(item.content.text); |
| 66 | + const fragments = await splitChunks( |
| 67 | + preprocessed, |
| 68 | + 10, |
| 69 | + models[runtime.character.modelProvider].model?.[ModelClass.EMBEDDING], |
| 70 | + 5 |
| 71 | + ); |
| 72 | + |
| 73 | + for (const fragment of fragments) { |
| 74 | + const embedding = await embed(runtime, fragment); |
| 75 | + await runtime.knowledgeManager.createMemory({ |
| 76 | + // We namespace the knowledge base uuid to avoid id |
| 77 | + // collision with the document above. |
| 78 | + id: stringToUuid(item.id + fragment), |
| 79 | + roomId: runtime.agentId, |
| 80 | + agentId: runtime.agentId, |
| 81 | + userId: runtime.agentId, |
| 82 | + createdAt: Date.now(), |
| 83 | + content: { |
| 84 | + source: item.id, |
| 85 | + text: fragment, |
| 86 | + }, |
| 87 | + embedding, |
| 88 | + }); |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +export function preprocess(content: string): string { |
| 93 | + return ( |
| 94 | + content |
| 95 | + // Remove code blocks and their content |
| 96 | + .replace(/```[\s\S]*?```/g, "") |
| 97 | + // Remove inline code |
| 98 | + .replace(/`.*?`/g, "") |
| 99 | + // Convert headers to plain text with emphasis |
| 100 | + .replace(/#{1,6}\s*(.*)/g, "$1") |
| 101 | + // Remove image links but keep alt text |
| 102 | + .replace(/!\[(.*?)\]\(.*?\)/g, "$1") |
| 103 | + // Remove links but keep text |
| 104 | + .replace(/\[(.*?)\]\(.*?\)/g, "$1") |
| 105 | + // Remove HTML tags |
| 106 | + .replace(/<[^>]*>/g, "") |
| 107 | + // Remove horizontal rules |
| 108 | + .replace(/^\s*[-*_]{3,}\s*$/gm, "") |
| 109 | + // Remove comments |
| 110 | + .replace(/\/\*[\s\S]*?\*\//g, "") |
| 111 | + .replace(/\/\/.*/g, "") |
| 112 | + // Normalize whitespace |
| 113 | + .replace(/\s+/g, " ") |
| 114 | + // Remove multiple newlines |
| 115 | + .replace(/\n{3,}/g, "\n\n") |
| 116 | + // strip all special characters |
| 117 | + .replace(/[^a-zA-Z0-9\s]/g, "") |
| 118 | + // Remove Discord mentions |
| 119 | + .replace(/<@!?\d+>/g, "") |
| 120 | + .trim() |
| 121 | + .toLowerCase() |
| 122 | + ); |
| 123 | +} |
| 124 | + |
| 125 | +export default { |
| 126 | + get, |
| 127 | + set, |
| 128 | + process, |
| 129 | +}; |
0 commit comments