tencent cloud

SDK Sample Project

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:41:49
AI-Translated
This document describes the official sample projects of CodeBuddy Agent SDK, helping you quickly understand various usage scenarios of the SDK.

Sample Repository

All sample code is hosted in the official repository:
git clone https://cnb.cool/codebuddy/agent-sdk-demos.git
cd agent-sdk-demos

Sample Overview

Example
Language
Core Feature
Scenario
quick-start
TypeScript
Basic APIs, Message Streaming, and Hooks
SDK Getting Started
multi-turn-session
TypeScript
Multi-turn conversations and session recovery
Interactive Applications
research-assistant
Python
Multi-agent Collaboration
Complex Task Decomposition
profile-builder
TypeScript
Web search and document generation
Information Collection
chat-demo
TypeScript
WebSocket and streaming responses
Web Applications
mail-assistant
TypeScript
MCP protocol and custom tools
Business System Integration
spreadsheet-assistant
TypeScript
Electron IPC
Desktop Applications

Preparing the Environment

Prerequisites

Bun or Node.js 18+
Python 3.10+ (Python examples)
CodeBuddy CLI login authentication is complete.

Installing the SDK

TypeScript
Python
npm install @tencent-ai/agent-sdk
pip install codebuddy-agent-sdk

Authentication Method

The SDK supports multiple authentication methods:
1. Reuse CLI login state: If you have already logged in through the codebuddy command, the SDK automatically uses the existing credentials.
2. API Key authentication: Configure it through environment variables.
For detailed authentication configuration, see Settings Configuration - Authentication.

Basic Example

quick-start: SDK Getting Started

Demonstrates the basic usage of the query() API, including message stream processing and the Hooks mechanism.
import { query } from '@tencent-ai/agent-sdk';

const conversation = query({
prompt: 'Hello! Please introduce what you can do.',
options: {
model: 'claude-4.5',
maxTurns: 100,
allowedTools: ['Read', 'Write', 'Bash', 'Glob', 'Grep'],
},
});

for await (const message of conversation) {
if (message.type === 'assistant') {
const text = message.message.content.find(c => c.type === 'text');
if (text) console.log(text.text);
}
if (message.type === 'result') {
console.log(`Done. Duration: ${message.duration_ms}ms`);
}
}
Run the example:
cd quick-start
npm install
npx tsx quick-start.ts

multi-turn-session: Multi-Turn Conversation

Demonstrates how to use the Session API to implement multi-turn conversations and session restoration.
import { unstable_v2_createSession, unstable_v2_resumeSession } from '@tencent-ai/agent-sdk';

// Create a session
await using session = unstable_v2_createSession({ model: 'claude-4.5' });

// First round
await session.send('What year is it?');
for await (const msg of session.stream()) { /* ... */ }

// Second round (context is maintained)
await session.send('What year is it 10 years from now?');
for await (const msg of session.stream()) { /* ... */ }
Run the example:
cd multi-turn-session
npm install
npx tsx examples.ts basic # Basic session
npx tsx examples.ts multi-turn # Multi-turn conversation
npx tsx examples.ts resume # Session restoration

Advanced Examples

research-assistant: Multi-Agent Collaboration

A Python example that demonstrates how to define multiple specialized sub-agents to collaboratively complete complex tasks.
Workflow:
1. The main Agent breaks down the research request into subtasks.
2. The researcher uses WebSearch to search for information and saves it to files/research_notes/.
3. The data analyst extracts data from the research notes and generates charts to files/charts/.
4. The report writer consolidates the content and generates a PDF report to files/reports/.
from codebuddy_agent_sdk import CodeBuddySDKClient, CodeBuddyAgentOptions, AgentDefinition

agents = {
"researcher": AgentDefinition(
description="Use web search to collect research information",
tools=["WebSearch", "Write"],
model="claude-haiku-4.5"
),
"data-analyst": AgentDefinition(
description="Extract data from research notes and generate charts",
tools=["Glob", "Read", "Bash", "Write"],
model="claude-haiku-4.5"
),
"report-writer": AgentDefinition(
description="Consolidate research and data to generate a PDF report",
tools=["Skill", "Glob", "Read", "Write", "Bash"],
model="claude-haiku-4.5"
)
}

options = CodeBuddyAgentOptions(
allowed_tools=["Task"], # The main Agent can only delegate tasks.
agents=agents,
model="claude-haiku-4.5"
)

async with CodeBuddySDKClient(options=options) as client:
await client.query("Research the development of quantum computing in 2025")
async for msg in client.receive_response():
# Process messages
Run the example:
cd research-assistant
uv sync
uv run python research_agent/agent.py

profile-builder: Information Collection and Document Generation

Demonstrate the WebSearch tool and document generation capabilities.
const q = query({
prompt: `Search for information about "${personName}" and create a professional resume`,
options: {
allowedTools: ['WebSearch', 'WebFetch', 'Bash', 'Write', 'Read'],
systemPrompt: 'You are a resume writing expert...',
},
});
Run the example:
cd profile-builder
npm install
npm start "Name"
# Output: agent/custom_scripts/resume.docx

Web Application Integration

chat-demo: Streaming Response Architecture

Demonstrate how to integrate the SDK into a Web application and implement streaming responses over WebSocket.
Architecture:
Browser (React) ←─ WebSocket ─→ Express Server ←─ SDK query()
Server-side encapsulation:
import { query } from "@tencent-ai/agent-sdk";

export class Agent {
async sendMessage(content: string) {
this.stream = query({
prompt: content,
options: {
maxTurns: 1,
allowedTools: ['Bash', 'Read', 'Write', 'WebSearch'],
},
})[Symbol.asyncIterator]();
}

async *getOutputStream() {
while (true) {
const { value, done } = await this.stream.next();
if (done) break;
yield value;
}
}
}
Run the example:
cd chat-demo
npm install
npm run dev
# Backend: http://localhost:3001
# Frontend: http://localhost:5173

mail-assistant: MCP Tool Extension

Demonstrate how to extend Agent capabilities through the MCP protocol to implement email system operations.
const q = query({
prompt: 'Find important unread emails from this week',
options: {
allowedTools: [
'Read', 'Write', 'Bash',
'mcp__email__search_inbox', // MCP tool
'mcp__email__read_emails'
],
mcpServers: {
"email": customEmailServer
},
},
});
Run the example:
cd mail-assistant
cp .env.example .env # Configure IMAP credentials
bun install
bun run dev
# Visit http://localhost:3000

Desktop Application Integration

spreadsheet-assistant: Electron Integration

Demonstrate how to integrate the SDK into an Electron application through IPC.
Main process:
import { query } from '@tencent-ai/agent-sdk';

ipcMain.on('agent:query', async (event, data) => {
for await (const message of query({ prompt: data.content, options })) {
event.reply('agent:response', message);
}
});
Renderer process:
window.electron.ipcRenderer.on('agent:response', (message) => {
// Update the UI
});

window.electron.ipcRenderer.sendMessage('agent:query', { content: 'Create a sales report' });
Run the example:
cd spreadsheet-assistant
npm install
npm start

Hooks Security Control

All examples support security control through Hooks:
const q = query({
prompt: '...',
options: {
hooks: {
PreToolUse: [{
matcher: 'Write|Edit',
hooks: [async (input) => {
const filePath = input.tool_input.file_path;
// Restrict the write directory
if (!filePath.startsWith('/allowed/path/')) {
return { decision: 'block', stopReason: 'Path not allowed' };
}
return { continue: true };
}]
}]
}
}
});

References

SDK Overview - Complete introduction to the SDK
TypeScript SDK Reference - Detailed TypeScript API documentation
Python SDK Reference - Detailed Python API documentation
MCP Integration - MCP Server Configuration
Sub-Agent System - Detailed Explanation of Multi-Agent Collaboration


Help and Support

Was this page helpful?

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

Feedback