docs
0
# Agent Definitions
1
2
Define custom agents with specific tools, prompts, and models for specialized tasks. Agents are reusable configurations that encapsulate behavior for specific use cases.
3
4
## Capabilities
5
6
### Agent Definition
7
8
Custom agent configuration dataclass.
9
10
```python { .api }
11
@dataclass
12
class AgentDefinition:
13
"""Custom agent configuration."""
14
15
description: str
16
prompt: str
17
tools: list[str] | None = None
18
model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
19
```
20
21
**Fields:**
22
23
- `description` (str): Human-readable description of what the agent does. Helps users understand the agent's purpose.
24
25
- `prompt` (str): System prompt that defines the agent's behavior and expertise.
26
27
- `tools` (list[str] | None): List of allowed tools for this agent. If None, inherits from parent configuration.
28
29
- `model` (Literal["sonnet", "opus", "haiku", "inherit"] | None): Model to use for this agent:
30
- `"sonnet"`: Claude Sonnet (balanced performance and speed)
31
- `"opus"`: Claude Opus (maximum capability)
32
- `"haiku"`: Claude Haiku (fast and efficient)
33
- `"inherit"`: Inherit from parent configuration
34
- `None`: Use default model
35
36
**Usage Example:**
37
38
```python
39
from claude_agent_sdk import AgentDefinition
40
41
# Code reviewer agent
42
reviewer = AgentDefinition(
43
description="Reviews code for quality and best practices",
44
prompt="You are an expert code reviewer. Focus on code quality, security, and best practices.",
45
tools=["Read", "Grep", "Glob"],
46
model="sonnet"
47
)
48
49
# Documentation writer agent
50
doc_writer = AgentDefinition(
51
description="Writes technical documentation",
52
prompt="You are a technical writer. Create clear, comprehensive documentation.",
53
tools=["Read", "Write", "Glob"],
54
model="sonnet"
55
)
56
57
# Bug fixer agent
58
bug_fixer = AgentDefinition(
59
description="Diagnoses and fixes bugs",
60
prompt="You are a debugging expert. Find and fix bugs efficiently.",
61
tools=["Read", "Write", "Edit", "Bash", "Grep"],
62
model="opus"
63
)
64
```
65
66
### Using Agents
67
68
Agents are configured via `ClaudeAgentOptions.agents` and can be invoked by Claude during execution.
69
70
```python
71
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition
72
73
# Define agents
74
agents = {
75
"reviewer": AgentDefinition(
76
description="Code reviewer",
77
prompt="Review code for quality",
78
tools=["Read", "Grep"],
79
model="sonnet"
80
),
81
"writer": AgentDefinition(
82
description="Documentation writer",
83
prompt="Write clear documentation",
84
tools=["Read", "Write"],
85
model="sonnet"
86
)
87
}
88
89
# Use with options
90
options = ClaudeAgentOptions(
91
agents=agents,
92
allowed_tools=["Read", "Write", "Grep"]
93
)
94
```
95
96
### Setting Source
97
98
Configuration source levels for agent definitions.
99
100
```python { .api }
101
SettingSource = Literal["user", "project", "local"]
102
```
103
104
**Values:**
105
106
- `"user"`: User-level settings (applies to all projects for this user)
107
- `"project"`: Project-level settings (applies to this specific project)
108
- `"local"`: Local directory settings (applies to current directory only)
109
110
**Usage Example:**
111
112
```python
113
from claude_agent_sdk import ClaudeAgentOptions
114
115
# Load settings from specific sources
116
options = ClaudeAgentOptions(
117
setting_sources=["project", "local"] # Exclude user settings
118
)
119
120
# Load only project settings
121
options = ClaudeAgentOptions(
122
setting_sources=["project"]
123
)
124
125
# Load all settings (default behavior)
126
options = ClaudeAgentOptions(
127
setting_sources=["user", "project", "local"]
128
)
129
```
130
131
## Complete Examples
132
133
### Specialized Development Agents
134
135
```python
136
from claude_agent_sdk import (
137
ClaudeAgentOptions, AgentDefinition, query,
138
AssistantMessage, TextBlock
139
)
140
import anyio
141
142
# Define specialized agents
143
agents = {
144
"python_expert": AgentDefinition(
145
description="Python development expert",
146
prompt="""You are an expert Python developer with deep knowledge of:
147
- Python best practices and idioms
148
- Async/await programming
149
- Type hints and mypy
150
- Testing with pytest
151
- Performance optimization
152
Always write clean, well-documented Python code.""",
153
tools=["Read", "Write", "Edit", "Bash", "Grep"],
154
model="sonnet"
155
),
156
157
"security_auditor": AgentDefinition(
158
description="Security vulnerability auditor",
159
prompt="""You are a security expert specializing in:
160
- Code vulnerability analysis
161
- Security best practices
162
- OWASP Top 10
163
- Dependency security
164
Review code for security issues and suggest fixes.""",
165
tools=["Read", "Grep", "Glob"],
166
model="opus"
167
),
168
169
"test_writer": AgentDefinition(
170
description="Test suite creator",
171
prompt="""You are a testing expert who writes:
172
- Comprehensive unit tests
173
- Integration tests
174
- Edge case coverage
175
- Clear test documentation
176
Use pytest and follow testing best practices.""",
177
tools=["Read", "Write", "Bash"],
178
model="sonnet"
179
),
180
181
"doc_generator": AgentDefinition(
182
description="Documentation generator",
183
prompt="""You are a technical writer who creates:
184
- Clear API documentation
185
- Usage examples
186
- Architecture diagrams (as text)
187
- README files
188
Write documentation that developers love to read.""",
189
tools=["Read", "Write", "Glob"],
190
model="sonnet"
191
),
192
}
193
194
# Use agents
195
async def main():
196
options = ClaudeAgentOptions(
197
agents=agents,
198
allowed_tools=["Read", "Write", "Edit", "Bash", "Grep", "Glob"]
199
)
200
201
async for msg in query(
202
prompt="Review my Python code for security issues",
203
options=options
204
):
205
if isinstance(msg, AssistantMessage):
206
for block in msg.content:
207
if isinstance(block, TextBlock):
208
print(block.text)
209
210
anyio.run(main)
211
```
212
213
### Project-Specific Agents
214
215
```python
216
from claude_agent_sdk import AgentDefinition
217
218
# Web application agents
219
web_agents = {
220
"frontend": AgentDefinition(
221
description="Frontend React developer",
222
prompt="""You are a React expert specializing in:
223
- Modern React with hooks
224
- TypeScript
225
- Component design
226
- Accessibility
227
- Performance optimization""",
228
tools=["Read", "Write", "Edit", "Bash"],
229
model="sonnet"
230
),
231
232
"backend": AgentDefinition(
233
description="Backend API developer",
234
prompt="""You are a backend expert specializing in:
235
- RESTful API design
236
- Database optimization
237
- Authentication/authorization
238
- Error handling
239
- API documentation""",
240
tools=["Read", "Write", "Edit", "Bash"],
241
model="sonnet"
242
),
243
244
"devops": AgentDefinition(
245
description="DevOps engineer",
246
prompt="""You are a DevOps expert specializing in:
247
- CI/CD pipelines
248
- Docker and containerization
249
- Infrastructure as code
250
- Monitoring and logging
251
- Cloud deployment""",
252
tools=["Read", "Write", "Bash"],
253
model="sonnet"
254
),
255
}
256
```
257
258
### Data Science Agents
259
260
```python
261
from claude_agent_sdk import AgentDefinition
262
263
data_agents = {
264
"data_analyst": AgentDefinition(
265
description="Data analysis expert",
266
prompt="""You are a data analyst expert in:
267
- Pandas and NumPy
268
- Data cleaning and preprocessing
269
- Exploratory data analysis
270
- Statistical analysis
271
- Data visualization with matplotlib/seaborn""",
272
tools=["Read", "Write", "Bash"],
273
model="sonnet"
274
),
275
276
"ml_engineer": AgentDefinition(
277
description="Machine learning engineer",
278
prompt="""You are an ML engineer specializing in:
279
- Scikit-learn, PyTorch, TensorFlow
280
- Model training and evaluation
281
- Feature engineering
282
- Model optimization
283
- Production ML systems""",
284
tools=["Read", "Write", "Bash"],
285
model="opus"
286
),
287
288
"data_engineer": AgentDefinition(
289
description="Data pipeline engineer",
290
prompt="""You are a data engineer expert in:
291
- ETL pipelines
292
- Data warehousing
293
- SQL optimization
294
- Apache Spark
295
- Data quality""",
296
tools=["Read", "Write", "Bash"],
297
model="sonnet"
298
),
299
}
300
```
301
302
### Code Maintenance Agents
303
304
```python
305
from claude_agent_sdk import AgentDefinition
306
307
maintenance_agents = {
308
"refactorer": AgentDefinition(
309
description="Code refactoring specialist",
310
prompt="""You are a refactoring expert who:
311
- Improves code structure
312
- Reduces complexity
313
- Eliminates code smells
314
- Maintains functionality
315
- Adds clear documentation""",
316
tools=["Read", "Write", "Edit", "Grep"],
317
model="sonnet"
318
),
319
320
"debugger": AgentDefinition(
321
description="Bug investigation and fixing",
322
prompt="""You are a debugging expert who:
323
- Analyzes error messages
324
- Traces code execution
325
- Identifies root causes
326
- Implements fixes
327
- Adds tests for bug cases""",
328
tools=["Read", "Write", "Edit", "Bash", "Grep"],
329
model="opus"
330
),
331
332
"optimizer": AgentDefinition(
333
description="Performance optimization",
334
prompt="""You are a performance expert who:
335
- Profiles code
336
- Identifies bottlenecks
337
- Optimizes algorithms
338
- Improves memory usage
339
- Measures improvements""",
340
tools=["Read", "Write", "Edit", "Bash"],
341
model="opus"
342
),
343
344
"updater": AgentDefinition(
345
description="Dependency updater",
346
prompt="""You are a dependency management expert who:
347
- Updates dependencies safely
348
- Resolves version conflicts
349
- Tests after updates
350
- Documents changes
351
- Handles breaking changes""",
352
tools=["Read", "Write", "Edit", "Bash"],
353
model="sonnet"
354
),
355
}
356
```
357
358
### Documentation Agents
359
360
```python
361
from claude_agent_sdk import AgentDefinition
362
363
doc_agents = {
364
"api_documenter": AgentDefinition(
365
description="API documentation writer",
366
prompt="""You create API documentation including:
367
- Endpoint descriptions
368
- Request/response examples
369
- Error codes
370
- Authentication details
371
- Usage guidelines""",
372
tools=["Read", "Write", "Glob"],
373
model="sonnet"
374
),
375
376
"readme_writer": AgentDefinition(
377
description="README file creator",
378
prompt="""You write comprehensive README files with:
379
- Project overview
380
- Installation instructions
381
- Usage examples
382
- Configuration guide
383
- Contributing guidelines""",
384
tools=["Read", "Write", "Glob"],
385
model="sonnet"
386
),
387
388
"tutorial_creator": AgentDefinition(
389
description="Tutorial and guide writer",
390
prompt="""You create step-by-step tutorials with:
391
- Clear learning objectives
392
- Progressive examples
393
- Common pitfalls
394
- Best practices
395
- Exercises""",
396
tools=["Read", "Write"],
397
model="sonnet"
398
),
399
}
400
```
401
402
### Architecture and Design Agents
403
404
```python
405
from claude_agent_sdk import AgentDefinition
406
407
architecture_agents = {
408
"architect": AgentDefinition(
409
description="System architecture designer",
410
prompt="""You design software architecture considering:
411
- Scalability requirements
412
- Design patterns
413
- Technology choices
414
- Trade-offs
415
- Future extensibility""",
416
tools=["Read", "Write"],
417
model="opus"
418
),
419
420
"reviewer": AgentDefinition(
421
description="Architecture review specialist",
422
prompt="""You review architecture for:
423
- Design pattern usage
424
- Component coupling
425
- System boundaries
426
- Performance implications
427
- Security considerations""",
428
tools=["Read", "Grep", "Glob"],
429
model="opus"
430
),
431
432
"diagrammer": AgentDefinition(
433
description="Architecture diagram creator",
434
prompt="""You create architecture diagrams (as text) showing:
435
- Component relationships
436
- Data flow
437
- Integration points
438
- Deployment topology
439
- Mermaid diagram syntax""",
440
tools=["Read", "Write"],
441
model="sonnet"
442
),
443
}
444
```
445
446
## Agent Configuration Best Practices
447
448
### 1. Clear Descriptions
449
450
Write descriptions that clearly communicate the agent's purpose:
451
452
```python
453
# Good
454
AgentDefinition(
455
description="Python security auditor specialized in OWASP vulnerabilities",
456
...
457
)
458
459
# Less clear
460
AgentDefinition(
461
description="Code checker",
462
...
463
)
464
```
465
466
### 2. Detailed Prompts
467
468
Provide comprehensive system prompts that define expertise and behavior:
469
470
```python
471
AgentDefinition(
472
description="API documentation writer",
473
prompt="""You are an expert technical writer specializing in API documentation.
474
475
Your documentation includes:
476
- Clear endpoint descriptions with HTTP methods
477
- Request/response schemas with examples
478
- Authentication requirements
479
- Error codes and handling
480
- Rate limiting information
481
- Usage examples in multiple languages
482
483
You write in a clear, concise style that developers appreciate.
484
Always include practical examples.""",
485
...
486
)
487
```
488
489
### 3. Minimal Tool Sets
490
491
Only provide tools necessary for the agent's task:
492
493
```python
494
# Security auditor - read-only
495
AgentDefinition(
496
description="Security auditor",
497
tools=["Read", "Grep", "Glob"], # No Write/Edit
498
...
499
)
500
501
# Code fixer - needs write access
502
AgentDefinition(
503
description="Bug fixer",
504
tools=["Read", "Write", "Edit", "Bash"],
505
...
506
)
507
```
508
509
### 4. Appropriate Model Selection
510
511
Choose models based on task complexity:
512
513
```python
514
# Simple tasks - use Haiku
515
AgentDefinition(
516
description="File organizer",
517
model="haiku",
518
...
519
)
520
521
# Standard tasks - use Sonnet
522
AgentDefinition(
523
description="Code reviewer",
524
model="sonnet",
525
...
526
)
527
528
# Complex tasks - use Opus
529
AgentDefinition(
530
description="Architecture designer",
531
model="opus",
532
...
533
)
534
535
# Inherit from parent
536
AgentDefinition(
537
description="Helper agent",
538
model="inherit",
539
...
540
)
541
```
542
543
### 5. Reusable Agent Libraries
544
545
Organize agents into reusable libraries:
546
547
```python
548
# agents/python_agents.py
549
def get_python_agents():
550
return {
551
"python_dev": AgentDefinition(...),
552
"python_tester": AgentDefinition(...),
553
"python_doc": AgentDefinition(...),
554
}
555
556
# agents/web_agents.py
557
def get_web_agents():
558
return {
559
"frontend": AgentDefinition(...),
560
"backend": AgentDefinition(...),
561
"fullstack": AgentDefinition(...),
562
}
563
564
# Use in project
565
from agents.python_agents import get_python_agents
566
from agents.web_agents import get_web_agents
567
568
all_agents = {
569
**get_python_agents(),
570
**get_web_agents(),
571
}
572
573
options = ClaudeAgentOptions(agents=all_agents)
574
```
575
576
### 6. Testing Agents
577
578
Test agent configurations before deployment:
579
580
```python
581
async def test_agent(agent_name: str, agent_def: AgentDefinition, test_prompt: str):
582
"""Test an agent with a sample prompt."""
583
options = ClaudeAgentOptions(
584
agents={agent_name: agent_def},
585
allowed_tools=agent_def.tools or []
586
)
587
588
async for msg in query(prompt=test_prompt, options=options):
589
if isinstance(msg, AssistantMessage):
590
for block in msg.content:
591
if isinstance(block, TextBlock):
592
print(f"[{agent_name}] {block.text}")
593
594
# Test security auditor
595
await test_agent(
596
"security",
597
AgentDefinition(
598
description="Security auditor",
599
prompt="You are a security expert...",
600
tools=["Read", "Grep"],
601
model="sonnet"
602
),
603
"Review this code for SQL injection vulnerabilities"
604
)
605
```
606
607
## Agent Composition Patterns
608
609
### Hierarchical Agents
610
611
Main agent delegates to specialized sub-agents:
612
613
```python
614
agents = {
615
"lead": AgentDefinition(
616
description="Lead developer - coordinates tasks",
617
prompt="You coordinate development work and delegate to specialists.",
618
tools=["Read", "Write"],
619
model="opus"
620
),
621
"specialist_security": AgentDefinition(
622
description="Security specialist",
623
prompt="You handle security reviews.",
624
tools=["Read", "Grep"],
625
model="sonnet"
626
),
627
"specialist_testing": AgentDefinition(
628
description="Testing specialist",
629
prompt="You write comprehensive tests.",
630
tools=["Read", "Write", "Bash"],
631
model="sonnet"
632
),
633
}
634
```
635
636
### Pipeline Agents
637
638
Agents work in sequence:
639
640
```python
641
pipeline_agents = {
642
"analyzer": AgentDefinition(
643
description="Code analyzer",
644
prompt="Analyze code and identify issues.",
645
tools=["Read", "Grep", "Glob"],
646
model="sonnet"
647
),
648
"fixer": AgentDefinition(
649
description="Code fixer",
650
prompt="Fix identified issues.",
651
tools=["Read", "Write", "Edit"],
652
model="sonnet"
653
),
654
"validator": AgentDefinition(
655
description="Code validator",
656
prompt="Validate fixes and run tests.",
657
tools=["Read", "Bash"],
658
model="sonnet"
659
),
660
}
661
```
662
663
## Agent Invocation
664
665
Claude can invoke agents during execution. The SDK manages agent lifecycle and tool access automatically based on agent definitions.
666
667
**Note**: The exact mechanism for invoking agents is handled by Claude Code internally. Define agents in `ClaudeAgentOptions.agents` and Claude will use them as needed based on your prompt.
668
669
```python
670
options = ClaudeAgentOptions(
671
agents={
672
"reviewer": AgentDefinition(
673
description="Code reviewer",
674
prompt="Review code for quality",
675
tools=["Read", "Grep"],
676
model="sonnet"
677
)
678
}
679
)
680
681
# Claude can invoke the reviewer agent when needed
682
async for msg in query(
683
prompt="Please review my Python code for issues",
684
options=options
685
):
686
print(msg)
687
```
688