The Memory API automatically assembles optimal context for queries. It combines semantic search, graph exploration, and episode history to build information for LLMs.
Overview
const client = new NdxClient ({
apiKey: process . env . NEURADEX_API_KEY ,
projectId: 'your-project-id' ,
});
// Access Memory API
const context = await client . memory . getContext ( 'query' );
const related = await client . memory . exploreRelated ( 'knowledge-id' );
Method List
Method Description getContext(query, options?)Get context for a query exploreRelated(knowledgeId, options?)Explore related knowledge
getContext()
Assembles optimized context for a query.
Process Flow
Semantic Search : Search for knowledge related to the query
Graph Exploration : Multi-hop exploration of related knowledge
Episode Retrieval : Get related Q&A history and change history
Optimization : Adjust results to fit within token budget
Formatting : Format for LLM consumption
Parameters
Search query (natural language)
Maximum token count for context
Include episodes like Q&A history
Include related knowledge
Maximum depth for graph exploration
Return Value
interface Context {
items : ContextItem []; // Context components
totalTokens : number ; // Total token count
truncated : boolean ; // Whether truncated due to budget
formatted : string ; // Formatted string for LLM
}
interface ContextItem {
type : 'knowledge' | 'related' | 'episode' ;
id : string ;
title ?: string ;
content : string ;
score : number ;
tokens : number ;
}
Usage
// Basic usage
const context = await client . memory . getContext ( 'Tell me about the return process' );
console . log ( `Tokens: ${ context . totalTokens } ` );
console . log ( `Truncated: ${ context . truncated } ` );
// Include in LLM prompt
const prompt = `
Answer the user's question using the following information.
## Reference Information
${ context . formatted }
## Question
Tell me about the return process
` ;
Option Adjustments
// Limit token budget
const context = await client . memory . getContext ( 'question' , {
tokenBudget: 2000 , // For smaller models
});
// Exclude episodes (knowledge only)
const context = await client . memory . getContext ( 'question' , {
includeEpisodes: false ,
});
// Shallow exploration (direct relations only)
const context = await client . memory . getContext ( 'question' , {
maxDepth: 1 ,
});
// Deep exploration (more related information)
const context = await client . memory . getContext ( 'question' , {
maxDepth: 3 ,
tokenBudget: 16000 ,
});
Examining Context Items
const context = await client . memory . getContext ( 'question' );
// Check items by type
const knowledge = context . items . filter ( item => item . type === 'knowledge' );
const related = context . items . filter ( item => item . type === 'related' );
const episodes = context . items . filter ( item => item . type === 'episode' );
console . log ( `Direct hits: ${ knowledge . length } ` );
console . log ( `Related knowledge: ${ related . length } ` );
console . log ( `Episodes: ${ episodes . length } ` );
// Display by score
for ( const item of context . items . sort (( a , b ) => b . score - a . score )) {
console . log ( `[ ${ item . type } ] ${ item . title ?? item . id } ( ${ item . score . toFixed ( 2 ) } )` );
}
Explore related knowledge from a specified knowledge entry. Multi-hop exploration (BFS) discovers knowledge that isn’t directly connected.
Parameters
Maximum exploration depth
Return Value
interface ExploreResult {
relatedNodes : RelatedKnowledge []; // Discovered knowledge
paths : GraphPath []; // Discovered paths
depth : number ; // Actual exploration depth
}
interface RelatedKnowledge {
id : string ;
title : string ;
content : string ;
path : GraphPath ; // Path to this knowledge
}
interface GraphPath {
nodeIds : string []; // Knowledge IDs on the path
edgeIds : string []; // Edge IDs on the path
totalWeight : number ; // Total weight of the path
}
Usage
// Explore related knowledge
const result = await client . memory . exploreRelated ( 'knowledge-id' );
console . log ( `Discovered knowledge: ${ result . relatedNodes . length } ` );
console . log ( `Exploration depth: ${ result . depth } ` );
// Display discovered knowledge
for ( const node of result . relatedNodes ) {
const hops = node . path . nodeIds . length - 1 ;
console . log ( ` ${ node . title } ( ${ hops } hops)` );
}
Deep Exploration
// Explore wider range
const result = await client . memory . exploreRelated ( 'knowledge-id' , {
maxDepth: 3 ,
});
// Classify by hop count
const byHops = new Map < number , RelatedKnowledge []>();
for ( const node of result . relatedNodes ) {
const hops = node . path . nodeIds . length - 1 ;
if ( ! byHops . has ( hops )) byHops . set ( hops , []);
byHops . get ( hops ) ! . push ( node );
}
for ( const [ hops , nodes ] of byHops ) {
console . log ( ` ${ hops } hops: ${ nodes . length } items` );
}
Use Cases
RAG Application
import { NdxClient } from '@neuradex/sdk' ;
import OpenAI from 'openai' ;
const neuradex = new NdxClient ({
apiKey: process . env . NEURADEX_API_KEY ,
projectId: process . env . NEURADEX_PROJECT_ID ,
});
const openai = new OpenAI ();
async function askQuestion ( question : string ) : Promise < string > {
// Get context
const context = await neuradex . memory . getContext ( question , {
tokenBudget: 4000 ,
includeEpisodes: true ,
});
// Generate answer with LLM
const response = await openai . chat . completions . create ({
model: 'gpt-4o' ,
messages: [
{
role: 'system' ,
content: `You are an assistant. Answer using the following information.
${ context . formatted } ` ,
},
{ role: 'user' , content: question },
],
});
return response . choices [ 0 ]. message . content ?? '' ;
}
Knowledge Graph Visualization
async function buildGraph ( startId : string ) {
const result = await client . memory . exploreRelated ( startId , {
maxDepth: 2 ,
});
// Build graph data
const nodes = new Map < string , { id : string ; title : string }>();
const edges : Array <{ from : string ; to : string }> = [];
for ( const related of result . relatedNodes ) {
nodes . set ( related . id , { id: related . id , title: related . title });
// Extract edges from paths
const path = related . path . nodeIds ;
for ( let i = 0 ; i < path . length - 1 ; i ++ ) {
edges . push ({ from: path [ i ], to: path [ i + 1 ] });
}
}
return {
nodes: Array . from ( nodes . values ()),
edges ,
};
}
Next Steps
Knowledge API Knowledge management
Episodes API Event and history recording