Getting started with the Claude Agent SDK


Photo by the Author
The obvious Getting started
Tired of documentation about duct-pating, tools, and lifting together? This page Claude Agent SDK it allows you to change Claude code “Edit → Build → Run” workflow into real, structured agents, so you can run tasks, wire command applications, and ship command applications without tons of glue code. If you already like to use It's a scar In the terminal, this software development kit (SDK) gives you the same vibe with the right layout, shape, and focus.
In this tutorial, you'll set up the Claude Agent and build a small, multi-tool CLI that touches the final steps (programmed. Along the way, you'll see how to register tools, manage context, and orchestrate local agent loops forflows such as vulnerability, code generation, and capture.
The obvious What is Agent Claude?
-Obubizin' Claude Sonnet 4.5 It marks a significant improvement in skills, which contain a state-of-the-art model that goes through the benchmarks of the consulting industry, statistics, and long-term operations. This release includes chrome extensions, memory tool, and information generation features. The stand up part is it Claude Agent SDKbuilt on the foundation of Claude code.
The Agent for Claude Agent SDK enables developers to create, extend, and use applications powered by Claude. It allows integration with your environment, provides Claude access to your tools and helps the oudest of the environment you collect, including coding, research, note taking, and automation.
The obvious Setting up the Claude Agent SDK
Before building, make sure you set both Claude Code CLI once Claude Agent SDK.
// 1. Requirements
- Python: version 3.10 or higher.
- Node.js: CLI version 18+.
- Claude API key or an anthropic account.
// 2. Enter the Claude Code CLI
We will install the Claude Code CLI through Windows by typing the following command in PowerShell:
irm | iex
Then add this method to your program's environment:
Restart PowerShell and test:
For other platforms, consider using the NPM Package Manager:
npm i -g @anthropic-ai/claude-code
After installation, type claude in your account to sign in.
// 3. Install the Claude Agent SDK (Python)
Install the Claude Agent Python SDK using the PIP package manager.
pip install claude-agent-sdk
If you get a CLINotFoundErrorMake sure Claude Cli is properly installed and installed on your system.
The obvious Building a multi-tool application with the Claude Agent SDK
In this section, we will build A clue The application, which tracks the market live across various industries, including startups, AI, Finance, and sustainability.
It's inclusive Claude Sonnet 4.5, The websech, Webfetch scriptagain Local Storage Tools in one multi-agent system.
Create a python file trend_smith.py And add the following code to it:
// 1. Import & Basic Settings
This loads the Python libraries, the agent's agent types, a small help menu, the name of the model, and a soft gray text style for the status lines.
import Asyncio import time import OS NOS ENTIVETE from DateTime TetTeme from PathLib import method ( Claudeasuent Helper , ClaudesdkClient , ClaudesSsuent , TextMessage , Tool Quick Scan of Multi source (Auto-Satas Markdown) / Scan Short scan of one page / Help / Logout / Your logout / Quit ""[90m"
RESET = " 33[0m"
// 2. System Prompt & Report Destination
This sets the “house rules” for answers (fast, compact, consistent sections) and chooses a reports/ folder next to your script for saved briefs.
SYS = """You are TrendSmith, a fast, concise trend researcher.
- Finish quickly (~20 s).
- For /trend: ≤1 WebSearch + ≤2 WebFetch from distinct domains.
- For /scan: ≤1 WebFetch only.
Return for /trend:
TL;DR (1 line)
3-5 Signals (short bullets)
Key Players, Risks, 30/90-day Watchlist
Sources (markdown: **Title** -- URL)
Return for /scan: 5 bullets + TL;DR + Sources.
After finishing /trend, the client will auto-save your full brief.
"""
BASE = Path(__file__).parent
REPORTS = BASE / "reports"
// 3. Saving Files Safely
These helpers make filenames safe, create folders if needed, and always try a home-folder fallback so your report still gets saved.
def _ts():
return datetime.now().strftime("%Y%m%d_%H%M")
def _sanitize(s: str):
return re.sub(r"[^w-.]+ "," _ ", s) .strip (" _ ") or "def _esuwa_safe (method: PAST) without writing If directory / permission fails back to ~ / trendsmith / reports. "" "" fb.write_text(text, encoding = "UTF-8") Return FB def save
// 4. Tracking each run
This saves what you need in one request: Stream script, model, tool count, token usage, then reset sanity before next request.
class State:
def __init__(self):
self.brief = ""
self.model_raw = None
self.usage = {}
self.cost = None
self.last_cmd = None
self.last_topic = None
self.tools = {}
self.t0 = 0.0
self.t1 = 0.0
def reset(self):
self.brief = ""
self.model_raw = None
self.usage = {}
self.cost = None
self.tools = {}
self.t0 = time.perf_counter()
self.t1 = 0.0
def friendly_model(name: str | None) -> str:
if not name:
return MODEL
n = (name or "").lower()
if "sonnet-4-5" in n or "sonnet_4_5" in n:
return "Claude 4.5 Sonnet"
if "sonnet" in n:
return "Claude Sonnet"
if "haiku" in n:
return "Claude Haiku"
if "opus" in n:
return "Claude Opus"
return name or "Unknown"
// 5. Short run summary
This prints a neat clean box to show the model, tokens, tool usage, and time, without mixing in your broadcast content.
def usage_footer(st: State, opts_model: str):
st.t1 = st.t1 or time.perf_counter()
dur = st.t1 - st.t0
usage = st.usage or {}
it = usage.get("input_tokens")
ot = usage.get("output_tokens")
total = usage.get("total_tokens")
if total is None and (it is not None or ot is not None):
total = (it or 0) + (ot or 0)
tools_used = ", ".join(f"{k}×{v}" for k, v in st.tools.items()) or "--"
model_label = friendly_model(st.model_raw or opts_model)
box = [
"┌─ Run Summary ─────────────────────────────────────────────",
f"│ Model: {model_label}",
f"│ Tokens: {total if total is not None else '?'}"
+ (f" (in={it if it is not None else '?'} | out={ot if ot is not None else '?'})"
if (it is not None or ot is not None) else ""),
f"│ Tools: {tools_used}",
f"│ Duration: {dur:.1f}s",
"└───────────────────────────────────────────────────────────",
]
print(GRAY + "n".join(box) + RESET, file=sys.stderr)
// 6. Main loop (all-one)
This starts the app, reads your command, asks the AI, broadcasts the answer, saves /trend Reports, then prints a summary.
async def main():
"""Setup → REPL → parse → query/stream → auto-save → summary."""
st = State()
_ensure_dir(REPORTS)
opts = ClaudeAgentOptions(
model=MODEL,
system_prompt=SYS,
allowed_tools=["WebFetch", "WebSearch"],
)
print("📈 TrendSmith nn" + HELP)
async with ClaudeSDKClient(options=opts) as client:
while True:
# Read input
try:
user = input("nYou: ").strip()
except (EOFError, KeyboardInterrupt):
print("nBye!")
break
if not user:
continue
low = user.lower()
# Basic commands
if low in {"/exit", "exit", "quit"}:
print("Bye!")
break
if low in {"/help", "help"}:
print(HELP)
continue
# Parse into a prompt
if low.startswith("/trend "):
topic = user.split(" ", 1)[1].strip().strip('"')
if not topic:
print('e.g. /trend "AI chip startups"')
continue
st.last_cmd, st.last_topic = "trend", topic
prompt = f"Run a fast trend scan for '{topic}' following the output spec."
elif low.startswith("/scan "):
q = user.split(" ", 1)[1].strip()
if not q:
print('e.g. /scan "AI hardware news"')
continue
st.last_cmd, st.last_topic = "scan", q
prompt = f"Quick scan for '{q}' in under 10s (≤1 WebFetch). Return 5 bullets + TL;DR + sources."
else:
st.last_cmd, st.last_topic = "free", None
prompt = user
# Execute request and stream results
st.reset()
print(f"{GRAY}▶ Working...{RESET}")
try:
await client.query(prompt)
except Exception as e:
print(f"{GRAY}❌ Query error: {e}{RESET}")
continue
try:
async for m in client.receive_response():
if isinstance(m, AssistantMessage):
st.model_raw = st.model_raw or m.model
for b in m.content:
if isinstance(b, TextBlock):
st.brief += b.text or ""
print(b.text or "", end="")
elif isinstance(b, ToolUseBlock):
name = b.name or "Tool"
st.tools[name] = st.tools.get(name, 0) + 1
print(f"{GRAY}n🛠 Tool: {name}{RESET}")
elif isinstance(b, ToolResultBlock):
pass # quiet tool payloads
elif isinstance(m, ResultMessage):
st.usage = m.usage or {}
st.cost = m.total_cost_usd
except Exception as e:
print(f"{GRAY}n⚠ Stream error: {e}{RESET}")
# Auto-save trend briefs and show the summary
if st.last_cmd == "trend" and st.brief.strip():
try:
saved_path = save_report(st.last_topic or "trend", st.brief)
print(f"n{GRAY}✅ Auto-saved → {saved_path}{RESET}")
except Exception as e:
print(f"{GRAY}⚠ Save error: {e}{RESET}")
st.t1 = time.perf_counter()
usage_footer(st, opts.model)
if __name__ == "__main__":
asyncio.run(main())
The obvious Testing the Trendsmith program
Now we will test the application using a Python file. Here's a quick refresher on how to use the CLI:
- / TREND “
“ → Short scan of multi source, automatically stored inreports/._ .md - / Scan “
“ → One quick scan (≤1 webfetch), printers only. - / Help → Instructions.
- / Get out → he stops.


Photo by the Author
We used the /trend First AI chip search option.
/trend "AI chip startups"
Because of this, the application has used various search tools and tools to gather information from various websites.


Photo by the Author
Finally, it provided a complete response, Auto saved the report to a Markdown file, and generated an implementation summary. It cost US $ 0.136.


Photo by the Author
Here is a preview of the Markdown report archived on ai chips Startups.


Photo by the Author
Now we will test the scan option and generate a summary about the topic using a web search.
It uses a simple Web Search and Download Tool to generate a brief summary of the topic.


Photo by the Author
The obvious Final thoughts
This application ran well, and worked with Claude Agent SDK it was really nice. If you already have Claude code Edit, I highly recommend trying to change the dynamics of your day-to-day reliable, repeatable terminal work Agentic Clis.
Use it to:
- Change standard dev tasks (debug, test, deploy).
- Simple script analytics or ops
- Package your flow into a usable, usable tool.
The SDK is perfect for aspiring professionals tighten up, to revealagain low glue code above. And yes, you can even ask Claude code to help you build your own agentic app with the SDK.
Abid Awan Awan (@ 1Abidaliawan) is a certified trainer for a scientist with a passion for machine learning models. Currently, he specializes in content creation and technical blogging on machine learning and data science technologies. Avid holds a master's degree in technology management and a bachelor's degree in telecommunication engineering. His idea is to build an AI product using a graph neural network for students struggling with mental illness.


