@usetransactional/memory
v1.0.2
Published
Transactional Memory SDK for TypeScript/JavaScript
Downloads
300
Maintainers
Readme
@usetransactional/memory
Official TypeScript/JavaScript SDK for Transactional Memory - a powerful memory system for AI applications with semantic search, knowledge graphs, and context management.
Installation
npm install @usetransactional/memory
# or
yarn add @usetransactional/memory
# or
pnpm add @usetransactional/memoryQuick Start
import { MemoryClient } from '@usetransactional/memory';
const client = new MemoryClient({
apiKey: process.env.TRANSACTIONAL_API_KEY!,
});
// Add a memory
await client.add({
content: 'User prefers TypeScript over JavaScript',
userId: 'user_123',
});
// Search memories
const results = await client.search({
query: 'programming language preferences',
userId: 'user_123',
});
// Get context for LLM prompts
const context = await client.getContext({
userId: 'user_123',
query: 'What programming language does the user prefer?',
});
console.log(context.context);
// Output: "User Preferences:\n- Prefers TypeScript over JavaScript"Features
- Memory Management: Add, update, delete, and search memories
- Semantic Search: Find relevant memories using hybrid search (keyword + embedding)
- Session Management: Organize memories into sessions
- User Profiles: Maintain persistent user profiles with static and dynamic facts
- Knowledge Graph: Explore relationships between entities
- URL Ingestion: Extract and store content from web pages
- PDF Ingestion: Parse and store content from PDF documents
- Context Generation: Build context for LLM prompts
Configuration
const client = new MemoryClient({
// Required
apiKey: 'your-api-key',
// Optional
baseUrl: 'https://api.usetransactional.com', // Default
timeout: 30000, // Request timeout in ms (default: 30000)
maxRetries: 3, // Max retry attempts (default: 3)
headers: {}, // Custom headers
});API Reference
Memory Operations
Add Memory
const result = await client.add({
content: 'User mentioned they work at Acme Corp',
userId: 'user_123',
sessionId: 'session_abc', // Optional
type: MemoryEntityType.FACT, // Optional
metadata: { source: 'chat' }, // Optional
});Search Memories
const results = await client.search({
query: 'where does the user work?',
userId: 'user_123',
types: [MemoryEntityType.FACT], // Optional filter
strategy: 'hybrid', // 'auto' | 'keyword' | 'semantic' | 'hybrid'
threshold: 0.7, // Minimum similarity (0-1)
limit: 10, // Max results
includeRelated: true, // Include related entities
});Get/Update/Delete Memory
// Get
const memory = await client.get(sessionId, memoryId);
// Update
const updated = await client.update(sessionId, memoryId, {
name: 'new_name',
properties: { updated: true },
});
// Delete
await client.delete(sessionId, memoryId);Session Operations
// Create session
const session = await client.sessions.create({
userId: 'user_123',
agentId: 'my-agent',
ttl: 86400, // 24 hours
config: {
autoExtract: true,
autoSummarize: false,
},
});
// Get session
const session = await client.sessions.get(sessionId);
// List sessions
const { data, meta } = await client.sessions.list({
userId: 'user_123',
status: MemorySessionStatus.ACTIVE,
page: 1,
limit: 20,
});
// Update session
await client.sessions.update(sessionId, {
ttl: 172800, // Extend to 48 hours
});
// Delete session
await client.sessions.delete(sessionId);Context Generation
const context = await client.getContext({
userId: 'user_123',
sessionId: 'session_abc', // Optional
query: 'What are the user preferences?', // Focus context on this
maxTokens: 4000,
includeProfile: true,
includeFacts: true,
includePreferences: true,
});
// Use in LLM prompt
const systemPrompt = `You are a helpful assistant.
Context about the user:
${context.context}`;Profile Operations
// Get profile
const profile = await client.profiles.get('user_123');
// Upsert profile
const updated = await client.profiles.upsert('user_123', {
staticFacts: {
name: 'John Doe',
timezone: 'America/New_York',
},
dynamicFacts: {
interests: ['AI', 'TypeScript'],
},
});
// Delete profile
await client.profiles.delete('user_123');Content Ingestion
URL Ingestion
const result = await client.ingest.url({
url: 'https://example.com/article',
userId: 'user_123',
sessionId: 'session_abc', // Optional
options: {
extractEntities: true,
generateEmbeddings: true,
},
});PDF Ingestion
import { readFileSync } from 'fs';
const pdfBuffer = readFileSync('document.pdf');
const result = await client.ingest.pdf({
file: pdfBuffer,
filename: 'document.pdf',
userId: 'user_123',
options: {
extractEntities: true,
generateEmbeddings: true,
},
});Text Ingestion
const result = await client.ingest.text({
content: 'Some markdown or code content',
contentType: 'markdown',
sessionId: 'session_abc',
});Graph Operations
// Get graph
const graph = await client.graph.get({
sessionId: 'session_abc',
depth: 2,
entityTypes: [MemoryEntityType.FACT, MemoryEntityType.TOPIC],
limit: 100,
});
// Traverse from entity
const related = await client.graph.traverse({
startEntityId: 'entity_xyz',
depth: 2,
direction: 'outbound',
});Error Handling
import {
MemoryError,
AuthenticationError,
ValidationError,
NotFoundError,
RateLimitError,
} from '@usetransactional/memory';
try {
await client.search({ query: 'test' });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof NotFoundError) {
console.error(`${error.resourceType} not found`);
} else if (error instanceof ValidationError) {
console.error('Validation failed:', error.fieldErrors);
} else if (error instanceof MemoryError) {
console.error(`Error ${error.code}: ${error.message}`);
}
}TypeScript Support
This SDK is written in TypeScript and provides full type definitions:
import type {
Memory,
Session,
SearchResult,
ContextResult,
MemoryEntityType,
} from '@usetransactional/memory';License
MIT
