# How to Clear Chat Memory Across L0-L3 Layers for Privacy in TencentDB Agent Memory

> Learn how to clear chat memory across L0-L3 layers for privacy using the clearChatMemory API. Preserve asset identifiers for future use and ensure data security.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: how-to-guide
- Published: 2026-09-02

---

**Use the `clearChatMemory` asset-level API to wipe all conversation data across L0-L3 layers while preserving the memory asset identifier and metadata for reuse.**

The TencentDB-Agent-Memory SDK provides a purpose-built mechanism for privacy compliance and data retention policies. When you need to erase all traces of conversation history without destroying the underlying memory asset, the `clearChatMemory` method executes a comprehensive wipe of the hierarchical memory store—from raw conversation logs to synthesized core memories—while keeping the asset container intact for future sessions.

## Understanding the L0-L3 Memory Architecture

The TencentDB-Agent-Memory system organizes chat history into four distinct layers, each requiring specific handling during a privacy cleanup operation.

### What Gets Cleared vs. Preserved

When you invoke `clearChatMemory`, the operation targets these specific data layers defined in the client implementations:

- **L0 (Conversation Logs):** Raw message transcripts and interaction logs
- **L1 (Atomic Notes):** Extracted factual snippets and observations
- **L2 (Scenario Files):** Context-specific memory compilations and session summaries  
- **L3 (Core Memory):** Persistent long-term facts and user preferences
- **Vectors:** All embedded representations used for semantic retrieval
- **Uploaded Files:** Any documents or attachments associated with the memory asset

The following **asset metadata remains intact**:
- `memory_id` (the unique asset identifier)
- Team and agent bindings (`team_id`, `agent_id`)
- Access control lists (ACL) and ownership records
- Visibility settings and descriptive name fields

This design allows you to maintain the same `memory_id` across sessions while ensuring no residual conversation data persists between clear operations.

## Clearing Memory via the SDK Clients

Both the TypeScript and Python SDKs implement identical `clearChatMemory` functionality in their v3 clients, accepting a list of `memory_ids` (maximum 100 per request) rather than relying on the standard isolation triple (`team_id`, `agent_id`, `user_id`).

### TypeScript Implementation

In [`sdk/memory-core/typescript/src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/typescript/src/v3/client.ts) (lines 67-95), the `MemoryClient` exposes the `clearChatMemory` method:

```typescript
import { MemoryClient } from "@tencentdb-agent-memory/memory-sdk-ts-v2";

const client = new MemoryClient({
  endpoint: "https://memory.tencentyun.com",
  apiKey: "sk-mem-...",               // obtained from the panel
  serviceId: "mem-instance-id",
  teamId: "team-xyz",
  agentId: "agent-abc",
  userId: "user-123",
  // sessionId is optional – omit for cross-session aggregation
});

async function clearChatMemory() {
  const res = await client.clearChatMemory({ 
    memory_ids: ["chat_memory-t1-agt1"] 
  });

  if (!res.all_cleared) {
    const retryable = res.items.filter(i => !i.cleared && i.retryable);
    console.log("Retryable items:", retryable);
    // later you may call clearChatMemory again with the same IDs
  } else {
    console.log("All chat memories cleared.");
  }
}

clearChatMemory().catch(console.error);

```

### Python Implementation

The Python counterpart in [`sdk/memory-core/python/tencentdb_agent_memory/v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/sdk/memory-core/python/tencentdb_agent_memory/v3/client.py) (lines 25-53) provides identical functionality through the `clear_chat_memory` method:

```python
from tencentdb_agent_memory.v3 import MemoryClient

client = MemoryClient(
    endpoint="https://memory.tencentyun.com",
    api_key="sk-mem-...",          # from the panel

    service_id="mem-instance-id",
    team_id="team-xyz",
    agent_id="agent-abc",
    user_id="user-123",
    # session_id optional – leave None for cross-session aggregation

)

def clear_chat_memory():
    resp = client.clear_chat_memory(["chat_memory-t1-agt1"])

    if not resp["all_cleared"]:
        retryable = [i for i in resp["items"] 
                    if not i["cleared"] and i.get("retryable")]
        print("Retryable items:", retryable)
        # you can retry later with the same memory IDs

    else:
        print("All chat memories cleared.")

clear_chat_memory()

```

## Handling Permissions and Authorization

Understanding the authorization boundary is critical when clearing chat memory across L0-L3 layers, as the kernel and panel backend enforce different permission models.

### Kernel-Level vs. Panel Backend Authorization

**Kernel-level calls** (direct SDK usage) perform **no user-level authorization** for the clear operation according to the source code comments in [`typescript/src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/typescript/src/v3/client.ts) (lines 82-84). Any client with valid API credentials can clear any memory ID supplied in the request, regardless of ownership.

For environments requiring strict "owner-only" enforcement, route requests through the panel backend endpoint:

```bash
curl -X POST "https://panel.tencentyun.com/api/v1/chat-memory/clear" \
  -H "Authorization: Bearer <panel-token>" \
  -H "Content-Type: application/json" \
  -d '{"memory_ids": ["chat_memory-t1-agt1"]}'

```

The panel backend validates ownership before forwarding the request to the kernel, ensuring users can only clear memory assets they explicitly own or have permission to modify.

## Response Handling and Retry Logic

The `clearChatMemory` operation is **idempotent**—calling it multiple times on the same `memory_id` returns a successful response with `all_cleared: true` rather than raising an error.

Parse the response structure to handle partial failures:

- **`all_cleared`**: Boolean indicating whether every requested memory was fully wiped
- **`items`**: Array containing per-memory status objects with:
  - `cleared`: Boolean confirmation of deletion success for that specific memory
  - `retryable`: Boolean flag indicating whether the server attempted automatic retries

If `retryable` is `true` for any item, the operation encountered transient failures but marked the item for later retry. You can safely re-invoke `clearChatMemory` using the same ID list to complete the cleanup without risking data duplication or partial state corruption.

## Summary

- **`clearChatMemory`** is an asset-level API that wipes L0-L3 data, vectors, and files while preserving the `memory_id` and metadata bindings
- Scope is defined by the **`memory_ids`** array parameter (max 100 IDs), ignoring the standard isolation triple
- **TypeScript** and **Python** v3 clients implement identical functionality in [`src/v3/client.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/src/v3/client.ts) and [`v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/v3/client.py) respectively
- The kernel performs **no ownership checks**—use the panel backend `/api/v1/chat-memory/clear` endpoint for owner-only enforcement
- The operation is **idempotent** and returns detailed per-item status with `retryable` flags for handling partial failures

## Frequently Asked Questions

### What is the difference between clearing memory and deleting a memory asset?

Clearing memory wipes all conversation data across L0-L3 layers, vectors, and uploaded files while preserving the asset container—including its `memory_id`, team/agent bindings, and ACL configurations. Deleting an asset removes the entire memory record from the system. Use clearing when you need to reset conversation history while maintaining the same memory identifier for continuity.

### Why does clearChatMemory ignore the team_id/agent_id/user_id isolation triple?

The operation scopes exclusively via the `memory_ids` list provided in the request. This design allows bulk clearing across multiple assets without requiring multiple client instances or permission context switches. The kernel validates the API credentials but does not filter by the isolation triple, relying instead on the explicit ID list for precision targeting.

### How do I enforce owner-only clearing for sensitive data?

Invoke the panel backend endpoint `POST /api/v1/chat-memory/clear` instead of the direct SDK method. The panel layer performs ownership validation before executing the clear command, ensuring users can only wipe memory assets associated with their credentials. Direct SDK calls to the kernel bypass this check for performance in trusted environments.

### Is the clearChatMemory operation truly idempotent?

Yes. Repeated calls with the same `memory_ids` return `all_cleared: true` without error or side effects. If a previous call left某些 items in a retryable state due to transient failures, subsequent calls will complete the cleanup and update the `cleared` status accordingly. You may safely retry failed clears using identical parameters until `all_cleared` confirms completion.