claude-code-sdk
БесплатноБез исполняемых скриптовНе проверенClaude Code SDK integration for building AI-powered applications with OAuth and API Key authentication
от miles990★ 26 звёзд на GitHubОб этом скилле
Claude Code SDK Integration
Overview
Claude Code SDK (claude-code-sdk) 是 Anthropic 官方提供的 Python 套件,用於在應用程式中整合 Claude AI Agent 功能。它支援 OAuth 認證(透過 claude login)和 API Key 認證,讓開發者可以利用 Claude Max/Pro 訂閱或 API 計費方案。這個 SDK 是建立 AI-powered 應用程式的關鍵工具,特別適合需要程式碼生成、檔案操作、或多輪對話的場景。
Key Concepts
認證方式
Description: Claude Code SDK 支援兩種認證方式 Key Features:
- OAuth 認證: 使用
claude login後存儲在~/.claude/的憑證 - API Key 認證: 透過
ANTHROPIC_API_KEY環境變數
Use Cases:
- OAuth:個人開發、有 Max/Pro 訂閱的用戶
- API Key:生產環境、需要計量計費的服務
SDK 核心 API
Description: query() 函數是主要的非同步介面
Key Features:
- 非同步迭代器回傳訊息
- 支援 streaming 和完整回應
- 可配置工具權限和執行限制
Use Cases: 程式碼生成、檔案操作、研究任務、唯讀分析
工具類型 (ToolType)
Description: SDK 支援多種內建工具 Key Features:
READ,WRITE,EDIT- 檔案操作BASH- 終端命令執行GLOB,GREP- 檔案搜尋WEB_FETCH- 網頁抓取
Best Practices
- 雙重認證檢查
- 同時支援 OAuth 和 API Key
- 優先使用 OAuth(免費使用 Max/Pro 配額)
- API Key 作為後備方案
def check_auth_status() -> dict:
status = {
'api_key_set': bool(os.environ.get('ANTHROPIC_API_KEY')),
'oauth_logged_in': False,
}
# 檢查 OAuth 登入狀態
claude_dir = os.path.expanduser('~/.claude')
if os.path.exists(claude_dir):
auth_files = ['credentials.json', 'settings.json', '.credentials.json']
for auth_file in auth_files:
if os.path.exists(os.path.join(claude_dir, auth_file)):
status['oauth_logged_in'] = True
break
# 只需要其中一種認證
status['auth_available'] = status['api_key_set'] or status['oauth_logged_in']
return status
- 增加 Buffer Size
- 預設 buffer 太小,處理大型回應會出錯
- 建議增加到 50MB
try:
from claude_code_sdk._internal.transport import subprocess_cli
subprocess_cli._MAX_BUFFER_SIZE = 50 * 1024 * 1024 # 50MB
except Exception as e:
print(f"Failed to patch SDK buffer size: {e}")
- 使用 Singleton Pattern
- 避免重複初始化
- 共享狀態和配置
_claude_service: Optional['ClaudeCodeService'] = None
def get_claude_code() -> 'ClaudeCodeService':
global _claude_service
if _claude_service is None:
_claude_service = ClaudeCodeService()
return _claude_service
- 預設配置模式
- 依據使用場景限制工具權限
- 降低風險,提升安全性
@dataclass
class AgentConfig:
allowed_tools: List[str]
max_turns: int = 30
cwd: Optional[str] = None
@classmethod
def coding(cls) -> 'AgentConfig':
"""開發模式:完整權限"""
return cls(
allowed_tools=['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'],
max_turns=50
)
@classmethod
def research(cls) -> 'AgentConfig':
"""研究模式:可上網"""
return cls(
allowed_tools=['Read', 'Glob', 'Grep', 'WebFetch'],
max_turns=20
)
@classmethod
def readonly(cls) -> 'AgentConfig':
"""唯讀模式:最安全"""
return cls(
allowed_tools=['Read', 'Glob', 'Grep'],
max_turns=10
)
Common Pitfalls
Pitfall 1: 直接在前端呼叫 SDK
- Problem: claude-code-sdk 是 Python 套件,無法在瀏覽器中運行
- Solution: 必須建立後端 API 服務
- Example:
# ❌ 錯誤:嘗試在前端使用
# JavaScript 無法直接使用 Python SDK
# ✅ 正確:建立 FastAPI 後端
from fastapi import FastAPI
from claude_code_sdk import query
app = FastAPI()
@app.post("/api/generate")
async def generate(prompt: str):
result = []
async for msg in query(prompt=prompt):
result.append(msg)
return {"result": result}
Pitfall 2: 忘記處理非同步
- Problem: SDK 是非同步的,忘記 await 會導致錯誤
- Solution: 使用 async/await 或 asyncio
# ❌ 錯誤
def run_sync():
for msg in query(prompt="Hello"): # TypeError
print(msg)
# ✅ 正確
async def run_async():
async for msg in query(prompt="Hello"):
print(msg)
Pitfall 3: 混淆 Claude API 和 Claude Code SDK
- Problem:
- Claude API (
anthropic套件) - 直接 HTTP API,需要 API Key - Claude Code SDK (
claude-code-sdk) - Agent 功能,支援 OAuth
- Claude API (
- Solution: 根據需求選擇正確的套件
| 特性 | Claude API | Claude Code SDK |
|---|---|---|
| 認證 | API Key only | OAuth + API Key |
| 功能 | 純對話 | Agent (檔案/終端操作) |
| 計費 | API 用量計費 | Max/Pro 訂閱可用 |
| 套件 | anthropic |
claude-code-sdk |
Patterns & Anti-Patterns
Patterns (Do This)
完整的服務封裝:
from dataclasses import dataclass, field
from typing import AsyncIterator, Optional, List, Dict, Any
from claude_code_sdk import query, ClaudeCodeOptions, AssistantMessage, TextBlock
@dataclass
class ClaudeCodeService:
"""Claude Code 服務封裝"""
async def run(self, prompt: str, config: Optional[AgentConfig] = None) -> Dict[str, Any]:
"""執行並收集完整結果"""
options = ClaudeCodeOptions(
allowed_tools=config.allowed_tools if config else None,
max_turns=config.max_turns if config else 30,
cwd=config.cwd
)
result_texts = []
tool_calls = []
async for message in query(prompt=prompt, options=options):
if
Установить claude-code-sdk в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл claude-code-sdk?
Claude Code SDK integration for building AI-powered applications with OAuth and API Key authentication
Как установить скилл claude-code-sdk?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл claude-code-sdk запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic