# How to Use the Python SDK for Agent Memory Integration with TencentDB

> Integrate agent memory with TencentDB using the Python SDK. Explore synchronous and asynchronous clients for secure data isolation across teams, agents, users, and sessions.

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

---

**The TencentDB Agent Memory Python SDK provides a type-safe wrapper around the memory service HTTP API, exposing synchronous MemoryClient and asynchronous AsyncMemoryClient classes that enforce strict isolation across team, agent, user, and session boundaries.**

The TencentDB Agent Memory service enables persistent storage and retrieval of LLM agent conversations, atomic state, and user profiles. The official Python SDK, available in the TencentCloud/TencentDB-Agent-Memory repository, abstracts the underlying v3 HTTP endpoints into a clean interface that handles request signing, TLS verification, and automatic retries.

## Core Architecture and Client Classes

The SDK centers on two primary client implementations defined in [`tencentdb_agent_memory/v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/v3/client.py):

- **MemoryClient** – Synchronous client for blocking I/O operations
- **AsyncMemoryClient** – Asynchronous counterpart using `async`/`await` patterns

Both classes expose identical method signatures for L0-L3 memory operations, including `add_conversation()`, `query_conversation()`, `search_conversation()`, `count_conversation()`, and profile helpers like `read_scenario()`. The internal `_IsolationCtx` class manages the isolation context, providing helper methods `base_body()`, `resolve_session()`, and `resolve_session_for_write()` to construct valid request payloads.

HTTP transport is handled by thin stubs in [`tencentdb_agent_memory/_http.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/_http.py) (synchronous `HttpStub`) and [`tencentdb_agent_memory/_v3_http.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/_v3_http.py) (asynchronous `AsyncHttpStub`), which manage request signing and optional TLS verification. Validation errors raise `ParamError` from [`tencentdb_agent_memory/errors.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/errors.py).

## Installation and Client Initialization

Install the SDK from PyPI using pip:

```bash
pip install tencentdb-agent-memory

```

Instantiate `MemoryClient` with mandatory isolation identifiers. According to the `_validate_construction` method in [`client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/client.py), `team_id`, `agent_id`, and `user_id` are required at construction time; omission raises `ParamError`. The `session_id` is optional for read operations but required for writes.

```python
from tencentdb_agent_memory.v3 import MemoryClient

client = MemoryClient(
    endpoint="https://memory.tencentyun.com",
    api_key="sk-<YOUR_API_KEY>",
    service_id="mem-<SERVICE_ID>",
    team_id="team-123",
    agent_id="agent-xyz",
    user_id="user-abc",
    session_id="session-001",  # Optional for reads; enforced for writes

)

```

## Logging and Querying Conversations

The SDK distinguishes between write and read isolation requirements. For **write operations** like `add_conversation()`, the client enforces a non-empty `session_id` via `resolve_session_for_write()`. **Read operations** such as `query_conversation()`, `search_conversation()`, and `count_conversation()` allow cross-session aggregation when `session_id` is omitted.

```python

# Write operation (requires session_id)

resp = client.add_conversation(messages=[
    {"role": "user", "content": "Hello, agent!"},
    {"role": "assistant", "content": "Hi! How can I help you?"},
])

# Read operation (session_id optional)

history = client.query_conversation(limit=10)
print(history["data"])

```

## Managing Isolation Contexts

The `with_isolation()` method returns a shallow clone of the client with specified isolation fields overridden. This enables per-call context switching without recreating the HTTP transport layer or re-authenticating.

```python

# Switch to a different session for a single operation

session_client = client.with_isolation(session_id="session-002")
session_client.add_conversation(messages=[
    {"role": "user", "content": "New session context"}
])

```

The underlying `_IsolationCtx` ensures that `team`, `agent`, `user`, and optional `task` identifiers remain strictly separated across all API calls.

## Atomic Data and Profile Storage

Use `update_atomic()` to store key-value state data outside of conversation history:

```python

# Store derived state

client.update_atomic(
    id="current_topic",
    content="weather forecast",
    background="derived from user query",
)

# Retrieve atomic entries by type

atoms = client.query_atomic(type="topic", limit=5)

```

For L2-L3 profile operations, `read_scenario()` accesses user profile files without requiring a session context:

```python
profile = client.read_scenario("notes/2026Q2.md")
print(profile["content"])

```

## Asynchronous Usage Patterns

For high-concurrency applications, `AsyncMemoryClient` provides identical functionality using asyncio:

```python
import asyncio
from tencentdb_agent_memory.v3 import AsyncMemoryClient

async def process_memory():
    async_client = AsyncMemoryClient(
        endpoint="https://memory.tencentyun.com",
        api_key="sk-<YOUR_API_KEY>",
        service_id="mem-<SERVICE_ID>",
        team_id="team-123",
        agent_id="agent-xyz",
        user_id="user-abc",
    )
    
    await async_client.add_conversation(messages=[
        {"role": "user", "content": "Async message"}
    ])
    return await async_client.query_conversation(limit=5)

asyncio.run(process_memory())

```

## Error Handling and Validation

The SDK performs early validation through `ParamError` exceptions defined in [`tencentdb_agent_memory/errors.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/errors.py). Catch these exceptions to handle missing required fields or invalid isolation contexts:

```python
from tencentdb_agent_memory.errors import ParamError

try:
    # Attempting write without session_id raises ParamError

    client.with_isolation(session_id=None).add_conversation(messages=[])
except ParamError as e:
    print("Validation failed:", e)

```

## Summary

- **Mandatory isolation**: `team_id`, `agent_id`, and `user_id` are required when constructing `MemoryClient` or `AsyncMemoryClient`.
- **Session semantics**: `session_id` is required for write operations (`add_conversation`) but optional for read operations (`query_conversation`, `search_conversation`).
- **Context switching**: Use `with_isolation()` to create scoped client clones without reinstantiating transport layers.
- **Dual interface**: Both synchronous and asynchronous clients share identical method signatures in [`tencentdb_agent_memory/v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/v3/client.py).
- **Atomic storage**: `update_atomic()` and `query_atomic()` manage key-value state separate from conversation history.

## Frequently Asked Questions

### What are the mandatory parameters for initializing the MemoryClient?

According to the `_validate_construction` method in [`tencentdb_agent_memory/v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/v3/client.py), you must provide `team_id`, `agent_id`, and `user_id` when instantiating either `MemoryClient` or `AsyncMemoryClient`. The constructor raises `ParamError` from [`tencentdb_agent_memory/errors.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/errors.py) if any of these identifiers are missing or empty.

### When is session_id required versus optional in the Python SDK?

The `session_id` parameter is optional for read-only operations such as `query_conversation()`, `search_conversation()`, and `count_conversation()`, allowing cross-session aggregation. However, write operations like `add_conversation()` enforce a non-empty `session_id` through the internal `resolve_session_for_write()` helper, raising an error if omitted.

### How do I switch between different sessions without creating a new client instance?

Invoke the `with_isolation()` method on any existing client instance. This returns a shallow clone with overridden isolation fields (such as `session_id`) while reusing the underlying HTTP transport and authentication credentials. This pattern avoids the overhead of TCP connection re-establishment and API key re-validation.

### What is the difference between MemoryClient and AsyncMemoryClient?

`MemoryClient` provides blocking, synchronous I/O suitable for scripts and traditional web frameworks, while `AsyncMemoryClient` exposes identical methods using `async`/`await` syntax for non-blocking operations in asyncio-based applications. Both classes are defined in [`tencentdb_agent_memory/v3/client.py`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/tencentdb_agent_memory/v3/client.py) and utilize the same `_IsolationCtx` logic for request payload construction.