How to Use the TypeScript SDK to Manage Chat Memory Layers in TencentDB Agent Memory
The TencentDB Agent Memory TypeScript SDK exposes the V3Client.clearChatMemory method to atomically purge all four logical layers (L0‑L3) while preserving asset metadata, alongside layer-specific read/write utilities via MemoryPromptClient and generic core APIs.
The TencentDB-Agent-Memory repository provides a TypeScript SDK that enables developers to programmatically manipulate chat memory assets through a layered storage architecture. By using the TypeScript SDK to manage Chat Memory layers, you can build stateful agent workflows that efficiently handle conversation context across raw utterances, indexed records, vector embeddings, and consolidated prompt files.
Understanding the Four Chat Memory Layers
Chat memory in the TencentDB ecosystem is divided into four logical tiers that represent different stages of data refinement:
- L0 – Raw chat utterances stored as plain text.
- L1 – Token‑level index records for fast lookup.
- L2 – Vector embeddings and profile metadata for semantic search.
- L3 – Consolidated prompt‑ready files consumed directly by agents.
Each layer serves a distinct purpose in the retrieval‑augmented generation pipeline, and the SDK allows you to target them individually or clear them collectively.
Clearing Chat Memory Assets with V3Client
The only chat‑memory‑specific operation that the SDK currently ships is clearing an entire memory asset while preserving its configuration metadata (owner, ACL, and name). This operation is implemented in src/v3/client.ts within the V3Client class.
The clearChatMemory Method
The V3Client.clearChatMemory method sends a POST /v3/chat-memory/clear request that atomically wipes all four layers for each supplied memory_id. The operation is idempotent—calling it again on an already‑cleared memory returns success with zero deletions.
import { V3Client } from './src/v3/client';
import { V3ChatMemoryClearRequest } from './src/v3/types';
// Clear specific memory assets
async function clearMemories(memoryIds: string[]) {
const req: V3ChatMemoryClearRequest = { memory_ids: memoryIds };
const resp = await client.clearChatMemory(req);
return resp.data;
}
The method signature and validation logic are located at V3Client.clearChatMemory in the source tree.
Request Validation and Limits
Before transmitting the request, the SDK validates that the memory_ids array meets strict criteria:
- Must contain between 1 and 100 unique identifiers.
- Each string must be non‑empty.
- All IDs must belong to the
chat_memoryasset type.
If any ID is missing or belongs to a different asset type, the entire batch is rejected and the service returns a failure for the complete request rather than partial success.
Handling Batch Responses and Errors
The response type V3ChatMemoryClearData (defined in src/v3/types.ts) contains per‑asset status codes that indicate success or specific failure reasons:
function reportClearResult(data: V3ChatMemoryClearData) {
data.items.forEach(item => {
console.log(`Memory ${item.memory_id}: cleared=${item.cleared}`);
if (!item.cleared) {
console.warn(` Reason: ${item.reason}`);
if (item.retryable) console.info(' Will retry later');
}
});
console.log('All cleared?', data.all_cleared);
}
Each item includes fields for cleared, reason, retryable, and attempts, allowing you to implement robust retry logic for transient failures.
Reading and Writing Individual Layers
While clearing targets the entire asset, reading and writing operations typically target specific layers. The SDK provides both generic core APIs and specialized helpers for this purpose.
Using MemoryPromptClient for L3 Operations
To interact with the L3 layer (consolidated prompts), use the MemoryPromptClient defined in src/v3/memory-prompt-client.ts. This helper accepts the MemoryPromptLayer enumeration from src/v3/memory-prompt-types.ts to specify the target tier:
import { MemoryPromptLayer } from './src/v3/memory-prompt-types';
import { MemoryPromptClient } from './src/v3/memory-prompt-client';
const promptClient = new MemoryPromptClient(client);
// Write a prompt file to the L3 layer
await promptClient.writePrompt({
memory_id: 'mem-12345',
layer: MemoryPromptLayer.L3,
content: 'You are a helpful assistant...',
});
// Read the same prompt back
const prompt = await promptClient.readPrompt({
memory_id: 'mem-12345',
layer: MemoryPromptLayer.L3,
});
console.log('Prompt content:', prompt.content);
The MemoryPromptLayer enum maps directly to L0 through L3, enabling type‑safe layer selection for downstream operations.
Accessing L0, L1, and L2 via Core APIs
For layers other than L3, or for custom data access patterns, the V3Client exposes readCore and writeCore methods (implemented in src/v3/client.ts). These generic entry points accept layer identifiers and handle the underlying transport to the V3 gateway, allowing you to manipulate raw utterances (L0), index records (L1), and vector profiles (L2) programmatically.
Practical Implementation Patterns
Combining the clear operation with layer‑specific writes enables common agent memory workflows.
The Memory Recycling Workflow
A typical pattern involves clearing existing state and immediately seeding new L3 content without destroying the asset identity:
async function recycleMemory(memoryId: string, newPrompt: string) {
// Clear all layers atomically
await client.clearChatMemory({ memory_ids: [memoryId] });
// Write new prompt to L3
await promptClient.writePrompt({
memory_id: memoryId,
layer: MemoryPromptLayer.L3,
content: newPrompt,
});
}
This workflow preserves the memory_id and its access controls while resetting conversational context.
Inspecting Operation Results
When debugging batch clear operations, iterate over the items array in the response to identify specific failures. Check the all_cleared boolean for quick validation that the entire batch succeeded before proceeding with subsequent write operations.
Summary
- Four logical layers (L0‑L3) store progressively refined chat data, from raw utterances to prompt‑ready files.
V3Client.clearChatMemoryinsrc/v3/client.tsprovides the only chat‑specific SDK operation, atomically clearing all layers while preserving asset metadata.- Batch constraints limit requests to 1‑100 unique
memory_ids, with strict validation that rejects the entire batch if any ID is invalid. MemoryPromptClientand theMemoryPromptLayerenum insrc/v3/memory-prompt-types.tsoffer type‑safe access to layer L3 for prompt management.- Generic core APIs (
readCore/writeCore) enable direct manipulation of L0, L1, and L2 storage tiers when specialized helpers are insufficient.
Frequently Asked Questions
What is the difference between clearing and deleting a chat memory asset?
Clearing via V3Client.clearChatMemory wipes the data in all four layers (L0‑L3) but preserves the asset's metadata, including its ID, owner, and ACL configuration. Deleting an asset would remove the configuration entirely, requiring you to recreate access controls. Clearing is the preferred method for recycling a memory_id between conversation sessions.
How do I target a specific layer when reading chat memory?
Use the MemoryPromptClient helper class for L3 (prompt layer) operations, passing the MemoryPromptLayer.L3 enum value. For other layers (L0‑L2), use the generic readCore method available on V3Client, specifying the appropriate layer identifier in the request parameters.
Is the clearChatMemory operation safe to retry?
Yes. The clearChatMemory operation is idempotent according to the implementation in src/v3/client.ts. If you retry a request after a network timeout, the second call will return success and report zero deletions if the first attempt already cleared the data, ensuring your application can safely implement automatic retry logic.
What happens if one memory ID in a batch does not exist?
The entire batch fails. The SDK validates that all memory_ids exist and belong to the chat_memory asset type before executing the clear operation. If any single ID is missing or invalid, the service returns an error response for the complete request, and no layers are cleared for any ID in the batch. You must correct the invalid ID and resubmit the complete list.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →