How to Add Conversation History Using the TypeScript SDK in TencentDB-Agent-Memory

The TypeScript SDK exposes the conversationAdd method in SkillClient to incrementally append conversation turns to a session buffer, returning "archived" when extraction triggers or "ok" when buffering continues.

The TencentDB-Agent-Memory repository provides a TypeScript SDK for persisting and extracting skills from conversational AI interactions. Adding conversation history using the TypeScript SDK requires instantiating the MemoryCoreClient and invoking the conversationAdd method with properly isolated session identifiers and schema-compliant messages. The SDK automatically validates inputs locally and triggers asynchronous skill extraction when buffer thresholds are exceeded.

Understanding the conversationAdd API

The conversationAdd method is implemented in sdk/memory-core/typescript/src/v3/skill-client.ts (lines 94-101) and serves as the primary interface for appending conversation turns to the memory buffer.

Required Isolation Fields

Every call to conversationAdd must include four required isolation fields to ensure proper namespacing and data separation:

  • session_id – Unique identifier for the conversation session
  • user_id – Identifier for the participating user
  • team_id – Team or organization scope for the memory partition
  • agent_id – Specific agent instance handling the conversation

The SDK validates these fields locally using validateRequiredStrings before transmitting the request.

Message Schema Validation

The SDK enforces a strict five-role schema defined in skill-types.ts and validated against the server-side gateway schema in MemoryCore/src/gateway/skill-schemas.ts. Each SkillMessage must specify exactly one of the following roles:

  • system – System-level instructions and context
  • user – Input messages from the end user
  • assistant – Generated responses from the AI
  • tool_call – Invocations of external tools
  • tool_result – Results returned from tool executions

Before transmitting, the SDK runs validateMessages to ensure schema compliance, preventing malformed data from reaching the server.

Step-by-Step Implementation

Initialize the MemoryCoreClient

First, create an instance of MemoryCoreClient (defined in sdk/memory-core/typescript/src/v3/client.ts) with your endpoint configuration and optional default isolation values:

import { MemoryCoreClient } from '@tencentdb/memory-core-sdk';

const client = new MemoryCoreClient({
  baseURL: 'https://api.tencentyun.com',
  // Optional: set default team_id, user_id here if consistent across calls
});

Prepare SkillMessage Arrays

Construct arrays of SkillMessage objects representing individual conversation turns. Each turn can contain multiple messages to capture full contextual exchanges:

import { SkillMessage } from '@tencentdb/memory-core-sdk/types';

const turnMessages: SkillMessage[] = [
  { role: 'user', content: 'What is the weather in Beijing today?' },
  { 
    role: 'assistant', 
    content: 'The weather in Beijing is sunny with a high of 28°C.' 
  },
];

Execute conversationAdd Calls

Invoke the method through the skill namespace, passing the isolation IDs and message array:

import { SkillConversationAddRequest } from '@tencentdb/memory-core-sdk/types';

const addReq: SkillConversationAddRequest = {
  session_id: 'sess-12345',
  user_id: 'user-abc',
  team_id: 'team-xyz',
  agent_id: 'agent-001',
  messages: turnMessages,
};

const response = await client.skill.conversationAdd(addReq);

Handle Response Status

Check the response status to determine if skill extraction occurred:

  • "ok" – Messages buffered successfully; no extraction triggered yet
  • "archived" – Buffer threshold reached; skill extraction task initiated automatically

When status is "archived", the response includes a task_id field referencing the extraction job:

if (response.status === 'archived') {
  console.log('Skill extraction initiated, task_id:', response.task_id);
}

Batch Importing Historical Conversations

To replay existing dialog histories, iterate over stored turns and invoke conversationAdd sequentially. This ensures each historical turn passes through the SDK's validation and buffering pipeline:

async function replayHistory(
  client: MemoryCoreClient, 
  history: SkillMessage[][], 
  isolationConfig: { session_id: string; user_id: string; team_id: string; agent_id: string }
) {
  for (const turn of history) {
    const resp = await client.skill.conversationAdd({
      ...isolationConfig,
      messages: turn,
    });
    
    if (resp.status === 'archived') {
      console.log(`Turn archived with task: ${resp.task_id}`);
    }
  }
}

Key Source Files and Architecture

Understanding the source structure helps debug validation errors and extend functionality:

Summary

  • The TypeScript SDK provides conversationAdd in SkillClient to buffer conversation turns and trigger skill extraction automatically when thresholds are met
  • Four isolation fields (session_id, user_id, team_id, agent_id) are required for every call to ensure proper memory namespacing
  • Messages must conform to the five-role schema (system, user, assistant, tool_call, tool_result) enforced by validateMessages
  • Local validation occurs via validateRequiredStrings and validateMessages before network transmission to prevent invalid requests
  • A response status of "archived" indicates the buffer reached its configured limit and a skill extraction task was created

Frequently Asked Questions

What are the required parameters for conversationAdd?

The conversationAdd method requires four isolation string fields (session_id, user_id, team_id, agent_id) and a messages array containing valid SkillMessage objects. The SDK validates these locally using validateRequiredStrings before sending requests to the server endpoint.

How do I know when skill extraction is triggered?

When the accumulated buffer reaches configured size or byte thresholds, conversationAdd returns a response object with status set to "archived" and includes a task_id field. If the status is "ok", the turn was buffered successfully without triggering extraction.

Can I import existing conversation histories using the SDK?

Yes. Iterate over historical conversation turns chronologically and invoke conversationAdd for each turn sequentially. This replays the dialogue through the SDK's validation and buffering pipeline, treating historical data identically to real-time streams.

What message roles does the TypeScript SDK support?

The SDK supports five specific roles defined in skill-types.ts and validated against the gateway schema: system, user, assistant, tool_call, and tool_result. Each message in the array must specify one of these roles, or the validateMessages function will throw a validation error before the request transmits.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →