docs
0
# Agent Definitions
1
2
Define custom agents with specific behaviors, tools, prompts, and models. Agents allow you to create specialized AI assistants tailored for specific tasks or domains.
3
4
## Capabilities
5
6
### AgentDefinition
7
8
Configuration for a custom agent.
9
10
```python { .api }
11
@dataclass
12
class AgentDefinition:
13
"""
14
Agent definition configuration.
15
16
Defines a custom agent with specific capabilities, behavior, and model.
17
Agents can have specialized prompts, restricted tool access, and use
18
specific models for their tasks.
19
20
Use cases:
21
- Task-specific agents (reviewer, implementer, tester)
22
- Domain experts (security, performance, documentation)
23
- Role-based assistants (junior developer, senior architect)
24
- Workflow stages (planning, execution, verification)
25
26
Attributes:
27
description: Human-readable agent description
28
prompt: System prompt defining agent behavior
29
tools: Available tools for this agent
30
model: Model to use for this agent
31
"""
32
33
description: str
34
"""Agent description.
35
36
A human-readable description of what this agent does and when to use it.
37
This helps understand the agent's purpose and capabilities.
38
39
Example:
40
"Code review expert who focuses on security and best practices"
41
"Implementation specialist who writes clean, tested code"
42
"Documentation writer who creates clear, comprehensive docs"
43
"""
44
45
prompt: str
46
"""Agent system prompt.
47
48
The system prompt that defines the agent's behavior, personality, and
49
capabilities. This is the core instruction that shapes how the agent
50
responds and acts.
51
52
The prompt should:
53
- Define the agent's role and expertise
54
- Specify behavioral guidelines
55
- Set output format expectations
56
- Include relevant constraints or rules
57
58
Example:
59
"You are a security-focused code reviewer. When reviewing code:
60
1. Check for common vulnerabilities (XSS, SQL injection, etc.)
61
2. Verify input validation and sanitization
62
3. Review authentication and authorization logic
63
4. Flag hardcoded secrets or credentials
64
Always provide specific line numbers and remediation suggestions."
65
"""
66
67
tools: list[str] | None = None
68
"""Available tools.
69
70
List of tool names this agent can use. If None, the agent inherits
71
tool permissions from the parent configuration.
72
73
Restricting tools helps:
74
- Prevent unwanted actions (e.g., reviewer can't modify code)
75
- Focus agent capabilities (e.g., docs writer only needs Read)
76
- Enforce workflow boundaries (e.g., planner can't execute)
77
78
Example:
79
["Read", "Grep", "Glob"] # Read-only agent
80
["Write", "Edit", "MultiEdit"] # Editor agent
81
["Bash"] # Executor agent
82
None # Inherit from parent
83
"""
84
85
model: Literal["sonnet", "opus", "haiku", "inherit"] | None = None
86
"""Model to use.
87
88
The Claude model this agent should use. Options:
89
- 'sonnet': Claude Sonnet (balanced performance)
90
- 'opus': Claude Opus (maximum capability)
91
- 'haiku': Claude Haiku (fast and efficient)
92
- 'inherit': Use parent model configuration
93
- None: Use default model
94
95
Choose based on task requirements:
96
- Use 'opus' for complex reasoning and code generation
97
- Use 'sonnet' for balanced general-purpose work
98
- Use 'haiku' for simple, fast operations
99
- Use 'inherit' to match parent configuration
100
"""
101
```
102
103
### SystemPromptPreset
104
105
System prompt preset configuration.
106
107
```python { .api }
108
class SystemPromptPreset(TypedDict):
109
"""
110
System prompt preset configuration.
111
112
Allows using a preset system prompt with optional additional text.
113
Currently only supports the "claude_code" preset.
114
115
Fields:
116
type: Must be "preset"
117
preset: Preset name (currently only "claude_code")
118
append: Optional text to append to the preset
119
"""
120
121
type: Literal["preset"]
122
"""Type marker.
123
124
Must be "preset" to indicate this is a preset configuration.
125
"""
126
127
preset: Literal["claude_code"]
128
"""Preset name.
129
130
The name of the preset to use. Currently only "claude_code" is
131
supported, which provides the standard Claude Code system prompt.
132
"""
133
134
append: NotRequired[str]
135
"""Text to append.
136
137
Optional text to append to the preset prompt. Use this to add
138
additional instructions or constraints while keeping the base
139
preset behavior.
140
141
Example:
142
"Additionally, focus on performance optimization"
143
"Always explain your reasoning before taking action"
144
"""
145
```
146
147
### SettingSource
148
149
Setting source types for loading configuration.
150
151
```python { .api }
152
SettingSource = Literal["user", "project", "local"]
153
"""
154
Setting source types.
155
156
Specifies which setting files to load:
157
- 'user': User-level settings (~/.config/claude/)
158
- 'project': Project-level settings (.claude/ in project root)
159
- 'local': Local settings (.claude/ in current directory)
160
161
Used in ClaudeAgentOptions.setting_sources to control which
162
configuration files are loaded.
163
"""
164
```
165
166
## Usage Examples
167
168
### Basic Agent Definition
169
170
```python
171
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
172
173
# Define a code reviewer agent
174
reviewer = AgentDefinition(
175
description="Code review expert",
176
prompt="""You are a code reviewer. Focus on:
177
- Code quality and best practices
178
- Potential bugs and edge cases
179
- Security vulnerabilities
180
- Performance issues
181
Provide specific feedback with line numbers.""",
182
tools=["Read", "Grep", "Glob"],
183
model="sonnet"
184
)
185
186
options = ClaudeAgentOptions(
187
agents={"reviewer": reviewer}
188
)
189
190
async for msg in query(prompt="Review this codebase", options=options):
191
print(msg)
192
```
193
194
### Multiple Specialized Agents
195
196
```python
197
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
198
199
# Define specialized agents for different tasks
200
agents = {
201
"reviewer": AgentDefinition(
202
description="Code review expert",
203
prompt="You are a code reviewer. Find bugs, security issues, and suggest improvements.",
204
tools=["Read", "Grep"],
205
model="sonnet"
206
),
207
208
"implementer": AgentDefinition(
209
description="Code implementation expert",
210
prompt="You are an implementation expert. Write clean, tested, documented code.",
211
tools=["Read", "Write", "Edit", "Bash"],
212
model="sonnet"
213
),
214
215
"documenter": AgentDefinition(
216
description="Documentation specialist",
217
prompt="You are a documentation expert. Write clear, comprehensive documentation.",
218
tools=["Read", "Write"],
219
model="haiku" # Faster for docs
220
),
221
222
"tester": AgentDefinition(
223
description="Testing specialist",
224
prompt="You are a testing expert. Write comprehensive tests with good coverage.",
225
tools=["Read", "Write", "Bash"],
226
model="sonnet"
227
)
228
}
229
230
options = ClaudeAgentOptions(agents=agents)
231
232
async for msg in query(
233
prompt="First review, then implement, document, and test",
234
options=options
235
):
236
print(msg)
237
```
238
239
### Security-Focused Agent
240
241
```python
242
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
243
244
security_agent = AgentDefinition(
245
description="Security auditor",
246
prompt="""You are a security expert. When analyzing code:
247
248
1. Check for OWASP Top 10 vulnerabilities
249
2. Review authentication and authorization
250
3. Look for hardcoded secrets
251
4. Verify input validation
252
5. Check for injection vulnerabilities
253
6. Review cryptographic implementations
254
7. Check for insecure dependencies
255
256
For each issue found:
257
- Provide file and line number
258
- Explain the vulnerability
259
- Suggest remediation
260
- Rate severity (Critical/High/Medium/Low)""",
261
tools=["Read", "Grep", "Glob"],
262
model="opus" # Use most capable model for security
263
)
264
265
options = ClaudeAgentOptions(
266
agents={"security": security_agent}
267
)
268
269
async for msg in query(prompt="Perform security audit", options=options):
270
print(msg)
271
```
272
273
### Performance Optimization Agent
274
275
```python
276
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
277
278
performance_agent = AgentDefinition(
279
description="Performance optimization expert",
280
prompt="""You are a performance optimization expert. Analyze code for:
281
282
1. Algorithmic complexity (O(n), O(n²), etc.)
283
2. Memory usage and leaks
284
3. Unnecessary computations
285
4. Database query efficiency
286
5. Caching opportunities
287
6. Concurrency issues
288
7. Resource cleanup
289
290
Provide:
291
- Current performance characteristics
292
- Optimization suggestions
293
- Expected improvements
294
- Code examples""",
295
tools=["Read", "Grep", "Bash"],
296
model="opus"
297
)
298
299
options = ClaudeAgentOptions(
300
agents={"performance": performance_agent}
301
)
302
303
async for msg in query(prompt="Optimize this application", options=options):
304
print(msg)
305
```
306
307
### Read-Only Analysis Agent
308
309
```python
310
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
311
312
# Agent that can only read, never modify
313
analyzer = AgentDefinition(
314
description="Code analyzer (read-only)",
315
prompt="""You are a code analyzer. Examine code and provide insights:
316
- Architecture and design patterns
317
- Code organization and structure
318
- Dependencies and imports
319
- Complexity metrics
320
- Potential refactoring opportunities
321
322
You cannot modify code, only analyze and provide recommendations.""",
323
tools=["Read", "Grep", "Glob"], # No write tools
324
model="sonnet"
325
)
326
327
options = ClaudeAgentOptions(
328
agents={"analyzer": analyzer}
329
)
330
331
async for msg in query(prompt="Analyze architecture", options=options):
332
print(msg)
333
```
334
335
### Agent with Inherited Tools
336
337
```python
338
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
339
340
# Agent that inherits tool permissions from parent
341
flexible_agent = AgentDefinition(
342
description="Flexible assistant",
343
prompt="You are a general-purpose assistant. Adapt to the task at hand.",
344
tools=None, # Inherit from ClaudeAgentOptions.allowed_tools
345
model="inherit" # Inherit model from parent
346
)
347
348
options = ClaudeAgentOptions(
349
allowed_tools=["Read", "Write", "Bash"], # Agent will use these
350
model="claude-sonnet-4-5", # Agent will use this
351
agents={"assistant": flexible_agent}
352
)
353
354
async for msg in query(prompt="Help with this task", options=options):
355
print(msg)
356
```
357
358
### Workflow with Agent Pipeline
359
360
```python
361
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
362
363
# Define agents for different workflow stages
364
planner = AgentDefinition(
365
description="Planning agent",
366
prompt="""You are a planning expert. Create detailed implementation plans:
367
1. Break down requirements
368
2. Identify dependencies
369
3. Define tasks and subtasks
370
4. Estimate complexity
371
5. Suggest order of implementation
372
373
Output a structured plan, not code.""",
374
tools=["Read", "Grep"],
375
model="sonnet"
376
)
377
378
implementer = AgentDefinition(
379
description="Implementation agent",
380
prompt="""You are an implementation expert. Follow the plan and:
381
1. Write clean, maintainable code
382
2. Add appropriate error handling
383
3. Include helpful comments
384
4. Follow coding standards""",
385
tools=["Read", "Write", "Edit"],
386
model="sonnet"
387
)
388
389
verifier = AgentDefinition(
390
description="Verification agent",
391
prompt="""You are a verification expert. Check that:
392
1. Implementation matches plan
393
2. Code works as expected
394
3. Error cases are handled
395
4. Tests pass""",
396
tools=["Read", "Bash"],
397
model="sonnet"
398
)
399
400
options = ClaudeAgentOptions(
401
agents={
402
"planner": planner,
403
"implementer": implementer,
404
"verifier": verifier
405
}
406
)
407
408
async for msg in query(
409
prompt="Plan, implement, and verify a new feature",
410
options=options
411
):
412
print(msg)
413
```
414
415
### Documentation Agent
416
417
```python
418
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
419
420
docs_agent = AgentDefinition(
421
description="Documentation specialist",
422
prompt="""You are a documentation expert. Create clear, comprehensive documentation:
423
424
For functions/classes:
425
- Purpose and usage
426
- Parameters and return values
427
- Examples
428
- Edge cases and limitations
429
430
For projects:
431
- Overview and architecture
432
- Setup instructions
433
- Usage examples
434
- API reference
435
436
Write in clear, simple language. Use examples liberally.""",
437
tools=["Read", "Write"],
438
model="haiku" # Fast for documentation
439
)
440
441
options = ClaudeAgentOptions(
442
agents={"documenter": docs_agent}
443
)
444
445
async for msg in query(prompt="Document this codebase", options=options):
446
print(msg)
447
```
448
449
### Testing Agent
450
451
```python
452
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
453
454
testing_agent = AgentDefinition(
455
description="Testing specialist",
456
prompt="""You are a testing expert. Create comprehensive tests:
457
458
1. Unit tests for individual functions
459
2. Integration tests for component interaction
460
3. Edge case and error condition tests
461
4. Performance tests for critical paths
462
463
Use appropriate testing frameworks (pytest, unittest, etc.)
464
Aim for high code coverage
465
Include both positive and negative test cases
466
Add clear test names and docstrings""",
467
tools=["Read", "Write", "Bash"],
468
model="sonnet"
469
)
470
471
options = ClaudeAgentOptions(
472
agents={"tester": testing_agent}
473
)
474
475
async for msg in query(prompt="Write comprehensive tests", options=options):
476
print(msg)
477
```
478
479
### Using SystemPromptPreset
480
481
```python
482
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
483
484
# Agent using preset with custom addition
485
agent = AgentDefinition(
486
description="Enhanced Claude Code agent",
487
prompt={
488
"type": "preset",
489
"preset": "claude_code",
490
"append": """
491
Additionally:
492
- Always explain your reasoning
493
- Ask clarifying questions when needed
494
- Suggest improvements proactively
495
"""
496
},
497
tools=None,
498
model="inherit"
499
)
500
501
options = ClaudeAgentOptions(
502
agents={"enhanced": agent}
503
)
504
505
async for msg in query(prompt="Help with this project", options=options):
506
print(msg)
507
```
508
509
### Agent with Setting Sources
510
511
```python
512
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
513
514
# Load only project and local settings, not user settings
515
options = ClaudeAgentOptions(
516
setting_sources=["project", "local"], # Skip user settings
517
agents={
518
"team_agent": AgentDefinition(
519
description="Team-configured agent",
520
prompt="Follow team conventions and project standards",
521
tools=["Read", "Write"],
522
model="sonnet"
523
)
524
}
525
)
526
527
async for msg in query(prompt="Work on this project", options=options):
528
print(msg)
529
```
530
531
### Domain-Specific Agents
532
533
```python
534
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
535
536
# Database expert
537
db_agent = AgentDefinition(
538
description="Database expert",
539
prompt="""You are a database expert specializing in SQL and optimization.
540
- Design efficient schemas
541
- Write optimized queries
542
- Review indexes and performance
543
- Suggest migrations""",
544
tools=["Read", "Write"],
545
model="opus"
546
)
547
548
# API designer
549
api_agent = AgentDefinition(
550
description="API design expert",
551
prompt="""You are an API design expert. Design RESTful APIs:
552
- Clear endpoint structure
553
- Proper HTTP methods
554
- Consistent naming
555
- Good error handling
556
- OpenAPI documentation""",
557
tools=["Read", "Write"],
558
model="sonnet"
559
)
560
561
# Frontend specialist
562
frontend_agent = AgentDefinition(
563
description="Frontend expert",
564
prompt="""You are a frontend expert. Build great UIs:
565
- Accessible components
566
- Responsive design
567
- Modern CSS/frameworks
568
- Performance optimization
569
- Cross-browser compatibility""",
570
tools=["Read", "Write", "Bash"],
571
model="sonnet"
572
)
573
574
options = ClaudeAgentOptions(
575
agents={
576
"database": db_agent,
577
"api": api_agent,
578
"frontend": frontend_agent
579
}
580
)
581
582
async for msg in query(
583
prompt="Design database, API, and frontend for user management",
584
options=options
585
):
586
print(msg)
587
```
588
589
### Agent Switching Based on Context
590
591
```python
592
from claude_agent_sdk import ClaudeAgentOptions, AgentDefinition, query
593
594
# Define agents for different phases
595
agents = {
596
"planner": AgentDefinition(
597
description="High-level planner",
598
prompt="Create detailed plans. Don't implement, just plan.",
599
tools=["Read"],
600
model="opus"
601
),
602
"executor": AgentDefinition(
603
description="Implementation executor",
604
prompt="Implement according to plan. Focus on correct implementation.",
605
tools=["Read", "Write", "Bash"],
606
model="sonnet"
607
)
608
}
609
610
options = ClaudeAgentOptions(agents=agents)
611
612
# Phase 1: Planning
613
async for msg in query(prompt="Plan the implementation", options=options):
614
print(msg)
615
616
# Phase 2: Execution
617
async for msg in query(prompt="Execute the plan", options=options):
618
print(msg)
619
```
620