### Quick Start: Initialize MindCache Provider and Chat UI Source: https://context7_llms This snippet demonstrates the basic setup for integrating MindCache into a React application. It initializes the MindCacheProvider with OpenAI configuration and includes the MindCacheChat component for a pre-built chat interface. ```tsx import { MindCacheProvider, MindCacheChat } from 'mindcache'; function App() { return ( ); } ``` -------------------------------- ### Simple Cloud Counter App Example (Next.js) Source: https://context7_llms A minimal Next.js application demonstrating a real-time counter synchronized across clients using MindCache Cloud. It utilizes the 'Simple (Demos)' connection pattern with an API key, suitable for quick setup and testing. ```typescript "use client"; import { useState, useEffect, useRef } from 'react'; import { MindCache } from 'mindcache'; export default function Home() { const [instanceId, setInstanceId] = useState(''); const [apiKey, setApiKey] = useState(''); const [connected, setConnected] = useState(false); const [count, setCount] = useState(null); const mindCacheRef = useRef(null); const handleConnect = async () => { if (!instanceId || !apiKey) return; const baseUrl = process.env.NEXT_PUBLIC_MINDCACHE_API_URL; if (!baseUrl) throw new Error('NEXT_PUBLIC_MINDCACHE_API_URL not set'); // SDK automatically fetches token using apiKey const mc = new MindCache({ cloud: { instanceId, apiKey, baseUrl } }); await mc.waitForSync(); const current = mc.get_value('counter'); setCount(Number(current) || 0); mc.subscribe('counter', (val: any) => { setCount(Number(val) || 0); }); mindCacheRef.current = mc; setConnected(true); }; // Auto-increment every second useEffect(() => { if (!connected || !mindCacheRef.current) return; const interval = setInterval(() => { const mc = mindCacheRef.current!; const next = (Number(mc.get_value('counter')) || 0) + 1; mc.set_value('counter', next); }, 1000); return () => clearInterval(interval); }, [connected]); return (
{!connected ? (
setInstanceId(e.target.value)} placeholder="Instance ID" /> setApiKey(e.target.value)} placeholder="API Key" />
) : (
Counter: {count}
)}
); } ``` ```bash NEXT_PUBLIC_MINDCACHE_API_URL=https://api.mindcache.dev ``` -------------------------------- ### MindCacheProvider Configuration Options Source: https://context7_llms This example shows various configuration options for the MindCacheProvider, including settings for local IndexedDB storage, AI provider details, and synchronization with a GitHub repository. ```tsx {children} ``` -------------------------------- ### Stream AI Responses with MindCache Tools in TypeScript Source: https://context7_llms Demonstrates how to stream text responses from an AI model while utilizing MindCache-generated tools. This example shows the setup for streaming and confirms that tool calls are executed automatically after streaming completes. ```typescript import { streamText } from 'ai'; const result = await streamText({ model: openai('gpt-4'), tools: mindcache.get_aisdk_tools(), system: mindcache.get_system_prompt(), prompt: userMessage }); // Stream the response for await (const chunk of result.textStream) { process.stdout.write(chunk); } // After streaming, tool calls have been executed // MindCache is updated automatically ``` -------------------------------- ### Install MindCache using npm Source: https://context7_llms Installs the MindCache library using npm. Requires Node.js >= 18.0.0 and TypeScript >= 5.0.0. The `ai` package is optional for Vercel AI SDK integration. ```bash npm install mindcache ``` -------------------------------- ### Basic Operations - Setting Values Source: https://context7_llms Provides the signature and examples for the `set_value` method, used to store data in MindCache. ```APIDOC ## Basic Operations - Setting Values ### Description This endpoint allows you to store data within MindCache. You can set simple string or number values, complex objects, or arrays. Optional attributes can be provided to control the behavior of the stored data. ### Method `set_value(key: string, value: any, attributes?: KeyAttributes): void` ### Endpoint N/A ### Parameters - **key** (string) - Required - The identifier for the data. - **value** (any) - Required - The data to be stored. It should be JSON-serializable. - **attributes** (KeyAttributes) - Optional - Metadata associated with the key, such as `readonly`, `visible`, or `tags`. ### Request Example ```typescript // Simple value mindcache.set_value('userName', 'Alice'); mindcache.set_value('age', 30); mindcache.set_value('isActive', true); // Complex value mindcache.set_value('settings', { theme: 'dark', fontSize: 14 }); // Array value mindcache.set_value('tags', ['important', 'work', 'project']); ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Cloudflare Durable Object Example Source: https://context7_llms A complete example of a Cloudflare Durable Object implementing MindCache. It handles requests for importing markdown, retrieving keys, and getting the system prompt, persisting state using Yjs. ```typescript import { MindCache } from 'mindcache/server'; import * as Y from 'yjs'; export class MindCacheInstanceDO { private doc: Y.Doc; private state: DurableObjectState; constructor(state: DurableObjectState) { this.state = state; this.doc = new Y.Doc(); } // Create SDK instance for this request private getSDK(): MindCache { return new MindCache({ doc: this.doc, accessLevel: 'system' }); } async fetch(request: Request): Promise { const url = new URL(request.url); if (url.pathname === '/import' && request.method === 'POST') { const { markdown } = await request.json(); const sdk = this.getSDK(); sdk.fromMarkdown(markdown); await this.saveState(); return new Response(JSON.stringify({ success: true })); } if (url.pathname === '/keys' && request.method === 'GET') { const sdk = this.getSDK(); return new Response(JSON.stringify(sdk.getAll())); } if (url.pathname === '/prompt') { const sdk = this.getSDK(); return new Response(sdk.get_system_prompt()); } return new Response('Not found', { status: 404 }); } private async saveState(): Promise { const update = Y.encodeStateAsUpdate(this.doc); await this.state.storage.put('yjs_state', update); } } ``` -------------------------------- ### MindCache Cloud vs. IndexedDB Comparison Source: https://context7_llms Compares the features of MindCache's Cloud persistence and IndexedDB local persistence, highlighting differences in persistence scope, offline support, multi-device sync, collaboration, and setup complexity. ```markdown | Feature | IndexedDB | Cloud | |---|---|---| | Persistence | Local browser only | Across devices | | Offline support | Yes | Requires connection | | Multi-device sync | No | Yes | | Collaboration | No | Yes | | Setup complexity | None | Requires API keys | ``` -------------------------------- ### Local-First Sync with useLocalFirstSync and GitStore Source: https://context7_llms This example shows how to use the `useLocalFirstSync` hook to manage synchronization between local MindCache data and a GitHub repository using `@mindcache/gitstore`. It includes manual save/load functions and automatic sync options. ```tsx const { status, // 'idle' | 'loading' | 'saving' | 'error' lastSyncAt, hasLocalChanges, save, // Manual save load, // Manual load sync // Load then save } = useLocalFirstSync({ mindcache, gitstore: { owner: 'me', repo: 'data', token: async () => getToken() }, autoSyncInterval: 30000, saveDebounceMs: 5000 }); ``` -------------------------------- ### Get Key Attributes (TypeScript) Source: https://context7_llms Demonstrates how to retrieve the attributes associated with a specific key using the `get_attributes` method. The example shows accessing the returned `KeyAttributes` object. ```typescript // Signature get_attributes(key: string): KeyAttributes | undefined // Example const attrs = mindcache.get_attributes('apiKey'); // Returns: { readonly: true, visible: false, tags: ['credentials'] } if (attrs?.readonly) { console.log('This key is read-only'); } ``` -------------------------------- ### Complete Contact Manager Example (TypeScript) Source: https://context7_llms Demonstrates a full workflow: registering a 'Contact' type, setting a contact's value, and using AI to update the contact's phone number. The LLM updates the contact based on the provided schema and tools. ```typescript import { MindCache } from 'mindcache'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; const mc = new MindCache(); // Register Contact type mc.registerType('Contact', ` #Contact * name: full name * email: email address * phone: phone number * notes: additional context `); // Create initial contact mc.set_value('contact_bob', JSON.stringify({ name: 'Bob Jones', email: 'bob@example.com' }), { systemTags: ['SystemPrompt', 'LLMRead', 'LLMWrite'] }); mc.setType('contact_bob', 'Contact'); // Let LLM update contact const tools = mc.create_vercel_ai_tools(); const { text } = await generateText({ model: openai('gpt-4'), tools, system: mc.get_system_prompt(), prompt: 'Add phone number 555-1234 to Bob' }); // Contact is updated with proper schema console.log(mc.get_value('contact_bob')); // { name: 'Bob Jones', email: 'bob@example.com', phone: '555-1234' } ``` -------------------------------- ### MindCache Environment Variables Configuration Source: https://context7_llms Provides examples of environment variables required for MindCache, differentiating between server-side (API keys) and client-side (public URLs, instance IDs) configurations, particularly for Next.js applications. ```bash # .env.local (for Next.js apps) # Server-side only (never exposed to browser) MINDCACHE_API_KEY=mc_live_xxx # OR for delegate keys: MINDCACHE_API_KEY=del_xxx:sec_xxx # Client-side (exposed to browser, safe) NEXT_PUBLIC_MINDCACHE_API_URL=https://api.mindcache.dev # Instance IDs (exposed, just identifiers) NEXT_PUBLIC_INSTANCE_ID=your-instance-id ``` -------------------------------- ### Accessing MindCache Context with useMindCacheContext Source: https://context7_llms This example shows how to use the `useMindCacheContext` hook to access MindCache instances, loading states, API key management functions, and synchronization utilities within any component. ```tsx const { mindcache, // MindCache instance isLoaded, // Ready to use? hasApiKey, // API key configured? setApiKey, // Set API key getModel, // Get AI model instance syncToGitStore // Manual sync to GitHub } = useMindCacheContext(); ``` -------------------------------- ### Get System Prompt with Types (TypeScript) Source: https://context7_llms Retrieves the system prompt, which automatically includes available types, their keys with types, and schema definitions for typed keys. This is useful for providing context to AI models. ```typescript const systemPrompt = mc.get_system_prompt(); // Includes: // - Available types (Contact) // - Keys with their types // - Schema definitions for each typed key ``` -------------------------------- ### Filter Keys by Tag Using TypeScript Source: https://context7_llms Provides examples of filtering MindCache keys based on tags. It shows how to get all keys with a specific tag and how to retrieve entries associated with a tag, returning an array of objects. ```typescript // Get all keys with a specific tag const allKeys = Object.keys(mindcache.getAll()); const userKeys = allKeys.filter(key => mindcache.hasTag(key, 'user')); // Returns: ['userName', 'userEmail'] // Get entries with a specific tag const userEntries = Object.entries(mindcache.getAll()) .filter(([key]) => mindcache.hasTag(key, 'user')) .map(([key, entry]) => ({ key, value: entry.value })); ``` -------------------------------- ### Basic React Usage with useMindCache Hook Source: https://context7_llms This example shows the fundamental usage of the `useMindCache` hook in a React component for initializing MindCache with IndexedDB storage and handling loading and error states. ```tsx 'use client'; import { useMindCache } from 'mindcache'; function MyComponent() { const { mindcache, isLoaded, error } = useMindCache({ indexedDB: { dbName: 'my-app' } }); if (!isLoaded) return
Loading...
; if (error) return
Error: {error.message}
; return (

Hello, {mindcache.get_value('userName')}

); } ``` -------------------------------- ### Basic Operations - Getting Values Source: https://context7_llms Details the `get_value` method for retrieving data associated with a specific key from MindCache. ```APIDOC ## Basic Operations - Getting Values ### Description Retrieve the value associated with a given key from MindCache. If the key does not exist, `undefined` is returned. ### Method `get_value(key: string): any` ### Endpoint N/A ### Parameters - **key** (string) - Required - The identifier of the data to retrieve. ### Request Example ```typescript const name = mindcache.get_value('userName'); // Returns: 'Alice' const settings = mindcache.get_value('settings'); // Returns: { theme: 'dark', fontSize: 14 } const missing = mindcache.get_value('nonexistent'); // Returns: undefined ``` ### Response - **value** (any) - The retrieved value, or `undefined` if the key is not found. ### Response Example N/A ``` -------------------------------- ### Handling Tool Execution Errors with AI SDK Source: https://context7_llms Provides an example of how to gracefully handle errors that may occur during AI tool execution within the MindCache environment. It uses a try-catch block to identify and manage tool-specific errors during text generation. ```typescript import { generateText } from 'ai'; try { const { text, toolCalls } = await generateText({ model: openai('gpt-4'), tools: mindcache.get_aisdk_tools(), system: mindcache.get_system_prompt(), prompt: userMessage, }); } catch (error) { if (error.message.includes('tool')) { console.error('Tool execution failed:', error); // Handle tool-specific errors } throw error; } ``` -------------------------------- ### Use MindCache Tools with Vercel AI SDK in TypeScript Source: https://context7_llms Illustrates integrating MindCache-generated tools with the Vercel AI SDK for AI-driven interactions. It covers setting up memory, getting tools and system prompts, and handling AI responses that trigger tool calls. ```typescript import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { mindcache } from 'mindcache'; // Setup memory mindcache.set_value('userName', 'Alice'); mindcache.set_value('favoriteColor', 'blue'); mindcache.set_value('lastTask', 'planning vacation'); // Get tools and system prompt const tools = mindcache.get_aisdk_tools(); const systemPrompt = mindcache.get_system_prompt(); // Generate response const { text, toolCalls } = await generateText({ model: openai('gpt-4'), tools: tools, system: systemPrompt, prompt: 'Actually, my favorite color is green now.' }); // AI will call write_favoriteColor('green') // The tool executes automatically and updates mindcache // Verify the update console.log(mindcache.get_value('favoriteColor')); // Output: 'green' ``` -------------------------------- ### Invisible Keys Example (TypeScript) Source: https://context7_llms Illustrates the `visible` attribute. Keys with `visible: false` are not included in the system prompt generated for AI models, making them suitable for internal state or sensitive information that the AI does not need direct access to. ```typescript // Create invisible key (for internal use) mindcache.set_value('internalState', { step: 3 }, { visible: false }); // Won't appear in system prompt const prompt = mindcache.get_system_prompt(); // internalState is NOT mentioned // But you can still read it const state = mindcache.get_value('internalState'); // Returns: { step: 3 } ``` -------------------------------- ### Readonly Keys Example (TypeScript) Source: https://context7_llms Explains and demonstrates the `readonly` attribute. Keys marked as `readonly` cannot be modified by AI tools but can still be updated programmatically. AI SDK tools will not include write operations for these keys. ```typescript // Create readonly key mindcache.set_value('systemConfig', { maxRetries: 3 }, { readonly: true }); // AI tools will NOT include write_systemConfig const tools = mindcache.get_aisdk_tools(); // write_systemConfig is NOT in tools // But you can still modify it programmatically mindcache.set_value('systemConfig', { maxRetries: 5 }, { readonly: true }); ``` -------------------------------- ### Full AI Chat App with Local Persistence Source: https://mindcache.dev/ This example showcases a complete AI chat application built with MindCache, including local persistence using IndexedDB. It configures AI providers, models, API key storage, and MindCache settings for a robust client-side experience. ```jsx import { MindCacheProvider, MindCacheChat } from 'mindcache'; function App() { return ( ); } // That's it! No server, no API routes, no backend. ``` -------------------------------- ### Initialize and Use MindCache Instance Source: https://context7_llms Demonstrates how to import and use the MindCache library. It shows how to utilize the default singleton instance or create a custom instance of MindCache for managing key-value data. ```typescript import { mindcache } from 'mindcache'; // Use the default singleton instance mindcache.set_value('key', 'value'); // Or create your own instance import { MindCache } from 'mindcache'; const mc = new MindCache(); mc.set_value('key', 'value'); ``` -------------------------------- ### Configure MindCache with Direct API Key Authentication (Demos) Source: https://context7_llms Sets up MindCache for cloud synchronization using a direct API key. This method is simpler for quick demos as it doesn't require a backend route, but the API key is exposed in the browser. The SDK handles token fetching automatically. ```typescript // Client-side: No backend route needed! import { MindCache } from 'mindcache'; const mc = new MindCache({ cloud: { instanceId: 'your-instance-id', apiKey: 'del_xxx:sec_xxx', // Or 'mc_live_xxx' format baseUrl: 'https://api.mindcache.dev' } }); await mc.waitForSync(); mc.set_value('counter', 1); // Syncs instantly! // The SDK automatically: // 1. Calls POST {baseUrl}/api/ws-token with your API key // 2. Gets a short-lived token (60 seconds) // 3. Connects to WebSocket with the token // Supported API key formats: // - Regular API keys: mc_live_xxx or mc_test_xxx // - Delegate keys: del_xxx:sec_xxx ``` -------------------------------- ### Generate AI SDK Tools with TypeScript Source: https://context7_llms Shows how to generate tools for AI frameworks like Vercel AI SDK using MindCache. It demonstrates setting up values and then calling `get_aisdk_tools()` to create executable functions for the AI model. ```typescript // For Vercel AI SDK v5 (uses Zod schemas + tool() helper) // const tools = mc.create_vercel_ai_tools(); // Setup mindcache.set_value('userName', 'Alice'); mindcache.set_value('favoriteColor', 'blue'); mindcache.set_value('systemConfig', { debug: false }, { readonly: true }); // Generate tools const tools = mindcache.get_aisdk_tools(); // Returns: { // write_userName: { description: '...', parameters: {...}, execute: fn }, // write_favoriteColor: { description: '...', parameters: {...}, execute: fn } // } // Note: write_systemConfig is NOT included (readonly) ``` -------------------------------- ### Create AI SDK Tools (TypeScript) Source: https://context7_llms Generates tools compatible with different AI SDKs. `create_vercel_ai_tools` is for Vercel AI SDK v5 using Zod schemas, while `create_tools` provides raw JSON Schema for OpenAI, Anthropic, LangChain, and others. ```typescript // For Vercel AI SDK v5 (uses Zod schemas + tool() helper) const vercelTools = mc.create_vercel_ai_tools(); // For other frameworks (raw JSON Schema) const rawTools = mc.create_tools(); // Works with: OpenAI SDK, Anthropic SDK, LangChain, etc. ``` -------------------------------- ### MindCache Core Operations Source: https://context7_llms Documentation for the core methods of the MindCache class, including setting, getting, deleting, and managing key-value data. ```APIDOC ## MindCache Class - Core Operations ### Description Provides an overview of the fundamental methods for interacting with MindCache data, such as `set_value`, `get_value`, `delete`, `has`, and `clear`. ### Methods - **`set_value(key: string, value: any, attributes?: KeyAttributes): void`** - Sets or updates the value associated with a given key. Optionally applies attributes. - **`get_value(key: string): any`** - Retrieves the value associated with a key. Returns `undefined` if the key does not exist. - **`delete(key: string): void`** - Removes the key-value pair from MindCache. - **`has(key: string): boolean`** - Checks if a key exists in MindCache. - **`clear(): void`** - Removes all key-value pairs from MindCache. ### Request Example (Core Operations) ```typescript // Set a value mindcache.set_value('user_name', 'Alice'); // Get a value const name = mindcache.get_value('user_name'); // 'Alice' // Check if a key exists if (mindcache.has('user_name')) { console.log('User name exists'); } // Delete a key mindcache.delete('user_name'); // Clear all data mindcache.clear(); ``` ### Response - Methods typically return `void` or `boolean` as indicated. ``` -------------------------------- ### Getting All Data Source: https://context7_llms Retrieves all data stored in MindCache. This method returns a record of all keys and their associated entries, including values and attributes. ```APIDOC ## GET /getAll ### Description Retrieves all data stored in MindCache as a record of key-value pairs. ### Method GET ### Endpoint /getAll ### Parameters None ### Request Example ```typescript const allData = mindcache.getAll(); ``` ### Response #### Success Response (200) - **Record** - An object where keys are strings representing data keys and values are KeyEntry objects containing the data value and attributes. #### Response Example ```json { "userName": { "value": "Alice", "attributes": {...} }, "preferences": { "value": {...}, "attributes": {...} } } ``` ``` -------------------------------- ### Basic Usage of MindCache with IndexedDB Persistence Source: https://context7_llms Demonstrates how to initialize MindCache with IndexedDB for local browser persistence. It covers setting database and store names, debounce time, and waiting for data to load before use. ```typescript import { MindCache } from 'mindcache'; const mc = new MindCache({ indexedDB: { dbName: 'my-app-db', // Database name storeName: 'my-store', // Object store name debounceMs: 500 // Delay before saving (batches writes) } }); // Wait for data to load from IndexedDB await mc.waitForSync(); // Now use normally - changes auto-save mc.set_value('userName', 'Alice'); mc.set_value('preferences', { theme: 'dark' }); // On page reload, data is automatically restored ``` -------------------------------- ### Custom Types (v3.6+) Source: https://context7_llms Enables the definition and use of custom data schemas using Markdown, guiding LLM output and ensuring data consistency. ```APIDOC ## Custom Types (v3.6+) ### Registering a Type #### `registerType(typeName: string, schema: string): void` Defines a new custom data type using a Markdown-based schema. * **typeName** (string) - The name for the custom type (e.g., 'Contact'). * **schema** (string) - A Markdown string describing the type's fields and their purpose. **Example:** ```typescript import { MindCache } from 'mindcache'; const mc = new MindCache(); mc.registerType('Contact', ` #Contact * name: full name of the contact * email: email address (primary) * phone: phone number (mobile preferred) * company: company or organization name * role: job title or role * notes: any additional context about this person `); ``` ### Assigning Types to Keys #### `set_value(key: string, value: any, options?: SetValueOptions): void` (with type option) Sets the value for a key. When used with custom types, it ensures the data conforms to the schema. #### `setType(key: string, typeName: string): void` Assigns a previously registered custom type to an existing key. This also sets the underlying storage type to 'json'. * **key** (string) - The identifier of the key. * **typeName** (string) - The name of the registered custom type. **Example:** ```typescript // Set value for a contact, then assign the type mc.set_value('contact_alice', JSON.stringify({ name: 'Alice Smith', email: 'alice@example.com', company: 'Acme Corp', role: 'Engineer' }), { systemTags: ['SystemPrompt', 'LLMRead', 'LLMWrite'] }); mc.setType('contact_alice', 'Contact'); ``` ### Querying Types #### `getKeyType(key: string): string | null` Retrieves the custom type name assigned to a specific key. * **key** (string) - The identifier of the key. **Returns:** The type name string, or null if no custom type is assigned. #### `getTypeSchema(typeName: string): TypeSchema | null` Retrieves the schema definition for a registered type. * **typeName** (string) - The name of the registered type. **Returns:** An object containing the schema details, or null if the type is not found. #### `getRegisteredTypes(): string[]` Returns a list of all currently registered custom type names. **Example:** ```typescript const typeName = mc.getKeyType('contact_alice'); // Returns: 'Contact' const schema = mc.getTypeSchema('Contact'); // Returns schema object const types = mc.getRegisteredTypes(); // Returns: ['Contact'] ``` ### LLM Tool Integration When keys are associated with custom types, the generated LLM tools automatically include schema information, providing guidance to the LLM for generating structured output that conforms to the defined schema. **Example:** ```typescript // Generate tools, schema guidance is embedded in tool descriptions const tools = mc.create_vercel_ai_tools(); // The description for a tool like 'write_contact_alice' will include the 'Contact' schema. ``` ``` -------------------------------- ### Core Concepts - MindCache Instance Source: https://context7_llms Demonstrates how to import and use the default singleton instance of MindCache or create a custom instance. ```APIDOC ## Core Concepts - MindCache Instance ### Description This section explains how to interact with the MindCache library by either using the globally available singleton instance or by creating a new, independent instance. ### Method Import and instantiate ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { mindcache } from 'mindcache'; // Use the default singleton instance mindcache.set_value('key', 'value'); // Or create your own instance import { MindCache } from 'mindcache'; const mc = new MindCache(); mc.set_value('key', 'value'); ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Generate Basic System Prompt with MindCache Source: https://context7_llms Generates a basic system prompt by retrieving user information like userName and userRole from MindCache. It also includes built-in temporal keys like $date and $time. Sensitive keys with 'visible: false' are excluded. ```typescript // Signature get_system_prompt(): string // Setup mindcache.set_value('userName', 'Alice'); mindcache.set_value('userRole', 'developer'); mindcache.set_value('secretKey', 'abc123', { visible: false }); // Generate const prompt = mindcache.get_system_prompt(); // Returns something like: // "userName: Alice. You can rewrite "userName" by using the write_userName tool. // userRole: developer. You can rewrite "userRole" by using the write_userRole tool. // $date: 2025-01-15 // $time: 14:30:00" // Note: secretKey is NOT included (visible: false) ``` -------------------------------- ### Get Formatted Memory String from MindCache Source: https://context7_llms Retrieves a formatted string of the current memory in MindCache, excluding tool instructions. This is useful for constructing prompts or displaying user context. ```typescript // Signature getSTM(): string // Get formatted memory string (without tool instructions) const memory = mindcache.getSTM(); // Returns: // "userName: Alice // userRole: developer // preferences: {"theme":"dark"}" ``` -------------------------------- ### Retrieve Tags for an Entry in TypeScript Source: https://context7_llms Shows how to get all tags associated with a specific MindCache entry using the `getTags` function. This function returns an array of strings, where each string is a tag. ```typescript // Signature // getTags(key: string): string[] // Example const tags = mindcache.getTags('userName'); // Returns: ['user', 'context'] ``` -------------------------------- ### AI Agent Memory with MindCache Source: https://context7_llms Example of using MindCache to store conversation context and user preferences for an AI agent. The stored context is then used to generate a more personalized system prompt. ```typescript // Store conversation context mindcache.set_value('userName', 'Alice', { tags: ['context'] }); mindcache.set_value('currentTask', 'Planning vacation', { tags: ['context'] }); mindcache.set_value('preferences', { budget: 'medium', style: 'adventure' }); // AI can read context and update as conversation progresses const tools = mindcache.get_aisdk_tools(); const systemPrompt = ` You are a travel planning assistant. ${mindcache.getTagged('context')} Help the user plan their vacation based on their preferences. `; ``` -------------------------------- ### Combine Formatted Memory with Custom Instructions Source: https://context7_llms Shows how to combine the formatted memory string obtained from `mindcache.getSTM()` with custom instructions to create a comprehensive system prompt for an AI assistant. ```typescript const customSystemPrompt = ` You are a helpful AI assistant. ## User Context ${mindcache.getSTM()} ## Your Capabilities You can update the user's information using the available tools. Always confirm before making changes. `; ``` -------------------------------- ### Next.js API Route Integration Source: https://context7_llms Example of integrating MindCache into a Next.js API route to stream text responses from an AI model, utilizing user-specific MindCache instances for context and tools. ```typescript // pages/api/chat.ts or app/api/chat/route.ts import { MindCache } from 'mindcache'; import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; export async function POST(req: Request) { const { messages, instanceId } = await req.json(); // Connect to user's MindCache instance const mc = new MindCache({ cloud: { instanceId, apiKey: process.env.MINDCACHE_API_KEY, } }); await mc.waitForSync(); // Generate response with tools const result = await streamText({ model: openai('gpt-4'), tools: mc.get_aisdk_tools(), system: mc.get_system_prompt(), messages, }); mc.disconnect(); return result.toAIStreamResponse(); } ``` -------------------------------- ### Get All Data Source: https://context7_llms Retrieves all data stored in MindCache. It returns a record where keys are data identifiers and values are KeyEntry objects containing the data and its attributes. This function is useful for iterating over all stored items. ```typescript // Signature getAll(): Record // Example const allData = mindcache.getAll(); // Returns: { // userName: { value: 'Alice', attributes: {...} }, // preferences: { value: {...}, attributes: {...} } // } // Iterate over all keys for (const [key, entry] of Object.entries(mindcache.getAll())) { console.log(`${key}: ${JSON.stringify(entry.value)}`); } ``` -------------------------------- ### Real-Time Sync with MindCache Source: https://context7_llms Demonstrates how to set values and subscribe to changes in real-time across multiple clients using MindCache. It covers subscribing to specific keys and all changes. ```typescript // Client A: Sets a value mc.set_value('counter', 42); // Client B: Subscribes to changes mc.subscribe('counter', (value) => { console.log('Counter updated by another user:', value); // Outputs: 'Counter updated by another user: 42' }); // Or subscribe to all changes mc.subscribeToAll(() => { console.log('Something changed!'); updateUI(mc.getAll()); }); ``` -------------------------------- ### Complete State Serialization and Deserialization for MindCache Source: https://context7_llms Allows getting the complete MindCache state as an object (`serialize`) and restoring the state from such an object (`deserialize`). This provides a more robust way to manage the entire cache state. ```typescript // Get complete state object const state = mindcache.serialize(); // Returns: { keys: {...}, metadata: {...} } // Restore complete state mindcache.deserialize(state); ``` -------------------------------- ### AI-Assisted Data Entry with MindCache Source: https://context7_llms Illustrates how MindCache can be used to store structured data and how AI can populate this data from natural language inputs. It shows the process of setting up fields and how AI calls can map to MindCache methods. ```typescript // Store structured data mindcache.set_value('customer_name', '', { tags: ['customer'] }); mindcache.set_value('customer_email', '', { tags: ['customer'] }); mindcache.set_value('customer_phone', '', { tags: ['customer'] }); // AI can fill in data from natural language // User: "The customer is John Smith, john@example.com, 555-1234" // AI calls: write_customer_name('John Smith') // write_customer_email('john@example.com') // write_customer_phone('555-1234') ``` -------------------------------- ### Basic Template Injection (TypeScript) Source: https://context7_llms Shows how to use the `injectSTM` method to perform basic template injection. Placeholders like `{{key}}` in a string are replaced with their corresponding values stored in MindCache. ```typescript // Signature injectSTM(template: string): string // Setup mindcache.set_value('userName', 'Alice'); mindcache.set_value('city', 'New York'); mindcache.set_value('role', 'developer'); // Inject values const message = mindcache.injectSTM( 'Hello {{userName}}! Welcome to {{city}}.' ); // Returns: 'Hello Alice! Welcome to New York.' const prompt = mindcache.injectSTM( 'You are helping {{userName}}, a {{role}} based in {{city}}.' ); // Returns: 'You are helping Alice, a developer based in New York.' ``` -------------------------------- ### Create and Use Template Keys in TypeScript Source: https://context7_llms Demonstrates how to set and retrieve values using template keys in MindCache. Template keys allow for dynamic resolution of placeholders within their string values. Ensure the 'mindcache' library is imported. ```typescript // Create a template key mindcache.set_value('greeting', 'Hello {{userName}}!', { template: true }); mindcache.set_value('userName', 'Alice'); // When getting a template key, placeholders are resolved const greeting = mindcache.get_value('greeting'); // Returns: 'Hello Alice!' ``` -------------------------------- ### MindCache IndexedDB Configuration Options Source: https://context7_llms Lists the available configuration options for MindCache's IndexedDB persistence, including database name, store name, key, and debounce milliseconds, with their default values. ```typescript interface IndexedDBConfig { dbName?: string; // Default: 'mindcache_db' storeName?: string; // Default: 'mindcache_store' key?: string; // Default: 'mindcache_data' debounceMs?: number; // Default: 1000 } ``` -------------------------------- ### Handling Key Not Found Errors in MindCache Source: https://context7_llms Explains how MindCache handles requests for non-existent keys. It clarifies that accessing a non-existent key returns `undefined` rather than throwing an error, and demonstrates the recommended practice of checking for `undefined` values. ```typescript // Key not found const value = mindcache.get_value('nonexistent'); // Returns: undefined (not an error) // Always check for undefined const userName = mindcache.get_value('userName') ?? 'Guest'; ``` -------------------------------- ### Basic Operations - Checking Existence Source: https://context7_llms Explains how to use the `has` method to check if a key exists in MindCache. ```APIDOC ## Basic Operations - Checking Existence ### Description Determine whether a specific key exists within MindCache. ### Method `has(key: string): boolean` ### Endpoint N/A ### Parameters - **key** (string) - Required - The identifier to check for. ### Request Example ```typescript if (mindcache.has('userName')) { console.log('User is set'); } const exists = mindcache.has('preferences'); // Returns: true or false ``` ### Response - **exists** (boolean) - `true` if the key exists, `false` otherwise. ### Response Example N/A ``` -------------------------------- ### Server-Side MindCache Initialization and Usage Source: https://context7_llms This snippet shows how to import and use the server-specific MindCache export in Node.js environments. It allows for server-side data manipulation without browser dependencies. Key functions include setting values and getting system prompts. ```typescript // Use the server-specific export (no browser dependencies) import { MindCache } from 'mindcache/server'; const mc = new MindCache(); mc.set_value('key', 'value'); const prompt = mc.get_system_prompt(); ``` -------------------------------- ### Document Management (v3.1+) Source: https://context7_llms Manages collaborative documents for real-time editing with LLMs. Supports creating, getting, and updating document content using plain text or Y.Text for rich editor integration. Character-level edits and smart replace are also available. ```typescript // Create a new document mc.set_document('notes', '# My Notes'); // Create empty document mc.set_document('draft'); // Get Y.Text for editor binding (Quill, CodeMirror, etc.) const yText = mc.get_document('notes'); // get_value returns plain text for documents const text = mc.get_value('notes'); // Insert at position mc.insert_text('notes', 0, 'New heading\n'); // Delete range mc.delete_text('notes', 0, 12); // set_value on documents uses diff for small changes automatically mc.set_value('notes', '# Updated Notes'); // How it works: // - Changes < 80%: Uses fast-diff for incremental operations // - Changes > 80%: Full replacement (more efficient for rewrites) const tools = mc.get_aisdk_tools(); // For document key 'notes': // - write_notes: Replace entire document // - append_notes: Add text to end // - insert_notes: Insert at position // - edit_notes: Find and replace ``` -------------------------------- ### Custom Type Registration (v3.6+) Source: https://context7_llms Enables defining structured data schemas using Markdown for guiding LLM output. Custom types ensure consistency and provide schema information for LLM tools, facilitating structured data generation and manipulation. ```typescript import { MindCache } from 'mindcache'; const mc = new MindCache(); // Define a Contact type with Markdown schema mc.registerType('Contact', ` #Contact * name: full name of the contact * email: email address (primary) * phone: phone number (mobile preferred) * company: company or organization name * role: job title or role * notes: any additional context about this person `); // Create a key and assign the type mc.set_value('contact_alice', JSON.stringify({ name: 'Alice Smith', email: 'alice@example.com', company: 'Acme Corp', role: 'Engineer' }), { systemTags: ['SystemPrompt', 'LLMRead', 'LLMWrite'] }); // Assign the custom type (also sets underlying type to 'json') mc.setType('contact_alice', 'Contact'); // Get the custom type for a key const typeName = mc.getKeyType('contact_alice'); // Returns: 'Contact' // Get the schema definition const schema = mc.getTypeSchema('Contact'); // Returns: { name: 'Contact', fields: [...], rawSchema: '...' } // List all registered types const types = mc.getRegisteredTypes(); // Returns: ['Contact'] // Generate tools - schema is embedded in tool descriptions const tools = mc.create_vercel_ai_tools(); // The write_contact_alice tool description includes: // - The Contact schema fields // - Example JSON format // - Guidance for the LLM to follow the schema ``` -------------------------------- ### Set Key Attributes (TypeScript) Source: https://context7_llms Shows how to set attributes for a key, either at creation time using `set_value` with an options object, or by updating existing attributes using `set_attributes`. ```typescript // At creation time mindcache.set_value('apiKey', 'secret123', { readonly: true, visible: false }); // Update attributes later mindcache.set_attributes('apiKey', { readonly: true, visible: false, tags: ['credentials', 'sensitive'] }); ``` -------------------------------- ### Collaborative Editing with MindCache Source: https://context7_llms Demonstrates how to enable real-time collaborative editing for a shared document instance using MindCache. It shows how to connect to a cloud instance, subscribe to changes made by other editors, and automatically sync local modifications. ```typescript const mc = new MindCache({ cloud: { instanceId: 'shared-doc-123', tokenEndpoint: '/api/ws-token' } }); mc.subscribeToAll(() => { updateUI(mc.getAll()); }); mc.set_value('paragraph_1', 'Updated text...'); ``` -------------------------------- ### Environment Configuration for MindCache (Bash) Source: https://context7_llms This file defines environment variables for a Next.js application integrating with MindCache. It separates server-side secrets, such as the API key, from client-side configurations like the API base URL and instance ID. This ensures that sensitive credentials are not exposed to the browser. ```bash # Server-side only (never exposed) MINDCACHE_API_KEY=del_xxx:sec_xxx # Client-side (safe to expose) NEXT_PUBLIC_MINDCACHE_API_URL=https://api.mindcache.dev NEXT_PUBLIC_INSTANCE_ID=your-instance-id ``` -------------------------------- ### MindCache Core Operations (TypeScript) Source: https://context7_llms Demonstrates fundamental operations for interacting with MindCache, including setting, getting, checking existence, deleting, retrieving all data, template injection, LLM tool creation, custom type registration, tag management, attribute updates, event subscriptions, and serialization. ```typescript import { mindcache } from 'mindcache'; // Set value mindcache.set_value('key', 'value'); mindcache.set_value('key', 'value', { readonly: true, tags: ['tag1'] }); // Get value const value = mindcache.get_value('key'); // Check existence if (mindcache.has('key')) { ... } // Delete mindcache.delete('key'); // Get all const all = mindcache.getAll(); // Template injection const result = mindcache.injectSTM('Hello {{name}}!'); // LLM tools const tools = mindcache.create_vercel_ai_tools(); // For Vercel AI SDK const rawTools = mindcache.create_tools(); // For other frameworks const prompt = mindcache.get_system_prompt(); // Custom types (v3.6+) mindcache.registerType('Contact', '#Contact\n* name: full name\n* email: email'); mindcache.setType('contact_alice', 'Contact'); const typeName = mindcache.getKeyType('contact_alice'); // Tags mindcache.addTag('key', 'tagName'); const tagged = mindcache.getTagged('tagName'); // Update attributes only (v3.2+) mindcache.set_attributes('key', { tags: ['new-tag'] }); // Events mindcache.subscribe('key', (value) => console.log(value)); mindcache.subscribeToAll(() => console.log('changed')); // Serialization const json = mindcache.toJSON(); mindcache.fromJSON(json); ```