# Claude Agent SDK: Python & TypeScript

> **Terakhir diverifikasi**: 2026-10-20 · 📄 Sesuai dokumentasi resmi (ikhtisar Claude Agent SDK, referensi Python dan TypeScript, diperiksa 2026-10-20)

Claude Agent SDK adalah paket resmi Anthropic untuk menggunakan Claude Code sebagai library: pasang `claude-agent-sdk` untuk Python atau `@anthropic-ai/claude-agent-sdk` untuk TypeScript, lalu panggil `query()`. Ini adalah library yang menjalankan binary Claude Code, dengan tool, izin, sesi, dan hook bawaan, sehingga Anda dapat menyematkan kemampuan Claude Code ke dalam aplikasi Anda sendiri (diperiksa 2026-10-20).

## Apa itu Claude Agent SDK?

Claude Agent SDK menyediakan blok bangunan untuk membantu Anda membuat aplikasi yang dapat:

- **Memahami instruksi bahasa alami** dan mengeksekusi tugas kompleks
- **Menggunakan tool** (pencarian, eksekusi kode, operasi file, dll.)
- **Mempertahankan konteks percakapan** untuk interaksi multi-giliran
- **Terhubung ke layanan eksternal** (melalui server MCP)

## Pasang Agent SDK

### Python

```bash
pip install claude-agent-sdk
```

### TypeScript

```bash
npm install @anthropic-ai/claude-agent-sdk
```

Versi SDK mengikuti versi Claude Code yang dibundel: pada contoh resmi, SDK v0.3.191 membundel Claude Code v2.1.191 (diperiksa 2026-10-20). Dokumentasi ini menggunakan Claude Code 2.1.330 (lihat [panduan instalasi](/docs/getting-started/installation)); periksa catatan rilis SDK untuk versi yang dibundel pada rilis saat ini.

## Mulai cepat dengan query()

### Python

```python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions()
    async for message in query(prompt="Create a Python web server", options=options):
        print(message)

asyncio.run(main())
```

### TypeScript

```ts
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Create a Python web server",
  options: {}
})) {
  console.log(message);
}
```

`query()` membuat sesi baru secara default; untuk beberapa pertukaran dalam sesi yang sama, gunakan `ClaudeSDKClient` di Python (diperiksa 2026-10-20).

## Konfigurasi QCode

`ClaudeAgentOptions(env={...})` di Python menggabungkan variabel di atas environment proses yang diwariskan:

```python
from claude_agent_sdk import ClaudeAgentOptions

options = ClaudeAgentOptions(
    env={
        "ANTHROPIC_BASE_URL": "https://api.qcode.cc/api",  # switch to https://asia.qcode.cc/api if mainland China access is unstable
        "ANTHROPIC_AUTH_TOKEN": "cr_your_api_key",
    }
)
```

Di TypeScript, `options.env` menggantikan `process.env`, jadi sebarkan `...process.env` untuk mempertahankan variabel yang diwariskan seperti `PATH`:

```ts
const options = { env: { ...process.env, ANTHROPIC_BASE_URL: "https://api.qcode.cc/api", ANTHROPIC_AUTH_TOKEN: "cr_..." } };
```

Autentikasi dengan API key: dokumentasi resmi menyatakan bahwa pengembang pihak ketiga tidak boleh menawarkan login claude.ai untuk produk yang dibangun di atas SDK (diperiksa 2026-10-20). QCode menagih per token, dengan tarif per model tercantum di [qcode.cc/models](https://qcode.cc/models).

## Agent SDK vs Claude Code CLI vs Client SDK

| Item | Agent SDK | Claude Code CLI | Client SDK |
|------|-----------|-----------------|------------|
| Bentuk | Library Python / TypeScript | Antarmuka terminal | `anthropic` / `@anthropic-ai/sdk` |
| Cara menjalankan | Library yang menjalankan binary Claude Code | Penggunaan interaktif di terminal | Memanggil Messages API secara langsung |
| Yang sudah bawaan | Tool, izin, sesi, dan hook | Tool, izin, sesi, dan hook | Anda menangani pemanggilan tool di kode Anda sendiri |
| Digunakan untuk | Menyematkan Claude Code ke aplikasi Anda sendiri | Pengembangan interaktif harian | Memanggil Messages API secara langsung |

## Client SDK: memanggil Messages API secara langsung

Contoh di bawah menggunakan Client SDK (`anthropic` / `@anthropic-ai/sdk`), bukan Agent SDK; gunakan ini bila Anda hanya perlu memanggil Messages API secara langsung.

### Pasang Client SDK

#### Python SDK

```bash
pip install anthropic
```

#### TypeScript SDK

```bash
npm install @anthropic-ai/sdk
```

### Panggilan Message Dasar

```python
from anthropic import Anthropic

# Via QCode.cc API
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Explain what a RESTful API is"}
    ]
)

print(message.content[0].text)
```

### Respons Streaming

```python
with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a Python quicksort function"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

### Penggunaan Tool

Tool Use adalah kemampuan inti Agen, yang memungkinkan model memanggil tool eksternal.

#### Definisikan Tool

```python
from anthropic import Anthropic

client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_api_key"
)

# Define search tool
tools = [
    {
        "name": "search_web",
        "description": "Search the web for information",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search keywords"
                }
            },
            "required": ["query"]
        }
    },
    {
        "name": "calculate",
        "description": "Perform mathematical calculations",
        "input_schema": {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "Mathematical expression, e.g., '2 + 3 * 4'"
                }
            },
            "required": ["expression"]
        }
    }
]

# Send message with tools
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"}
    ],
    tools=tools
)

# Define a safe calculator before processing tool calls:
# tool arguments returned by the model can also be steered by prompt injection —
# never execute them with eval().
import ast
import operator

_OPS = {ast.Add: operator.add, ast.Sub: operator.sub,
        ast.Mult: operator.mul, ast.Div: operator.truediv}

def safe_calculate(expression: str):
    """Allow only numbers and + - * / so no arbitrary code can run."""
    def _eval(node):
        if isinstance(node, ast.Expression):
            return _eval(node.body)
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](_eval(node.left), _eval(node.right))
        raise ValueError("only numbers and + - * / are supported")

    return _eval(ast.parse(expression, mode="eval"))

# Process tool calls
for content in message.content:
    if content.type == "text":
        print(content.text)
    elif content.type == "tool_use":
        print(f"Calling tool: {content.name}")
        print(f"Parameters: {content.input}")

        # Simulate executing the tool
        if content.name == "calculate":
            result = safe_calculate(content.input["expression"])
            tool_result = str(result)
        elif content.name == "search_web":
            tool_result = f"Results for '{content.input['query']}'..."

        # Send the result back to the model
        message = client.messages.create(
            model="claude-opus-5-5",
            max_tokens=4096,
            messages=[
                {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"},
                message,
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "tool_result",
                            "tool_use_id": content.id,
                            "content": tool_result
                        }
                    ]
                }
            ],
            tools=tools
        )
```

### Pemanggilan Tool Streaming

```python
with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Create a file named hello.py that prints 'Hello, World!'"}
    ],
    tools=[
        {
            "name": "write_file",
            "description": "Write content to a file",
            "input_schema": {
                "type": "object",
                "properties": {
                    "filename": {"type": "string"},
                    "content": {"type": "string"}
                },
                "required": ["filename", "content"]
            }
        }
    ]
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            if event.delta.type == "text_delta":
                print(event.delta.text, end="", flush=True)
            elif event.delta.type == "input_json_delta":
                print(event.delta.partial_json, end="", flush=True)
```

### Prompt Caching

Prompt Caching dapat menurunkan biaya secara signifikan untuk percakapan panjang:

```python
# System prompt (will be cached)
system_prompt = """You are a professional code review assistant.
Your responsibilities:
1. Check code security
2. Identify performance issues
3. Verify code standards
4. Provide improvement suggestions
"""

# Use cache_control to mark cacheable content
message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    system=[
        {
            "type": "text",
            "text": system_prompt,
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "Review @src/auth/login.ts"}
    ]
)
```

### Contoh Membangun Agen

```python
from anthropic import Anthropic
from typing import List

class CodeReviewAgent:
    def __init__(self, api_key: str):
        self.client = Anthropic(
            base_url="https://api.qcode.cc/api",
            api_key=api_key
        )
        self.system_prompt = """You are a professional code review assistant.
Focus on: security, performance, readability, best practices.
Output for each review: issue list, severity, fix suggestions."""

    def review(self, code_snippet: str) -> str:
        message = self.client.messages.create(
            model="claude-opus-5-5",
            max_tokens=4096,
            system=self.system_prompt,
            messages=[
                {"role": "user", "content": f"Review this code:\n\n{code_snippet}"}
            ]
        )
        return message.content[0].text

# Usage
agent = CodeReviewAgent("cr_your_api_key")
result = agent.review("SELECT * FROM users WHERE id = " + user_id)
```

### Konfigurasi QCode.cc untuk Client SDK

```python
import os

# Method 1: Environment variable
os.environ["ANTHROPIC_BASE_URL"] = "https://api.qcode.cc/api"
os.environ["ANTHROPIC_AUTH_TOKEN"] = "cr_your_key"

client = Anthropic()  # Auto-reads environment variables

# Method 2: Asia node (recommended for mainland China)
client = Anthropic(
    base_url="https://api.qcode.cc/api",
    api_key="cr_your_key"
)
```

## Langkah selanjutnya

- [Referensi API](/docs/getting-started/endpoints-and-api-paths) - Dokumentasi parameter API lengkap
- [Panduan Pemilihan Model](/docs/usage/model-selection) - Pilih model yang tepat
- [Server MCP](/docs/advanced/mcp) - Hubungkan layanan eksternal untuk memperluas kemampuan