YouTip LogoYouTip

Claude Agent Sdk

Title: Claude Agent SDK Tutorial | Rookie Tutorial Claude Agent SDK enables you to build AI Agents that can autonomously read files, run commands, search the web, edit code, and more. Claude Agent SDK exposes the tools, Agent loop, and context management capabilities that power Claude Code as programmable Python and TypeScript libraries. In simple terms, this is an SDK that lets you use Claude Code as a library. You can embed it into your applications, CI pipelines, or automation scripts to build AI Agents that can autonomously complete complex tasks. * * * ## Core Capabilities The SDK comes with built-in tools for reading files, running commands, and editing code. Your Agent doesn't need to implement tool execution logic itself and can start working immediately. Main capabilities include: | Capability | Description | | --- | --- | | **Built-in Tools** | File read/write, terminal commands, code editing, web search, etc. | | **Hooks** | Execute custom logic before/after tool calls | | **Subagents** | Decompose large tasks and delegate them to independent sub-agents for parallel execution | | **MCP Servers** | Connect to databases, browsers, external APIs, etc. | | **Permission Control** | Fine-grained control over what Agents can do and when user approval is required | | **Sessions** | Build multi-turn conversation Agents that maintain context | * * * ## Prerequisites * **Node.js 18+** (TypeScript) or **Python 3.10+** * An **Anthropic account** and API Key ((https://platform.claude.com/)) * * * ## Step 1: Install SDK ### TypeScript npm install @anthropic-ai/claude-agent-sdk > The TypeScript SDK bundles the Claude Code binary for your current platform as an optional dependency, so you don't need to install Claude Code separately. ### Python # Using pip pip install claude-agent-sdk # Or using uv (recommended) uv add claude-agent-sdk > Note: Claude Code CLI is automatically installed with the package, no separate installation needed! The SDK uses the bundled CLI by default. > > If you want to use a system-level installation or specify a version, you can specify the path via `ClaudeAgentOptions(cli_path="/path/to/claude")`. * * * ## Step 2: Configure API Key Get the API Key from (https://platform.claude.com/), then create a `.env` file in your project directory: ANTHROPIC_API_KEY=your-api-key-here Or set it as an environment variable: export ANTHROPIC_API_KEY=your-api-key-here ### Third-Party Cloud Platform Support The SDK also supports authentication through third-party API providers: Amazon Bedrock (set `CLAUDE_CODE_USE_BEDROCK=1` environment variable and configure AWS credentials), Google Vertex AI (set `CLAUDE_CODE_USE_VERTEX=1`), and Microsoft Azure (set `CLAUDE_CODE_USE_FOUNDRY=1`). > ⚠️ **Important**: Unless prior approval is obtained from Anthropic, third-party developers are not permitted to offer claude.ai login or rate limiting in products built on Claude Agent SDK. Please use the API Key authentication method described in the documentation. * * * ## Step 3: Run Your First Agent The following example creates an Agent that lists files in the current directory: ### Python ## Example import asyncio from claude_agent_sdk import query, ClaudeAgentOptions async def main(): async for message in query( prompt="What files are in this directory?", options=ClaudeAgentOptions(allowed_tools=["Bash","Glob"]), ): if hasattr(message,"result"): print(message.result) asyncio.run(main()) ### TypeScript ## Example import{ query } from "@anthropic-ai/claude-agent-sdk"; async function main(){ for await (const message of query({ prompt:"What files are in this directory?", options:{ allowedTools:["Bash","Glob"]}, })){ if("result"in message){ console.log(message.result); } } } main(); * * * ## Practical: Build an Auto-Fix Bug Agent The following complete example demonstrates the core usage of the Agent SDK. ### Prepare a Buggy File Create `utils.py` with two intentional bugs: ## Example def calculate_average(numbers): total =0 for num in numbers: total += num return total / len(numbers)# Bug: Division by zero on empty list def get_user_name(user): return user.upper()# Bug: TypeError when user is None ### Write the Agent Create `agent.py`: ## Example import asyncio from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage async def main(): async for message in query( prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.", options=ClaudeAgentOptions( allowed_tools=["Read","Edit","Glob"],# Allowed tools permission_mode="acceptEdits",# Auto-approve file edits ), ): if isinstance(message, AssistantMessage): for block in message.content: if hasattr(block,"text"): print(block.text)# Claude's reasoning process elif hasattr(block,"name"): print(f"Tool: {block.name}")# Tool being called elif isinstance(message, ResultMessage): print(f"Done: {message.subtype}")# Final result asyncio.run(main()) ### Run python agent.py After running, check `utils.py` and you'll see the Agent autonomously completed the following: 1. **Read** the `utils.py` file 2. **Analyzed** the code logic and identified edge cases that could cause crashes 3. **Edited** the file and added proper error handling * * * ## Core Concepts Explained ### Function β€” Entry Point to Agent Loop `query` is the main entry point for creating an Agent loop. It returns an async iterator, so you use `async for` to stream messages in real-time as Claude works. The loop ends when Claude completes the task or encounters an error. The SDK handles orchestration (tool execution, context management, retries) β€” you just consume this message stream. Each iteration produces a message, which could be: * Claude's reasoning process * A tool call * Tool call result * Final result ### Tools β€” Control What Agents Can Do | Tool Combination | Agent Capability | | --- | --- | | `Read`, `Glob`, `Grep` | Read-only analysis | | `Read`, `Edit`, `Glob` | Analyze and modify code | | `Read`, `Edit`, `Bash`, `Glob`, `Grep` | Full automation | | Add `WebSearch` |
← Codex App InterfaceAssembly Memory Mgmt β†’