# Getting Started with Claude Agent SDK

Claude Agent SDK is Anthropic's official development kit for building AI Agent applications based on Claude models. Unlike Claude Code (CLI tool), the SDK targets developers, enabling you to integrate Claude capabilities into your own applications.

## What is Claude Agent SDK?

Claude Agent SDK provides building blocks to help you create applications that can:

- **Understand natural language instructions** and execute complex tasks
- **Use tools** (search, code execution, file operations, etc.)
- **Maintain conversation context** for multi-turn interactions
- **Connect to external services** (via MCP servers)

## Install SDK

### Python SDK

```bash
pip install anthropic
```

### TypeScript SDK

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

## Quick Start

### Basic Message Call

```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",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Explain what a RESTful API is"}
    ]
)

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

### Streaming Response

```python
with client.messages.stream(
    model="claude-opus-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)
```

## Tool Use

Tool Use is the core capability of Agents, allowing the model to call external tools.

### Define Tools

```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",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"}
    ],
    tools=tools
)

# 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 = eval(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",
            max_tokens=4096,
            messages=[
                {"role": "user", "content": "Calculate (15 + 25) * 2 and search for what this means"},
                message,
                {
                    "role": "user",
                    "content": None,
                    "type": "tool_result",
                    "tool_use_id": content.id,
                    "content": tool_result
                }
            ],
            tools=tools
        )
```

## Streaming Tool Calls

```python
with client.messages.stream(
    model="claude-opus-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 == "tool_use_delta":
                print(f"\n[Tool Call] {event.delta.name}")
```

## Prompt Caching

Prompt Caching can significantly reduce costs for long conversations:

```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",
    max_tokens=4096,
    system=[
        {
            "type": "text",
            "text": system_prompt,
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": "Review @src/auth/login.ts"}
    ]
)
```

## Agent Building Example

```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",
            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)
```

## Difference from Claude Code

| Feature | Claude Agent SDK | Claude Code |
|---------|------------------|-------------|
| Target User | Developers | Individual developers |
| Runtime | Your application | Command line |
| File Operations | Implement yourself | Built-in |
| Terminal Commands | Implement yourself | Built-in |
| Git Integration | Implement yourself | Built-in |
| Use Case | Build AI applications | Programming assistance |

## QCode.cc Configuration

```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"
)
```

## Next Steps

- [API Reference](/docs/getting-started/endpoints-and-api-paths) - Complete API parameter documentation
- [Model Selection Guide](/docs/usage/model-selection) - Choose the right model
- [MCP Servers](/docs/advanced/mcp) - Connect external services to extend capabilities