TypeScript SDK for Spectre - Agent Memory & Context Persistence Service
npm install spectre-sdkTypeScript SDK for Spectre - Agent Memory & Context Persistence Service.
Give your AI agents persistent, searchable memory across conversations.
``bash`
npm install spectre-sdkor
yarn add spectre-sdkor
pnpm add spectre-sdk
`typescript
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);
`
- Authentication
- Client Configuration
- Agent Management
- Memory Operations
- Search & Retrieval
- Temporal Queries
- Usage & Billing
- Error Handling
- Advanced Features
- TypeScript Types
`typescript
// Register a new account
const { api_key, user_id } = await SpectreClient.register(
"user@example.com",
"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(
"user@example.com",
"password123"
);
`
`typescript
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));`
`typescript`
// Warning: This invalidates your current key!
const { api_key } = await client.regenerateApiKey();
// Save this new key - it won't be shown again
`typescript
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],
},
});
`
Agents are containers for memories. Each agent has isolated storage.
`typescript`
const agent = await client.createAgent({
name: "customer-support-bot",
description: "Handles customer inquiries",
extra_data: {
department: "support",
version: "1.0",
},
});
`typescript${agent.name}: ${agent.description}
const { agents, total } = await client.listAgents();
for (const agent of agents) {
console.log();`
}
`typescript`
const agent = await client.getAgent(agentId);
`typescript`
const updated = await client.updateAgent(agentId, {
name: "new-name",
description: "Updated description",
extra_data: { version: "2.0" },
});
`typescript`
// Warning: This deletes all memories for this agent!
await client.deleteAgent(agentId);
`typescript
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,
},
});
`
| 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 |
`typescript`
const memory = await client.getMemory(agentId, memoryId);
`typescript`
await client.delete(agentId, memoryId);
`typescriptDeleted ${deleted_count} memories
// GDPR "right to be forgotten"
const { deleted_count } = await client.deleteAllMemories(agentId);
console.log();`
Find memories by meaning, not just keywords:
`typescript
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});`
}
Retrieve recent memories for LLM context windows:
`typescript
// 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");
Query memories by time range and filters:
`typescript
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,
});
`
`typescript
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);`
`typescript${period.billing_period}: ${period.api_calls_count} calls
const history = await client.getUsageHistory(6); // Last 6 months
for (const period of history.periods) {
console.log();`
}
The SDK provides typed errors for different failure scenarios:
`typescript
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});`
}
}
Modify requests before they're sent:
`typescript
// Add custom headers
const removeInterceptor = client.addRequestInterceptor((url, options) => {
return {
...options,
headers: {
...options.headers,
"X-Custom-Header": "value",
},
};
});
// Remove interceptor when done
removeInterceptor();
`
Process responses before they're returned:
`typescript${response.status} ${response.url}
client.addResponseInterceptor(async (response) => {
// Log all responses
console.log();`
return response;
});
`typescript
// 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 },
});
`
All types are exported for TypeScript users:
`typescript
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";
`
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
| 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 |
| Method | Description |
|--------|-------------|
| SpectreClient.register(email, password, baseUrl?) | Register new account |SpectreClient.login(email, password, baseUrl?)` | Login to account |
|
MIT