0
# Advanced Features
1
2
Planning, evaluation, event system, and plugin framework for sophisticated agent behaviors and custom extensions.
3
4
## Capabilities
5
6
### Planning System
7
8
Classes for implementing planning and reasoning strategies in agents.
9
10
```python { .api }
11
class BasePlanner:
12
"""Base class for planners."""
13
14
def __init__(self, **kwargs):
15
"""
16
Initialize base planner.
17
18
Args:
19
**kwargs: Planner configuration parameters
20
"""
21
pass
22
23
def create_plan(
24
self,
25
goal: str,
26
context: dict = None,
27
constraints: list = None,
28
**kwargs
29
) -> dict:
30
"""
31
Create a plan to achieve the given goal.
32
33
Args:
34
goal (str): Goal to achieve
35
context (dict, optional): Planning context
36
constraints (list, optional): Planning constraints
37
**kwargs: Additional planning parameters
38
39
Returns:
40
dict: Plan with steps and metadata
41
"""
42
pass
43
44
def execute_plan(self, plan: dict, **kwargs) -> dict:
45
"""
46
Execute a generated plan.
47
48
Args:
49
plan (dict): Plan to execute
50
**kwargs: Additional execution parameters
51
52
Returns:
53
dict: Execution results
54
"""
55
pass
56
57
def adapt_plan(self, plan: dict, feedback: dict, **kwargs) -> dict:
58
"""
59
Adapt plan based on feedback.
60
61
Args:
62
plan (dict): Original plan
63
feedback (dict): Execution feedback
64
**kwargs: Additional adaptation parameters
65
66
Returns:
67
dict: Adapted plan
68
"""
69
pass
70
71
class BuiltInPlanner(BasePlanner):
72
"""Built-in planner implementation."""
73
74
def __init__(
75
self,
76
max_steps: int = 10,
77
planning_model: str = None,
78
**kwargs
79
):
80
"""
81
Initialize built-in planner.
82
83
Args:
84
max_steps (int): Maximum planning steps
85
planning_model (str, optional): Model for planning
86
**kwargs: Additional configuration parameters
87
"""
88
pass
89
90
class PlanReActPlanner(BasePlanner):
91
"""Plan-ReAct planner implementation."""
92
93
def __init__(
94
self,
95
reasoning_model: str = None,
96
action_model: str = None,
97
**kwargs
98
):
99
"""
100
Initialize Plan-ReAct planner.
101
102
Args:
103
reasoning_model (str, optional): Model for reasoning
104
action_model (str, optional): Model for actions
105
**kwargs: Additional configuration parameters
106
"""
107
pass
108
```
109
110
### Evaluation Framework
111
112
Classes for evaluating agent performance and behavior.
113
114
```python { .api }
115
class AgentEvaluator:
116
"""Agent evaluation framework (optional dependency)."""
117
118
def __init__(
119
self,
120
evaluation_metrics: list = None,
121
benchmark_datasets: list = None,
122
**kwargs
123
):
124
"""
125
Initialize agent evaluator.
126
127
Args:
128
evaluation_metrics (list, optional): Metrics to evaluate
129
benchmark_datasets (list, optional): Datasets for benchmarking
130
**kwargs: Additional configuration parameters
131
"""
132
pass
133
134
def evaluate_agent(
135
self,
136
agent,
137
test_cases: list,
138
metrics: list = None,
139
**kwargs
140
) -> dict:
141
"""
142
Evaluate agent performance on test cases.
143
144
Args:
145
agent: Agent to evaluate
146
test_cases (list): Test cases for evaluation
147
metrics (list, optional): Specific metrics to compute
148
**kwargs: Additional evaluation parameters
149
150
Returns:
151
dict: Evaluation results with scores and analysis
152
"""
153
pass
154
155
def compare_agents(
156
self,
157
agents: list,
158
test_cases: list,
159
**kwargs
160
) -> dict:
161
"""
162
Compare multiple agents on same test cases.
163
164
Args:
165
agents (list): Agents to compare
166
test_cases (list): Test cases for comparison
167
**kwargs: Additional comparison parameters
168
169
Returns:
170
dict: Comparison results and rankings
171
"""
172
pass
173
174
def generate_report(self, evaluation_results: dict, **kwargs) -> str:
175
"""
176
Generate evaluation report.
177
178
Args:
179
evaluation_results (dict): Results from evaluation
180
**kwargs: Additional report parameters
181
182
Returns:
183
str: Formatted evaluation report
184
"""
185
pass
186
```
187
188
### Event System
189
190
Classes for handling events and communication between agents.
191
192
```python { .api }
193
class Event:
194
"""Event object for agent communication."""
195
196
def __init__(
197
self,
198
event_type: str,
199
source: str,
200
target: str = None,
201
data: dict = None,
202
timestamp: float = None,
203
**kwargs
204
):
205
"""
206
Initialize event.
207
208
Args:
209
event_type (str): Type of event
210
source (str): Event source identifier
211
target (str, optional): Event target identifier
212
data (dict, optional): Event data payload
213
timestamp (float, optional): Event timestamp
214
**kwargs: Additional event parameters
215
"""
216
pass
217
218
def get_data(self) -> dict:
219
"""
220
Get event data.
221
222
Returns:
223
dict: Event data payload
224
"""
225
pass
226
227
def set_data(self, data: dict):
228
"""
229
Set event data.
230
231
Args:
232
data (dict): Event data to set
233
"""
234
pass
235
236
def to_dict(self) -> dict:
237
"""
238
Convert event to dictionary.
239
240
Returns:
241
dict: Event as dictionary
242
"""
243
pass
244
245
class EventActions:
246
"""Actions associated with events."""
247
248
AGENT_START = "agent_start"
249
AGENT_FINISH = "agent_finish"
250
TOOL_CALL = "tool_call"
251
TOOL_RESULT = "tool_result"
252
ERROR = "error"
253
MESSAGE = "message"
254
TRANSFER = "transfer"
255
256
@classmethod
257
def get_all_actions(cls) -> list:
258
"""
259
Get all available event actions.
260
261
Returns:
262
list: List of event action types
263
"""
264
pass
265
```
266
267
### Plugin System
268
269
Classes for creating and managing plugins to extend ADK functionality.
270
271
```python { .api }
272
class BasePlugin:
273
"""Base class for plugins."""
274
275
def __init__(
276
self,
277
name: str,
278
version: str = "1.0.0",
279
description: str = None,
280
**kwargs
281
):
282
"""
283
Initialize base plugin.
284
285
Args:
286
name (str): Plugin name
287
version (str): Plugin version
288
description (str, optional): Plugin description
289
**kwargs: Additional plugin parameters
290
"""
291
pass
292
293
def initialize(self, context: dict = None):
294
"""
295
Initialize the plugin.
296
297
Args:
298
context (dict, optional): Initialization context
299
"""
300
pass
301
302
def activate(self):
303
"""Activate the plugin."""
304
pass
305
306
def deactivate(self):
307
"""Deactivate the plugin."""
308
pass
309
310
def get_capabilities(self) -> list:
311
"""
312
Get plugin capabilities.
313
314
Returns:
315
list: List of plugin capabilities
316
"""
317
pass
318
319
def handle_event(self, event: Event) -> dict:
320
"""
321
Handle an event.
322
323
Args:
324
event (Event): Event to handle
325
326
Returns:
327
dict: Event handling result
328
"""
329
pass
330
```
331
332
### Example Providers
333
334
Classes for managing examples and demonstrations for agents.
335
336
```python { .api }
337
class BaseExampleProvider:
338
"""Base class for example providers."""
339
340
def __init__(self, **kwargs):
341
"""
342
Initialize base example provider.
343
344
Args:
345
**kwargs: Provider configuration parameters
346
"""
347
pass
348
349
def get_examples(
350
self,
351
task_type: str = None,
352
count: int = 5,
353
**kwargs
354
) -> list:
355
"""
356
Get examples for a task type.
357
358
Args:
359
task_type (str, optional): Type of task
360
count (int): Number of examples to retrieve
361
**kwargs: Additional retrieval parameters
362
363
Returns:
364
list: List of Example objects
365
"""
366
pass
367
368
def add_example(self, example: 'Example'):
369
"""
370
Add an example to the provider.
371
372
Args:
373
example (Example): Example to add
374
"""
375
pass
376
377
class Example:
378
"""Example object."""
379
380
def __init__(
381
self,
382
input_text: str,
383
output_text: str,
384
task_type: str = None,
385
metadata: dict = None,
386
**kwargs
387
):
388
"""
389
Initialize example.
390
391
Args:
392
input_text (str): Example input
393
output_text (str): Example output
394
task_type (str, optional): Type of task this example demonstrates
395
metadata (dict, optional): Additional example metadata
396
**kwargs: Additional example parameters
397
"""
398
pass
399
400
class VertexAiExampleStore(BaseExampleProvider):
401
"""Vertex AI example store (optional dependency)."""
402
403
def __init__(
404
self,
405
project_id: str,
406
location: str = "us-central1",
407
example_store_id: str = None,
408
**kwargs
409
):
410
"""
411
Initialize Vertex AI example store.
412
413
Args:
414
project_id (str): Google Cloud project ID
415
location (str): Vertex AI location
416
example_store_id (str, optional): Example store identifier
417
**kwargs: Additional configuration parameters
418
"""
419
pass
420
```
421
422
## Usage Examples
423
424
### Planning with Agents
425
426
```python
427
from google.adk.planners import BuiltInPlanner
428
from google.adk.agents import Agent
429
430
# Create planner
431
planner = BuiltInPlanner(
432
max_steps=8,
433
planning_model="gemini-2.0-flash"
434
)
435
436
# Create planning agent
437
planning_agent = Agent(
438
name="strategic_planner",
439
model="gemini-2.0-flash",
440
instruction="Create detailed plans to achieve complex goals",
441
planner=planner
442
)
443
444
# Use agent with planning
445
response = planning_agent.run(
446
"Create a plan to launch a new product in 6 months, "
447
"including market research, development, and marketing phases"
448
)
449
450
# Get the generated plan
451
plan = planner.create_plan(
452
goal="Launch new product in 6 months",
453
context={"budget": 100000, "team_size": 5},
454
constraints=["must complete market research first", "budget limit $100k"]
455
)
456
457
print(f"Plan steps: {len(plan['steps'])}")
458
for step in plan['steps']:
459
print(f"- {step['description']} (Duration: {step['duration']})")
460
```
461
462
### Agent Evaluation
463
464
```python
465
from google.adk.evaluation import AgentEvaluator
466
from google.adk.agents import Agent
467
468
# Create test agents
469
agent_a = Agent(name="agent_a", model="gemini-2.0-flash")
470
agent_b = Agent(name="agent_b", model="gemini-2.0-flash", temperature=0.3)
471
472
# Create evaluator
473
evaluator = AgentEvaluator(
474
evaluation_metrics=["accuracy", "relevance", "coherence"],
475
benchmark_datasets=["qa_dataset", "reasoning_dataset"]
476
)
477
478
# Define test cases
479
test_cases = [
480
{"input": "What is the capital of France?", "expected": "Paris"},
481
{"input": "Explain photosynthesis", "expected": "Process where plants..."},
482
{"input": "Solve: 2x + 5 = 15", "expected": "x = 5"}
483
]
484
485
# Evaluate single agent
486
results_a = evaluator.evaluate_agent(
487
agent=agent_a,
488
test_cases=test_cases,
489
metrics=["accuracy", "relevance"]
490
)
491
492
# Compare multiple agents
493
comparison = evaluator.compare_agents(
494
agents=[agent_a, agent_b],
495
test_cases=test_cases
496
)
497
498
# Generate report
499
report = evaluator.generate_report(comparison)
500
print(report)
501
```
502
503
### Event System Usage
504
505
```python
506
from google.adk.events import Event, EventActions
507
from google.adk.agents import Agent
508
509
# Create event handler
510
def handle_tool_call(event: Event):
511
print(f"Tool called: {event.get_data()['tool_name']}")
512
print(f"Parameters: {event.get_data()['parameters']}")
513
514
def handle_agent_finish(event: Event):
515
print(f"Agent finished: {event.source}")
516
print(f"Result: {event.get_data()['result']}")
517
518
# Create events
519
tool_event = Event(
520
event_type=EventActions.TOOL_CALL,
521
source="research_agent",
522
data={
523
"tool_name": "google_search",
524
"parameters": {"query": "AI advances 2024"}
525
}
526
)
527
528
finish_event = Event(
529
event_type=EventActions.AGENT_FINISH,
530
source="research_agent",
531
data={"result": "Research completed successfully"}
532
)
533
534
# Handle events
535
handle_tool_call(tool_event)
536
handle_agent_finish(finish_event)
537
```
538
539
### Custom Plugin Development
540
541
```python
542
from google.adk.plugins import BasePlugin
543
from google.adk.events import Event, EventActions
544
545
class LoggingPlugin(BasePlugin):
546
def __init__(self):
547
super().__init__(
548
name="logging_plugin",
549
version="1.0.0",
550
description="Plugin for logging agent activities"
551
)
552
self.log_file = "agent_activities.log"
553
554
def initialize(self, context=None):
555
print(f"Initializing {self.name}")
556
# Setup logging configuration
557
558
def activate(self):
559
print(f"Activating {self.name}")
560
561
def handle_event(self, event: Event) -> dict:
562
# Log different types of events
563
if event.event_type == EventActions.TOOL_CALL:
564
self._log_tool_call(event)
565
elif event.event_type == EventActions.AGENT_FINISH:
566
self._log_agent_finish(event)
567
568
return {"status": "logged"}
569
570
def _log_tool_call(self, event: Event):
571
with open(self.log_file, "a") as f:
572
f.write(f"TOOL_CALL: {event.source} -> {event.get_data()}\n")
573
574
def _log_agent_finish(self, event: Event):
575
with open(self.log_file, "a") as f:
576
f.write(f"AGENT_FINISH: {event.source} completed\n")
577
578
# Use plugin
579
logging_plugin = LoggingPlugin()
580
logging_plugin.initialize()
581
logging_plugin.activate()
582
583
# Plugin handles events automatically when integrated with agents
584
```
585
586
### Example Management
587
588
```python
589
from google.adk.examples import BaseExampleProvider, Example
590
591
class CustomExampleProvider(BaseExampleProvider):
592
def __init__(self):
593
super().__init__()
594
self.examples = []
595
596
def add_example(self, example: Example):
597
self.examples.append(example)
598
599
def get_examples(self, task_type=None, count=5, **kwargs):
600
if task_type:
601
filtered = [e for e in self.examples if e.task_type == task_type]
602
return filtered[:count]
603
return self.examples[:count]
604
605
# Create example provider
606
provider = CustomExampleProvider()
607
608
# Add examples
609
provider.add_example(Example(
610
input_text="What is machine learning?",
611
output_text="Machine learning is a subset of AI that enables computers to learn...",
612
task_type="explanation"
613
))
614
615
provider.add_example(Example(
616
input_text="Calculate 15% of 200",
617
output_text="15% of 200 is 30",
618
task_type="calculation"
619
))
620
621
# Use with agent
622
from google.adk.agents import Agent
623
624
agent = Agent(
625
name="learning_agent",
626
model="gemini-2.0-flash",
627
example_provider=provider
628
)
629
630
# Agent can use examples for few-shot learning
631
response = agent.run("What is deep learning?") # Uses explanation examples
632
```
633
634
### ReAct Planning
635
636
```python
637
from google.adk.planners import PlanReActPlanner
638
from google.adk.agents import Agent
639
from google.adk.tools import google_search
640
641
# Create ReAct planner
642
react_planner = PlanReActPlanner(
643
reasoning_model="gemini-2.0-flash",
644
action_model="gemini-2.0-flash"
645
)
646
647
# Create agent with ReAct planning
648
react_agent = Agent(
649
name="research_analyst",
650
model="gemini-2.0-flash",
651
instruction="Research topics systematically using reasoning and actions",
652
tools=[google_search],
653
planner=react_planner
654
)
655
656
# Agent uses Reason-Act-Observe cycles
657
response = react_agent.run(
658
"Research the latest developments in quantum computing and "
659
"analyze their potential impact on cybersecurity"
660
)
661
```
662
663
### Comprehensive Advanced Setup
664
665
```python
666
from google.adk.agents import Agent
667
from google.adk.planners import BuiltInPlanner
668
from google.adk.evaluation import AgentEvaluator
669
from google.adk.plugins import BasePlugin
670
from google.adk.examples import BaseExampleProvider
671
from google.adk.events import Event, EventActions
672
673
# Create advanced agent with all features
674
planner = BuiltInPlanner(max_steps=10)
675
evaluator = AgentEvaluator()
676
example_provider = CustomExampleProvider()
677
678
class AdvancedPlugin(BasePlugin):
679
def handle_event(self, event):
680
# Custom event handling logic
681
return {"handled": True}
682
683
plugin = AdvancedPlugin()
684
685
# Advanced agent configuration
686
advanced_agent = Agent(
687
name="advanced_assistant",
688
model="gemini-2.0-flash",
689
instruction="Advanced agent with planning, evaluation, and plugin support",
690
planner=planner,
691
example_provider=example_provider,
692
plugins=[plugin]
693
)
694
695
# The agent now has access to all advanced features
696
response = advanced_agent.run("Solve a complex multi-step problem")
697
```