# Erste Schritte mit dem Claude Agent SDK

Claude Agent SDK ist das offizielle Entwicklungstoolkit von Anthropic für die Erstellung von AI-Agent-Anwendungen auf Basis von Claude-Modellen. Im Gegensatz zu Claude Code (CLI-Tool) richtet sich das SDK an Entwickler und ermöglicht es Ihnen, Claude-Funktionen in eigene Anwendungen zu integrieren.

## Was ist das Claude Agent SDK?

Claude Agent SDK stellt die Bausteine bereit, mit denen Sie Anwendungen erstellen können, die Folgendes tun:

- **Natürlichsprachliche Anweisungen verstehen** und komplexe Aufgaben ausführen
- **Tools verwenden** (Suche, Codeausführung, Dateioperationen usw.)
- **Gesprächskontext für mehrere Interaktionsrunden beibehalten**
- **Mit externen Diensten verbinden** (über MCP-Server)

## SDK installieren

### Python SDK

```bash
pip install anthropic
```

### TypeScript SDK

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

## Schnellstart

### Einfacher Nachrichtenaufruf

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

```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 ist die Kernfunktion von Agenten und ermöglicht es dem Modell, externe Tools aufzurufen.

### Tools definieren

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

```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 kann die Kosten bei langen Konversationen erheblich senken:

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

## Beispiel: Agent-Erstellung

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

## Unterschiede zu Claude Code

| Merkmal | Claude Agent SDK | Claude Code |
|---------|------------------|-------------|
| Zielgruppe | Entwickler | Einzelentwickler |
| Laufzeitumgebung | Ihre Anwendung | Kommandozeile |
| Dateioperationen | Selbst implementieren | Integriert |
| Terminalbefehle | Selbst implementieren | Integriert |
| Git-Integration | Selbst implementieren | Integriert |
| Anwendungsfall | KI-Anwendungen erstellen | Programmierassistenz |

## QCode.cc Konfiguration

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

## Nächste Schritte

- [API-Referenz](/docs/getting-started/endpoints-and-api-paths) – Vollständige Dokumentation der API-Parameter
- [Modellauswahl-Handbuch](/docs/usage/model-selection) – Das richtige Modell wählen
- [MCP-Server](/docs/advanced/mcp) – Externe Dienste verbinden, um Funktionen zu erweitern