@cilow/sdk
v0.2.1
Published
Complete TypeScript SDK for Cilow - AI Memory Infrastructure with multi-framework support
Maintainers
Readme
@cilow/sdk
Complete TypeScript SDK for Cilow - AI Memory Infrastructure with multi-framework support.
Installation
npm install @cilow/sdk
# or
yarn add @cilow/sdk
# or
pnpm add @cilow/sdkQuick Start
import { Cilow } from '@cilow/sdk';
const cilow = new Cilow({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-api-key'
});
// Store a memory
await cilow.remember("User prefers dark mode", { tags: ["preference", "ui"] });
// Search memories
const memories = await cilow.recall("user preferences");
// Delete memories
await cilow.forget({ tags: ["temporary"] });Features
- Simple API:
remember,recall,forgetfor easy memory management - Full TypeScript Support: Complete type definitions for all APIs
- Framework Integrations: Vercel AI SDK, OpenAI, LangChain
- React Hooks:
useMemory,useRecall,useMemoryContext - WebSocket Support: Real-time memory updates and graph changes
- Multi-tier Memory: Hot, warm, cold memory tiers for optimal performance
Core Client
Basic Operations
import { Cilow } from '@cilow/sdk';
const cilow = new Cilow({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-api-key'
});
// Store a memory
const memoryId = await cilow.remember("Important information", {
tags: ["important"],
userId: "user-123",
metadata: { source: "chat" }
});
// Search memories with semantic similarity
const results = await cilow.recall("important information", {
limit: 10,
minRelevance: 0.5,
tags: ["important"]
});
// Delete memories
await cilow.forget({ memoryId: "mem-123" });
await cilow.forget({ tags: ["old"], userId: "user-123" });Advanced Operations
// Get a specific memory
const memory = await cilow.getMemory("mem-123");
// Update a memory
const updated = await cilow.updateMemory("mem-123", {
content: "Updated content",
tags: ["updated"]
});
// List memories with pagination
const list = await cilow.listMemories({
limit: 20,
offset: 0,
userId: "user-123",
tags: ["preference"]
});
// Get context for AI prompts
const context = await cilow.getContext("recent discussions", {
maxTokens: 2000,
userId: "user-123"
});
// Store conversation turns
await cilow.storeConversation({
userMessage: "What's the weather?",
assistantResponse: "The weather is sunny today.",
userId: "user-123",
sessionId: "session-abc"
});
// Get statistics
const stats = await cilow.getStats();
console.log(`Total memories: ${stats.totalMemories}`);Graph Operations
// Create graph nodes
const node = await cilow.createGraphNode("Person", "John Doe", {
email: "[email protected]"
});
// Create relationships
const edge = await cilow.createGraphEdge(
node.id,
"other-node-id",
"KNOWS",
{ since: "2024" }
);
// Traverse the graph
const subgraph = await cilow.traverseGraph({
startNodeId: node.id,
maxDepth: 3,
relationshipTypes: ["KNOWS", "WORKS_WITH"]
});Vercel AI SDK Integration
import { createCilowTools, createCilowContext } from '@cilow/sdk/providers/vercel';
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
// Create tools for AI to use
const tools = createCilowTools({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-key',
defaultUserId: 'user-123'
});
// Use with streamText
const result = await streamText({
model: anthropic('claude-sonnet-4-20250514'),
tools,
messages: [
{ role: 'user', content: 'What do you remember about me?' }
]
});
// Or use context injection
const getContext = createCilowContext({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-key',
maxTokens: 2000
});
const context = await getContext('previous discussions');
const response = await streamText({
model: anthropic('claude-sonnet-4-20250514'),
system: `You are a helpful assistant.\n\nContext:\n${context.context}`,
prompt: 'Continue our discussion'
});Context Middleware
import { createContextMiddleware } from '@cilow/sdk/providers/vercel';
const withMemory = createContextMiddleware({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-key'
});
// Automatically inject memory context
const messagesWithContext = await withMemory(originalMessages, {
userId: 'user-123',
maxTokens: 2000
});OpenAI SDK Integration
import OpenAI from 'openai';
import { createCilowOpenAI } from '@cilow/sdk/providers/openai';
const openai = new OpenAI();
const cilowAI = createCilowOpenAI(openai, {
apiUrl: 'https://api.cilow.ai',
apiKey: 'cilow-key',
autoStore: true // Automatically store conversations
});
// Memory context is automatically injected
const { completion, memoriesUsed } = await cilowAI.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'user', content: 'Based on our previous discussions, what should I focus on?' }
]
});
console.log(`Used ${memoriesUsed} memories for context`);
console.log(completion.choices[0].message.content);
// Direct memory access
await cilowAI.remember("Important insight", { tags: ["insight"] });
const memories = await cilowAI.recall("insights");LangChain Integration
Memory Class
import { CilowMemory } from '@cilow/sdk/providers/langchain';
import { ConversationChain } from 'langchain/chains';
import { ChatOpenAI } from '@langchain/openai';
const memory = new CilowMemory({
apiUrl: 'https://api.cilow.ai',
apiKey: 'cilow-key',
userId: 'user-123',
sessionId: 'session-abc'
});
const chain = new ConversationChain({
llm: new ChatOpenAI(),
memory
});
const response = await chain.call({
input: 'What did we discuss last time?'
});Retriever for RAG
import { CilowRetriever } from '@cilow/sdk/providers/langchain';
import { RetrievalQAChain } from 'langchain/chains';
const retriever = new CilowRetriever({
apiUrl: 'https://api.cilow.ai',
apiKey: 'cilow-key',
topK: 5
});
const chain = RetrievalQAChain.fromLLM(
new ChatOpenAI(),
retriever
);
const answer = await chain.call({
query: 'What are the key points from our meetings?'
});Vector Store
import { CilowVectorStore } from '@cilow/sdk/providers/langchain';
const vectorStore = new CilowVectorStore({
apiUrl: 'https://api.cilow.ai',
apiKey: 'cilow-key'
});
// Add documents
await vectorStore.addDocuments([
{ pageContent: 'Meeting notes from Monday', metadata: { topic: 'standup' } },
{ pageContent: 'Product requirements document', metadata: { topic: 'product' } }
]);
// Similarity search
const results = await vectorStore.similaritySearch('standup notes', 5);
// With scores
const resultsWithScores = await vectorStore.similaritySearchWithScore('standup notes');React Hooks
import {
CilowProvider,
useMemory,
useRecall,
useMemoryContext,
useMemorySubscription,
useDebouncedSearch
} from '@cilow/sdk/react';
// Wrap your app with the provider
function App() {
return (
<CilowProvider
apiUrl="https://api.cilow.ai"
apiKey="your-key"
userId="user-123"
enableWebSocket={true}
>
<YourApp />
</CilowProvider>
);
}
// Use memory operations
function MemoryManager() {
const { remember, forget, isLoading, error } = useMemory();
const handleSave = async () => {
await remember("Important note", { tags: ["note"] });
};
return (
<button onClick={handleSave} disabled={isLoading}>
Save Memory
</button>
);
}
// Search memories
function SearchComponent() {
const { data, search, isLoading } = useRecall();
const handleSearch = () => {
search("user preferences", { limit: 10 });
};
return (
<div>
<button onClick={handleSearch}>Search</button>
{data.map(result => (
<div key={result.memory.id}>
<p>{result.memory.content}</p>
<span>Score: {(result.score * 100).toFixed(0)}%</span>
</div>
))}
</div>
);
}
// Debounced search
function LiveSearch() {
const { query, setQuery, results, isLoading } = useDebouncedSearch({
delay: 300,
minLength: 2
});
return (
<div>
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search memories..."
/>
{isLoading && <p>Searching...</p>}
{results.map(r => (
<div key={r.memory.id}>{r.memory.content}</div>
))}
</div>
);
}
// Get context for AI
function ChatWithContext() {
const { getContext, isLoading } = useMemoryContext();
const sendMessage = async (message: string) => {
const { context, memoriesUsed } = await getContext(message);
// Use context with your AI provider
const response = await callAI({
system: `Context:\n${context}`,
message
});
};
return <ChatUI onSend={sendMessage} />;
}
// Real-time updates
function LiveMemoryFeed() {
const { latestEvent, events, isConnected } = useMemorySubscription({
userId: 'user-123',
eventTypes: ['memory.created', 'memory.updated']
});
useEffect(() => {
if (latestEvent?.type === 'memory.created') {
console.log('New memory:', latestEvent.memory);
}
}, [latestEvent]);
return (
<div>
<p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
<p>Events: {events.length}</p>
</div>
);
}WebSocket Support
import { CilowWebSocket } from '@cilow/sdk/websocket';
const ws = new CilowWebSocket({
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-key',
reconnectAttempts: 5,
heartbeatInterval: 30000
});
// Connect
await ws.connect();
// Subscribe to events
ws.subscribe({ userId: 'user-123' });
// Listen for memory events
ws.onMemoryCreated((event) => {
console.log('New memory:', event.memory);
});
ws.onMemoryUpdated((event) => {
console.log('Updated memory:', event.memory);
});
ws.onMemoryDeleted((event) => {
console.log('Deleted memory ID:', event.memoryId);
});
// Listen for graph events
ws.onGraphNodeCreated((event) => {
console.log('New node:', event.node);
});
// Connection status
ws.onConnectionStatus((event) => {
console.log('Connection:', event.status, event.reason);
});
// Wait for specific event
const event = await ws.once('memory.created', 5000);
// Disconnect
ws.disconnect();TypeScript Types
The SDK exports comprehensive TypeScript types:
import type {
// Core types
Memory,
MemorySummary,
MemoryTier,
SearchResult,
// Graph types
GraphNode,
GraphEdge,
GraphSubgraph,
// Event types
CilowEvent,
MemoryCreatedEvent,
MemoryUpdatedEvent,
// Configuration
CilowConfig,
WebSocketConfig,
// API types
PaginatedResponse,
ContextResult,
} from '@cilow/sdk';Error Handling
import { CilowApiError, isApiError } from '@cilow/sdk';
try {
await cilow.getMemory('invalid-id');
} catch (error) {
if (error instanceof CilowApiError) {
console.log('API Error:', error.message);
console.log('Code:', error.code);
console.log('Status:', error.statusCode);
console.log('Details:', error.details);
}
}Configuration Options
const cilow = new Cilow({
// Required
apiUrl: 'https://api.cilow.ai',
apiKey: 'your-api-key',
// Optional
timeout: 30000, // Request timeout (ms)
retries: 3, // Retry attempts
debug: false, // Enable debug logging
headers: { // Custom headers
'X-Custom-Header': 'value'
}
});License
MIT
