

Picture by Writer
# Introduction
Uninterested in duct-taping scripts, instruments, and prompts collectively? The Claude Agent SDK enables you to flip your Claude Code “plan → construct → run” workflow into actual, programmable brokers, so you’ll be able to automate duties, wire up instruments, and ship command line interface (CLI) apps with out tons of glue code. In the event you already like utilizing Claude within the terminal, this software program improvement equipment (SDK) provides you an identical vibe with correct construction, state, and extensibility.
On this tutorial, you’ll arrange the Claude Agent SDK and construct a small, multi-tool CLI that chains steps end-to-end (plan → act → confirm). Alongside the way in which, you will see tips on how to register instruments, handle context, and orchestrate agent loops for native workflows like debugging, code era, and deployment.
# What’s the Claude Agent SDK?
Anthropic‘s Claude Sonnet 4.5 marks a big development in capabilities, that includes a state-of-the-art coding mannequin that excels in business benchmarks for reasoning, arithmetic, and long-context duties. This launch features a Chrome extension, a reminiscence software, and doc era options. The standout element is the Claude Agent SDK, constructed on the inspiration of Claude Code.
The Claude Agent SDK allows builders to create, prolong, and customise purposes powered by Claude. It permits integration together with your native setting, granting Claude entry to your instruments and facilitating the orchestration of complicated workflows, together with coding, analysis, note-taking, and automation.
# Setting Up the Claude Agent SDK
Earlier than constructing, be sure you’ve arrange each Claude Code CLI and the Claude Agent SDK.
// 1. Conditions
// 2. Set up Claude Code CLI
We are going to set up the Claude Code CLI on Home windows by typing the next command in PowerShell:
irm https://claude.ai/set up.ps1 | iex
Then add this path to your system setting:
Restart PowerShell and check:
For different platforms, think about using the npm bundle supervisor:
npm i -g @anthropic-ai/claude-code
After set up, sort claude in your terminal to register.
// 3. Set up the Claude Agent SDK (Python)
Set up the Claude Agent Python SDK utilizing the pip bundle supervisor.
pip set up claude-agent-sdk
In the event you get a CLINotFoundError, make sure the Claude CLI is appropriately put in and included in your PATH.
# Constructing a Multi-Software App with the Claude Agent SDK
On this part, we’ll construct the TrendSmith utility, which tracks dwell market tendencies throughout varied industries, together with startups, AI, finance, and sustainability.
It combines Claude Sonnet 4.5, WebSearch, WebFetch, and native storage instruments right into a single multi-agent system.
Create the Python file trend_smith.py and add the next code to it:
// 1. Imports & Primary Settings
This masses Python libraries, the Claude Agent SDK sorts, a tiny assist menu, the mannequin title, and gentle grey textual content styling for standing traces.
import asyncio
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from claude_agent_sdk import (
AssistantMessage,
ClaudeAgentOptions,
ClaudeSDKClient,
ResultMessage,
TextBlock,
ToolResultBlock,
ToolUseBlock,
)
HELP = """Instructions:
/pattern Fast multi-source scan (auto-saves markdown)
/scan Brief one-page scan
/assist /exit Assist / Give up
"""
MODEL = os.getenv("CLAUDE_MODEL", "sonnet") # e.g. "sonnet-4.5"
GRAY = " 33[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 "untitled"
def _ensure_dir(p: Path):
attempt:
p.mkdir(dad and mom=True, exist_ok=True)
besides Exception:
go
def _safe_write(path: Path, textual content: str) -> Path:
"""Write textual content to path; if listing/permission fails, fall again to ~/TrendSmith/reviews."""
attempt:
_ensure_dir(path.dad or mum)
path.write_text(textual content, encoding="utf-8")
return path
besides Exception:
home_reports = Path.dwelling() / "TrendSmith"https://www.kdnuggets.com/"reviews"
_ensure_dir(home_reports)
fb = home_reports / path.title
fb.write_text(textual content, encoding="utf-8")
return fb
def save_report(subject: str, textual content: str) -> Path:
filename = f"{_sanitize(subject)}_{_ts()}.md"
goal = REPORTS / filename
return _safe_write(goal, textual content.strip() + "n")
// 4. Monitoring Every Run
This retains what you want for one request: streamed textual content, mannequin, software counts, token utilization, and timing, then resets cleanly earlier than the subsequent request.
class State:
def __init__(self):
self.transient = ""
self.model_raw = None
self.utilization = {}
self.price = None
self.last_cmd = None
self.last_topic = None
self.instruments = {}
self.t0 = 0.0
self.t1 = 0.0
def reset(self):
self.transient = ""
self.model_raw = None
self.utilization = {}
self.price = None
self.instruments = {}
self.t0 = time.perf_counter()
self.t1 = 0.0
def friendly_model(title: str | None) -> str:
if not title:
return MODEL
n = (title or "").decrease()
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 title or "Unknown"
// 5. Brief Run Abstract
This prints a neat grey field to point out the mannequin, tokens, software utilization, and length, with out mixing into your streamed content material.
def usage_footer(st: State, opts_model: str):
st.t1 = st.t1 or time.perf_counter()
dur = st.t1 - st.t0
utilization = st.utilization or {}
it = utilization.get("input_tokens")
ot = utilization.get("output_tokens")
whole = utilization.get("total_tokens")
if whole is None and (it isn't None or ot will not be None):
whole = (it or 0) + (ot or 0)
tools_used = ", ".be part of(f"{ok}×{v}" for ok, v in st.instruments.objects()) or "--"
model_label = friendly_model(st.model_raw or opts_model)
field = [
"┌─ 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".be part of(field) + RESET, file=sys.stderr)
// 6. The Major Loop (All-in-One)
This begins the app, reads your command, asks the AI, streams the reply, saves /pattern reviews, and prints the abstract.
async def principal():
"""Setup → REPL → parse → question/stream → auto-save → abstract."""
st = State()
_ensure_dir(REPORTS)
opts = ClaudeAgentOptions(
mannequin=MODEL,
system_prompt=SYS,
allowed_tools=["WebFetch", "WebSearch"],
)
print("📈 TrendSmith nn" + HELP)
async with ClaudeSDKClient(choices=opts) as shopper:
whereas True:
# Learn enter
attempt:
consumer = enter("nYou: ").strip()
besides (EOFError, KeyboardInterrupt):
print("nBye!")
break
if not consumer:
proceed
low = consumer.decrease()
# Primary instructions
if low in {"/exit", "exit", "stop"}:
print("Bye!")
break
if low in {"/assist", "assist"}:
print(HELP)
proceed
# Parse right into a immediate
if low.startswith("/pattern "):
subject = consumer.break up(" ", 1)[1].strip().strip('"')
if not subject:
print('e.g. /pattern "AI chip startups"')
proceed
st.last_cmd, st.last_topic = "pattern", subject
immediate = f"Run a quick pattern scan for '{subject}' following the output spec."
elif low.startswith("/scan "):
q = consumer.break up(" ", 1)[1].strip()
if not q:
print('e.g. /scan "AI {hardware} information"')
proceed
st.last_cmd, st.last_topic = "scan", q
immediate = f"Fast scan for '{q}' in underneath 10s (≤1 WebFetch). Return 5 bullets + TL;DR + sources."
else:
st.last_cmd, st.last_topic = "free", None
immediate = consumer
# Execute request and stream outcomes
st.reset()
print(f"{GRAY}▶ Working...{RESET}")
attempt:
await shopper.question(immediate)
besides Exception as e:
print(f"{GRAY}❌ Question error: {e}{RESET}")
proceed
attempt:
async for m in shopper.receive_response():
if isinstance(m, AssistantMessage):
st.model_raw = st.model_raw or m.mannequin
for b in m.content material:
if isinstance(b, TextBlock):
st.transient += b.textual content or ""
print(b.textual content or "", finish="")
elif isinstance(b, ToolUseBlock):
title = b.title or "Software"
st.instruments[name] = st.instruments.get(title, 0) + 1
print(f"{GRAY}n🛠 Software: {title}{RESET}")
elif isinstance(b, ToolResultBlock):
go # quiet software payloads
elif isinstance(m, ResultMessage):
st.utilization = m.utilization or {}
st.price = m.total_cost_usd
besides Exception as e:
print(f"{GRAY}n⚠ Stream error: {e}{RESET}")
# Auto-save pattern briefs and present the abstract
if st.last_cmd == "pattern" and st.transient.strip():
attempt:
saved_path = save_report(st.last_topic or "pattern", st.transient)
print(f"n{GRAY}✅ Auto-saved → {saved_path}{RESET}")
besides Exception as e:
print(f"{GRAY}⚠ Save error: {e}{RESET}")
st.t1 = time.perf_counter()
usage_footer(st, opts.mannequin)
if __name__ == "__main__":
asyncio.run(principal())
# Testing the TrendSmith Utility
We are going to now check the app by working the Python file. Here’s a fast recap on tips on how to use the CLI utility:
- /pattern “
“ → transient multi-source scan, auto-saved toreviews/._ .md - /scan “
“ → one-page fast scan (≤1 WebFetch), prints solely. - /assist → reveals instructions.
- /exit → quits.


Picture by Writer
Now we have used the /pattern choice to seek for AI chip startups.
/pattern "AI chip startups"
Because of this, the app has used varied search and internet scraping instruments to collect info from completely different web sites.


Picture by Writer
In the end, it has supplied the total response, auto-saved the report within the markdown file, and generated the utilization abstract. It price us $0.136.


Picture by Writer
Here’s a preview of the saved Markdown report on the AI Chips Startups.


Picture by Writer
We are going to now check the scanning possibility and generate a abstract in regards to the subject utilizing an internet search.
It makes use of a easy internet search and fetch software to generate a brief abstract on the subject.


Picture by Writer
# Remaining Ideas
This app ran easily, and dealing with the Claude Agent SDK was genuinely enjoyable. If you’re already on the Claude Code plan, I extremely advocate making an attempt it to rework your day-to-day terminal workflow into dependable, repeatable agentic CLIs.
Use it to:
- Automate frequent dev duties (debug, check, deploy).
- Script easy analytics or ops routines.
- Package deal your circulation right into a reusable, shareable software.
The SDK is an efficient match for professionals who need stability, reproducibility, and low glue-code overhead. And sure, you’ll be able to even ask Claude Code that will help you construct the agentic utility itself with the SDK.
Abid Ali Awan (@1abidaliawan) is an authorized information scientist skilled who loves constructing machine studying fashions. Presently, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in expertise administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college students fighting psychological sickness.


Picture by Writer
# Introduction
Uninterested in duct-taping scripts, instruments, and prompts collectively? The Claude Agent SDK enables you to flip your Claude Code “plan → construct → run” workflow into actual, programmable brokers, so you’ll be able to automate duties, wire up instruments, and ship command line interface (CLI) apps with out tons of glue code. In the event you already like utilizing Claude within the terminal, this software program improvement equipment (SDK) provides you an identical vibe with correct construction, state, and extensibility.
On this tutorial, you’ll arrange the Claude Agent SDK and construct a small, multi-tool CLI that chains steps end-to-end (plan → act → confirm). Alongside the way in which, you will see tips on how to register instruments, handle context, and orchestrate agent loops for native workflows like debugging, code era, and deployment.
# What’s the Claude Agent SDK?
Anthropic‘s Claude Sonnet 4.5 marks a big development in capabilities, that includes a state-of-the-art coding mannequin that excels in business benchmarks for reasoning, arithmetic, and long-context duties. This launch features a Chrome extension, a reminiscence software, and doc era options. The standout element is the Claude Agent SDK, constructed on the inspiration of Claude Code.
The Claude Agent SDK allows builders to create, prolong, and customise purposes powered by Claude. It permits integration together with your native setting, granting Claude entry to your instruments and facilitating the orchestration of complicated workflows, together with coding, analysis, note-taking, and automation.
# Setting Up the Claude Agent SDK
Earlier than constructing, be sure you’ve arrange each Claude Code CLI and the Claude Agent SDK.
// 1. Conditions
// 2. Set up Claude Code CLI
We are going to set up the Claude Code CLI on Home windows by typing the next command in PowerShell:
irm https://claude.ai/set up.ps1 | iex
Then add this path to your system setting:
Restart PowerShell and check:
For different platforms, think about using the npm bundle supervisor:
npm i -g @anthropic-ai/claude-code
After set up, sort claude in your terminal to register.
// 3. Set up the Claude Agent SDK (Python)
Set up the Claude Agent Python SDK utilizing the pip bundle supervisor.
pip set up claude-agent-sdk
In the event you get a CLINotFoundError, make sure the Claude CLI is appropriately put in and included in your PATH.
# Constructing a Multi-Software App with the Claude Agent SDK
On this part, we’ll construct the TrendSmith utility, which tracks dwell market tendencies throughout varied industries, together with startups, AI, finance, and sustainability.
It combines Claude Sonnet 4.5, WebSearch, WebFetch, and native storage instruments right into a single multi-agent system.
Create the Python file trend_smith.py and add the next code to it:
// 1. Imports & Primary Settings
This masses Python libraries, the Claude Agent SDK sorts, a tiny assist menu, the mannequin title, and gentle grey textual content styling for standing traces.
import asyncio
import os
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from claude_agent_sdk import (
AssistantMessage,
ClaudeAgentOptions,
ClaudeSDKClient,
ResultMessage,
TextBlock,
ToolResultBlock,
ToolUseBlock,
)
HELP = """Instructions:
/pattern Fast multi-source scan (auto-saves markdown)
/scan Brief one-page scan
/assist /exit Assist / Give up
"""
MODEL = os.getenv("CLAUDE_MODEL", "sonnet") # e.g. "sonnet-4.5"
GRAY = " 33[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 "untitled"
def _ensure_dir(p: Path):
attempt:
p.mkdir(dad and mom=True, exist_ok=True)
besides Exception:
go
def _safe_write(path: Path, textual content: str) -> Path:
"""Write textual content to path; if listing/permission fails, fall again to ~/TrendSmith/reviews."""
attempt:
_ensure_dir(path.dad or mum)
path.write_text(textual content, encoding="utf-8")
return path
besides Exception:
home_reports = Path.dwelling() / "TrendSmith"https://www.kdnuggets.com/"reviews"
_ensure_dir(home_reports)
fb = home_reports / path.title
fb.write_text(textual content, encoding="utf-8")
return fb
def save_report(subject: str, textual content: str) -> Path:
filename = f"{_sanitize(subject)}_{_ts()}.md"
goal = REPORTS / filename
return _safe_write(goal, textual content.strip() + "n")
// 4. Monitoring Every Run
This retains what you want for one request: streamed textual content, mannequin, software counts, token utilization, and timing, then resets cleanly earlier than the subsequent request.
class State:
def __init__(self):
self.transient = ""
self.model_raw = None
self.utilization = {}
self.price = None
self.last_cmd = None
self.last_topic = None
self.instruments = {}
self.t0 = 0.0
self.t1 = 0.0
def reset(self):
self.transient = ""
self.model_raw = None
self.utilization = {}
self.price = None
self.instruments = {}
self.t0 = time.perf_counter()
self.t1 = 0.0
def friendly_model(title: str | None) -> str:
if not title:
return MODEL
n = (title or "").decrease()
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 title or "Unknown"
// 5. Brief Run Abstract
This prints a neat grey field to point out the mannequin, tokens, software utilization, and length, with out mixing into your streamed content material.
def usage_footer(st: State, opts_model: str):
st.t1 = st.t1 or time.perf_counter()
dur = st.t1 - st.t0
utilization = st.utilization or {}
it = utilization.get("input_tokens")
ot = utilization.get("output_tokens")
whole = utilization.get("total_tokens")
if whole is None and (it isn't None or ot will not be None):
whole = (it or 0) + (ot or 0)
tools_used = ", ".be part of(f"{ok}×{v}" for ok, v in st.instruments.objects()) or "--"
model_label = friendly_model(st.model_raw or opts_model)
field = [
"┌─ 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".be part of(field) + RESET, file=sys.stderr)
// 6. The Major Loop (All-in-One)
This begins the app, reads your command, asks the AI, streams the reply, saves /pattern reviews, and prints the abstract.
async def principal():
"""Setup → REPL → parse → question/stream → auto-save → abstract."""
st = State()
_ensure_dir(REPORTS)
opts = ClaudeAgentOptions(
mannequin=MODEL,
system_prompt=SYS,
allowed_tools=["WebFetch", "WebSearch"],
)
print("📈 TrendSmith nn" + HELP)
async with ClaudeSDKClient(choices=opts) as shopper:
whereas True:
# Learn enter
attempt:
consumer = enter("nYou: ").strip()
besides (EOFError, KeyboardInterrupt):
print("nBye!")
break
if not consumer:
proceed
low = consumer.decrease()
# Primary instructions
if low in {"/exit", "exit", "stop"}:
print("Bye!")
break
if low in {"/assist", "assist"}:
print(HELP)
proceed
# Parse right into a immediate
if low.startswith("/pattern "):
subject = consumer.break up(" ", 1)[1].strip().strip('"')
if not subject:
print('e.g. /pattern "AI chip startups"')
proceed
st.last_cmd, st.last_topic = "pattern", subject
immediate = f"Run a quick pattern scan for '{subject}' following the output spec."
elif low.startswith("/scan "):
q = consumer.break up(" ", 1)[1].strip()
if not q:
print('e.g. /scan "AI {hardware} information"')
proceed
st.last_cmd, st.last_topic = "scan", q
immediate = f"Fast scan for '{q}' in underneath 10s (≤1 WebFetch). Return 5 bullets + TL;DR + sources."
else:
st.last_cmd, st.last_topic = "free", None
immediate = consumer
# Execute request and stream outcomes
st.reset()
print(f"{GRAY}▶ Working...{RESET}")
attempt:
await shopper.question(immediate)
besides Exception as e:
print(f"{GRAY}❌ Question error: {e}{RESET}")
proceed
attempt:
async for m in shopper.receive_response():
if isinstance(m, AssistantMessage):
st.model_raw = st.model_raw or m.mannequin
for b in m.content material:
if isinstance(b, TextBlock):
st.transient += b.textual content or ""
print(b.textual content or "", finish="")
elif isinstance(b, ToolUseBlock):
title = b.title or "Software"
st.instruments[name] = st.instruments.get(title, 0) + 1
print(f"{GRAY}n🛠 Software: {title}{RESET}")
elif isinstance(b, ToolResultBlock):
go # quiet software payloads
elif isinstance(m, ResultMessage):
st.utilization = m.utilization or {}
st.price = m.total_cost_usd
besides Exception as e:
print(f"{GRAY}n⚠ Stream error: {e}{RESET}")
# Auto-save pattern briefs and present the abstract
if st.last_cmd == "pattern" and st.transient.strip():
attempt:
saved_path = save_report(st.last_topic or "pattern", st.transient)
print(f"n{GRAY}✅ Auto-saved → {saved_path}{RESET}")
besides Exception as e:
print(f"{GRAY}⚠ Save error: {e}{RESET}")
st.t1 = time.perf_counter()
usage_footer(st, opts.mannequin)
if __name__ == "__main__":
asyncio.run(principal())
# Testing the TrendSmith Utility
We are going to now check the app by working the Python file. Here’s a fast recap on tips on how to use the CLI utility:
- /pattern “
“ → transient multi-source scan, auto-saved toreviews/._ .md - /scan “
“ → one-page fast scan (≤1 WebFetch), prints solely. - /assist → reveals instructions.
- /exit → quits.


Picture by Writer
Now we have used the /pattern choice to seek for AI chip startups.
/pattern "AI chip startups"
Because of this, the app has used varied search and internet scraping instruments to collect info from completely different web sites.


Picture by Writer
In the end, it has supplied the total response, auto-saved the report within the markdown file, and generated the utilization abstract. It price us $0.136.


Picture by Writer
Here’s a preview of the saved Markdown report on the AI Chips Startups.


Picture by Writer
We are going to now check the scanning possibility and generate a abstract in regards to the subject utilizing an internet search.
It makes use of a easy internet search and fetch software to generate a brief abstract on the subject.


Picture by Writer
# Remaining Ideas
This app ran easily, and dealing with the Claude Agent SDK was genuinely enjoyable. If you’re already on the Claude Code plan, I extremely advocate making an attempt it to rework your day-to-day terminal workflow into dependable, repeatable agentic CLIs.
Use it to:
- Automate frequent dev duties (debug, check, deploy).
- Script easy analytics or ops routines.
- Package deal your circulation right into a reusable, shareable software.
The SDK is an efficient match for professionals who need stability, reproducibility, and low glue-code overhead. And sure, you’ll be able to even ask Claude Code that will help you construct the agentic utility itself with the SDK.
Abid Ali Awan (@1abidaliawan) is an authorized information scientist skilled who loves constructing machine studying fashions. Presently, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in expertise administration and a bachelor’s diploma in telecommunication engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college students fighting psychological sickness.
















