spectre-sdk
v0.2.0
Published
TypeScript SDK for Spectre - Agent Memory & Context Persistence Service
Maintainers
Readme
Spectre SDK
TypeScript SDK for Spectre - Agent Memory & Context Persistence Service.
Give your AI agents persistent, searchable memory across conversations.
Installation
npm install spectre-sdk
# or
yarn add spectre-sdk
# or
pnpm add spectre-sdkQuick Start
import { SpectreClient } from "spectre-sdk";
// Initialize the client
const client = new SpectreClient("am_your_api_key", {
baseUrl: "https://api.spectre.ai", // or http://localhost:8080 for local dev
});
// Create an agent
const agent = await client.createAgent({
name: "my-assistant",
description: "A helpful AI assistant",
});
// Store memories
await client.store(agent.id, {
content: "User prefers dark mode and concise responses",
memory_type: "preference",
tags: ["ui", "communication"],
});
await client.store(agent.id, {
content: "User is a software engineer working on React projects",
memory_type: "fact",
tags: ["work", "skills"],
});
// Search memories semantically
const results = await client.search(agent.id, "user preferences for UI");
console.log(results[0].memory.content);
// "User prefers dark mode and concise responses"
// Get recent context for LLM prompts
const context = await client.getContext(agent.id, 10);Table of Contents
- Authentication
- Client Configuration
- Agent Management
- Memory Operations
- Search & Retrieval
- Temporal Queries
- Usage & Billing
- Error Handling
- Advanced Features
- TypeScript Types
Authentication
Getting an API Key
// Register a new account
const { api_key, user_id } = await SpectreClient.register(
"[email protected]",
"password123",
"https://api.spectre.ai" // optional, defaults to localhost
);
// Or login to existing account (returns user info, not API key)
const userInfo = await SpectreClient.login(
"[email protected]",
"password123"
);Using the API Key
const client = new SpectreClient("am_your_api_key");
// Verify your key works
const me = await client.me();
console.log(`Logged in as ${me.email} (${me.tier} tier)`);Regenerating API Keys
// Warning: This invalidates your current key!
const { api_key } = await client.regenerateApiKey();
// Save this new key - it won't be shown againClient Configuration
const client = new SpectreClient("am_your_api_key", {
// API endpoint (default: http://localhost:8080)
baseUrl: "https://api.spectre.ai",
// Request timeout in ms (default: 30000)
timeout: 60000,
// Retry configuration
retry: {
maxRetries: 3, // Number of retries (default: 3)
baseDelay: 1000, // Initial delay in ms (default: 1000)
maxDelay: 30000, // Maximum delay in ms (default: 30000)
// Status codes to retry (default: [429, 500, 502, 503, 504])
retryableStatuses: [429, 500, 502, 503, 504],
},
});Agent Management
Agents are containers for memories. Each agent has isolated storage.
Create Agent
const agent = await client.createAgent({
name: "customer-support-bot",
description: "Handles customer inquiries",
extra_data: {
department: "support",
version: "1.0",
},
});List Agents
const { agents, total } = await client.listAgents();
for (const agent of agents) {
console.log(`${agent.name}: ${agent.description}`);
}Get Agent
const agent = await client.getAgent(agentId);Update Agent
const updated = await client.updateAgent(agentId, {
name: "new-name",
description: "Updated description",
extra_data: { version: "2.0" },
});Delete Agent
// Warning: This deletes all memories for this agent!
await client.deleteAgent(agentId);Memory Operations
Store a Memory
const memory = await client.store(agentId, {
// Required: the content to remember
content: "User mentioned they're planning a trip to Japan",
// Optional: categorize the memory
memory_type: "fact", // conversation | fact | preference | task | summary | custom
// Optional: associate with a session
session_id: "chat-session-123",
// Optional: add searchable tags
tags: ["travel", "japan", "plans"],
// Optional: custom metadata
extra_data: {
source: "chat",
confidence: 0.95,
},
});Memory Types
| Type | Description | Example |
|------|-------------|---------|
| conversation | Chat messages and dialogue | "User: How do I reset my password?" |
| fact | Factual information | "User works at TechCorp as a developer" |
| preference | User preferences | "User prefers email over phone calls" |
| task | Tasks and reminders | "User needs to submit report by Friday" |
| summary | Condensed information | "Key points from last week's discussions" |
| custom | Any other type | Custom application data |
Get a Memory
const memory = await client.getMemory(agentId, memoryId);Delete a Memory
await client.delete(agentId, memoryId);Delete All Memories
// GDPR "right to be forgotten"
const { deleted_count } = await client.deleteAllMemories(agentId);
console.log(`Deleted ${deleted_count} memories`);Search & Retrieval
Semantic Search
Find memories by meaning, not just keywords:
const results = await client.search(agentId, "user preferences for notifications", {
limit: 10, // Max results (default: 10, max: 100)
min_score: 0.7, // Minimum similarity (0.0 - 1.0)
memory_type: "preference",
session_id: "session-123",
tags: ["settings"], // Must have ALL tags
});
for (const result of results) {
console.log(`[${(result.score * 100).toFixed(1)}%] ${result.memory.content}`);
}Get Recent Context
Retrieve recent memories for LLM context windows:
// Get last 20 memories
const memories = await client.getContext(agentId, 20);
// Get memories from a specific session
const sessionMemories = await client.getContext(agentId, 20, "session-123");
// Build context string for LLM
const contextString = memories
.map(m => `[${m.memory_type}] ${m.content}`)
.join("\n");Temporal Queries
Query memories by time range and filters:
const memories = await client.queryTemporal(agentId, {
// Time range
date_from: new Date("2024-01-01"),
date_to: new Date("2024-01-31"),
// Filters
memory_type: "fact",
session_id: "session-123",
tags: ["important"],
// Pagination
limit: 50,
});Usage & Billing
Get Current Usage
const usage = await client.getUsage();
console.log(`
Tier: ${usage.tier}
Memories: ${usage.total_memories} / ${usage.limits.max_memories}
API Calls: ${usage.total_api_calls} / ${usage.limits.max_api_calls}
Storage: ${(usage.total_storage_bytes / 1024 / 1024).toFixed(2)} MB
`);Get Usage History
const history = await client.getUsageHistory(6); // Last 6 months
for (const period of history.periods) {
console.log(`${period.billing_period}: ${period.api_calls_count} calls`);
}Error Handling
The SDK provides typed errors for different failure scenarios:
import {
SpectreClient,
SpectreError,
AuthenticationError,
RateLimitError,
NotFoundError,
PaymentRequiredError,
} from "spectre-sdk";
try {
await client.search(agentId, "query");
} catch (error) {
if (error instanceof AuthenticationError) {
// 401: Invalid or expired API key
console.error("Please check your API key");
} else if (error instanceof RateLimitError) {
// 429: Too many requests
console.error("Rate limited, retrying...");
} else if (error instanceof NotFoundError) {
// 404: Agent or memory not found
console.error("Resource not found");
} else if (error instanceof PaymentRequiredError) {
// 402: Tier limit exceeded
console.error("Upgrade required:", error.message);
} else if (error instanceof SpectreError) {
// Other API errors
console.error(`Error ${error.statusCode}: ${error.message}`);
}
}Advanced Features
Request Interceptors
Modify requests before they're sent:
// Add custom headers
const removeInterceptor = client.addRequestInterceptor((url, options) => {
return {
...options,
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
});
// Remove interceptor when done
removeInterceptor();Response Interceptors
Process responses before they're returned:
client.addResponseInterceptor(async (response) => {
// Log all responses
console.log(`${response.status} ${response.url}`);
return response;
});Custom Retry Configuration
// Aggressive retry for critical operations
const robustClient = new SpectreClient("am_key", {
retry: {
maxRetries: 5,
baseDelay: 500,
maxDelay: 60000,
},
});
// No retries for time-sensitive operations
const fastClient = new SpectreClient("am_key", {
retry: { maxRetries: 0 },
});TypeScript Types
All types are exported for TypeScript users:
import type {
Agent,
AgentCreateInput,
AgentUpdateInput,
Memory,
MemoryCreateInput,
MemoryType,
SearchOptions,
SearchResult,
TemporalQuery,
UsageStats,
UsageHistory,
TokenResponse,
} from "spectre-sdk";
// MemoryType values
type MemoryType = "conversation" | "fact" | "preference" | "task" | "summary" | "custom";Examples
See the examples directory for complete examples:
basic.ts- Getting started with agents and memoriesagent-workflow.ts- Multi-agent and session managementsearch-advanced.ts- Semantic search and temporal queries
API Reference
SpectreClient
| Method | Description |
|--------|-------------|
| constructor(apiKey, options?) | Create a new client |
| me() | Get current user info |
| regenerateApiKey() | Generate new API key |
| createAgent(input) | Create an agent |
| listAgents() | List all agents |
| getAgent(id) | Get agent by ID |
| updateAgent(id, input) | Update an agent |
| deleteAgent(id) | Delete an agent |
| store(agentId, input) | Store a memory |
| search(agentId, query, options?) | Semantic search |
| getContext(agentId, limit?, sessionId?) | Get recent memories |
| getMemory(agentId, memoryId) | Get memory by ID |
| delete(agentId, memoryId) | Delete a memory |
| deleteAllMemories(agentId) | Delete all memories |
| queryTemporal(agentId, query) | Temporal query |
| getUsage() | Get current usage |
| getUsageHistory(months?) | Get usage history |
| addRequestInterceptor(fn) | Add request interceptor |
| addResponseInterceptor(fn) | Add response interceptor |
Static Methods
| Method | Description |
|--------|-------------|
| SpectreClient.register(email, password, baseUrl?) | Register new account |
| SpectreClient.login(email, password, baseUrl?) | Login to account |
License
MIT
