spinny:~/writing $ less building-ai-agents-claude-agent-sdk.md
12Claude Agent SDK आपको उसी एजेंट लूप तक प्रोग्रामेटिक एक्सेस देता है जो Claude Code को शक्ति प्रदान करता है। आपके एजेंट फाइलें पढ़ सकते हैं, शेल कमांड एक्सीक्यूट कर सकते हैं, वेब खोज सकते हैं, कोड एडिट कर सकते हैं, MCP सर्वर के माध्यम से एक्सटर्नल API कॉल कर सकते हैं, और सब-एजेंट्स को ऑर्केस्ट्रेट कर सकते हैं - सब कुछ TypeScript या Python की कुछ ही लाइनों से।34स्टैंडर्ड Anthropic Client SDK के विपरीत जहां आप अपना खुद का टूल लूप बनाते हैं, Agent SDK टूल एक्सीक्यूशन, कॉन्टेक्स्ट मैनेजमेंट, रीट्राइज, और ऑर्केस्ट्रेशन को आंतरिक रूप से संभालता है। आप बताएं कि आप क्या चाहते हैं, टूल्स प्रदान करें, और एजेंट बाकी सब खुद समझ लेता है।56## आर्किटेक्चर78SDK एक सरल लूप का पालन करता है: **कॉन्टेक्स्ट इकट्ठा करो, एक्शन लो, सत्यापित करो, दोहराओ**।910```mermaid11graph TD12 Input[User Prompt] --> Loop[Agent Loop]13 Loop --> Reason[Claude Reasons]14 Reason --> Tool[Call Tool]15 Tool --> Result[Tool Result]16 Result --> Loop17 Reason --> Done[Final Response]1819 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end2526 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end3132 Tool --> T133 Tool --> M134```3536मुख्य एंट्री पॉइंट `query()` है, जो एक async iterator रिटर्न करता है जो एजेंट के काम करते समय मैसेज स्ट्रीम करता है। हर मैसेज आपको बताता है कि एजेंट क्या कर रहा है: रीजनिंग, टूल कॉल करना, रिज़ल्ट प्राप्त करना, या फाइनल आउटपुट देना।3738## शुरू करें3940### इंस्टॉलेशन4142```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk4546# Python47pip install claude-agent-sdk48```4950आपको अपने एनवायरनमेंट में `ANTHROPIC_API_KEY` के रूप में एक Anthropic API key सेट करनी होगी।5152### आपका पहला एजेंट5354```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";5657const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});6364for await (const message of conversation) {65 if (message.type === "assistant") {66 process.stdout.write(message.content);67 }68 if (message.type === "result" && message.subtype === "success") {69 console.log("\nDone:", message.result);70 }71}72```7374बस इतना ही। एजेंट Glob का उपयोग करके फाइलें खोजेगा, Grep से TODO पैटर्न सर्च करेगा, Read से मैच देखेगा, और एक स्ट्रक्चर्ड सारांश रिटर्न करेगा। आपको ऑर्केस्ट्रेशन लॉजिक लिखने की जरूरत नहीं है - SDK इसे संभालता है।7576### Python समतुल्य7778```python79from claude_agent_sdk import query8081async for message in query(82 prompt="Find all TODO comments in the codebase and create a summary",83 options={"allowed_tools": ["Read", "Glob", "Grep"]},84):85 if message.type == "assistant":86 print(message.content, end="")87 if message.type == "result" and message.subtype == "success":88 print(f"\nDone: {message.result}")89```9091## बिल्ट-इन टूल्स9293SDK में वही टूल्स शामिल हैं जो Claude Code में उपलब्ध हैं:9495| टूल | विवरण |96|------|-------------|97| **Read** | फाइल कंटेंट पढ़ें |98| **Write** | नई फाइलें बनाएं |99| **Edit** | मौजूदा फाइलों में टारगेटेड एडिट करें |100| **Bash** | शेल कमांड एक्सीक्यूट करें |101| **Glob** | पैटर्न से फाइलें खोजें |102| **Grep** | regex से फाइल कंटेंट सर्च करें |103| **WebSearch** | वेब सर्च करें |104| **WebFetch** | एक URL फेच करें और उसका कंटेंट रिटर्न करें |105| **AskUserQuestion** | यूजर से इनपुट मांगें |106107आप `allowedTools` के माध्यम से नियंत्रित करते हैं कि एजेंट कौन से टूल्स उपयोग कर सकता है। अगर कोई टूल लिस्ट में नहीं है, तो एजेंट उसे कॉल नहीं कर सकता।108109## परमिशन मोड110111चूंकि एजेंट वास्तविक सिस्टम पर वास्तविक कमांड एक्सीक्यूट करते हैं, परमिशन मायने रखती हैं।112113| मोड | व्यवहार | उपयोग का मामला |114|------|----------|----------|115| `default` | कस्टम `canUseTool` कॉलबैक हर कॉल पर फैसला करता है | बारीक नियंत्रण |116| `acceptEdits` | फाइल ऑपरेशन ऑटो-अप्रूव, Bash के लिए प्रॉम्प्ट | डेवलपमेंट वर्कफ्लो |117| `dontAsk` | allowedTools में नहीं तो अस्वीकार | प्रतिबंधित एजेंट |118| `bypassPermissions` | सब कुछ ऑटोमैटिकली अप्रूव | विश्वसनीय सैंडबॉक्स्ड एनवायरनमेंट |119| `auto` | मॉडल क्लासिफायर सेफ्टी तय करता है | संतुलित ऑटोमेशन |120121```typescript122const conversation = query({123 prompt: "Refactor the auth module to use JWT",124 options: {125 allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],126 permissionMode: "acceptEdits",127 },128});129```130131प्रोडक्शन उपयोग के लिए, हमेशा एजेंट्स को सैंडबॉक्स्ड एनवायरनमेंट (कंटेनर, VMs) में चलाएं और सबसे प्रतिबंधात्मक परमिशन मोड का उपयोग करें जो एजेंट को अपना काम करने देता हो।132133## MCP के साथ कस्टम टूल्स बनाना134135SDK की असली ताकत एजेंट्स को अपने खुद के टूल्स से विस्तारित करने में है। कस्टम टूल्स इन-प्रोसेस MCP सर्वर के रूप में परिभाषित होते हैं - कोई सबप्रोसेस मैनेजमेंट नहीं, कोई नेटवर्क ओवरहेड नहीं।136137### उदाहरण: वेदर टूल138139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142143const getTemperature = tool(144 "get_temperature",145 "Get the current temperature at a location",146 {147 latitude: z.number().describe("Latitude"),148 longitude: z.number().describe("Longitude"),149 },150 async ({ latitude, longitude }) => {151 const res = await fetch(152 `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&temperature_unit=celsius`153 );154 const data = await res.json();155 return {156 content: [157 {158 type: "text",159 text: `Current temperature: ${data.current.temperature_2m}C`,160 },161 ],162 };163 }164);165166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171172for await (const message of query({173 prompt: "What's the weather like in Rome?",174 options: {175 mcpServers: { weather: weatherServer },176 allowedTools: ["mcp__weather__get_temperature"],177 },178})) {179 if (message.type === "result" && message.subtype === "success") {180 console.log(message.result);181 }182}183```184185कस्टम टूल्स `mcp__{server_name}__{tool_name}` नामकरण परंपरा का पालन करते हैं। आप `allowedTools` में वाइल्डकार्ड का उपयोग कर सकते हैं: `"mcp__weather__*"` वेदर सर्वर के सभी टूल्स को अनुमति देता है।186187### उदाहरण: डेटाबेस क्वेरी टूल188189```typescript190const queryDb = tool(191 "query_database",192 "Run a read-only SQL query against the application database",193 {194 sql: z.string().describe("SQL SELECT query to execute"),195 },196 async ({ sql }) => {197 // Validate: only allow SELECT queries198 if (!sql.trim().toUpperCase().startsWith("SELECT")) {199 return {200 content: [{ type: "text", text: "Error: Only SELECT queries are allowed." }],201 };202 }203204 const result = await pool.query(sql);205 return {206 content: [207 {208 type: "text",209 text: JSON.stringify(result.rows, null, 2),210 },211 ],212 };213 }214);215```216217## एक्सटर्नल MCP सर्वर से कनेक्ट करना218219इन-प्रोसेस टूल्स के अलावा, आप किसी भी मौजूदा MCP सर्वर से कनेक्ट कर सकते हैं - वही सर्वर जो Claude Desktop, Cursor, और अन्य MCP क्लाइंट्स के साथ काम करते हैं।220221```typescript222for await (const message of query({223 prompt: "Check the latest issues in the frontend repo and summarize them",224 options: {225 mcpServers: {226 github: {227 command: "npx",228 args: ["-y", "@modelcontextprotocol/server-github"],229 env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN },230 },231 },232 allowedTools: ["mcp__github__*"],233 },234})) {235 // ...236}237```238239आप कई MCP सर्वर को मिला सकते हैं। एजेंट सभी कनेक्टेड सर्वर से सभी टूल्स देखता है और आवश्यकतानुसार उनका उपयोग करता है।240241```mermaid242graph LR243 Agent[Your Agent] --> SDK[Agent SDK]244 SDK --> InProcess[In-process MCP\nCustom Tools]245 SDK --> GitHub[GitHub MCP Server]246 SDK --> Postgres[PostgreSQL MCP Server]247 SDK --> Slack[Slack MCP Server]248```249250## मल्टी-एजेंट ऑर्केस्ट्रेशन251252जटिल वर्कफ्लो के लिए, आप विशेष सब-एजेंट्स परिभाषित कर सकते हैं जिनसे पैरेंट एजेंट काम सौंपता है। हर सब-एजेंट का अपना प्रॉम्प्ट, टूल्स, और फोकस एरिया होता है।253254```typescript255for await (const message of query({256 prompt: "Review the PR, check for security issues, and update the changelog",257 options: {258 allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep", "Agent"],259 agents: [260 {261 name: "security-reviewer",262 description: "Reviews code for security vulnerabilities",263 prompt: "You are a security expert. Analyze code for OWASP Top 10 vulnerabilities.",264 allowedTools: ["Read", "Glob", "Grep"],265 },266 {267 name: "changelog-writer",268 description: "Updates the CHANGELOG.md file based on recent changes",269 prompt: "You maintain the project changelog. Follow Keep a Changelog format.",270 allowedTools: ["Read", "Edit", "Bash"],271 },272 ],273 },274})) {275 // The parent agent will:276 // 1. Read the PR diff277 // 2. Delegate security review to security-reviewer278 // 3. Delegate changelog update to changelog-writer279 // 4. Synthesize results280}281```282283डेलिगेशन सक्षम करने के लिए पैरेंट के `allowedTools` में `"Agent"` शामिल करें। सब-एजेंट्स अपने खुद के टूल्स के साथ चलते हैं और स्पष्ट रूप से अनुमति दिए बिना पैरेंट के टूल्स एक्सेस नहीं कर सकते।284285```mermaid286graph TD287 Parent[Parent Agent] --> SR[Security Reviewer\nRead, Glob, Grep]288 Parent --> CW[Changelog Writer\nRead, Edit, Bash]289 SR --> Report[Security Report]290 CW --> Updated[Updated CHANGELOG]291 Report --> Parent292 Updated --> Parent293 Parent --> Final[Final Summary]294```295296## सेशन और निरंतरता297298एजेंट सेशन का उपयोग करके कई क्वेरीज़ में कॉन्टेक्स्ट बनाए रख सकते हैं। पहली इंटरैक्शन से `session_id` कैप्चर करें और बाद की क्वेरीज़ में `resume` में पास करें।299300```typescript301let sessionId: string | undefined;302303// First query304for await (const message of query({305 prompt: "Read the project structure and understand the architecture",306 options: { allowedTools: ["Read", "Glob", "Grep"] },307})) {308 if (message.type === "init") {309 sessionId = message.session_id;310 }311}312313// Follow-up query (same session, full context preserved)314for await (const message of query({315 prompt: "Now refactor the auth module based on what you learned",316 resume: sessionId,317 options: { allowedTools: ["Read", "Edit", "Bash"] },318})) {319 // Agent remembers the full project context from the first query320}321```322323## Claude Managed Agents324325अगर आप एजेंट इंफ्रास्ट्रक्चर खुद होस्ट नहीं करना चाहते, तो **Claude Managed Agents** (अप्रैल 2026 में लॉन्च) एक पूरी तरह से मैनेज्ड क्लाउड सर्विस प्रदान करता है। Anthropic कंटेनर चलाता है, स्केलिंग संभालता है, और एक स्ट्रीमिंग API प्रदान करता है।326327```mermaid328graph LR329 subgraph "Self-hosted (Agent SDK)"330 Code[Your Code] --> SDK2[Agent SDK]331 SDK2 --> API[Claude API]332 SDK2 --> Tools[Your Tools]333 end334335 subgraph "Managed Agents"336 App[Your App] --> MAPI[Managed Agents API]337 MAPI --> Container[Anthropic-hosted Container]338 Container --> API2[Claude API]339 Container --> Tools2[Tools in Container]340 end341```342343मुख्य अंतर: Agent SDK के साथ, आप अपने खुद के इंफ्रास्ट्रक्चर में एजेंट लूप चलाते हैं। Managed Agents के साथ, Anthropic आपके लिए एजेंट होस्ट और चलाता है। आप सेशन-बेस्ड API के माध्यम से इंटरैक्ट करते हैं और Server-Sent Events के माध्यम से इवेंट प्राप्त करते हैं।344345**प्राइसिंग:**346- **Agent SDK**: केवल स्टैंडर्ड Claude API टोकन दरें। होस्टिंग आप संभालते हैं।347- **Managed Agents**: टोकन दरें प्लस $0.08 प्रति सेशन-घंटा (प्रति मिलीसेकंड बिल)।348349## प्रोडक्शन बेस्ट प्रैक्टिसेज350351### 1. हमेशा सैंडबॉक्स करें352353प्रोडक्शन मशीन पर कभी भी अप्रतिबंधित परमिशन के साथ एजेंट न चलाएं। कंटेनर (Docker, Fly.io, Modal) या सैंडबॉक्स्ड एनवायरनमेंट (E2B, Vercel Sandbox) का उपयोग करें।354355### 2. टूल एक्सेस सीमित करें356357न्यूनतम विशेषाधिकार के सिद्धांत का पालन करें। रिपोर्ट जनरेट करने वाले एजेंट को `Bash` या `Write` की जरूरत नहीं है।358359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366367### 3. गार्डरेल्स के लिए Hooks का उपयोग करें368369Hooks आपको एक्सीक्यूशन से पहले और बाद में टूल कॉल्स को इंटरसेप्ट करने देते हैं। इनका उपयोग लॉगिंग, वैलिडेशन, और रेट लिमिटिंग के लिए करें।370371```typescript372const conversation = query({373 prompt: "Analyze the codebase",374 options: {375 allowedTools: ["Read", "Glob", "Grep"],376 hooks: {377 PreToolUse: async (toolName, input) => {378 console.log(`Tool call: ${toolName}`, input);379 // Return false to block the call380 if (toolName === "Bash" && input.command.includes("rm")) {381 return false;382 }383 return true;384 },385 },386 },387});388```389390### 4. एरर को सुचारू रूप से हैंडल करें391392एजेंट लूप एरर उत्पन्न कर सकता है - टूल फेलियर, API रेट लिमिट, कॉन्टेक्स्ट विंडो ओवरफ्लो। हमेशा मैसेज टाइप चेक करें।393394```typescript395for await (const message of conversation) {396 switch (message.type) {397 case "assistant":398 // Agent reasoning399 break;400 case "tool_use":401 // Agent is calling a tool402 break;403 case "result":404 if (message.subtype === "error") {405 console.error("Agent failed:", message.error);406 }407 break;408 }409}410```411412### 5. टोकन उपयोग की निगरानी करें413414एजेंट लूप काफी टोकन खपत कर सकते हैं, विशेषकर बड़े कोडबेस के साथ। SDK में ऑटोमैटिक कॉन्टेक्स्ट कम्पैक्शन शामिल है, लेकिन आपको फिर भी उपयोग की निगरानी करनी चाहिए।415416## निष्कर्ष417418Claude Agent SDK एक LLM को प्रश्न-उत्तर मशीन से जूनियर डेवलपर जैसी किसी चीज़ में बदल देता है। आपके एजेंट पढ़ सकते हैं, लिख सकते हैं, एक्सीक्यूट कर सकते हैं, सत्यापित कर सकते हैं, और इटरेट कर सकते हैं - वही वर्कफ्लो जो एक इंसान अपनाता है।419420छोटे से शुरू करें: कुछ बिल्ट-इन टूल्स के साथ एक एजेंट बनाएं। फिर अपने विशिष्ट डोमेन के लिए कस्टम MCP टूल्स जोड़ें। जब आपके वर्कफ्लो को विशेषज्ञता की आवश्यकता हो तो मल्टी-एजेंट ऑर्केस्ट्रेशन तक स्केल करें।421422एजेंट लूप वही है जो Claude Code को शक्ति प्रदान करता है। अगर वह सॉफ्टवेयर बना सकता है, तो आपके एजेंट भी बना सकते हैं।423424> **शुरुआत की चेकलिस्ट:**425>426> - [x] SDK इंस्टॉल करें (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] अपने एनवायरनमेंट में `ANTHROPIC_API_KEY` सेट करें428> - [x] बिल्ट-इन टूल्स (Read, Glob, Grep) के साथ एक सरल एजेंट बनाएं429> - [x] इन-प्रोसेस MCP सर्वर के माध्यम से कस्टम टूल जोड़ें430> - [x] एक एक्सटर्नल MCP सर्वर (GitHub, PostgreSQL, आदि) कनेक्ट करें431> - [x] सब-एजेंट्स के साथ मल्टी-एजेंट ऑर्केस्ट्रेशन लागू करें432> - [x] प्रोडक्शन के लिए सैंडबॉक्स्ड एनवायरनमेंट सेट करें433> - [x] लॉगिंग और गार्डरेल्स के लिए hooks जोड़ें434
:Claude Agent SDK के साथ AI एजेंट बनाना: एक व्यावहारिक गाइडlines 1-434 (END) — press q to close