Reference
API Reference
Complete reference for every Memory class method with parameters, return types, and working examples.
Memory Class
The Memory class is your main entry point for all Memcity operations.
Constructor
import { Memory } from "memcity";
import { components } from "./_generated/api";
const memory = new Memory(components.memcity, config);| Parameter | Type | Description |
|---|---|---|
component | UseApi<typeof ComponentApi> | The installed Memcity Convex component |
config | MemoryConfig | Configuration object (see Configuration) |
Core Methods (All Tiers)
memory.createOrg(ctx, options)
Create a top-level organization container. All knowledge bases, users, and quotas belong to an org.
const orgId = await memory.createOrg(ctx, {
name: "Acme Corp",
});| Param | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Organization display name |
Returns: string — the organization ID.
memory.createKnowledgeBase(ctx, options)
Create a knowledge base — a container for related documents. Community tier is limited to 1 KB.
const kbId = await memory.createKnowledgeBase(ctx, {
orgId: "org_abc123",
name: "Product Documentation",
description: "All product docs, guides, and tutorials",
});| Param | Type | Required | Description |
|---|---|---|---|
orgId | string | Yes | Parent organization ID |
name | string | Yes | KB display name |
description | string | No | What this KB contains |
Returns: string — the knowledge base ID.
memory.ingestText(ctx, options)
Ingest plain text content. The text is automatically chunked, embedded, and indexed.
await memory.ingestText(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
text: "Your document content here...",
source: "document.md",
});| Param | Type | Required | Description |
|---|---|---|---|
orgId | string | Yes | Organization ID |
knowledgeBaseId | string | Yes | Target knowledge base |
text | string | Yes | The content to ingest |
source | string | No | Source identifier (used in citations) |
principals | string[] | No | ACL principals (Team tier) |
Returns: { documentId: string, chunkCount: number }
memory.getContext(ctx, options)
Search a knowledge base using the full RAG pipeline. This is the main search method.
const results = await memory.getContext(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
query: "How does authentication work?",
});| Param | Type | Required | Description |
|---|---|---|---|
orgId | string | Yes | Organization ID |
knowledgeBaseId | string | No | Filter to specific KB (omit for all) |
query | string | Yes | The search query |
userId | string | No | User ID for episodic memory (Pro+) |
conversationId | string | No | Conversation context (Pro+) |
principals | string[] | No | User's ACL principals (Team) |
config | Partial<MemoryConfig> | No | Override config for this search |
Returns: ContextResult
interface ContextResult {
results: Array<{
text: string; // The matching text content
score: number; // Relevance score (0-1)
confidence: number; // Confidence level (0-1)
source: string; // Source document identifier
documentId: string; // Convex document ID
chunkId: string; // Specific chunk ID
citations: {
source: string; // File name
heading: string; // Section heading breadcrumb
page: number; // Page number (if applicable)
lineStart: number; // Starting line
lineEnd: number; // Ending line
} | null;
}>;
queryType: "simple" | "moderate" | "complex";
fromCache: boolean; // Whether embedding was cached
timings: {
total: number; // Total pipeline time (ms)
embedding: number; // Embedding generation time
search: number; // Vector + BM25 search time
reranking: number; // Reranker time
graph: number; // GraphRAG traversal time
};
}Example with all options:
const results = await memory.getContext(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
query: "What are the deployment requirements?",
userId: "user_456", // Include episodic memories
conversationId: "conv_789", // Include conversation context
principals: ["user:alice", "role:engineer"], // ACL filter
config: {
search: { maxResults: 5, reranking: true },
},
});
for (const result of results.results) {
console.log(`[${result.confidence.toFixed(2)}] ${result.text}`);
if (result.citations) {
console.log(` Source: ${result.citations.source} > ${result.citations.heading}`);
}
}Pro Methods
memory.ingestUrl(ctx, options)
Ingest content from a URL. The page is fetched, text is extracted, and it goes through the standard ingestion pipeline.
await memory.ingestUrl(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
url: "https://docs.example.com/api-reference",
});| Param | Type | Required | Description |
|---|---|---|---|
orgId | string | Yes | Organization ID |
knowledgeBaseId | string | Yes | Target knowledge base |
url | string | Yes | The URL to fetch and ingest |
SSRF protection blocks internal IPs (127.0.0.1, 10.x.x.x, 192.168.x.x).
memory.getUploadUrl(ctx)
Get a presigned URL for uploading a file to Convex storage.
const uploadUrl = await memory.getUploadUrl(ctx);
// Use this URL to POST the file from your frontendReturns: string — a temporary upload URL valid for ~1 hour.
memory.processUploadedFile(ctx, options)
Process a previously uploaded file. Supports 25+ file types.
const result = await memory.processUploadedFile(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
storageId: "storage_abc", // From the upload step
fileName: "report.pdf",
});
// { success: true, chunkCount: 47, documentId: "doc_xyz" }| Param | Type | Required | Description |
|---|---|---|---|
orgId | string | Yes | Organization ID |
knowledgeBaseId | string | Yes | Target knowledge base |
storageId | Id<"_storage"> | Yes | Convex storage ID from upload |
fileName | string | Yes | Original file name (used for type detection) |
memory.batchIngest(ctx, options)
Ingest multiple text documents in a single call.
await memory.batchIngest(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
documents: [
{ text: "First document...", source: "doc1.md" },
{ text: "Second document...", source: "doc2.md" },
{ text: "Third document...", source: "doc3.md" },
],
});memory.addMemory(ctx, options)
Add an episodic memory for a user. See Episodic Memory.
await memory.addMemory(ctx, {
orgId: "org_abc123",
userId: "user_456",
content: "Prefers TypeScript over JavaScript",
type: "preference", // "preference" | "fact" | "context" | "summary"
});memory.listMemories(ctx, options)
List all episodic memories for a user, sorted by strength.
const memories = await memory.listMemories(ctx, {
orgId: "org_abc123",
userId: "user_456",
});
for (const mem of memories) {
console.log(`[${mem.type}] ${mem.content} (strength: ${mem.strength})`);
}memory.deleteDocument(ctx, options)
Delete a document and all associated data. This performs a cascading delete:
- Collect all chunks belonging to the document
- Remove graph edges connected to those chunks
- Delete the chunks and their embeddings
- Remove orphaned entities and relationships
- Delete associated summaries (RAPTOR)
- Remove ACLs
- Delete from Convex storage (if file-based)
- Update KB document counters
- Update quota counters
- Delete the document record itself
await memory.deleteDocument(ctx, {
orgId: "org_abc123",
documentId: "doc_xyz",
});memory.deleteKnowledgeBase(ctx, options)
Delete an entire knowledge base. This cascades through all documents in the KB (each with a full document cascade), then removes KB-level summaries and the KB record itself.
await memory.deleteKnowledgeBase(ctx, {
orgId: "org_abc123",
knowledgeBaseId: "kb_xyz",
});Team Methods
memory.setDocumentAcl(ctx, options)
Set the access control list for a document. See Access Control.
await memory.setDocumentAcl(ctx, {
orgId: "org_abc123",
documentId: "doc_xyz",
principals: ["user:alice", "role:admin", "group:engineering"],
});memory.getAuditLog(ctx, options)
Retrieve audit log entries. See Audit Logging.
const logs = await memory.getAuditLog(ctx, {
orgId: "org_abc123",
action: "search", // Optional: filter by action type
actor: "user:alice", // Optional: filter by actor
after: Date.now() - 86400000, // Optional: time range
limit: 100,
});memory.setQuota(ctx, options)
Set usage quotas for an organization. See Usage Quotas.
await memory.setQuota(ctx, {
orgId: "org_abc123",
quotas: {
searchesPerDay: 1000,
ingestionsPerDay: 100,
maxDocuments: 500,
maxStorageBytes: 1073741824,
},
});memory.getQuotaStatus(ctx, options)
Get current usage vs. quota limits.
const status = await memory.getQuotaStatus(ctx, {
orgId: "org_abc123",
});
console.log(`Searches: ${status.searches.used}/${status.searches.limit}`);
console.log(`Documents: ${status.documents.used}/${status.documents.limit}`);Error Handling
Common Errors
| Error | Cause | How to Handle |
|---|---|---|
Tier "community" cannot use this feature | Calling a Pro/Team method on Community | Upgrade tier or use a different method |
Organization not found | Invalid orgId | Verify the org was created |
Knowledge base not found | Invalid knowledgeBaseId | Verify the KB was created |
Quota exceeded | Over the usage limit | Check status, wait for reset, or upgrade |
Knowledge base limit reached | Community tier, already have 1 KB | Upgrade to Pro for unlimited KBs |
JINA_API_KEY not set | Missing environment variable | Set it via npx convex env set |
OPENROUTER_API_KEY not set | Missing env var (Pro+) | Set it via npx convex env set |
Error Handling Pattern
try {
const results = await memory.getContext(ctx, { orgId, query: "..." });
return results;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (msg.includes("Quota exceeded")) {
// Graceful degradation
return { results: [], error: "Rate limit reached" };
}
if (msg.includes("not found")) {
// Resource doesn't exist
return { results: [], error: "Resource not found" };
}
// Unexpected error — rethrow
throw error;
}