# SDK Demo Projects

This document introduces the official demo projects for CodeBuddy Agent SDK, helping you quickly understand various SDK usage scenarios.

## Demo Repository

All demo code is hosted in the official repository:

**Repository URL**: <https://cnb.cool/codebuddy/agent-sdk-demos>

```bash
git clone https://cnb.cool/codebuddy/agent-sdk-demos.git
cd agent-sdk-demos
```

## Demo Overview

| Demo | Language | Core Features | Use Case |
|------|----------|---------------|----------|
| quick-start | TypeScript | Basic API, Message Streaming, Hooks | SDK Getting Started |
| multi-turn-session | TypeScript | Multi-turn Conversations, Session Recovery | Interactive Applications |
| research-assistant | Python | Multi-Agent Collaboration | Complex Task Decomposition |
| profile-builder | TypeScript | Web Search, Document Generation | Information Collection |
| chat-demo | TypeScript | WebSocket, Streaming Response | Web Applications |
| mail-assistant | TypeScript | MCP Protocol, Custom Tools | Business System Integration |
| spreadsheet-assistant | TypeScript | Electron IPC | Desktop Applications |

## Environment Setup

### Prerequisites

- [Bun](https://bun.sh) or Node.js 18+
- Python 3.10+ (for Python demos)
- CodeBuddy CLI login authentication completed

### Install SDK

::: code-group

```bash [TypeScript]
npm install @tencent-ai/agent-sdk
```

```bash [Python]
pip install codebuddy-agent-sdk
```

:::

### Authentication Methods

SDK supports multiple authentication methods:

1. **Reuse CLI Login State**: If you have logged in via the `codebuddy` command, SDK automatically uses existing credentials
2. **API Key Authentication**: Configure via environment variables

For detailed authentication configuration, please refer to [Settings Configuration - Authentication](settings.md#authentication)

## Basic Demos

### quick-start: SDK Getting Started

Demonstrates basic usage of the `query()` API, including message stream handling and Hooks mechanism.

```typescript
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(`Completed in ${message.duration_ms}ms`);
  }
}
```

**Run Demo**:

```bash
cd quick-start
npm install
npx tsx quick-start.ts
```

### multi-turn-session: Multi-turn Conversations

Demonstrates Session API for multi-turn conversations and session recovery.

```typescript
import { unstable_v2_createSession, unstable_v2_resumeSession } from '@tencent-ai/agent-sdk';

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

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

// Second turn (maintaining context)
await session.send('What year is it 10 years from now?');
for await (const msg of session.stream()) { /* ... */ }
```

**Run Demo**:

```bash
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 recovery
```

## Advanced Demos

### research-assistant: Multi-Agent Collaboration

Python demo showing how to define multiple specialized sub-agents collaborating on complex tasks.

**Workflow**:

1. **Main Agent** breaks down research requests into subtasks
2. **Researcher** uses WebSearch to gather information, saves to `files/research_notes/`
3. **Data Analyst** extracts data from research notes, generates charts to `files/charts/`
4. **Report Writer** consolidates content, generates PDF reports to `files/reports/`

```python
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 PDF reports",
        tools=["Skill", "Glob", "Read", "Write", "Bash"],
        model="claude-haiku-4.5"
    )
}

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

async with CodeBuddySDKClient(options=options) as client:
    await client.query("Research quantum computing developments in 2025")
    async for msg in client.receive_response():
        # Handle message
```

**Run Demo**:

```bash
cd research-assistant
uv sync
uv run python research_agent/agent.py
```

### profile-builder: Information Collection and Document Generation

Demonstrates WebSearch tool and document generation capabilities.

```typescript
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 Demo**:

```bash
cd profile-builder
npm install
npm start "Name"
# Output: agent/custom_scripts/resume.docx
```

## Web Application Integration

### chat-demo: Streaming Response Architecture

Demonstrates how to integrate SDK into web applications with WebSocket for streaming responses.

**Architecture**:

```
Browser (React) ←─ WebSocket ─→ Express Server ←─ SDK query()
```

**Server-side Wrapper**:

```typescript
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 Demo**:

```bash
cd chat-demo
npm install
npm run dev
# Backend: http://localhost:3001
# Frontend: http://localhost:5173
```

### mail-assistant: MCP Tool Extension

Demonstrates extending Agent capabilities through MCP protocol for email system operations.

```typescript
const q = query({
  prompt: 'Find unread important emails from this week',
  options: {
    allowedTools: [
      'Read', 'Write', 'Bash',
      'mcp__email__search_inbox',   // MCP tools
      'mcp__email__read_emails'
    ],
    mcpServers: {
      "email": customEmailServer
    },
  },
});
```

**Run Demo**:

```bash
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

Demonstrates SDK integration in Electron applications via IPC.

**Main Process**:

```typescript
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**:

```typescript
window.electron.ipcRenderer.on('agent:response', (message) => {
  // Update UI
});

window.electron.ipcRenderer.sendMessage('agent:query', { content: 'Create sales report' });
```

**Run Demo**:

```bash
cd spreadsheet-assistant
npm install
npm start
```

## Hooks Security Control

All demos support security control through Hooks:

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

## Related Documentation

- [SDK Overview](sdk.md) - Complete SDK introduction
- [TypeScript SDK Reference](sdk-typescript.md) - TypeScript API detailed documentation
- [Python SDK Reference](sdk-python.md) - Python API detailed documentation
- [MCP Integration](mcp.md) - MCP server configuration
- [Sub-Agent System](sub-agents.md) - Multi-Agent collaboration details
