tencent cloud

Session Management

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:41:48
AI-Translated
Version Requirements: This document applies to CodeBuddy Agent SDK v0.1.0 and later versions.
This document describes how to manage sessions in the SDK, including obtaining session IDs, resuming sessions, forking sessions, and handling multi-turn conversations.

Overview

A Session is a core concept in CodeBuddy and is used to:
Maintain Conversation Context: In multi-turn conversations, the AI can remember previous content.
Session Resumption: You can resume from where you left off.
Session Forking: Create a branch from a point to explore different directions.
Each session has a unique session_id, which can be used for subsequent resumption.

Obtaining the Session ID

At the start of a session, the SDK returns an initialization message of type system, which contains the session_id.

Using the query API

TypeScript
Python
import { query } from '@tencent-ai/agent-sdk';

let sessionId: string | undefined;

const q = query({
prompt: 'Help me build a Web application',
options: {
model: 'deepseek-v3.1'
}
});

for await (const message of q) {
// Obtain the session_id from the initialization message
if (message.type === 'system' && message.subtype === 'init') {
sessionId = message.session_id;
console.log(`Session ID: ${sessionId}`);
// Save the sessionId for later resumption.
}

console.log(message);
}

// The sessionId can be saved to a database or a file.
import asyncio
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions, SystemMessage

session_id = None

async def main():
global session_id

options = CodeBuddyAgentOptions(model="deepseek-v3.1")

async for message in query(prompt="Help me build a Web application", options=options):
# Obtain the session_id from the initialization message
if isinstance(message, SystemMessage):
session_id = message.data.get("session_id")
print(f"Session ID: {session_id}")
# Save the session_id for later resumption.

print(message)

asyncio.run(main())
# The session_id can be saved to a database or a file.

Using the v2 Session API (TypeScript)

import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

const session = unstable_v2_createSession({
model: 'deepseek-v3.1'
});

await session.send('Help me build a Web application');

for await (const message of session.stream()) {
if (message.type === 'system' && message.subtype === 'init') {
console.log(`Session ID: ${message.session_id}`);
}
console.log(message);
}

// Use session.sessionId to obtain it (available after initialization).
console.log(`Session ID: ${session.sessionId}`);

session.close();

Using the Client API (Python)

from codebuddy_agent_sdk import CodeBuddySDKClient, CodeBuddyAgentOptions

async def main():
options = CodeBuddyAgentOptions(model="deepseek-v3.1")

async with CodeBuddySDKClient(options=options) as client:
await client.query("Help me build a Web application")

async for message in client.receive_response():
if isinstance(message, SystemMessage):
print(f"Session ID: {message.data.get('session_id')}")
print(message)

Restoring a Session

You can use the previously saved session_id to resume the session and continue the previous conversation.

Using the resume Option

TypeScript - query API
TypeScript - v2 API
Python
import { query } from '@tencent-ai/agent-sdk';

// Use the previously saved session_id.
const savedSessionId = 'abc123-xyz789';

const q = query({
prompt: 'Continue our previous work',
options: {
model: 'deepseek-v3.1',
resume: savedSessionId // Resume the specified session
}
});

for await (const message of q) {
console.log(message);
}
import { unstable_v2_resumeSession } from '@tencent-ai/agent-sdk';

// Use the previously saved session_id.
const savedSessionId = 'abc123-xyz789';

const session = unstable_v2_resumeSession(savedSessionId, {
model: 'deepseek-v3.1'
});

await session.send('Continue our previous work');

for await (const message of session.stream()) {
console.log(message);
}

session.close();
from codebuddy_agent_sdk import query, CodeBuddyAgentOptions

# Use the previously saved session_id.
saved_session_id = "abc123-xyz789"

options = CodeBuddyAgentOptions(
model="deepseek-v3.1",
resume=saved_session_id # Resume the specified session
)

async for message in query(prompt="Continue our previous work", options=options):
print(message)

Resuming the Most Recent Session

You can use the continue / continue_conversation option to automatically continue the most recent session:
TypeScript
Python
const q = query({
prompt: 'Continue',
options: {
model: 'deepseek-v3.1',
continue: true // Continue the most recent session
}
});
options = CodeBuddyAgentOptions(
model="deepseek-v3.1",
continue_conversation=True # Continue the most recent session
)

Multi-Turn Conversation

Multi-turn conversation allows multiple interactions within the same session, maintaining contextual coherence.

TypeScript: Using the query API

Each new query call uses resume to resume the session:
import { query } from '@tencent-ai/agent-sdk';

async function multiTurnWithQuery() {
let sessionId: string;

// First round of conversation
const q1 = query({
prompt: 'Help me create a React project',
options: { model: 'deepseek-v3.1' }
});

for await (const msg of q1) {
if (msg.type === 'system' && msg.subtype === 'init') {
sessionId = msg.session_id;
}
if (msg.type === 'result') {
console.log('First round completed');
}
}

// Second round of conversation (resume the session)
const q2 = query({
prompt: 'Add a user login page',
options: {
model: 'deepseek-v3.1',
resume: sessionId
}
});

for await (const msg of q2) {
if (msg.type === 'result') {
console.log('Second round completed');
}
}

// Third round of conversation
const q3 = query({
prompt: 'Add form validation',
options: {
model: 'deepseek-v3.1',
resume: sessionId
}
});

for await (const msg of q3) {
console.log(msg);
}
}

TypeScript: Using the v2 Session API

The v2 API provides a more streamlined multi-turn conversation experience:
import { unstable_v2_createSession } from '@tencent-ai/agent-sdk';

async function multiTurnWithSession() {
const session = unstable_v2_createSession({
model: 'deepseek-v3.1'
});

try {
// First round of conversation
await session.send('Help me create a React project');
for await (const msg of session.stream()) {
console.log(msg);
}

// Second round of conversation (context is automatically maintained)
await session.send('Add a user login page');
for await (const msg of session.stream()) {
console.log(msg);
}

// Third round of conversation
await session.send('Add form validation');
for await (const msg of session.stream()) {
console.log(msg);
}

} finally {
session.close();
}
}

Python: Using CodeBuddySDKClient

from codebuddy_agent_sdk import CodeBuddySDKClient, CodeBuddyAgentOptions

async def multi_turn_conversation():
options = CodeBuddyAgentOptions(model="deepseek-v3.1")

async with CodeBuddySDKClient(options=options) as client:
# First Round of Conversation
await client.query("Help me create a React project")
async for msg in client.receive_response():
print(msg)

# Second Round of Conversation (Context Is Automatically Maintained)
await client.query("Add a user login page")
async for msg in client.receive_response():
print(msg)

# Third Round of Conversation
await client.query("Add form validation")
async for msg in client.receive_response():
print(msg)

References

SDK Overview - Quick Start and Usage Examples
SDK Permission Control - Permission Modes and canUseTool
TypeScript SDK Reference - Complete API Reference
Python SDK Reference - Complete API Reference


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback