Class: SqlKnowledgeGraph
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:174
Persistent knowledge graph backed by SQLite via Brain.
Implements the full IKnowledgeGraph interface using the knowledge_nodes
and knowledge_edges tables. Extended entity/relation fields that don't
have dedicated columns are serialized into the JSON properties / metadata
columns.
Example
const brain = await Brain.openSqlite('/tmp/agent-brain.sqlite');
const graph = new SqlKnowledgeGraph(brain);
await graph.initialize();
const entity = await graph.upsertEntity({
type: 'person',
label: 'Alice',
properties: { role: 'engineer' },
confidence: 0.95,
source: { type: 'user_input', timestamp: new Date().toISOString() },
});
Implements
Constructors
Constructor
new SqlKnowledgeGraph(
brain):SqlKnowledgeGraph
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:182
Parameters
brain
A Brain instance whose async StorageAdapter methods are used for all queries.
Returns
SqlKnowledgeGraph
Methods
clear()
clear():
Promise<void>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1301
Delete all rows from knowledge_nodes and knowledge_edges. Wipes the knowledge graph completely.
Returns
Promise<void>
Implementation of
decayMemories()
decayMemories(
decayFactor?):Promise<number>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1205
Decay the confidence of all memory-type nodes by a multiplicative factor.
This simulates the Ebbinghaus forgetting curve — memories that are not accessed (reinforced) gradually fade.
Parameters
decayFactor?
number
Multiplicative factor in (0, 1). Default 0.95.
Returns
Promise<number>
The number of memory nodes whose confidence was reduced.
Implementation of
deleteEntity()
deleteEntity(
id):Promise<boolean>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:365
Delete an entity and all its associated relations (incoming and outgoing).
Returns true if the entity existed and was deleted.
Parameters
id
string
Returns
Promise<boolean>
Implementation of
deleteRelation()
deleteRelation(
id):Promise<boolean>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:495
Delete a single relation by its ID.
Returns true if the relation existed and was deleted.
Parameters
id
string
Returns
Promise<boolean>
Implementation of
IKnowledgeGraph.deleteRelation
extractFromText()
extractFromText(
_text,_options?):Promise<{entities:KnowledgeEntity[];relations:KnowledgeRelation[]; }>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1130
Extract entities and relations from text.
This operation requires an LLM and is not supported at the store level. Use the Memory facade for LLM-powered extraction.
Parameters
_text
string
_options?
entityTypes?
extractRelations?
boolean
Returns
Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>
Throws
Always — extraction requires an LLM.
Implementation of
IKnowledgeGraph.extractFromText
findPath()
findPath(
sourceId,targetId,maxDepth?):Promise<object[] |null>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:862
Find the shortest path between two entities using a bidirectional BFS implemented via a recursive CTE.
Returns an ordered array of { entity, relation? } steps from source to
target, or null if no path exists within maxDepth hops.
Parameters
sourceId
string
targetId
string
maxDepth?
number
Returns
Promise<object[] | null>
Implementation of
getEntity()
getEntity(
id):Promise<KnowledgeEntity|undefined>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:281
Retrieve a single entity by its ID.
Returns undefined if the entity does not exist.
Parameters
id
string
Returns
Promise<KnowledgeEntity | undefined>
Implementation of
getMemory()
getMemory(
id):Promise<EpisodicMemory|undefined>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:591
Get an episodic memory by ID.
Looks up the knowledge_node with the given ID and type = 'memory',
then unpacks the memory-specific fields from the properties JSON.
Parameters
id
string
Returns
Promise<EpisodicMemory | undefined>
Implementation of
getNeighborhood()
getNeighborhood(
entityId,depth?):Promise<{entities:KnowledgeEntity[];relations:KnowledgeRelation[]; }>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:943
Get the neighbourhood of an entity — all entities and relations within
depth hops.
Parameters
entityId
string
Centre entity.
depth?
number
Maximum number of hops (default 1).
Returns
Promise<{ entities: KnowledgeEntity[]; relations: KnowledgeRelation[]; }>
Implementation of
IKnowledgeGraph.getNeighborhood
getRelations()
getRelations(
entityId,options?):Promise<KnowledgeRelation[]>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:459
Get all relations for a given entity.
Parameters
entityId
string
The entity whose relations to retrieve.
options?
Optional filters: direction ('outgoing'|'incoming'|'both'), types.
direction?
"outgoing" | "incoming" | "both"
types?
Returns
Promise<KnowledgeRelation[]>
Implementation of
getStats()
getStats():
Promise<KnowledgeGraphStats>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1224
Get aggregate statistics about the knowledge graph.
Returns counts of entities, relations, memories, breakdowns by type, average confidence, and oldest/newest entry timestamps.
Returns
Promise<KnowledgeGraphStats>
Implementation of
initialize()
initialize():
Promise<void>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:196
Initialize the knowledge graph.
The schema is already created by Brain's constructor, so this is effectively a no-op. Provided to satisfy the IKnowledgeGraph contract.
Returns
Promise<void>
Implementation of
mergeEntities()
mergeEntities(
entityIds,primaryId):Promise<KnowledgeEntity>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1152
Merge multiple entities into one primary entity.
All relations (edges) pointing to or from the non-primary entities are re-linked to the primary entity. The non-primary entities are then deleted.
Parameters
entityIds
string[]
All entity IDs involved in the merge.
primaryId
string
The ID that survives the merge.
Returns
Promise<KnowledgeEntity>
Implementation of
queryEntities()
queryEntities(
options?):Promise<KnowledgeEntity[]>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:297
Query entities with optional filters.
Supports filtering by entity type, tags, owner, minimum confidence, full-text search, pagination (limit/offset), and time ranges.
Parameters
options?
Returns
Promise<KnowledgeEntity[]>
Implementation of
queryMemories()
queryMemories(
options?):Promise<EpisodicMemory[]>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:607
Query episodic memories with optional filters.
Supports filtering by memory sub-type, participants, minimum importance, time range, and result limit.
Parameters
options?
limit?
number
minImportance?
number
participants?
string[]
timeRange?
{ from?: string; to?: string; }
timeRange.from?
string
timeRange.to?
string
types?
("discovery" | "success" | "error" | "conversation" | "task" | "interaction")[]
Returns
Promise<EpisodicMemory[]>
Implementation of
recallMemories()
recallMemories(
query,topK?):Promise<EpisodicMemory[]>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:665
Recall relevant memories via keyword search against summaries.
Performs a case-insensitive substring match on the label (which contains the summary text). Increments accessCount and updates lastAccessedAt for each returned memory (Hebbian reinforcement).
Full semantic (embedding-based) recall requires the Memory facade.
Parameters
query
string
topK?
number
Returns
Promise<EpisodicMemory[]>
Implementation of
IKnowledgeGraph.recallMemories
recordMemory()
recordMemory(
memory):Promise<EpisodicMemory>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:513
Record an episodic memory.
Memories are stored as knowledge_nodes with type = 'memory'. The
memory-specific fields are packed into the properties JSON column.
Parameters
memory
Omit<EpisodicMemory, "id" | "createdAt" | "accessCount" | "lastAccessedAt">
Returns
Promise<EpisodicMemory>
Implementation of
semanticSearch()
semanticSearch(
options):Promise<SemanticSearchResult[]>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:1007
Semantic search across entities and/or memories.
Loads all embeddings from knowledge_nodes, computes cosine similarity
against the query embedding (if present in options), and returns the
top-K results above the minimum similarity threshold.
NOTE: This implementation requires the caller to provide a query embedding via a pre-processing step. If no nodes have embeddings, an empty array is returned. For full text-to-embedding semantic search, use the Memory facade.
Parameters
options
Returns
Promise<SemanticSearchResult[]>
Implementation of
IKnowledgeGraph.semanticSearch
traverse()
traverse(
startEntityId,options?):Promise<TraversalResult>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:718
Traverse the graph from a starting entity using BFS.
Uses a recursive CTE (Common Table Expression) to walk the graph up to
maxDepth hops from the start node. Results are grouped by depth level.
Parameters
startEntityId
string
ID of the entity to start traversal from.
options?
Optional: maxDepth, relationTypes, direction, minWeight, maxNodes.
Returns
Promise<TraversalResult>
Implementation of
upsertEntity()
upsertEntity(
entity):Promise<KnowledgeEntity>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:215
Insert or update a knowledge entity.
If entity.id is provided and exists, the row is updated (INSERT OR REPLACE).
If omitted, a new UUID is generated.
Extended fields (ownerId, tags, metadata, updatedAt) are packed into the
properties JSON column as underscore-prefixed keys to avoid collisions
with user-supplied properties.
Parameters
entity
Omit<KnowledgeEntity, "id" | "updatedAt" | "createdAt"> & object
Returns
Promise<KnowledgeEntity>
Implementation of
upsertRelation()
upsertRelation(
relation):Promise<KnowledgeRelation>
Defined in: packages/agentos/src/memory/retrieval/store/SqlKnowledgeGraph.ts:394
Insert or update a knowledge relation (edge).
Extended edge fields (label, properties, confidence, source, validFrom,
validTo) are packed into the metadata JSON column.
Parameters
relation
Omit<KnowledgeRelation, "id" | "createdAt"> & object
Returns
Promise<KnowledgeRelation>