@lineai/assistant-memory
v0.1.1
Published
TypeScript SDK for episodic and procedural memory for @lineAI assistant and agents
Maintainers
Readme
@lineai/assistant-memory
TypeScript SDK for Cognee API - Episodic and procedural memory for @lineAI assistant and agents
A functional, type-safe TypeScript SDK for interacting with the Cognee API. Build powerful knowledge graphs and semantic search applications with ease.
Features
- 🔒 Type-safe - Full TypeScript support with comprehensive type definitions
- 🧩 Functional - Immutable data structures and pure functions
- 🎯 Intelligent Search - Automatic query classification and mode selection
- 🚀 Zero Dependencies - Uses native fetch (Node 18+)
- 📦 Tree-shakeable - Import only what you need
- 🔍 11 Search Modes - From simple chunks to advanced chain-of-thought reasoning
Installation
npm install @lineai/assistant-memoryyarn add @lineai/assistant-memoryQuick Start
import { createCogneeClient, SearchType } from '@lineai/assistant-memory';
// Create client
const client = createCogneeClient({
baseURL: 'https://api.cognee.ai',
apiKey: 'your-api-key'
});
// Add data
const addResult = await client.add({
textData: ['Important information about our product'],
datasetName: 'product-docs'
});
// Transform into knowledge graph
if (addResult.success) {
await client.cognify({
datasets: ['product-docs']
});
}
// Search with automatic mode selection
const route = client.routeQuery('Who are the key stakeholders?');
console.log(route.recommendedMode); // GRAPH_COMPLETION_COT
const searchResult = await client.search({
query: 'Who are the key stakeholders?',
searchType: route.recommendedMode,
datasets: ['product-docs']
});
if (searchResult.success) {
searchResult.data.forEach(result => {
console.log(result.search_result);
});
}Core Concepts
Client Creation
import { createCogneeClient } from '@lineai/assistant-memory';
const client = createCogneeClient({
baseURL: 'https://api.cognee.ai',
apiKey: 'your-api-key',
timeout: 120000 // optional, default 2 minutes
});Data Management
Add Data
const result = await client.add({
textData: ['Text to add to knowledge base'],
datasetName: 'my-dataset',
nodeSet: ['optional-node-classification'] // optional
});Cognify (Build Knowledge Graph)
const result = await client.cognify({
datasets: ['my-dataset'],
customPrompt: 'Extract technical entities and relationships', // optional
temporalCognify: false // optional
});Delete Data
const result = await client.delete({
dataId: 'data-uuid',
datasetId: 'dataset-uuid',
mode: 'soft' // 'soft' or 'hard'
});Search Modes
The SDK supports 11 different search modes, each optimized for different query types:
Direct Retrieval (No LLM)
- CHUNKS - Fast raw text retrieval
- SUMMARIES - Pre-generated summaries
- INSIGHTS - Pre-extracted key insights
RAG (Single-Step LLM)
- RAG_COMPLETION - Standard retrieval-augmented generation
Graph-Enhanced (Leveraging Knowledge Graph)
- GRAPH_COMPLETION - Uses entity relationships
- GRAPH_SUMMARY_COMPLETION - Graph + summaries
- GRAPH_COMPLETION_COT - Chain-of-thought reasoning ⭐
- GRAPH_COMPLETION_CONTEXT_EXTENSION - Extended graph traversal
Specialized
- CODE - Optimized for code search
- CYPHER - Generate graph database queries
- NATURAL_LANGUAGE - Flexible conversational mode
- FEELING_LUCKY - Returns single best result
Intelligent Search Helpers
Automatic Mode Selection
// Classify query type
const queryType = client.classifyQuery('Who are the key consultants in NYC?');
// Returns: QueryType.ENTITY_LIST
// Select optimal search mode
const mode = client.selectSearchMode('Who are the key consultants in NYC?');
// Returns: SearchType.GRAPH_COMPLETION_COT
// Get full routing information
const route = client.routeQuery('Who are the key consultants in NYC?');
console.log(route);
// {
// query: "Who are the key consultants in NYC?",
// queryType: "entity_list",
// recommendedMode: "GRAPH_COMPLETION_COT",
// estimatedCost: "$$$$$",
// estimatedTime: 3.5,
// reasoning: "Entity list extraction requires Chain-of-Thought..."
// }Query Type Detection
// Check query characteristics
client.isEntityListQuery('Who are the experts?'); // true
client.isComparisonQuery('How does X differ from Y?'); // true
client.isNarrativeQuery('Why is this important?'); // true
client.isMultiHopQuery('If X then what should I do?'); // trueSearch Builder
import { createSearchBuilder } from '@lineai/assistant-memory';
const params = client.createSearchBuilder()
.query('Who are the consultants in NYC?')
.autoMode() // Automatically select best mode
.inDatasets(['my-dataset'])
.topK(5)
.withSystemPrompt('Be concise')
.build();
const result = await client.search(params);Cost & Performance Estimation
import { SearchType } from '@lineai/assistant-memory';
// Estimate costs before running query
const cost = client.estimateCost(SearchType.GRAPH_COMPLETION_COT);
// Returns: "$$$$$" (very high)
const time = client.estimateTime(SearchType.GRAPH_COMPLETION_COT);
// Returns: 3.5 (seconds)Search Mode Selection Guide
When to Use Each Mode
CHUNKS - Use for:
- Simple fact retrieval
- Exact text matching
- Debugging/development
- Speed is critical
RAG_COMPLETION - Use for:
- Narrative/explanatory questions
- "Why" questions
- Natural language output needed
GRAPH_COMPLETION - Use for:
- Entity comparisons
- Relationship-based questions
- When entities exist in graph
GRAPH_COMPLETION_COT ⭐ - Use for:
- Entity list extraction ("Who are the...")
- Multi-hop reasoning
- Complex queries with sub-questions
- Temporal queries
- Problem-solution patterns
- When other modes fail
GRAPH_COMPLETION_CONTEXT_EXTENSION - Use for:
- Exploratory queries
- Need comprehensive coverage
- Discovery of implicit connections
Performance Characteristics
| Mode | Speed | Cost | Accuracy (Complex) | |------|-------|------|-------------------| | CHUNKS | ⚡⚡⚡⚡⚡ | $ | Low | | RAG_COMPLETION | ⚡⚡⚡ | $$ | Medium | | GRAPH_COMPLETION | ⚡⚡ | $$$ | High | | GRAPH_COMPLETION_COT | ⚡ | $$$$$ | Very High |
Advanced Usage
Error Handling
The SDK uses a functional Result type for error handling:
import { createCogneeClient } from '@lineai/assistant-memory';
const result = await client.search({
query: 'test query',
searchType: 'CHUNKS'
});
if (result.success) {
// Access data
console.log(result.data);
} else {
// Handle error
switch (result.error.type) {
case 'AUTH_ERROR':
console.error('Authentication failed:', result.error.message);
break;
case 'NETWORK_ERROR':
console.error('Network error:', result.error.message);
break;
case 'API_ERROR':
console.error('API error:', result.error.statusCode, result.error.message);
break;
// ... handle other error types
}
}Visualization
const result = await client.visualize('dataset-uuid');
if (result.success) {
// result.data contains HTML visualization
fs.writeFileSync('graph.html', result.data);
}Search History
const history = await client.getSearchHistory();
if (history.success) {
history.data.forEach(item => {
console.log(`${item.createdAt}: ${item.text}`);
});
}API Reference
Client Methods
client.add(params)- Add text data to datasetclient.cognify(params)- Transform datasets into knowledge graphsclient.delete(params)- Delete data from datasetclient.search(params)- Search the knowledge graphclient.visualize(datasetId)- Generate graph visualizationclient.getSearchHistory()- Get user's search history
Search Helpers
client.classifyQuery(query)- Classify query typeclient.selectSearchMode(query)- Select optimal search modeclient.routeQuery(query)- Get full routing informationclient.estimateCost(mode)- Estimate cost for modeclient.estimateTime(mode)- Estimate time for modeclient.createSearchBuilder()- Create fluent search builder
Type Guards
client.isEntityListQuery(query)- Check if entity list queryclient.isComparisonQuery(query)- Check if comparison queryclient.isNarrativeQuery(query)- Check if narrative queryclient.isMultiHopQuery(query)- Check if multi-hop query
Examples
Basic Search
const result = await client.search({
query: 'What is the price range?',
searchType: 'CHUNKS',
topK: 5
});Entity Extraction
// Use COT for entity lists
const result = await client.search({
query: 'Who are the key lighting consultants in NYC?',
searchType: 'GRAPH_COMPLETION_COT',
datasets: ['market-research']
});Comparison Query
const result = await client.search({
query: 'How does Product A differ from Product B?',
searchType: 'GRAPH_COMPLETION',
datasets: ['products']
});Custom System Prompt
const result = await client.search({
query: 'Summarize the key points',
searchType: 'RAG_COMPLETION',
systemPrompt: 'Provide a concise 2-sentence summary',
datasets: ['documents']
});TypeScript Types
All types are fully exported for your convenience:
import type {
CogneeClient,
ClientConfig,
SearchParams,
SearchResult,
SearchType,
QueryType,
QueryRoute,
Result,
CogneeError,
UUID
} from '@lineai/assistant-memory';Development
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Lint
npm run test:lint
# Format
npm run fix:prettierLicense
MIT
