### Quick Start: Create, Save Message, and Update State (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates the basic workflow of creating a dialogue, adding an assistant's response, and updating the conversation's state using the DialogueDB class. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Create a dialogue with an initial message const dialogue = await db.createDialogue({ messages: [{ role: "user", content: "Hello!" }], }); // Add a response await dialogue.saveMessage({ role: "assistant", content: "Hi there!", }); // Update conversation state await dialogue.saveState({ topic: "greeting", }); ``` -------------------------------- ### Install DialogueDB Node.js SDK Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Installs the DialogueDB Node.js client SDK using npm. Ensure Node.js version 18 or higher is installed. ```bash npm install dialogue-db ``` -------------------------------- ### List and Filter Dialogues with DialogueDB Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Shows how to query dialogues using filters, pagination, and specific relationships like 'threadOf'. This example utilizes the DialogueDB client for Node.js and requires an API key. It demonstrates loading the next page of results and iterating through dialogue items. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // List dialogues with filters const result = await db.listDialogues({ namespace: "customer-support", limit: 50, tags: ["active", "urgent"], status: "active" }); console.log(`Found ${result.items.length} dialogues`); console.log(`Has more: ${result.next !== undefined}`); result.items.forEach(dialogue => { console.log(`${dialogue.id}: ${dialogue.label || "Untitled"}`); console.log(` Status: ${dialogue.status}`); console.log(` Messages: ${dialogue.totalMessages || 0}`); console.log(` Threads: ${dialogue.threadCount || 0}`); console.log(` Last active: ${dialogue.modified}`); }); // Load next page of results if (result.next) { const nextPage = await db.listDialogues({ namespace: "customer-support", limit: 50, next: result.next }); console.log(`Next page has ${nextPage.items.length} dialogues`); } // Filter by thread relationship const threads = await db.listDialogues({ threadOf: "dlg_parent123", limit: 100 }); console.log(`Found ${threads.items.length} child threads`); ``` -------------------------------- ### DialogueDB Direct API Operations (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Provides examples of using the direct API for common DialogueDB operations, including creating, getting, listing, updating, and removing dialogues, messages, and memory. It also includes search functionality. ```typescript import { api } from "dialogue-db"; // Dialogue operations const dialogue = await api.dialogue.create({ /* ... */ }); const fetched = await api.dialogue.get("id"); const listed = await api.dialogue.list({ limit: 10 }); const updated = await api.dialogue.update({ id: "id", state: {} }); await api.dialogue.remove("id"); // Single message operations const message = await api.message.create({ dialogueId: "id", role: "user", content: "...", }); await api.message.remove({ dialogueId: "id", id: "msg-id" }); // Bulk message operations const messages = await api.messages.create({ id: "dialogue-id", messages: [{ role: "user", content: "..." }], }); const messageList = await api.messages.list({ dialogueId: "id" }); // Memory operations const memory = await api.memory.create({ id: "k", value: "v" }); const mem = await api.memory.get("k"); await api.memory.update({ id: "k", value: "new-value" }); await api.memory.remove("k"); // Search const results = await api.search({ query: "...", object: "dialogue" }); ``` -------------------------------- ### Create and Retrieve Memory using Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Illustrates how to create and retrieve persistent memory objects. Memory can store structured data, facts, or user preferences that persist across conversations. This example shows creating memory with complex values and updating its tags. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Create memory with structured data const userPrefs = await db.createMemory({ id: "user_123_preferences", namespace: "customer-support", label: "User Preferences", description: "UI and notification preferences for user_123", value: { theme: "dark", language: "en", notifications: { email: true, sms: false, push: true }, timezone: "America/New_York" }, metadata: { userId: "user_123" }, tags: ["preferences", "settings"] }); console.log(`Created memory: ${userPrefs.id}`); // Retrieve the memory later const memory = await db.getMemory("user_123_preferences"); if (memory) { console.log("User preferences:", memory.value); // Output: User preferences: { theme: 'dark', language: 'en', ... } // Update tags await memory.saveTags(["preferences", "settings", "verified"]); } // Create memory for learned facts const userFacts = await db.createMemory({ id: "user_123_profile", value: { name: "Alice Johnson", company: "Acme Corp", role: "Engineering Manager", preferredContactTime: "mornings" }, label: "User Profile", tags: ["profile", "facts"] }); ``` -------------------------------- ### Search Dialogues, Messages, and Memories (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Illustrates how to perform semantic searches across different DialogueDB data types. Examples include searching dialogues with filters, searching messages, and searching memories with optional limits and filters. ```typescript // Search dialogues const dialogues = await db.searchDialogues("billing issue", { limit: 10, filter: { tags: ["support"] }, }); // Search messages const messages = await db.searchMessages("password reset", { limit: 20, }); // Search memories const memories = await db.searchMemories("user preferences", { limit: 5, }); ``` -------------------------------- ### Filtering Messages by Metadata (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates how to filter messages using date criteria and custom metadata like userId. This example shows a practical application of search options. ```typescript const messages = await db.searchMessages("order status", { filter: { createdMonth: 1, createdYear: 2025, }, metadata: { userId: "user_123" }, }); ``` -------------------------------- ### Initialize DialogueDB Client Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Initializes a new DialogueDB client instance using either an API key or an environment variable. This client is the entry point for all subsequent operations like creating dialogues, memories, and performing searches. Ensure you have valid API credentials before initialization. ```typescript import { DialogueDB } from "dialogue-db"; // Initialize with API key const db = new DialogueDB({ apiKey: "your-api-key-here" }); // Or use environment variable DIALOGUE_DB_API_KEY const db = new DialogueDB(); // The client is now ready to create dialogues, memories, and perform searches ``` -------------------------------- ### Class vs Data Objects Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Explains the difference between using the `DialogueDB` class methods and the direct API. ```APIDOC ## Advanced - Class vs Data Objects ### Description This section clarifies the distinction between the objects returned by the `DialogueDB` class methods and those returned by the direct API. ### DialogueDB Class Instances When using methods from the `DialogueDB` class, you receive class instances that have built-in methods for managing their state and tracking changes. #### Example: ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: "..." }); const dialogue = await db.getDialogue("id"); // Dialogue is a class instance dialogue.state = { updated: true }; console.log(dialogue.isDirty); // true - tracks unsaved changes await dialogue.save(); // Saves changes and resets dirty state console.log(dialogue.isDirty); // false ``` ### Direct API Data Objects Methods accessed via `api.` (the direct API) return plain data objects. These objects do not have the extra state-tracking methods found in class instances. #### Example: ```typescript import { api } from "dialogue-db"; const data = await api.dialogue.get("id"); // 'data' is a plain object // console.log(data.isDirty); // undefined - no state tracking methods ``` ``` -------------------------------- ### Using DialogueDB Class Instance (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Illustrates the difference between using the DialogueDB class instance and the direct API. The class instance provides methods for tracking changes and saving data. ```typescript const db = new DialogueDB({ apiKey: "..." }); const dialogue = await db.getDialogue("id"); // Class instance has methods and state tracking dialogue.state = { updated: true }; console.log(dialogue.isDirty); // true - tracks unsaved changes await dialogue.save(); console.log(dialogue.isDirty); // false ``` -------------------------------- ### Initialize DialogueDB Direct API (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Initializes the direct API interface for DialogueDB, allowing for direct mapping to REST endpoints. Configuration requires an API key. ```typescript import { api, createConfig } from "dialogue-db"; createConfig({ apiKey: "your-api-key" }); // Direct API calls map closely to REST endpoints const dialogue = await api.dialogue.create({ /* ... */ }); const messages = await api.messages.list({ dialogueId: "id" }); ``` -------------------------------- ### Using Direct API vs Class Instance (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Highlights that the direct API returns plain data objects without the additional methods and state tracking found in class instances obtained via the DialogueDB class. ```typescript const data = await api.dialogue.get("id"); // data.isDirty - undefined (not a class instance) ``` -------------------------------- ### Direct API Operations with DialogueDB Client Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Demonstrates direct access to DialogueDB API functions for creating, listing, updating, and removing dialogues, messages, and memories. It also shows how to perform searches directly through the API. Returns plain objects representing the resources. ```typescript import { api, createConfig } from "dialogue-db"; // Configure API key once createConfig({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Direct dialogue operations - returns plain objects const dialogue = await api.dialogue.create({ namespace: "support", messages: [ { role: "user", content: "Hello" } ], state: { step: 1 }, tags: ["new"] }); console.log("Created dialogue:", dialogue.id); // List dialogues with filters const { items, next } = await api.dialogue.list({ limit: 20, namespace: "support", tags: ["active"] }); console.log(`Found ${items.length} dialogues`); if (next) { console.log("More results available with pagination token"); } // Update dialogue const updated = await api.dialogue.update({ id: dialogue.id, state: { step: 2, resolved: false }, tags: ["active", "in-progress"] }); // Create single message const message = await api.message.create({ dialogueId: dialogue.id, role: "assistant", content: "How can I help you today?" }); // Create multiple messages const messages = await api.messages.create({ id: dialogue.id, messages: [ { role: "user", content: "I need help" }, { role: "assistant", content: "I'm here to assist" } ] }); // Memory operations const memory = await api.memory.create({ id: "key_001", value: { setting: "enabled" }, tags: ["config"] }); const retrieved = await api.memory.get("key_001"); console.log("Memory value:", retrieved?.value); // Search using direct API const searchResults = await api.search({ query: "billing questions", object: "dialogue", limit: 10, filter: { tags: ["support"] } }); console.log(`Search found ${searchResults.items.length} dialogues`); // Remove resources await api.message.remove({ dialogueId: dialogue.id, id: message.id }); await api.memory.remove("key_001"); await api.dialogue.remove(dialogue.id); ``` -------------------------------- ### Load Messages with Pagination using Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Demonstrates how to load messages from a dialogue in batches using pagination. This is essential for handling large conversation histories efficiently. It utilizes the `loadMessages` method with `limit` and `next` options. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); const dialogue = await db.getDialogue("dlg_xyz789"); // Initial load of first 50 messages await dialogue.loadMessages({ limit: 50 }); console.log(`Loaded ${dialogue.messages.length} messages`); console.log(`Has more: ${dialogue.hasMoreMessages}`); // Load next batch of messages if (dialogue.hasMoreMessages) { await dialogue.loadMessages({ limit: 50, next: true }); console.log(`Total messages now: ${dialogue.messages.length}`); } // Continue loading until all messages are retrieved while (dialogue.hasMoreMessages) { await dialogue.loadMessages({ limit: 50, next: true }); } console.log(`Loaded all ${dialogue.messages.length} messages`); ``` -------------------------------- ### Initialize DialogueDB Client (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Initializes the DialogueDB client using an API key, either directly or via environment variables. The apiKey is required for authentication. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); ``` ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: "your-api-key" }); ``` -------------------------------- ### Create a New Dialogue (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Creates a new dialogue with optional parameters including namespace, initial messages, state, metadata, and tags. The namespace helps in organizing dialogues. ```typescript const dialogue = await db.createDialogue({ namespace: "my-app", // Optional grouping messages: [ { role: "user", content: "Hello" }, ], state: { context: "onboarding" }, metadata: { userId: "123" }, tags: ["new"], }); ``` -------------------------------- ### Plan Limits Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Information on account plan limits for API requests, dialogues, messages, storage, and features, along with error handling for exceeding limits. ```APIDOC ## Plan Limits Account plans dictate resource limits, including: - API requests per month - Number of dialogues and messages - Storage capacity - Access to features like semantic search and auto-summarization Exceeding limits will result in a `429` status code with details about the specific limit reached. Plan settings can be managed in the DialogueDB dashboard. ### Response #### Error Response (429) - **message** (string) - Description of the limit that was exceeded. ``` -------------------------------- ### Create and Manage Threads using Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Shows how to create and manage conversation threads within a dialogue. Threads allow for branching conversations, useful for sub-tasks or alternative response paths. Includes creating threads, adding messages, and retrieving all threads for a dialogue. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); const parentDialogue = await db.getDialogue("dlg_xyz789"); // Create a thread for internal agent reasoning const reasoningThread = await parentDialogue.createThread({ metadata: { purpose: "chain-of-thought", visibility: "internal" }, tags: ["reasoning", "internal"] }); // Add reasoning steps to the thread await reasoningThread.saveMessages([ { role: "system", content: "Analyzing billing inquiry..." }, { role: "system", content: "Checking account for overages..." }, { role: "system", content: "Found usage spike on 2025-01-03" } ]); // Create thread for conversation branch const alternativeThread = await parentDialogue.createThread({ metadata: { purpose: "alternative-response" }, tags: ["branch"] }); // Get all threads for the parent dialogue const allThreads = await parentDialogue.getThreads(); console.log(`Parent dialogue has ${allThreads.length} threads`); allThreads.forEach(thread => { console.log(`Thread ${thread.id}: ${thread.metadata.purpose}`); }); ``` -------------------------------- ### Create a Memory (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Illustrates how to create a new memory entry in DialogueDB. This involves specifying an ID, value, label, description, and optional tags. Memories are used for persistent, searchable storage across conversations. ```typescript const memory = await db.createMemory({ id: "user-preferences", value: { theme: "dark", language: "en" }, label: "User Preferences", description: "Stores user UI preferences", tags: ["settings"], }); ``` -------------------------------- ### Search Dialogues Semantically using Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Demonstrates how to perform semantic searches on dialogues using natural language queries. This allows finding relevant conversations based on their content and metadata. Supports filtering by tags, creation date, and other metadata. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Search for dialogues about specific topics const billingDialogues = await db.searchDialogues("billing issues and payment problems", { limit: 10, filter: { tags: ["support"], createdYear: 2025, createdMonth: 1 }, metadata: { priority: "high" } }); console.log(`Found ${billingDialogues.length} billing-related dialogues`); billingDialogues.forEach(dialogue => { console.log(`Dialogue ${dialogue.id}: ${dialogue.label}`); console.log(` Created: ${dialogue.created}`); console.log(` Tags: ${dialogue.tags.join(", ")}`); console.log(` State:`, dialogue.state); }); // Search with date filters const recentDialogues = await db.searchDialogues("urgent customer issues", { limit: 20, filter: { createdDay: 5, createdMonth: 1, createdYear: 2025, tags: ["urgent"] } }); console.log(`Found ${recentDialogues.length} urgent dialogues from Jan 5, 2025`); ``` -------------------------------- ### Create and Retrieve Threads (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates creating a new thread linked to a dialogue and retrieving all threads associated with a dialogue. Threads are useful for branching conversations or separating concerns. ```typescript // Create a linked thread const thread = await dialogue.createThread({ metadata: { purpose: "internal-reasoning" }, }); // Get all threads for a dialogue const threads = await dialogue.getThreads(); ``` -------------------------------- ### Bulk Message Operations Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md APIs for creating and listing multiple messages in bulk for a dialogue. ```APIDOC ## Direct API - Bulk Message Operations ### Description Provides methods for creating multiple messages at once for a dialogue and for listing all messages within a dialogue. ### Methods - `api.messages.create(data: { id: string; messages: CreateMessageInput[] })`: Creates multiple messages for a dialogue. - `api.messages.list(options: { dialogueId: string })`: Lists all messages for a given dialogue ID. ### Request Example (Create Messages) ```json { "id": "dialogue-id", "messages": [ {"role": "user", "content": "First message"}, {"role": "assistant", "content": "First response"} ] } ``` ### Response Example (List Messages) ```json [ { "id": "message-id-1", "dialogueId": "dialogue-id", "role": "user", "content": "First message", "created": "2023-10-27T10:05:00Z", "modified": "2023-10-27T10:05:00Z", "metadata": {}, "tags": [] }, { "id": "message-id-2", "dialogueId": "dialogue-id", "role": "assistant", "content": "First response", "created": "2023-10-27T10:06:00Z", "modified": "2023-10-27T10:06:00Z", "metadata": {}, "tags": [] } ] ``` ``` -------------------------------- ### Dialogue Operations Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md APIs for creating, retrieving, listing, updating, and deleting dialogues. ```APIDOC ## Direct API - Dialogue Operations ### Description Provides methods for managing dialogues, including creation, retrieval, listing, updating, and deletion. ### Methods - `api.dialogue.create(data: CreateDialogueInput)`: Creates a new dialogue. - `api.dialogue.get(id: string)`: Retrieves a dialogue by its ID. - `api.dialogue.list(options?: { limit?: number })`: Lists dialogues with an optional limit. - `api.dialogue.update(data: { id: string; state: Record })`: Updates a dialogue's state. - `api.dialogue.remove(id: string)`: Deletes a dialogue by its ID. ### Request Example (Create Dialogue) ```json { "namespace": "example-namespace", "label": "Example Dialogue", "metadata": {"userId": "user_123"} } ``` ### Response Example (Get Dialogue) ```json { "id": "dialogue-id", "projectId": "project-id", "requestId": "request-id", "status": "active", "created": "2023-10-27T10:00:00Z", "modified": "2023-10-27T10:00:00Z", "tags": ["tag1"], "namespace": "example-namespace", "label": "Example Dialogue", "metadata": {"userId": "user_123"}, "totalMessages": 0 } ``` ``` -------------------------------- ### Load Paginated Messages (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Loads messages for a dialogue with support for pagination. Allows fetching initial messages and subsequent pages using a limit and a 'next' flag. ```typescript // Initial load await dialogue.loadMessages({ limit: 50 }); // Load more if (dialogue.hasMoreMessages) { await dialogue.loadMessages({ limit: 50, next: true }); } ``` -------------------------------- ### Manage Message Tags and Lifecycle with DialogueDB Node.js Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Demonstrates how to update message tags in batch or immediately, save changes, remove individual messages, and delete messages via the dialogue object. It uses the DialogueDB client for Node.js, assuming an active API key and existing dialogue. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); const dialogue = await db.getDialogue("dlg_xyz789"); // Get first message const message = dialogue.messages[0]; console.log(`Current tags: ${message.tags.join(", ")}`); // Update tags - batch mode message.tags = ["reviewed", "important", "flagged"]; console.log(message.isDirty); // true await message.save(); console.log(message.isDirty); // false // Or update tags immediately await message.saveTags(["reviewed", "important", "archived"]); // Remove message entirely await message.remove(); console.log(`Messages remaining: ${dialogue.messages.length}`); // Or remove via dialogue await dialogue.deleteMessage("msg_abc123"); // Remove multiple messages const messagesToRemove = dialogue.messages .filter(m => m.tags.includes("spam")) .map(m => m.id); for (const msgId of messagesToRemove) { await dialogue.deleteMessage(msgId); } console.log(`Cleaned up ${messagesToRemove.length} spam messages`); ``` -------------------------------- ### Paginate Dialogue Messages (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Illustrates how to retrieve messages from a dialogue and handle pagination. The `Dialogue` class provides `hasMoreMessages` to check for subsequent pages and `loadMessages` to fetch them, with options for `limit` and `next`. ```typescript const dialogue = await db.getDialogue("id"); // Check if more messages exist if (dialogue.hasMoreMessages) { // Load the next set of messages await dialogue.loadMessages({ limit: 50, next: true }); } ``` -------------------------------- ### Message Pagination Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Explains how the DialogueDB Node.js client handles message pagination, including checking for more messages and loading them. ```APIDOC ## Pagination The `Dialogue` class provides functionality for paginating messages within a dialogue. ### Request Example ```typescript const dialogue = await db.getDialogue("id"); // Check if more messages exist if (dialogue.hasMoreMessages) { await dialogue.loadMessages({ limit: 50, next: true }); } ``` ### Parameters #### Query Parameters - **limit** (number) - Optional - The maximum number of messages to load. - **next** (boolean) - Optional - If true, loads the next page of messages. ``` -------------------------------- ### Core Interfaces Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Defines the structure of core data objects like Dialogue, Message, and Memory. ```APIDOC ## TypeScript - Core Interfaces ### Description Defines the type structures for the main data entities within DialogueDB. ### Interfaces #### `IDialogue` Represents a dialogue conversation. ```typescript interface IDialogue { id: string; projectId: string; requestId: string; status: "active" | "ended" | "archived"; created: string; modified: string; tags: string[]; namespace?: string; threadOf?: string; label?: string; state?: Record; messages?: IMessage[]; metadata?: Record; totalMessages?: number; threadCount?: number; } ``` #### `IMessage` Represents a single message within a dialogue. ```typescript interface IMessage { id: string; dialogueId: string; role: string; content: string | object | object[]; created: string; modified: string; metadata: Record; tags: string[]; name?: string; } ``` #### `IMemory` Represents a stored memory item. ```typescript interface IMemory { id: string; value: string | number | boolean | object | any[]; metadata: Record; tags: string[]; created: string; modified: string; namespace?: string; label?: string; description?: string; } ``` ``` -------------------------------- ### Create New Dialogue Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Creates a new dialogue within DialogueDB, which acts as a container for conversation history. It can be initialized with optional messages, state, metadata, and tags. The creation process returns a dialogue object with a unique ID and the initial messages. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Create dialogue with initial messages and metadata const dialogue = await db.createDialogue({ namespace: "customer-support", label: "Billing inquiry", messages: [ { role: "user", content: "I have a question about my bill" }, { role: "assistant", content: "I'd be happy to help with your billing question." } ], state: { topic: "billing", priority: "high", step: 1 }, metadata: { userId: "user_123", channel: "web", sessionId: "sess_abc" }, tags: ["support", "billing"] }); console.log(`Created dialogue: ${dialogue.id}`); console.log(`Total messages: ${dialogue.messages.length}`); // Output: // Created dialogue: dlg_xyz789 // Total messages: 2 ``` -------------------------------- ### Input Types Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Defines the types used for creating and updating data entities. ```APIDOC ## TypeScript - Input Types ### Description Defines the structures for input data when creating or modifying DialogueDB entities. ### Types #### `CreateDialogueInput` Input for creating a new dialogue. ```typescript type CreateDialogueInput = { namespace?: string; threadOf?: string; label?: string; messages?: CreateMessageInput[]; state?: Record; metadata?: Record; tags?: string[]; }; ``` #### `CreateMessageInput` Input for creating a new message. ```typescript type CreateMessageInput = { role: string; content: string | object | object[]; id?: string; tags?: string[]; metadata?: Record; }; ``` #### `CreateMemoryInput` Input for creating a new memory entry. ```typescript type CreateMemoryInput = { value: string | number | boolean | object | any[]; id?: string; namespace?: string; label?: string; description?: string; tags?: string[]; metadata?: Record; }; ``` #### `SearchOptions` Options for filtering search queries. ```typescript type SearchOptions = { limit?: number; filter?: { tags?: string[]; created?: string; createdYear?: number; createdMonth?: number; createdDay?: number; modified?: string; modifiedYear?: number; modifiedMonth?: number; modifiedDay?: number; }; metadata?: Record; }; ``` ``` -------------------------------- ### Retrieve a Memory (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates how to fetch a specific memory by its ID. If the memory exists, its value is logged to the console. This is useful for recalling stored information. ```typescript const memory = await db.getMemory("user-preferences"); if (memory) { console.log(memory.value); // { theme: "dark", language: "en" } } ``` -------------------------------- ### Memory Operations Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md APIs for creating, retrieving, updating, and deleting memory entries. ```APIDOC ## Direct API - Memory Operations ### Description Provides methods for managing memory entries, including creation, retrieval, updating, and deletion. ### Methods - `api.memory.create(data: CreateMemoryInput)`: Creates a new memory entry. - `api.memory.get(id: string)`: Retrieves a memory entry by its ID. - `api.memory.update(data: { id: string; value: any })`: Updates an existing memory entry. - `api.memory.remove(id: string)`: Deletes a memory entry by its ID. ### Request Example (Create Memory) ```json { "id": "memory-key", "value": "some data", "namespace": "user-prefs", "tags": ["config"] } ``` ### Response Example (Get Memory) ```json { "id": "memory-key", "value": "some data", "metadata": {}, "tags": ["config"], "created": "2023-10-27T10:07:00Z", "modified": "2023-10-27T10:07:00Z", "namespace": "user-prefs" } ``` ``` -------------------------------- ### Save Behavior Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md This section details how to save state and tags for a dialogue using the DialogueDB Node.js client. It explains batched saves and immediate saves. ```APIDOC ## Save Behavior The `Dialogue` class allows for batched saving of state and tag changes locally before a single API call is made using the `save()` method. Alternatively, immediate saving can be performed using `saveState()` and `saveTags()` methods. Messages are always saved immediately via `saveMessage()` or `saveMessages()`. ### Request Example ```typescript // Batched save dialogue.state = { step: 1 }; dialogue.tags = ["important"]; await dialogue.save(); // Immediate saves await dialogue.saveState({ step: 1 }); await dialogue.saveTags(["important"]); ``` ### Response #### Success Response (200) - **void** - Operation successful. #### Response Example ```json // No response body on successful save operations ``` ``` -------------------------------- ### Search Options Interface (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Defines the structure for search options, including limits, filters by tags, dates, and custom metadata. Used to customize search queries in DialogueDB. ```typescript { limit?: number; filter?: { tags?: string[]; created?: string; createdYear?: number; createdMonth?: number; createdDay?: number; modified?: string; modifiedYear?: number; modifiedMonth?: number; modifiedDay?: number; }; metadata?: Record; } ``` -------------------------------- ### Search API Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md API for performing searches across dialogues with various filtering options. ```APIDOC ## Direct API - Search ### Description Allows you to search for dialogues based on a query string and provides options for filtering results by creation/modification dates, tags, and custom metadata. ### Method `api.search(options: { query: string; object?: 'dialogue' | 'message' | 'memory'; limit?: number; filter?: SearchOptions['filter']; metadata?: SearchOptions['metadata'] })` ### Parameters #### Query Parameters - **query** (string) - Required - The search query string. - **object** (string) - Optional - The type of object to search ('dialogue', 'message', 'memory'). Defaults to 'dialogue'. - **limit** (number) - Optional - Maximum number of results to return. - **filter** (object) - Optional - Filtering criteria for search results. - **tags** (string[]) - Filter by tags. - **created** (string) - Filter by creation date (ISO format). - **createdYear** (number) - Filter by creation year. - **createdMonth** (number) - Filter by creation month (1-12). - **createdDay** (number) - Filter by creation day (1-31). - **modified** (string) - Filter by modification date (ISO format). - **modifiedYear** (number) - Filter by modification year. - **modifiedMonth** (number) - Filter by modification month (1-12). - **modifiedDay** (number) - Filter by modification day (1-31). - **metadata** (object) - Optional - Filter by custom metadata key-value pairs. ### Request Example ```json { "query": "order status", "object": "dialogue", "limit": 5, "filter": { "createdMonth": 1, "createdYear": 2025 }, "metadata": { "userId": "user_123" } } ``` ### Response Example (Success Response) ```json [ { "id": "dialogue-id-1", "projectId": "project-id", "requestId": "request-id", "status": "active", "created": "2025-01-15T09:30:00Z", "modified": "2025-01-15T09:35:00Z", "tags": ["support"], "label": "Order Status Inquiry", "metadata": {"userId": "user_123"}, "totalMessages": 3 } ] ``` ``` -------------------------------- ### Manage Dialogue Tags (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Enables updating the tags associated with a dialogue. Tags can be set and saved later, or saved immediately using `saveTags`. ```typescript // Set and save later dialogue.tags = ["vip", "priority"]; await dialogue.save(); // Or save immediately await dialogue.saveTags(["vip", "priority"]); ``` -------------------------------- ### Input Validation Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Details the input validation rules enforced by the API, including handling of query parameters, metadata, tags, and IDs. ```APIDOC ## Input Validation The API enforces the following input validation rules: - **Unknown query parameters**: Rejected on list endpoints. Unsupported query parameters will result in an error. - **Metadata**: Must be flat (key-value pairs with string, number, or boolean values). Nested objects are not allowed. - **Tags**: Each tag has a maximum length of 64 characters. - **Dialogue IDs**: Always auto-generated. Any `id` provided during dialogue creation is ignored. - **Message IDs**: Can be provided or will be auto-generated if omitted. ``` -------------------------------- ### Retrieve a Dialogue by ID (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Fetches an existing dialogue from DialogueDB using its unique identifier. The result is a Dialogue object or null if not found. ```typescript const dialogue = await db.getDialogue("dialogue-id"); if (dialogue) { console.log(dialogue.messages); } ``` -------------------------------- ### Save Dialogue State and Tags (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates how to save changes to a dialogue's state and tags. Changes can be batched and saved in a single API call using `dialogue.save()`, or saved immediately using `dialogue.saveState()` and `dialogue.saveTags()`. Messages are always saved immediately. ```typescript const dialogue = await db.getDialogue("dialogue-id"); // Batch changes dialogue.state = { step: 1 }; dialogue.tags = ["important"]; await dialogue.save(); // Single API call saves both // Or use immediate methods await dialogue.saveState({ step: 1 }); // Saves immediately await dialogue.saveTags(["important"]); // Saves immediately // Messages are always saved immediately await dialogue.saveMessage({ text: "Hello" }); await dialogue.saveMessages([{ text: "World" }]); ``` -------------------------------- ### Update Dialogue State and Tags Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Modifies the state and tags associated with an existing dialogue. Changes can be batched locally and then saved with a single operation, or state and tags can be saved immediately. This allows for efficient management of conversation context and categorisation. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); const dialogue = await db.getDialogue("dlg_xyz789"); // Batch changes locally, then save once dialogue.state = { topic: "billing", resolved: true, satisfactionScore: 5, step: 3 }; dialogue.tags = ["support", "billing", "resolved"]; dialogue.label = "Billing inquiry - Resolved"; console.log(dialogue.isDirty); // true - has unsaved changes await dialogue.save(); console.log(dialogue.isDirty); // false - all changes saved // Or save state immediately without batching await dialogue.saveState({ topic: "billing", resolved: true }); // Or save tags immediately await dialogue.saveTags(["support", "resolved"]); ``` -------------------------------- ### Manage Dialogue State (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Allows updating the state of a dialogue. State can be modified and saved later, or saved immediately using `saveState`. ```typescript // Set and save later dialogue.state = { step: 2, context: "payment" }; await dialogue.save(); // Or save immediately await dialogue.saveState({ step: 2, context: "payment" }); ``` -------------------------------- ### Search Memories Semantically with DialogueDB Client Source: https://context7.com/dialoguedb/client-nodejs/llms.txt Retrieves stored memories based on semantic similarity to a query. Allows filtering by tags and searching based on metadata. Returns an array of memory objects, each with an ID, label, value, and description. ```typescript import { DialogueDB } from "dialogue-db"; const db = new DialogueDB({ apiKey: process.env.DIALOGUE_DB_API_KEY }); // Search for relevant user preferences and facts const userSettings = await db.searchMemories("user interface preferences and display settings", { limit: 5, filter: { tags: ["preferences"] } }); console.log(`Found ${userSettings.length} preference memories`); userSettings.forEach(memory => { console.log(`Memory ${memory.id}: ${memory.label}`); console.log(` Value:`, memory.value); console.log(` Description: ${memory.description}`); }); // Search for learned facts about users const customerKnowledge = await db.searchMemories("customer background and company information", { limit: 10, filter: { tags: ["profile", "facts"] }, metadata: { verified: true } }); console.log(`Found ${customerKnowledge.length} customer profiles`); customerKnowledge.forEach(memory => { console.log(`${memory.label}: ${JSON.stringify(memory.value, null, 2)}`); }); ``` -------------------------------- ### DialogueDB Input Types (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Defines TypeScript types for input parameters used in DialogueDB operations, such as creating dialogues, messages, and memories, as well as search options. ```typescript type CreateDialogueInput = { namespace?: string; threadOf?: string; label?: string; messages?: CreateMessageInput[]; state?: Record; metadata?: Record; tags?: string[]; }; type CreateMessageInput = { role: string; content: string | object | object[]; id?: string; tags?: string[]; metadata?: Record; }; type CreateMemoryInput = { value: string | number | boolean | object | any[]; id?: string; namespace?: string; label?: string; description?: string; tags?: string[]; metadata?: Record; }; type SearchOptions = { limit?: number; filter?: { tags?: string[]; created?: string; createdYear?: number; createdMonth?: number; createdDay?: number; modified?: string; modifiedYear?: number; modifiedMonth?: number; modifiedDay?: number; }; metadata?: Record; }; ``` -------------------------------- ### Single Message Operations Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md APIs for creating and deleting individual messages within a dialogue. ```APIDOC ## Direct API - Single Message Operations ### Description Provides methods for managing individual messages, including creation and deletion within a specific dialogue. ### Methods - `api.message.create(data: CreateMessageInput)`: Creates a new message. - `api.message.remove(data: { dialogueId: string; id: string })`: Deletes a message by its ID within a dialogue. ### Request Example (Create Message) ```json { "dialogueId": "dialogue-id", "role": "user", "content": "Hello, DialogueDB!" } ``` ### Response Example (Create Message) ```json { "id": "message-id", "dialogueId": "dialogue-id", "role": "user", "content": "Hello, DialogueDB!", "created": "2023-10-27T10:05:00Z", "modified": "2023-10-27T10:05:00Z", "metadata": {}, "tags": [] } ``` ``` -------------------------------- ### Access and Iterate Dialogue Messages (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Demonstrates how to access the messages array from a dialogue object and iterate through each message to log its role and content. This is a fundamental operation for processing conversation history. ```typescript const messages = dialogue.messages; for (const message of messages) { console.log(`${message.role}: ${message.content}`); } ``` -------------------------------- ### Update and Save Memory Tags (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Shows two ways to update the tags for a memory. Similar to messages, tags can be updated directly on the memory object followed by a `save()` call, or immediately via the `saveTags()` method. ```typescript memory.tags = ["archived"]; await memory.save(); // Or immediately await memory.saveTags(["archived"]); ``` -------------------------------- ### Core DialogueDB Interfaces (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Defines the core TypeScript interfaces for DialogueDB entities: IDialogue, IMessage, and IMemory. These interfaces outline the structure and properties of data objects used within the SDK. ```typescript interface IDialogue { id: string; projectId: string; requestId: string; status: "active" | "ended" | "archived"; created: string; modified: string; tags: string[]; // Optional fields namespace?: string; threadOf?: string; label?: string; state?: Record; messages?: IMessage[]; metadata?: Record; totalMessages?: number; threadCount?: number; } interface IMessage { id: string; dialogueId: string; role: string; content: string | object | object[]; created: string; modified: string; metadata: Record; tags: string[]; name?: string; } interface IMemory { id: string; value: string | number | boolean | object | any[]; metadata: Record; tags: string[]; created: string; modified: string; namespace?: string; label?: string; description?: string; } ``` -------------------------------- ### Save Messages to a Dialogue (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Persists one or more messages to an existing dialogue. Supports saving a single message or an array of messages. ```typescript // Single message const message = await dialogue.saveMessage({ role: "assistant", content: "How can I help?", }); // Multiple messages at once const messages = await dialogue.saveMessages([ { role: "user", content: "Question 1" }, { role: "user", content: "Question 2" }, ]); ``` -------------------------------- ### Update and Save Message Tags (TypeScript) Source: https://github.com/dialoguedb/client-nodejs/blob/main/readme.md Shows two methods for updating the tags associated with a message. The first method updates the tags property and requires a subsequent call to `save()`. The second method uses `saveTags()` for an immediate update. ```typescript const message = dialogue.messages[0]; // Set and save later message.tags = ["reviewed"]; await message.save(); // Or save immediately await message.saveTags(["reviewed"]); ```