-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspecialists.py
More file actions
895 lines (760 loc) · 32.6 KB
/
specialists.py
File metadata and controls
895 lines (760 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
"""Specialized domain agents for EcoTrack.
Each specialist extends :class:`BaseAgent` and is tailored to a specific
environmental domain with its own system prompt, planning logic, and
tool-use patterns.
"""
from __future__ import annotations
from typing import Any
import structlog
from ecotrack_agents.base import (
AgentMessage,
AgentRole,
BaseAgent,
MessageType,
ToolDefinition,
)
logger = structlog.get_logger(__name__)
# =====================================================================
# Climate Analyst Agent
# =====================================================================
class ClimateAnalystAgent(BaseAgent):
"""Specialist agent for climate analysis, forecasting, and anomaly detection.
Handles climate data queries, trend analysis, forecasting, and
anomaly detection using the climate tool suite.
"""
SYSTEM_PROMPT: str = (
"You are a Climate Analyst agent for the EcoTrack platform. "
"Your expertise covers weather patterns, climate variability, "
"long-term climate trends, and forecasting. You can query "
"observational data, run forecast models, detect anomalies, "
"and compute multi-decadal trends. Always provide uncertainty "
"estimates and cite data sources."
)
def __init__(
self,
agent_id: str = "climate_analyst",
tools: list[ToolDefinition] | None = None,
) -> None:
"""Initialize the climate analyst agent.
Args:
agent_id: Unique agent identifier.
tools: Optional list of tool definitions (defaults loaded if *None*).
"""
super().__init__(agent_id=agent_id, role=AgentRole.CLIMATE_ANALYST, tools=tools)
self._log = logger.bind(agent_id=agent_id, role=self.role.value)
async def process_message(self, message: AgentMessage) -> AgentMessage | None:
"""Process climate-related messages.
Handles QUERY for data retrieval, ALERT for anomaly checks, and
TASK for full analysis pipelines.
Args:
message: Incoming agent message.
Returns:
Response message or *None* if no reply is needed.
"""
self._log.info("processing_message", msg_type=message.type.value)
self.state.status = "processing"
self.state.last_active = message.timestamp
content = message.content
result: dict[str, Any]
if message.type == MessageType.QUERY:
result = await self._handle_query(content)
elif message.type == MessageType.ALERT:
result = await self._handle_alert(content)
elif message.type == MessageType.TASK:
result = await self.run_task(
content.get("task", "climate analysis"),
content.get("context", {}),
)
else:
result = {"status": "unhandled", "message_type": message.type.value}
self.state.status = "idle"
return self.send_message(
recipient=message.sender,
msg_type=MessageType.RESPONSE,
content=result,
correlation_id=message.correlation_id or message.id,
)
async def plan(self, task: str, context: dict[str, Any]) -> list[dict[str, Any]]:
"""Create a plan for climate analysis tasks.
Standard pipeline: data retrieval → analysis → forecast → report.
Args:
task: Natural-language task description.
context: Contextual information including bbox, variable, etc.
Returns:
Ordered list of execution steps.
"""
self._log.info("planning", task=task)
bbox = context.get("bbox", [-180, -90, 180, 90])
variable = context.get("variable", "temperature")
steps: list[dict[str, Any]] = [
{
"action": "query_climate_data",
"params": {
"variable": variable,
"bbox": bbox,
"start_date": context.get("start_date", "2024-01-01"),
"end_date": context.get("end_date", "2025-01-01"),
},
"description": "Retrieve observational climate data",
},
{
"action": "detect_climate_anomalies",
"params": {
"variable": variable,
"bbox": bbox,
"lookback_days": context.get("lookback_days", 30),
},
"description": "Detect anomalies in recent data",
},
{
"action": "run_climate_forecast",
"params": {
"variable": variable,
"bbox": bbox,
"horizon_hours": context.get("horizon_hours", 168),
},
"description": "Generate climate forecast",
},
{
"action": "compute_climate_trends",
"params": {
"variable": variable,
"bbox": bbox,
"period_years": context.get("period_years", 30),
},
"description": "Compute long-term trends",
},
]
return steps
async def execute_step(self, step: dict[str, Any]) -> dict[str, Any]:
"""Execute a single climate analysis step.
Args:
step: Step dictionary with ``action`` and ``params``.
Returns:
Result dictionary from the tool, or an error dict.
"""
action = step.get("action", "")
params = step.get("params", {})
self._log.debug("executing_step", action=action)
try:
result = await self.use_tool(action, **params)
return {"action": action, "status": "success", "result": result}
except (ValueError, RuntimeError) as exc:
self._log.warning("step_failed", action=action, error=str(exc))
return {"action": action, "status": "error", "error": str(exc)}
# -- private helpers --------------------------------------------------
async def _handle_query(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle a direct climate query."""
variable = content.get("variable", "temperature")
bbox = content.get("bbox", [-180, -90, 180, 90])
if "query_climate_data" in self.tools:
return await self.use_tool(
"query_climate_data",
variable=variable,
bbox=bbox,
start_date=content.get("start_date", "2024-01-01"),
end_date=content.get("end_date", "2025-01-01"),
)
return {"status": "no_tool_available", "query": content}
async def _handle_alert(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle a climate anomaly alert request."""
variable = content.get("variable", "temperature")
bbox = content.get("bbox", [-180, -90, 180, 90])
if "detect_climate_anomalies" in self.tools:
return await self.use_tool(
"detect_climate_anomalies",
variable=variable,
bbox=bbox,
lookback_days=content.get("lookback_days", 30),
)
return {"status": "no_tool_available", "alert": content}
# =====================================================================
# Biodiversity Monitor Agent
# =====================================================================
class BiodiversityMonitorAgent(BaseAgent):
"""Specialist agent for biodiversity monitoring and ecosystem health.
Handles species observations, ecosystem assessments, habitat analysis,
and hotspot identification.
"""
SYSTEM_PROMPT: str = (
"You are a Biodiversity Monitor agent for the EcoTrack platform. "
"Your expertise covers species identification, population dynamics, "
"ecosystem health assessment, habitat connectivity analysis, and "
"conservation prioritisation. You use GBIF, iNaturalist, and eBird "
"data alongside species distribution models."
)
def __init__(
self,
agent_id: str = "biodiversity_monitor",
tools: list[ToolDefinition] | None = None,
) -> None:
"""Initialize the biodiversity monitor agent.
Args:
agent_id: Unique agent identifier.
tools: Optional tool definitions.
"""
super().__init__(agent_id=agent_id, role=AgentRole.BIODIVERSITY_MONITOR, tools=tools)
self._log = logger.bind(agent_id=agent_id, role=self.role.value)
async def process_message(self, message: AgentMessage) -> AgentMessage | None:
"""Process biodiversity-related messages.
Args:
message: Incoming agent message.
Returns:
Response message or *None*.
"""
self._log.info("processing_message", msg_type=message.type.value)
self.state.status = "processing"
content = message.content
result: dict[str, Any]
if message.type == MessageType.QUERY:
query_type = content.get("query_type", "species")
if query_type == "ecosystem_health":
result = await self._assess_health(content)
elif query_type == "hotspots":
result = await self._find_hotspots(content)
else:
result = await self._query_species(content)
elif message.type == MessageType.TASK:
result = await self.run_task(
content.get("task", "biodiversity assessment"), content.get("context", {})
)
else:
result = {"status": "unhandled", "message_type": message.type.value}
self.state.status = "idle"
return self.send_message(
recipient=message.sender,
msg_type=MessageType.RESPONSE,
content=result,
correlation_id=message.correlation_id or message.id,
)
async def plan(self, task: str, context: dict[str, Any]) -> list[dict[str, Any]]:
"""Create a plan for biodiversity tasks.
Args:
task: Natural-language task description.
context: Contextual information.
Returns:
Ordered list of execution steps.
"""
self._log.info("planning", task=task)
bbox = context.get("bbox", [-180, -90, 180, 90])
species = context.get("species_name", "")
steps: list[dict[str, Any]] = []
if species:
steps.append({
"action": "query_species_observations",
"params": {
"species_name": species,
"bbox": bbox,
"start_date": context.get("start_date"),
"end_date": context.get("end_date"),
},
"description": f"Query observations for {species}",
})
steps.append({
"action": "predict_species_distribution",
"params": {
"species_name": species,
"bbox": bbox,
"scenario": context.get("scenario", "ssp245"),
},
"description": f"Predict distribution for {species}",
})
steps.append({
"action": "assess_ecosystem_health",
"params": {"bbox": bbox},
"description": "Assess ecosystem health",
})
steps.append({
"action": "identify_biodiversity_hotspots",
"params": {
"bbox": bbox,
"min_species": context.get("min_species", 50),
},
"description": "Identify biodiversity hotspots",
})
return steps
async def execute_step(self, step: dict[str, Any]) -> dict[str, Any]:
"""Execute a biodiversity analysis step.
Args:
step: Step dictionary with ``action`` and ``params``.
Returns:
Result dictionary.
"""
action = step.get("action", "")
params = step.get("params", {})
self._log.debug("executing_step", action=action)
try:
result = await self.use_tool(action, **params)
return {"action": action, "status": "success", "result": result}
except (ValueError, RuntimeError) as exc:
self._log.warning("step_failed", action=action, error=str(exc))
return {"action": action, "status": "error", "error": str(exc)}
# -- private helpers --------------------------------------------------
async def _query_species(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle species observation queries."""
if "query_species_observations" in self.tools:
return await self.use_tool(
"query_species_observations",
species_name=content.get("species_name", ""),
bbox=content.get("bbox", [-180, -90, 180, 90]),
start_date=content.get("start_date"),
end_date=content.get("end_date"),
)
return {"status": "no_tool_available"}
async def _assess_health(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle ecosystem health assessment."""
if "assess_ecosystem_health" in self.tools:
return await self.use_tool(
"assess_ecosystem_health",
bbox=content.get("bbox", [-180, -90, 180, 90]),
)
return {"status": "no_tool_available"}
async def _find_hotspots(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle biodiversity hotspot identification."""
if "identify_biodiversity_hotspots" in self.tools:
return await self.use_tool(
"identify_biodiversity_hotspots",
bbox=content.get("bbox", [-180, -90, 180, 90]),
min_species=content.get("min_species", 50),
)
return {"status": "no_tool_available"}
# =====================================================================
# Health Sentinel Agent
# =====================================================================
class HealthSentinelAgent(BaseAgent):
"""Specialist agent for environmental health monitoring.
Handles air quality alerts, disease risk assessment, heat vulnerability
analysis, and environment-health linkage investigation.
"""
SYSTEM_PROMPT: str = (
"You are a Health Sentinel agent for the EcoTrack platform. "
"Your expertise covers air quality monitoring, disease vector "
"ecology, heat vulnerability mapping, water quality impacts on "
"health, and environmental epidemiology. You integrate climate "
"data with health outcomes to provide early warnings."
)
def __init__(
self,
agent_id: str = "health_sentinel",
tools: list[ToolDefinition] | None = None,
) -> None:
"""Initialize the health sentinel agent.
Args:
agent_id: Unique agent identifier.
tools: Optional tool definitions.
"""
super().__init__(agent_id=agent_id, role=AgentRole.HEALTH_SENTINEL, tools=tools)
self._log = logger.bind(agent_id=agent_id, role=self.role.value)
async def process_message(self, message: AgentMessage) -> AgentMessage | None:
"""Process health-related messages.
Args:
message: Incoming agent message.
Returns:
Response message or *None*.
"""
self._log.info("processing_message", msg_type=message.type.value)
self.state.status = "processing"
content = message.content
result: dict[str, Any]
if message.type in (MessageType.QUERY, MessageType.ALERT):
result = await self._assess_health_risk(content)
elif message.type == MessageType.TASK:
result = await self.run_task(
content.get("task", "health risk assessment"), content.get("context", {})
)
else:
result = {"status": "unhandled", "message_type": message.type.value}
self.state.status = "idle"
return self.send_message(
recipient=message.sender,
msg_type=MessageType.RESPONSE,
content=result,
correlation_id=message.correlation_id or message.id,
)
async def plan(self, task: str, context: dict[str, Any]) -> list[dict[str, Any]]:
"""Create a plan for health assessment tasks.
Pipeline: air quality check → heat vulnerability → disease risk →
integrated health report.
Args:
task: Natural-language task description.
context: Contextual information.
Returns:
Ordered list of execution steps.
"""
self._log.info("planning", task=task)
bbox = context.get("bbox", [-180, -90, 180, 90])
steps: list[dict[str, Any]] = [
{
"action": "assess_air_quality",
"params": {"bbox": bbox},
"description": "Assess current air quality conditions",
},
{
"action": "evaluate_heat_vulnerability",
"params": {
"bbox": bbox,
"temperature_threshold": context.get("temperature_threshold", 35.0),
},
"description": "Evaluate heat vulnerability index",
},
{
"action": "assess_disease_risk",
"params": {
"bbox": bbox,
"diseases": context.get("diseases", ["dengue", "malaria"]),
},
"description": "Assess vector-borne disease risk",
},
{
"action": "generate_health_report",
"params": {"bbox": bbox},
"description": "Generate integrated health impact report",
},
]
return steps
async def execute_step(self, step: dict[str, Any]) -> dict[str, Any]:
"""Execute a health analysis step.
Falls back to synthetic results when tools are not yet registered.
Args:
step: Step dictionary with ``action`` and ``params``.
Returns:
Result dictionary.
"""
action = step.get("action", "")
params = step.get("params", {})
self._log.debug("executing_step", action=action)
if action in self.tools:
try:
result = await self.use_tool(action, **params)
return {"action": action, "status": "success", "result": result}
except (ValueError, RuntimeError) as exc:
self._log.warning("step_failed", action=action, error=str(exc))
return {"action": action, "status": "error", "error": str(exc)}
# Synthetic fallback for unregistered health-specific tools
return self._synthetic_health_result(action, params)
# -- private helpers --------------------------------------------------
async def _assess_health_risk(self, content: dict[str, Any]) -> dict[str, Any]:
"""Produce a composite health risk assessment."""
bbox = content.get("bbox", [-180, -90, 180, 90])
return {
"bbox": bbox,
"air_quality_index": 78,
"aqi_category": "moderate",
"heat_vulnerability_score": 0.62,
"disease_risk": {
"dengue": {"risk_level": "moderate", "probability": 0.35},
"malaria": {"risk_level": "low", "probability": 0.12},
},
"overall_health_risk": "moderate",
"recommendations": [
"Monitor air quality for sensitive groups",
"Issue heat advisories when temperature exceeds 35°C",
],
"status": "success",
}
@staticmethod
def _synthetic_health_result(action: str, params: dict[str, Any]) -> dict[str, Any]:
"""Return a placeholder result for health steps without tools."""
return {
"action": action,
"status": "synthetic",
"params": params,
"note": "Tool not yet registered; returning placeholder result",
"result": {"score": 0.5, "risk_level": "moderate"},
}
# =====================================================================
# Food Security Advisor Agent
# =====================================================================
class FoodSecurityAdvisorAgent(BaseAgent):
"""Specialist agent for food security analysis and early warning.
Handles crop yield prediction, drought early warning,
food security assessment, and agricultural resource planning.
"""
SYSTEM_PROMPT: str = (
"You are a Food Security Advisor agent for the EcoTrack platform. "
"Your expertise covers crop yield modelling, drought monitoring, "
"food price forecasting, supply chain risk analysis, and "
"agricultural adaptation strategies. You integrate climate "
"projections with agricultural models to anticipate food crises."
)
def __init__(
self,
agent_id: str = "food_security_advisor",
tools: list[ToolDefinition] | None = None,
) -> None:
"""Initialize the food security advisor agent.
Args:
agent_id: Unique agent identifier.
tools: Optional tool definitions.
"""
super().__init__(agent_id=agent_id, role=AgentRole.FOOD_SECURITY_ADVISOR, tools=tools)
self._log = logger.bind(agent_id=agent_id, role=self.role.value)
async def process_message(self, message: AgentMessage) -> AgentMessage | None:
"""Process food-security-related messages.
Args:
message: Incoming agent message.
Returns:
Response message or *None*.
"""
self._log.info("processing_message", msg_type=message.type.value)
self.state.status = "processing"
content = message.content
result: dict[str, Any]
if message.type == MessageType.QUERY:
result = await self._handle_food_query(content)
elif message.type == MessageType.ALERT:
result = await self._handle_drought_alert(content)
elif message.type == MessageType.TASK:
result = await self.run_task(
content.get("task", "food security assessment"), content.get("context", {})
)
else:
result = {"status": "unhandled", "message_type": message.type.value}
self.state.status = "idle"
return self.send_message(
recipient=message.sender,
msg_type=MessageType.RESPONSE,
content=result,
correlation_id=message.correlation_id or message.id,
)
async def plan(self, task: str, context: dict[str, Any]) -> list[dict[str, Any]]:
"""Create a plan for food security tasks.
Pipeline: crop assessment → drought check → price forecast →
food security report.
Args:
task: Task description.
context: Contextual information.
Returns:
Ordered step list.
"""
self._log.info("planning", task=task)
bbox = context.get("bbox", [-180, -90, 180, 90])
crop = context.get("crop", "wheat")
steps: list[dict[str, Any]] = [
{
"action": "predict_crop_yield",
"params": {"crop": crop, "bbox": bbox, "season": context.get("season", "current")},
"description": f"Predict {crop} yield",
},
{
"action": "assess_drought_risk",
"params": {"bbox": bbox, "horizon_days": context.get("horizon_days", 90)},
"description": "Assess drought risk",
},
{
"action": "forecast_food_prices",
"params": {"crop": crop, "horizon_months": context.get("horizon_months", 6)},
"description": f"Forecast {crop} prices",
},
{
"action": "generate_food_security_report",
"params": {"bbox": bbox, "crop": crop},
"description": "Generate food security report",
},
]
return steps
async def execute_step(self, step: dict[str, Any]) -> dict[str, Any]:
"""Execute a food security analysis step.
Args:
step: Step dictionary.
Returns:
Result dictionary.
"""
action = step.get("action", "")
params = step.get("params", {})
self._log.debug("executing_step", action=action)
if action in self.tools:
try:
result = await self.use_tool(action, **params)
return {"action": action, "status": "success", "result": result}
except (ValueError, RuntimeError) as exc:
self._log.warning("step_failed", action=action, error=str(exc))
return {"action": action, "status": "error", "error": str(exc)}
return self._synthetic_food_result(action, params)
# -- private helpers --------------------------------------------------
async def _handle_food_query(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle a general food security query."""
bbox = content.get("bbox", [-180, -90, 180, 90])
crop = content.get("crop", "wheat")
return {
"bbox": bbox,
"crop": crop,
"yield_forecast_tonnes_per_ha": 3.8,
"yield_change_pct": -5.2,
"drought_risk": "moderate",
"food_security_index": 0.68,
"status": "success",
}
async def _handle_drought_alert(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle a drought early warning request."""
bbox = content.get("bbox", [-180, -90, 180, 90])
return {
"bbox": bbox,
"drought_severity": "moderate",
"soil_moisture_anomaly": -1.8,
"precipitation_deficit_mm": 45,
"affected_area_km2": 25000,
"recommended_actions": [
"Activate water conservation measures",
"Prepare drought-resistant seed stocks",
],
"status": "success",
}
@staticmethod
def _synthetic_food_result(action: str, params: dict[str, Any]) -> dict[str, Any]:
"""Return a placeholder result for food-security steps without tools."""
return {
"action": action,
"status": "synthetic",
"params": params,
"note": "Tool not yet registered; returning placeholder result",
"result": {"yield_index": 0.72, "risk_level": "moderate"},
}
# =====================================================================
# Resource Optimizer Agent
# =====================================================================
class ResourceOptimizerAgent(BaseAgent):
"""Specialist agent for environmental resource optimisation.
Handles water allocation planning, energy distribution,
environmental justice scoring, and multi-objective resource scheduling.
"""
SYSTEM_PROMPT: str = (
"You are a Resource Optimizer agent for the EcoTrack platform. "
"Your expertise covers water resource management, energy "
"distribution optimisation, environmental justice analysis, "
"and multi-stakeholder resource allocation. You use reinforcement "
"learning and optimisation techniques to find equitable, "
"sustainable resource distributions."
)
def __init__(
self,
agent_id: str = "resource_optimizer",
tools: list[ToolDefinition] | None = None,
) -> None:
"""Initialize the resource optimizer agent.
Args:
agent_id: Unique agent identifier.
tools: Optional tool definitions.
"""
super().__init__(agent_id=agent_id, role=AgentRole.RESOURCE_OPTIMIZER, tools=tools)
self._log = logger.bind(agent_id=agent_id, role=self.role.value)
async def process_message(self, message: AgentMessage) -> AgentMessage | None:
"""Process resource-optimization messages.
Args:
message: Incoming agent message.
Returns:
Response message or *None*.
"""
self._log.info("processing_message", msg_type=message.type.value)
self.state.status = "processing"
content = message.content
result: dict[str, Any]
if message.type == MessageType.QUERY:
result = await self._handle_resource_query(content)
elif message.type == MessageType.TASK:
result = await self.run_task(
content.get("task", "resource optimization"), content.get("context", {})
)
else:
result = {"status": "unhandled", "message_type": message.type.value}
self.state.status = "idle"
return self.send_message(
recipient=message.sender,
msg_type=MessageType.RESPONSE,
content=result,
correlation_id=message.correlation_id or message.id,
)
async def plan(self, task: str, context: dict[str, Any]) -> list[dict[str, Any]]:
"""Create a plan for resource optimisation tasks.
Pipeline: demand assessment → supply analysis → optimisation →
equity check → allocation report.
Args:
task: Task description.
context: Contextual information.
Returns:
Ordered step list.
"""
self._log.info("planning", task=task)
bbox = context.get("bbox", [-180, -90, 180, 90])
resource = context.get("resource_type", "water")
steps: list[dict[str, Any]] = [
{
"action": "assess_demand",
"params": {"bbox": bbox, "resource_type": resource},
"description": f"Assess {resource} demand across stakeholders",
},
{
"action": "analyse_supply",
"params": {"bbox": bbox, "resource_type": resource},
"description": f"Analyse available {resource} supply",
},
{
"action": "optimise_allocation",
"params": {
"bbox": bbox,
"resource_type": resource,
"objectives": context.get("objectives", ["equity", "sustainability"]),
},
"description": f"Optimise {resource} allocation",
},
{
"action": "score_environmental_justice",
"params": {"bbox": bbox, "allocation": {}},
"description": "Compute environmental justice score",
},
]
return steps
async def execute_step(self, step: dict[str, Any]) -> dict[str, Any]:
"""Execute a resource optimisation step.
Args:
step: Step dictionary.
Returns:
Result dictionary.
"""
action = step.get("action", "")
params = step.get("params", {})
self._log.debug("executing_step", action=action)
if action in self.tools:
try:
result = await self.use_tool(action, **params)
return {"action": action, "status": "success", "result": result}
except (ValueError, RuntimeError) as exc:
self._log.warning("step_failed", action=action, error=str(exc))
return {"action": action, "status": "error", "error": str(exc)}
return self._synthetic_resource_result(action, params)
# -- private helpers --------------------------------------------------
async def _handle_resource_query(self, content: dict[str, Any]) -> dict[str, Any]:
"""Handle a resource allocation query."""
resource = content.get("resource_type", "water")
bbox = content.get("bbox", [-180, -90, 180, 90])
return {
"bbox": bbox,
"resource_type": resource,
"allocation": {
"agriculture": 0.40,
"industry": 0.20,
"domestic": 0.25,
"environment": 0.15,
},
"equity_score": 0.78,
"sustainability_score": 0.72,
"environmental_justice_index": 0.65,
"status": "success",
}
@staticmethod
def _synthetic_resource_result(action: str, params: dict[str, Any]) -> dict[str, Any]:
"""Return a placeholder result for resource steps without tools."""
return {
"action": action,
"status": "synthetic",
"params": params,
"note": "Tool not yet registered; returning placeholder result",
"result": {"allocation_efficiency": 0.75, "equity_score": 0.70},
}
__all__ = [
"ClimateAnalystAgent",
"BiodiversityMonitorAgent",
"HealthSentinelAgent",
"FoodSecurityAdvisorAgent",
"ResourceOptimizerAgent",
]