Skip to main content

JavaScript API

The JavaScript API provides client-side integration for web applications, with React components for visualization and user interfaces.

Installation

# Using npm
npm install reeflect reeflect-react

# Using yarn
yarn add reeflect reeflect-react

Core Classes

Reeflect

Main client class for interacting with the memory system.

Memory

Represents a memory object with content and metadata.

MemoryProvider

React context provider for accessing memory throughout an application.

MemoryComponents

React components for visualization and interaction with memories.

Basic Usage

Initialization

import { Reeflect } from 'reeflect';

// Initialize the client
const memory = new Reeflect({
apiKey: 'your_api_key',
endpoint: 'https://api.reeflect.ai/v1'
});

Memory Operations

// Create a memory
const memoryId = await memory.create({
content: 'The user prefers dark mode in all applications.',
namespace: 'user_preferences',
importance: 0.8,
tags: ['ui', 'theme', 'preference']
});

// Retrieve a memory
const memoryObj = await memory.retrieve(memoryId);

// Search memories
const searchResults = await memory.search({
query: 'What theme does the user prefer?',
namespace: 'user_preferences',
limit: 5
});

// Update a memory
await memory.update(memoryId, {
content: 'The user prefers dark mode for desktop, light mode for mobile.',
importance: 0.9
});

// Delete a memory
await memory.delete(memoryId);

Chat Integration

// Enhance a prompt with memories
const enhancedPrompt = await memory.enhancePrompt({
prompt: 'What theme should I use for the dashboard?',
namespace: 'user_preferences',
maxMemories: 3
});

// Using with OpenAI client
import { OpenAI } from 'openai';

const openai = new OpenAI({
apiKey: 'your_openai_api_key'
});

const response = await openai.chat.completions.create({
model: 'gpt-4-turbo-preview',
messages: [
{ role: 'system', content: 'You are a helpful assistant with memory.' },
{ role: 'user', content: enhancedPrompt }
]
});

React Components

MemoryProvider

// App.jsx
import React from 'react';
import { MemoryProvider } from 'reeflect-react';

const App = () => {
return (
<MemoryProvider
apiKey="your_api_key"
endpoint="https://api.reeflect.ai/v1"
defaultNamespace="user_preferences"
>
<YourApp />
</MemoryProvider>
);
};

// Component using memory
import { useMemory } from 'reeflect-react';

const UserPreferences = () => {
const { memories, isLoading, error, search } = useMemory();

React.useEffect(() => {
// Search for relevant memories on component mount
search({
query: 'ui preferences',
limit: 10
});
}, [search]);

if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<div>
<h2>User Preferences</h2>
<ul>
{memories.map(memory => (
<li key={memory.id}>
{memory.content}
<span className="badge">{memory.importance.toFixed(1)}</span>
</li>
))}
</ul>
</div>
);
};

MemoryGraph Component

import { MemoryGraph } from 'reeflect-react';

const MemoryVisualizer = () => {
const [selectedNode, setSelectedNode] = React.useState(null);

const handleNodeClick = (node) => {
setSelectedNode(node);
};

return (
<div className="memory-visualizer">
<h2>Memory Network</h2>

<MemoryGraph
namespace="user_preferences"
width={800}
height={600}
layout="force-directed"
colorBy="namespace"
sizeBy="importance"
onNodeClick={handleNodeClick}
/>

{selectedNode && (
<div className="node-details">
<h3>Memory Details</h3>
<p><strong>Content:</strong> {selectedNode.content}</p>
<p><strong>Importance:</strong> {selectedNode.importance.toFixed(2)}</p>
<p><strong>Created:</strong> {new Date(selectedNode.created_at).toLocaleString()}</p>
</div>
)}
</div>
);
};

MemoryChat Component

import { MemoryChat } from 'reeflect-react';

const ChatApp = () => {
const [messages, setMessages] = React.useState([]);

const handleNewMessage = (message) => {
setMessages((prev) => [...prev, message]);
};

return (
<div className="chat-container">
<h2>Memory-Enhanced Chat</h2>

<MemoryChat
messages={messages}
onNewMessage={handleNewMessage}
namespace="user_chat"
extractMemories={true}
showMemoryIndicator={true}
enhancePrompts={true}
model="gpt-4-turbo-preview"
systemPrompt="You are a helpful assistant with memory of past interactions."
/>

<div className="memory-explorer">
<h3>Recent Memories</h3>
<MemoryExplorer
namespace="user_chat"
limit={5}
sortBy="created_at"
order="desc"
/>
</div>
</div>
);
};

ReasoningPlayground Component

import { ReasoningPlayground } from 'reeflect-react';

const PlaygroundDemo = () => {
const [query, setQuery] = React.useState('What are the user\'s ui preferences?');

return (
<div className="playground-container">
<h2>Memory Reasoning Playground</h2>

<div className="controls">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Enter your query"
className="query-input"
/>
<button onClick={() => setQuery(query)}>Reason</button>
</div>

<ReasoningPlayground
query={query}
namespace="user_preferences"
showConfidence={true}
enableMemoryManipulation={true}
height={600}
/>
</div>
);
};

Advanced Usage

Custom Memory Hooks

import { createMemoryHook } from 'reeflect-react';

// Create a custom hook for a specific use case
const useUserPreferences = createMemoryHook({
namespace: 'user_preferences',
defaultQuery: 'ui preferences',
defaultLimit: 20,
refreshInterval: 60000, // Auto-refresh every minute
transformResult: (memories) => {
// Transform memories into a more usable format
return memories.reduce((acc, memory) => {
// Extract key-value pairs from memory content
const match = memory.content.match(/([^:]+):\s*(.+)/);
if (match) {
const [_, key, value] = match;
acc[key.trim().toLowerCase()] = value.trim();
}
return acc;
}, {});
}
});

Memory Mutations

import { useMemoryMutations } from 'reeflect-react';

const PreferenceEditor = () => {
const [content, setContent] = React.useState('');
const [importance, setImportance] = React.useState(0.7);
const [tags, setTags] = React.useState(['ui']);

const { createMemory, updateMemory, deleteMemory, isLoading, error } = useMemoryMutations();

const handleSubmit = async (e) => {
e.preventDefault();

try {
const memoryId = await createMemory({
content,
namespace: 'user_preferences',
importance,
tags
});

console.log('Created memory:', memoryId);
setContent('');
} catch (err) {
console.error('Error creating memory:', err);
}
};

return (
<form onSubmit={handleSubmit}>
<h3>Add Preference</h3>

<div className="form-group">
<label>Preference:</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Enter user preference..."
required
/>
</div>

<div className="form-group">
<label>Importance ({importance}):</label>
<input
type="range"
min="0"
max="1"
step="0.1"
value={importance}
onChange={(e) => setImportance(parseFloat(e.target.value))}
/>
</div>

<div className="form-group">
<label>Tags:</label>
<input
type="text"
value={tags.join(', ')}
onChange={(e) => setTags(e.target.value.split(',').map(t => t.trim()))}
placeholder="ui, theme, etc."
/>
</div>

<button type="submit" disabled={isLoading}>
{isLoading ? 'Saving...' : 'Save Preference'}
</button>

{error && <div className="error">Error: {error.message}</div>}
</form>
);
};

Full API Reference

For complete documentation of all JavaScript API classes, components, and hooks, please refer to the full JavaScript API reference.

Next Steps

Learn how to use the JavaScript API in specific scenarios: