memcity

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

ts
import { Memory } from "memcity";
import { components } from "./_generated/api";
 
const memory = new Memory(components.memcity, config);
ParameterTypeDescription
componentUseApi<typeof ComponentApi>The installed Memcity Convex component
configMemoryConfigConfiguration 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.

ts
const orgId = await memory.createOrg(ctx, {
  name: "Acme Corp",
});
ParamTypeRequiredDescription
namestringYesOrganization 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.

ts
const kbId = await memory.createKnowledgeBase(ctx, {
  orgId: "org_abc123",
  name: "Product Documentation",
  description: "All product docs, guides, and tutorials",
});
ParamTypeRequiredDescription
orgIdstringYesParent organization ID
namestringYesKB display name
descriptionstringNoWhat 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.

ts
await memory.ingestText(ctx, {
  orgId: "org_abc123",
  knowledgeBaseId: "kb_xyz",
  text: "Your document content here...",
  source: "document.md",
});
ParamTypeRequiredDescription
orgIdstringYesOrganization ID
knowledgeBaseIdstringYesTarget knowledge base
textstringYesThe content to ingest
sourcestringNoSource identifier (used in citations)
principalsstring[]NoACL 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.

ts
const results = await memory.getContext(ctx, {
  orgId: "org_abc123",
  knowledgeBaseId: "kb_xyz",
  query: "How does authentication work?",
});
ParamTypeRequiredDescription
orgIdstringYesOrganization ID
knowledgeBaseIdstringNoFilter to specific KB (omit for all)
querystringYesThe search query
userIdstringNoUser ID for episodic memory (Pro+)
conversationIdstringNoConversation context (Pro+)
principalsstring[]NoUser's ACL principals (Team)
configPartial<MemoryConfig>NoOverride config for this search

Returns: ContextResult

ts
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:

ts
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.

ts
await memory.ingestUrl(ctx, {
  orgId: "org_abc123",
  knowledgeBaseId: "kb_xyz",
  url: "https://docs.example.com/api-reference",
});
ParamTypeRequiredDescription
orgIdstringYesOrganization ID
knowledgeBaseIdstringYesTarget knowledge base
urlstringYesThe 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.

ts
const uploadUrl = await memory.getUploadUrl(ctx);
// Use this URL to POST the file from your frontend

Returns: string — a temporary upload URL valid for ~1 hour.

memory.processUploadedFile(ctx, options)

Process a previously uploaded file. Supports 25+ file types.

ts
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" }
ParamTypeRequiredDescription
orgIdstringYesOrganization ID
knowledgeBaseIdstringYesTarget knowledge base
storageIdId<"_storage">YesConvex storage ID from upload
fileNamestringYesOriginal file name (used for type detection)

memory.batchIngest(ctx, options)

Ingest multiple text documents in a single call.

ts
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.

ts
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.

ts
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:

  1. Collect all chunks belonging to the document
  2. Remove graph edges connected to those chunks
  3. Delete the chunks and their embeddings
  4. Remove orphaned entities and relationships
  5. Delete associated summaries (RAPTOR)
  6. Remove ACLs
  7. Delete from Convex storage (if file-based)
  8. Update KB document counters
  9. Update quota counters
  10. Delete the document record itself
ts
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.

ts
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.

ts
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.

ts
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.

ts
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.

ts
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

ErrorCauseHow to Handle
Tier "community" cannot use this featureCalling a Pro/Team method on CommunityUpgrade tier or use a different method
Organization not foundInvalid orgIdVerify the org was created
Knowledge base not foundInvalid knowledgeBaseIdVerify the KB was created
Quota exceededOver the usage limitCheck status, wait for reset, or upgrade
Knowledge base limit reachedCommunity tier, already have 1 KBUpgrade to Pro for unlimited KBs
JINA_API_KEY not setMissing environment variableSet it via npx convex env set
OPENROUTER_API_KEY not setMissing env var (Pro+)Set it via npx convex env set

Error Handling Pattern

ts
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;
}