-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.py
More file actions
1788 lines (1638 loc) · 76.9 KB
/
Copy pathmanager.py
File metadata and controls
1788 lines (1638 loc) · 76.9 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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import re
from typing import Dict, Any, List, Tuple, Optional
from agents import BaseAgent, DataQueryAgent, ModelExplanationAgent, DataPlottingAgent, GeneralQAAgent, ModellingSuggestionsAgent
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from pathlib import Path
from data_utils import (
_choice_prompt,
_infer_variable_intent,
_looks_like_comparison_request,
_looks_like_category_list_request,
_looks_like_data_request,
_looks_like_model_info_request,
_looks_like_plot_request,
_variable_matches_query_signal,
)
from canonical_aliases import canonical_scenario_from_query, preferred_variable_from_query
from link_router import format_relevant_links, suggest_links
from model_profiles import find_model_profile, format_model_profile_answer
from year_filters import extract_year_range
def _looks_like_site_navigation_request(query: str) -> bool:
q = str(query or "").strip().lower()
if not q:
return False
navigation_terms = (
"where can i find",
"where do i find",
"where is",
"open ",
"find ",
"link",
"url",
"page",
"website",
"application library",
"raw data application",
"data story",
"data stories",
"policy catalogue",
"policy catalog",
"database",
"explorer",
)
named_site_items = (
"aqueduct",
"climate watch",
"cdp open data portal",
"data portal",
"afolu transformation",
"buildings transformation",
"transportation transformation",
"transport transformation",
"industrial transformation",
)
data_story_items = (
"policy catalogue",
"policy catalog",
"recovery policy",
"circularity",
"decarbonisation data story",
"decarbonization data story",
"technology inventories",
"barriers and enablers",
"scenario metadata",
)
project_workspace_items = (
"iam compact",
"fit for 55",
"fit-for-55",
"renewable energy metrics",
"post glasgow",
"post-glasgow",
"steel relocation",
"cost of capital",
"behavioural change",
"behavioral change",
"technology constrained",
"tech constrained",
"ndc aspects",
"global impacts of ndcs",
"long term targets",
"long-term targets",
)
analysis_contact_items = (
"custom analysis",
"analysis service",
"analysis support",
"request analysis",
"contact iam paris",
"contact",
)
if any(term in q for term in navigation_terms) and any(term in q for term in named_site_items):
return True
# Generic navigation intent: a navigation verb/term paired with a site or
# documentation target. Targets are deliberately specific (no bare "results")
# so genuine data queries are not hijacked to general_qa.
nav_phrases = navigation_terms + (
"how do i access", "how can i access", "how do i open",
"give me the link", "send me the link", "take me to", "navigate to",
)
generic_site_targets = (
"documentation", "docs", "user guide", "scenario explorer",
"model documentation", "application library", "data portal",
"dashboard", "tutorial", "iam paris results", "paris results",
"results page", "scenario database",
)
if any(p in q for p in nav_phrases) and any(t in q for t in generic_site_targets):
return True
if any(term in q for term in data_story_items):
return True
if "global impacts of ndcs" in q:
return True
if any(term in q for term in project_workspace_items) and any(term in q for term in ("results", "workspace", "policy questions", "metrics", "pathways", "targets", "aspects", "policy")):
return True
if any(term in q for term in analysis_contact_items):
return True
if any(term in q for term in ("application library", "raw data application", "online model", "dashboard", "interactive map")):
return True
if all(term in q for term in ("agriculture", "forestry", "land")) and any(term in q for term in ("result", "results", "workspace", "transformation")):
return True
if "afolu" in q and any(term in q for term in ("transformation", "results", "workspace")):
return True
if "ndc" in q and any(term in q for term in ("transport", "transportation", "buildings", "building", "afolu")) and any(term in q for term in ("result", "results", "workspace")):
return True
if any(term in q for term in named_site_items) and any(term in q for term in ("result", "results", "workspace", "transformation")):
return True
return False
def _load_skill_guidance(max_chars: int = 2000) -> str:
skill_path = Path("skills/iam-timeseries-qa/SKILL.md")
if not skill_path.exists():
return ""
text = skill_path.read_text()
if text.lstrip().startswith("---"):
parts = text.split("---", 2)
if len(parts) == 3:
text = parts[2]
text = text.strip()
if len(text) > max_chars:
text = text[:max_chars].rstrip() + "\n\n[Skill guidance truncated]"
return text
from query_extractor import QueryEntityExtractor
VALID_AGENT_NAMES = {
"data_query",
"data_plotting",
"model_explanation",
"general_qa",
"modelling_suggestions",
}
class MultiAgentManager:
def __init__(self, shared_resources: Dict[str, Any], streaming: bool = True):
self.shared_resources = shared_resources
self.streaming = streaming
self.logger = logging.getLogger(self.__class__.__name__)
self.agents: Dict[str, BaseAgent] = {}
self._initialize_agents()
self.last_entities: Dict[str, Any] = {}
self.last_links: List[Dict[str, Any]] = []
self.last_route_decision: Dict[str, Any] = {}
self.turn_counter: int = 0
self.current_turn: int = 0
# Initialize Query Entity Extractor
self.entity_extractor = QueryEntityExtractor(
models=shared_resources.get("models", []),
ts_data=shared_resources.get("ts", []),
api_key=shared_resources["env"]["OPENAI_API_KEY"]
)
# LLM for intelligent query routing
self.router_llm = ChatOpenAI(
model_name="gpt-4-turbo",
temperature=0,
streaming=False,
timeout=30,
max_retries=1,
api_key=self.shared_resources["env"]["OPENAI_API_KEY"],
)
# Routing prompt
skill_guidance = _load_skill_guidance()
self.routing_prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(f"""You are a query classifier for an IAM PARIS climate data chatbot.
CLASSIFY into ONE category:
data_query - Questions about WHAT data exists:
- "which models" "what models" "list models" "how many models"
- "what scenarios" "list scenarios" "how many scenarios"
- "what variables" "list variables" "how many variables"
- "show me all data" "what regions" "which variables"
- Any question asking what models/scenarios/variables/regions are available
data_plotting - Requests to CREATE CHARTS:
- "plot" "graph" "chart" "visualize" data
- Any request to show trends over time
model_explanation - Questions EXPLAINING a MODEL:
- "what is GCAM" "explain REMIND" "how does model work"
- Specific model names with explain/what is
modelling_suggestions - Study suggestions:
- "suggest studies" "what to investigate" "research ideas"
general_qa - General climate questions:
- "climate change" "paris agreement" "policy"
- General knowledge questions
Respond with ONLY the category name, nothing else.
Skill guidance (for routing context):
{skill_guidance}
Question: {{query}}
Answer:"""),
HumanMessagePromptTemplate.from_template("Query: {query}")
])
def _looks_like_clarification_response(self, response: str) -> bool:
text = str(response or "")
markers = (
"Choose the variable:",
"Choose the region:",
"Choose the scenario:",
"Closest valid options:",
"Which variable should I use?",
"Which variable or region should I use instead?",
"Please provide the",
"I need one more detail",
"I don't have an active numbered choice",
"Reply with a number",
)
return any(marker.lower() in text.lower() for marker in markers)
def _append_relevant_links(
self,
response: str,
query: str,
entities: Optional[Dict[str, Any]],
agent_name: str,
) -> str:
if not response or "Relevant IAM PARIS links:" in response:
return response
is_clarification = self._looks_like_clarification_response(response)
catalog = self.shared_resources.get("link_catalog", [])
if not catalog:
self.last_links = []
return response
try:
variable_intent = _infer_variable_intent(query)
links = suggest_links(
query,
catalog,
agent_name=agent_name,
entities=entities or {},
variable_intent=variable_intent,
)
links = self._ensure_results_link_for_data_answer(links, catalog, agent_name)
except Exception as err:
self.logger.warning("Could not suggest IAM PARIS links: %s", err)
self.last_links = []
return response
self.last_links = links
formatted = format_relevant_links(links)
if not formatted or is_clarification:
return response
return f"{response.rstrip()}\n\n{formatted}"
def _grounded_site_navigation_answer(
self,
query: str,
entities: Optional[Dict[str, Any]],
) -> str:
catalog = self.shared_resources.get("link_catalog", [])
if not catalog:
self.last_links = []
return (
"I matched this as an IAM PARIS site/navigation request, but the link catalog is not loaded."
)
try:
links = suggest_links(
query,
catalog,
agent_name="general_qa",
entities=entities or {},
variable_intent=_infer_variable_intent(query),
)
except Exception as err:
self.logger.warning("Could not build grounded IAM PARIS link answer: %s", err)
self.last_links = []
return "I could not match this request to a reliable IAM PARIS link."
self.last_links = links
if not links:
return "I could not match this request to a reliable IAM PARIS link."
lines = ["Use these IAM PARIS links for this request:"]
formatted = format_relevant_links(links)
if formatted:
lines.extend(["", formatted])
search_hints = [
str(link.get("search_hint", "")).strip()
for link in links
if str(link.get("search_hint", "")).strip()
]
if search_hints:
lines.extend([
"",
"If the direct detail page is not available, open the Application Library and search for: "
+ ", ".join(dict.fromkeys(search_hints))
+ ".",
])
return "\n".join(lines)
def _ensure_results_link_for_data_answer(
self,
links: List[Dict[str, Any]],
catalog: List[Dict[str, Any]],
agent_name: str,
) -> List[Dict[str, Any]]:
if agent_name not in {"data_query", "data_plotting"}:
return links
link_text = " ".join(
" ".join(str(link.get(key) or "") for key in ("title", "url", "reason", "search_hint"))
for link in links
if isinstance(link, dict)
).lower()
if "results" in link_text or "/results" in link_text:
return links
fallback = next((item for item in catalog if item.get("url") == "https://iamparis.eu/results"), None)
if not fallback:
return links
result_link = {
"title": str(fallback.get("title", "IAM PARIS Results")),
"url": str(fallback.get("url", "https://iamparis.eu/results")),
"reason": "General IAM PARIS results page for data follow-ups.",
"confidence": 0.25,
"search_hint": str(fallback.get("search_hint", "")),
}
deduped = [
link for link in links
if str(link.get("url", "")) != result_link["url"]
]
if len(deduped) >= 3:
deduped = deduped[:2]
return [*deduped, result_link]
def _maybe_add_followup_guidance(self, response: str, query: str, agent_name: str) -> str:
text = str(response or "").strip()
if not text:
return response
if self._looks_like_clarification_response(text):
return response
if re.search(r"\breply with\b", text, re.IGNORECASE):
return response
answer_shape_is_real = bool(
text.startswith("###")
or text.startswith("Showing ")
or text.startswith("No data found")
or text.startswith("I could not find data")
or text.startswith("Could not identify")
or text.startswith("I found")
)
if not answer_shape_is_real:
return response
q = str(query or "").strip().lower()
if not q or agent_name not in {"data_query", "data_plotting"}:
return response
if any(
marker in q
for marker in (
"list variables",
"list models",
"list regions",
"list scenarios",
"show all variables",
"show all models",
"show all regions",
"which models are available",
"fit-for-55",
"fit for 55",
"ndc impacts",
)
):
if q != "show all scenarios":
return response
has_year_filter = bool(extract_year_range(query)[0] or extract_year_range(query)[1])
complete_baseline_query = "baseline" in q and (
has_year_filter
or any(term in q for term in ("solar capacity", "wind capacity", "under baseline"))
)
if complete_baseline_query or "latest" in q:
return response
if re.search(r"\bby\s+\d{4}\b", q) and not any(term in q for term in ("compare", "versus", "vs")):
return response
should_guide = bool(
self._is_generic_followup(query)
or self._is_contextual_dimension_followup(query)
or re.fullmatch(r"\d+", q)
or q == "show all scenarios"
or "help me find data" in q
or agent_name == "data_plotting"
or any(term in q for term in ("carbon dioxide", "co2", "emissions", "carbon from", "current policy"))
)
if not should_guide:
return response
return (
f"{text}\n\n"
"Reply with a scenario, model, region, or year to narrow the answer."
)
def _workspace_result_answer(self, query: str, response: str) -> str:
text = str(response or "").strip()
q = str(query or "").lower()
if not any(term in q for term in ("fit-for-55", "fit for 55", "net zero", "net-zero", "iam compact")):
return response
if not (
not text
or "i need one more detail" in text.lower()
or "please specify the variable, region, or scenario" in text.lower()
):
return response
return (
"The best match is the IAM COMPACT results workspace for Fit-for-55 and EU net-zero pathways. "
"Use the IAM PARIS links below to open the relevant policy-question workspace and related net-zero results."
)
def _model_metadata_fallback_answer(self, query: str, response: str, entities: Optional[Dict[str, Any]]) -> str:
text = str(response or "").strip()
model = str((entities or {}).get("model") or "").strip()
if not model:
return response
if not (
not text
or "i need one more detail" in text.lower()
or "please specify the variable, region, or scenario" in text.lower()
):
return response
profile = find_model_profile(model) or find_model_profile(query)
if profile:
return format_model_profile_answer(
profile,
requested_name=str(profile.get("name", "") or model),
asks_assumptions=bool(re.search(r"\bassumption\b|\bassumptions\b", str(query or "").lower())),
)
return (
f"I matched `{model}`, but IAM PARIS does not expose a dedicated assumptions/metadata page "
"for that model in the local model catalog. Use the IAM PARIS model and results links below "
"to inspect related documentation or available data."
)
def _models_covering_topic_answer(self, query: str) -> Optional[str]:
"""N4: when a model-list request carries a sector/topic qualifier, return a
deterministic subset of models that report data for that topic instead of the
full model list. Returns None when no topic is detected or metadata is missing."""
metadata = self.shared_resources.get("metadata")
if not metadata or not hasattr(metadata, "models_covering_topic"):
return None
category, models = metadata.models_covering_topic(query)
if not category or not models:
return None
total = len(metadata.all_model_names) if hasattr(metadata, "all_model_names") else None
shown = models[:20]
more = len(models) - len(shown)
lines = [
f"### Models covering {category}",
"",
f"{len(models)} model(s)"
+ (f" of {total}" if total else "")
+ f" report at least one {category.lower()} variable in IAM PARIS:",
"",
]
lines.append(", ".join(shown) + (f" … and {more} more" if more > 0 else ""))
lines.append("")
lines.append(f"Ask for a specific model (e.g. `tell me about {shown[0]}`) or a data query "
f"(e.g. `{category.lower()} emissions for Europe`) to go deeper.")
return "\n".join(lines)
def _repair_comparison_entities(self, query: str, entities: Optional[Dict[str, Any]]) -> Dict[str, Any]:
repaired = dict(entities or {})
q = str(query or "").lower()
if re.search(r"\b(greenhouse gas|greenhouse gases|ghg)\b", q):
repaired["variable"] = "Emissions|GHG"
confidence = dict(repaired.get("entity_confidence") or {})
confidence["variable"] = max(float(confidence.get("variable", 0) or 0), 0.9)
repaired["entity_confidence"] = confidence
available_variables = {
str(record.get("variable", "") or "")
for record in self.shared_resources.get("ts", [])
if isinstance(record, dict) and record.get("variable")
}
preferred_variable = preferred_variable_from_query(query, available_variables)
existing_variable = str(repaired.get("variable", "") or "").strip()
explicit_existing_variable = bool(existing_variable and existing_variable in str(query or ""))
if preferred_variable and not explicit_existing_variable:
repaired["variable"] = preferred_variable
confidence = dict(repaired.get("entity_confidence") or {})
confidence["variable"] = max(float(confidence.get("variable", 0) or 0), 0.9)
repaired["entity_confidence"] = confidence
available_scenarios = {
str(record.get("scenario", "") or "")
for record in self.shared_resources.get("ts", [])
if isinstance(record, dict) and record.get("scenario")
}
scenario = canonical_scenario_from_query(query, available_scenarios)
if scenario:
repaired["scenario"] = scenario
confidence = dict(repaired.get("entity_confidence") or {})
confidence["scenario"] = max(float(confidence.get("scenario", 0) or 0), 0.9)
repaired["entity_confidence"] = confidence
if not _looks_like_comparison_request(query):
return repaired
scenario_pair = re.search(
r"\bunder\s+(.+?)\s+(?:versus|vs|against|compared\s+with|compared\s+to)\s+(.+?)(?:\s+for\s+model\b|$)",
query,
re.IGNORECASE,
)
if scenario_pair:
scenarios = []
for raw_scenario in scenario_pair.groups():
matched = canonical_scenario_from_query(raw_scenario, available_scenarios)
if matched and matched not in scenarios:
scenarios.append(matched)
if len(scenarios) >= 2:
repaired["scenarios"] = scenarios
repaired["scenario"] = None
repaired["comparison"] = "scenario"
confidence = dict(repaired.get("entity_confidence") or {})
confidence["scenario"] = max(float(confidence.get("scenario", 0) or 0), 0.9)
confidence["comparison"] = max(float(confidence.get("comparison", 0) or 0), 0.9)
repaired["entity_confidence"] = confidence
has_wind = re.search(r"\bwind\b", q)
has_solar = re.search(r"\b(solar|pv|photovoltaic|photovoltaics)\b", q)
has_capacity_intent = re.search(r"\b(capacity|power|installed|pv)\b", q)
if not (has_wind and has_solar and has_capacity_intent):
return repaired
variables = [
"Capacity|Electricity|Wind",
"Capacity|Electricity|Solar",
]
existing = repaired.get("variables")
if isinstance(existing, list):
for variable in existing:
if variable and variable not in variables:
variables.append(str(variable))
repaired["variable"] = "Capacity|Electricity|Wind"
repaired["variables"] = variables
repaired["comparison"] = repaired.get("comparison") or "variable"
confidence = dict(repaired.get("entity_confidence") or {})
confidence["variable"] = max(float(confidence.get("variable", 0) or 0), 0.9)
confidence["comparison"] = max(float(confidence.get("comparison", 0) or 0), 0.85)
repaired["entity_confidence"] = confidence
return repaired
def _low_confidence_entity_prompt(self, entities: Optional[Dict[str, Any]]) -> str:
entities = entities or {}
confidence = entities.get("entity_confidence") or {}
labels = {
"variable": "variable",
"region": "region",
"scenario": "scenario",
"model": "model",
}
for field, label in labels.items():
value = entities.get(field)
score = confidence.get(field)
if value and isinstance(score, (int, float)) and score < 0.5:
return (
f"I matched `{value}` as the {label}, but confidence is low. "
f"Which {label} should I use?"
)
return ""
def _record_route_decision(
self,
agent_name: str,
confidence: float,
source: str,
reason: str,
) -> str:
self.last_route_decision = {
"agent": agent_name,
"confidence": round(float(confidence), 3),
"source": source,
"reason": reason,
}
self.logger.info(
"Route decision: agent=%s confidence=%.2f source=%s reason=%s",
agent_name,
confidence,
source,
reason,
)
return agent_name
def _mentions_known_model(self, query: str) -> bool:
q = (query or "").strip().lower()
if find_model_profile(q):
return True
model_names = [
str(m.get("modelName", "")).lower()
for m in self.shared_resources.get("models", [])
if m and m.get("modelName")
]
return any(
re.search(r"(?<!\w)" + re.escape(name) + r"(?!\w)", q)
for name in model_names[:200]
if name
)
def _deterministic_route_decision(
self,
query: str,
entities: Optional[Dict[str, Any]] = None,
) -> Optional[Dict[str, Any]]:
"""
Deterministic route order:
plot, data query, model info, availability/discovery, study/link suggestion, general QA.
Active clarification is handled before this helper in _route_single.
"""
q = (query or "").strip().lower()
entities = entities or {}
explicit_plot_query = _looks_like_plot_request(query)
explicit_data_query = _looks_like_data_request(query)
if explicit_plot_query or entities.get("action") == "plot":
return {
"agent": "data_plotting",
"confidence": 0.95 if explicit_plot_query else 0.85,
"source": "deterministic",
"reason": "plot request",
}
scenario_only_comparison_followup = bool(
re.match(
r"compare\s+(?:with|to|against)\s+(?:baseline|policy|current policies?|scenario|the scenario)",
q,
)
or re.match(
r"compare\s+.+\s+versus\s+(?:baseline|policy|current policies?|scenario|the scenario)\b",
q,
)
)
if not scenario_only_comparison_followup and _looks_like_comparison_request(query) and (
entities.get("variable")
or entities.get("variables")
or entities.get("model")
or entities.get("models")
or any(term in q for term in ("solar", "wind", "co2", "emission", "emissions", "gcam", "message", "remind", "witch"))
):
return {
"agent": "data_plotting",
"confidence": 0.9,
"source": "deterministic",
"reason": "comparison plot request",
}
if _looks_like_site_navigation_request(query):
return {
"agent": "general_qa",
"confidence": 0.88,
"source": "deterministic",
"reason": "site/navigation link request",
}
asks_model_expl = _looks_like_model_info_request(query)
explicit_what_is = bool(re.search(r"\bwhat\s+is\b", q) or re.search(r"\bwho\s+is\b", q))
mentions_model = self._mentions_known_model(query) or bool(entities.get("model"))
vague_model_info = bool(
asks_model_expl
and mentions_model
and "model" not in q
and not explicit_what_is
and re.search(r"\b(info|information)\b", q)
)
if vague_model_info:
return {
"agent": "data_query",
"confidence": 0.82,
"source": "deterministic",
"reason": "vague model information request",
}
if (asks_model_expl and ("model" in q or mentions_model)) or (explicit_what_is and mentions_model):
return {
"agent": "model_explanation",
"confidence": 0.9,
"source": "deterministic",
"reason": "model information request",
}
if explicit_data_query:
return {
"agent": "data_query",
"confidence": 0.9,
"source": "deterministic",
"reason": "data request",
}
if any(
_looks_like_category_list_request(query, category)
for category in ("models", "variables", "regions", "scenarios")
) or re.search(r"\b(list|available|what)\b.*\bworkspaces?\b", q):
return {
"agent": "data_query",
"confidence": 0.9,
"source": "deterministic",
"reason": "availability/discovery request",
}
if any(token in q for token in ("suggest", "research idea", "investigate", "study suggestion")):
return {
"agent": "modelling_suggestions",
"confidence": 0.82,
"source": "deterministic",
"reason": "study suggestion request",
}
if any(entities.get(k) for k in ("variable", "region", "scenario", "model")):
return {
"agent": "data_query",
"confidence": 0.75,
"source": "deterministic",
"reason": "extracted data entities",
}
if any(token in q for token in ("climate", "policy", "paris agreement", "decarbon", "mitigation")):
return {
"agent": "general_qa",
"confidence": 0.7,
"source": "deterministic",
"reason": "general climate/policy question",
}
return None
def _route_with_llm_fallback(self, query: str, entities: Optional[Dict[str, Any]]) -> str:
try:
result = self.routing_prompt | self.router_llm
response_obj = result.invoke({"query": query})
agent_name = str(response_obj.content or "").strip().lower()
if agent_name not in VALID_AGENT_NAMES:
fallback = self._classify_route_heuristic(query, entities)
return self._record_route_decision(
fallback,
0.55,
"heuristic",
f"invalid LLM route `{agent_name}`",
)
return self._record_route_decision(agent_name, 0.6, "llm", "unclear deterministic route")
except Exception as route_err:
self.logger.warning(
"Router LLM unavailable (%s). Falling back to heuristic routing.",
route_err,
)
fallback = self._classify_route_heuristic(query, entities)
return self._record_route_decision(fallback, 0.5, "heuristic", "router LLM unavailable")
def _classify_route_heuristic(self, query: str, entities: Optional[Dict[str, Any]] = None) -> str:
"""
Local, no-network route classifier used when router LLM is unavailable.
"""
q = (query or "").strip().lower()
entities = entities or {}
if _looks_like_plot_request(query):
return "data_plotting"
if _looks_like_site_navigation_request(query):
return "general_qa"
if find_model_profile(q):
mentions_profile_model = True
else:
mentions_profile_model = False
model_names = [
str(m.get("modelName", "")).lower()
for m in self.shared_resources.get("models", [])
if m and m.get("modelName")
]
mentions_model = any(
re.search(r"(?<!\w)" + re.escape(name) + r"(?!\w)", q)
for name in model_names[:200]
if name
) or mentions_profile_model
asks_model_expl = _looks_like_model_info_request(query)
explicit_what_is = bool(re.search(r"\bwhat\s+is\b", q) or re.search(r"\bwho\s+is\b", q))
if (asks_model_expl and ("model" in q or mentions_model)) or (explicit_what_is and mentions_model):
return "model_explanation"
if any(
_looks_like_category_list_request(query, category)
for category in ("models", "variables", "regions", "scenarios")
) or re.search(r"\b(list|available|what)\b.*\bworkspaces?\b", q):
return "data_query"
if any(entities.get(k) for k in ("variable", "region", "scenario", "model")):
return "data_query"
if _looks_like_data_request(query):
return "data_query"
return "general_qa"
def _is_provider_error(self, err: Exception) -> bool:
msg = str(err or "").lower()
return any(
token in msg
for token in (
"provider error",
"api key",
"insufficient_quota",
"rate limit",
"authentication",
"connection error",
"timeout",
"openai",
"401",
"403",
"429",
"5xx",
)
)
def _is_intentful_segment(self, segment: str) -> bool:
"""Heuristic check for whether a segment contains a recognizable intent."""
s = segment.lower()
intent_markers = [
"list", "show", "plot", "graph", "chart", "visualize", "compare", "vs", "versus",
"tell me about", "explain", "describe", "what models", "what variables",
"what scenarios", "available models", "available variables", "available scenarios",
"suggest", "research", "investigate"
]
return any(m in s for m in intent_markers)
def _split_multi_intent(self, query: str) -> List[str]:
"""
Split multi-intent queries into sub-queries using conservative heuristics.
"""
q = query.strip()
lower = q.lower()
if " and plot " in lower or lower.endswith(" and plot it") or " and plot it" in lower:
import re
parts = re.split(r"\s+and\s+", q)
parts = [p.strip() for p in parts if p and p.strip()]
return parts if len(parts) > 1 else [q]
intent_markers = [
"list", "show", "plot", "graph", "chart", "visualize", "compare",
"tell me about", "explain", "describe", "what models", "what variables",
"what scenarios", "available models", "available variables", "available scenarios"
]
intent_hits = sum(1 for m in intent_markers if m in lower)
if intent_hits < 2:
return [q]
import re
parts = re.split(r"\s+(?:and|then|also)\s+|;|\n", q)
parts = [p.strip() for p in parts if p and p.strip()]
# If split produced segments without intent, merge them back to previous
merged: List[str] = []
for part in parts:
if not merged:
merged.append(part)
continue
if self._is_intentful_segment(part):
merged.append(part)
else:
merged[-1] = f"{merged[-1]} {part}".strip()
return merged if len(merged) > 1 else [q]
def _compose_contextual_query(self, query: str, carried: Optional[Dict[str, Any]]) -> str:
"""
Enrich follow-up queries like "plot it" or "show me data" with the last
resolved variable, region, scenario, or model when available.
"""
if not carried:
return query
ql = query.lower()
variable = str(carried.get("variable", "") or "").strip()
region = str(carried.get("region", "") or "").strip()
scenario = str(carried.get("scenario", "") or "").strip()
model = str(carried.get("model", "") or "").strip()
if self._is_contextual_dimension_followup(query):
same_for = re.search(r"\bsame\s+for\s+(.+)$", query, re.IGNORECASE)
what_about = re.search(r"\b(?:what|how)\s+about\s+(.+)$", query, re.IGNORECASE)
compare_with = re.search(r"\bcompare\s+(?:with|to|against)\s+(.+)$", query, re.IGNORECASE)
scope_year = re.match(r"\s*((?:after|before|by|in|from)\s+\d{4}(?:\s*(?:to|until|-)\s*\d{4})?)\s*$", query, re.IGNORECASE)
if "show all scenarios" in ql:
parts = ["show all scenarios"]
if variable:
parts.append(f"for {variable}")
if region:
parts.append(f"in {region}")
if model:
parts.append(f"for model {model}")
return " ".join(parts)
if compare_with:
target = compare_with.group(1).strip()
parts = ["plot compare"]
if variable:
parts.append(variable)
if region:
parts.append(f"for {region}")
if scenario:
parts.append(f"under {scenario}")
if target:
parts.append(f"versus {target}")
if model:
parts.append(f"for model {model}")
if len(parts) > 1:
return " ".join(parts)
if scope_year:
replacement = scope_year.group(1).strip()
parts = ["show"]
if variable:
parts.append(variable)
if region:
parts.append(f"for {region}")
if scenario:
parts.append(f"under {scenario}")
parts.append(replacement)
if model:
parts.append(f"for model {model}")
if len(parts) > 1:
return " ".join(parts)
replacement = ""
if same_for:
replacement = same_for.group(1).strip()
elif what_about:
replacement = what_about.group(1).strip()
if replacement:
start_year, end_year = extract_year_range(replacement)
scenario_replacement = self._match_scenario_from_text(replacement)
parts = ["show"]
if variable:
parts.append(variable)
if start_year is not None or end_year is not None:
if region:
parts.append(f"for {region}")
if scenario:
parts.append(f"under {scenario}")
parts.append(replacement)
elif scenario_replacement:
if region:
parts.append(f"for {region}")
parts.append(f"under {scenario_replacement}")
else:
parts.append(f"for {replacement}")
if scenario:
parts.append(f"under {scenario}")
if model:
parts.append(f"for model {model}")
if len(parts) > 1:
return " ".join(parts)
if self._is_generic_followup(query):
if any(token in ql for token in ("plot", "graph", "chart")):
lead = "plot"
else:
lead = "show"
parts: List[str] = [lead]
if variable:
parts.append(variable)
if region:
parts.append(f"for {region}")
if scenario:
parts.append(f"under {scenario}")
if model:
parts.append(f"for model {model}")
if len(parts) > 1:
return " ".join(parts)