mnemonic-sdk
v0.2.0
Published
Official JavaScript/TypeScript SDK for Mnemonic - Persistent cognitive infrastructure for AI agents
Maintainers
Readme
Mnemonic JavaScript/TypeScript SDK
Official SDK for Mnemonic - Persistent cognitive infrastructure for AI agents.
Features
✅ Full TypeScript support - Complete type definitions and auto-complete
✅ Works everywhere - Node.js, Browser, Serverless
✅ v2 Network Effects - Quality scoring, effectiveness tracking, analytics
✅ Zero dependencies - Uses native fetch API
✅ Promise-based - Modern async/await API
Installation
npm install @mnemonic-ai/sdkOr with yarn:
yarn add @mnemonic-ai/sdkQuick Start
import { Mnemonic } from '@mnemonic-ai/sdk';
const mnemonic = new Mnemonic({
apiKey: 'mnemo_sk_...' // or set MNEMO_API_KEY env var
});
// 1. Create an agent
const agent = await mnemonic.createAgent({
externalId: 'my-agent',
name: 'Production Agent'
});
// 2. Recall lessons before task
const memory = await mnemonic.recall({
agentId: agent.id,
task: 'Deploy FastAPI to Railway',
limit: 5
});
console.log(`Found ${memory.lessons.length} relevant lessons`);
// 3. Agent executes task
// ... your agent code ...
// 4. Capture event after task
await mnemonic.capture({
agentId: agent.id,
task: 'Deploy FastAPI to Railway',
actions: [
{ type: 'create_file', target: 'railway.json', result: 'success' },
{ type: 'deploy', target: 'Railway', result: 'deployed' }
],
output: 'Successfully deployed!',
success: true,
timeTaken: 300000 // 5 minutes
});Configuration
Basic Setup
import { Mnemonic } from '@mnemonic-ai/sdk';
const mnemonic = new Mnemonic({
apiKey: 'mnemo_sk_...', // Required (or MNEMO_API_KEY env var)
baseUrl: 'https://api.mnemo.dev', // Optional (default shown)
timeout: 30000 // Optional, in milliseconds (default: 30s)
});Environment Variables
# .env
MNEMO_API_KEY=mnemo_sk_your_key_hereThen just:
const mnemonic = new Mnemonic(); // Auto-loads from envCore Methods
recall()
Retrieve relevant lessons before task execution.
const memory = await mnemonic.recall({
agentId: 'agent-123',
task: 'Optimize database queries',
limit: 5, // Optional, default: 5
minConfidence: 0.6, // Optional, default: 0.6
asPrompt: false // Optional, return formatted prompt
});
// Response
memory.lessons.forEach(lesson => {
console.log(`[${lesson.qualityScore?.toFixed(2)}] ${lesson.content}`);
console.log(` Source: ${lesson.source}`); // 'own' | 'team' | 'global'
});capture()
Record agent execution for reflection.
await mnemonic.capture({
agentId: 'agent-123',
task: 'Optimize database queries',
actions: [
{ type: 'analyze', target: 'queries.sql', result: 'slow queries found' },
{ type: 'optimize', target: 'user_query', result: 'added index' }
],
output: 'Query time reduced from 2s to 0.1s',
success: true,
timeTaken: 120000, // Optional, milliseconds
retries: 0, // Optional, default: 0
metadata: { // Optional
queriesOptimized: 3,
indexesAdded: 2
}
});Agent Management
createAgent()
const agent = await mnemonic.createAgent({
externalId: 'prod-agent-1',
name: 'Production Agent',
description: 'Main production agent',
metadata: { environment: 'production' }
});listAgents()
const agents = await mnemonic.listAgents();getAgentStats()
const stats = await mnemonic.getAgentStats('agent-123');
console.log(`Success rate: ${stats.successRate}%`);v2 Network Effects
reportLessonEffectiveness()
Track when lessons help (or don't).
// After using lessons from recall()
await mnemonic.reportLessonEffectiveness({
lessonId: 'lesson-uuid',
agentId: 'agent-123',
task: 'Deploy to Railway',
outcome: 'success', // 'success' | 'failure' | 'partial'
improvementMetrics: {
timeSavedMs: 1800000, // 30 minutes saved
retriesReduced: 2,
errorsAvoided: 1
}
});getLessonAnalytics()
Get quality metrics for a lesson.
const analytics = await mnemonic.getLessonAnalytics('lesson-uuid');
console.log(`
Lesson: ${analytics.content}
Quality Score: ${analytics.qualityScore}/1.00
Usage Count: ${analytics.usageCount}
Success Rate: ${(analytics.successRate * 100).toFixed(0)}%
`);getNetworkEffectsStats()
See the global knowledge network in action.
const stats = await mnemonic.getNetworkEffectsStats();
console.log(`
📊 NETWORK EFFECTS
Total Lessons: ${stats.totalLessons.toLocaleString()}
├─ Public: ${stats.publicLessons.toLocaleString()}
└─ Private: ${stats.privateLessons.toLocaleString()}
Cross-Tenant Learnings: ${stats.crossTenantLearningEvents.toLocaleString()}
Avg Quality: ${(stats.avgQualityScore * 100).toFixed(0)}%
🏆 TOP LESSON:
${stats.topLessons[0].content}
Quality: ${stats.topLessons[0].qualityScore.toFixed(2)}
`);Complete Example: Agent with Network Effects
import { Mnemonic } from '@mnemonic-ai/sdk';
const mnemonic = new Mnemonic({ apiKey: process.env.MNEMO_API_KEY });
async function runAgentTask() {
// 1. Create agent
const agent = await mnemonic.createAgent({
externalId: 'deployment-agent',
name: 'Deployment Agent'
});
// 2. Recall relevant lessons
const memory = await mnemonic.recall({
agentId: agent.id,
task: 'Deploy Next.js to Vercel',
limit: 5
});
console.log(`\n📚 Found ${memory.lessons.length} lessons:`);
memory.lessons.forEach((lesson, i) => {
const quality = lesson.qualityScore || 0.5;
const emoji = quality > 0.8 ? '🟢' : quality > 0.6 ? '🟡' : '🔴';
console.log(`${emoji} [${quality.toFixed(2)}] ${lesson.content.substring(0, 60)}...`);
});
// 3. Execute task (your agent logic)
const startTime = Date.now();
let success = true;
let output = '';
try {
// ... your deployment logic ...
output = 'Successfully deployed to Vercel';
} catch (error) {
success = false;
output = error.message;
}
const timeTaken = Date.now() - startTime;
// 4. Capture execution
await mnemonic.capture({
agentId: agent.id,
task: 'Deploy Next.js to Vercel',
actions: [
{ type: 'build', target: 'Next.js', result: 'success' },
{ type: 'deploy', target: 'Vercel', result: 'deployed' }
],
output,
success,
timeTaken
});
// 5. Report lesson effectiveness (v2)
for (const lesson of memory.lessons) {
if (lesson.source !== 'own') { // Track shared lessons
await mnemonic.reportLessonEffectiveness({
lessonId: lesson.id,
agentId: agent.id,
task: 'Deploy Next.js to Vercel',
outcome: success ? 'success' : 'failure',
improvementMetrics: {
timeSavedMs: success ? timeTaken * 0.3 : 0 // Estimate 30% faster
}
});
}
}
// 6. Check network effects
const stats = await mnemonic.getNetworkEffectsStats();
console.log(`\n🌐 Learning from ${stats.crossTenantLearningEvents} cross-company experiences!`);
}
runAgentTask().catch(console.error);TypeScript Support
Full TypeScript support with comprehensive type definitions:
import {
Mnemonic,
RecallResponse,
LessonHit,
LessonAnalytics,
NetworkEffectsStats
} from '@mnemonic-ai/sdk';
const mnemonic = new Mnemonic({ apiKey: '...' });
// All methods are fully typed
const memory: RecallResponse = await mnemonic.recall({
agentId: 'agent-123',
task: 'Deploy app'
});
// Auto-complete works everywhere
memory.lessons.forEach((lesson: LessonHit) => {
console.log(lesson.content); // ✓ Type-safe
console.log(lesson.qualityScore); // ✓ Optional property
});Error Handling
import {
Mnemonic,
AuthError,
NotFoundError,
RateLimitError,
MnemonicError
} from '@mnemonic-ai/sdk';
try {
await mnemonic.recall({ ... });
} catch (error) {
if (error instanceof AuthError) {
console.error('Invalid API key');
} else if (error instanceof NotFoundError) {
console.error('Agent not found');
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded');
} else if (error instanceof MnemonicError) {
console.error(`API error: ${error.message}`);
} else {
console.error('Unknown error:', error);
}
}React/Next.js Example
// hooks/useMnemonic.ts
import { Mnemonic } from '@mnemonic-ai/sdk';
import { useMemo } from 'react';
export function useMnemonic() {
return useMemo(
() => new Mnemonic({ apiKey: process.env.NEXT_PUBLIC_MNEMO_API_KEY }),
[]
);
}
// components/AgentDashboard.tsx
import { useMnemonic } from '@/hooks/useMnemonic';
import { useEffect, useState } from 'react';
export function AgentDashboard() {
const mnemonic = useMnemonic();
const [stats, setStats] = useState(null);
useEffect(() => {
mnemonic.getNetworkEffectsStats()
.then(setStats)
.catch(console.error);
}, [mnemonic]);
if (!stats) return <div>Loading...</div>;
return (
<div>
<h1>Network Effects</h1>
<p>Total Lessons: {stats.totalLessons.toLocaleString()}</p>
<p>Cross-Tenant: {stats.crossTenantLearningEvents.toLocaleString()}</p>
</div>
);
}Node.js Serverless Example
// Vercel/Netlify/AWS Lambda
import { Mnemonic } from '@mnemonic-ai/sdk';
export default async function handler(req, res) {
const mnemonic = new Mnemonic({
apiKey: process.env.MNEMO_API_KEY
});
const memory = await mnemonic.recall({
agentId: req.body.agentId,
task: req.body.task
});
return res.json(memory);
}Browser Example
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { Mnemonic } from 'https://cdn.jsdelivr.net/npm/@mnemonic-ai/sdk/+esm';
const mnemonic = new Mnemonic({ apiKey: 'mnemo_sk_...' });
const memory = await mnemonic.recall({
agentId: 'browser-agent',
task: 'Help user with task'
});
console.log('Lessons:', memory.lessons);
</script>
</head>
<body>
<h1>Mnemonic Browser Demo</h1>
</body>
</html>API Reference
Core Methods
| Method | Description |
|--------|-------------|
| recall(request) | Retrieve relevant lessons/procedures |
| capture(request) | Record agent execution |
Agent Management
| Method | Description |
|--------|-------------|
| createAgent(request) | Create new agent |
| listAgents() | List all agents |
| getAgentStats(agentId) | Get agent statistics |
Lessons & Procedures
| Method | Description |
|--------|-------------|
| listLessons(agentId?, limit?) | List lessons |
| listProcedures(agentId?) | List procedures |
| submitFeedback(request) | Submit feedback |
v2 Network Effects
| Method | Description |
|--------|-------------|
| reportLessonEffectiveness(request) | Track lesson outcomes |
| getLessonAnalytics(lessonId) | Get lesson quality metrics |
| getNetworkEffectsStats() | Get global network stats |
License
MIT
Links
Support
For questions or issues:
- GitHub Issues: https://github.com/Nirvana3339/mnemonic/issues
- Email: [email protected]
Built with ❤️ for the AI agent ecosystem
