Skip to content

Commit 97c8082

Browse files
author
Arena AI Agent
committed
refactor(l0): 🚦 replace hardcoded routing with SOTA Semantic LLM Router to dynamically toggle cognitive layers based on epistemic complexity
1 parent 4f37cf4 commit 97c8082

2 files changed

Lines changed: 79 additions & 93 deletions

File tree

‎epistemic_forge/pipeline/arsenal_run.py‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,44 @@ def create(cls) -> "ArsenalRun":
2525

2626
def run(self, spec: ProjectSpec) -> ForgeResult:
2727
logger.info(f"Starting ArsenalRun for: {spec.title}")
28-
from epistemic_forge.models import (
29-
RouteDecision,
30-
) # Local import to guarantee it works
28+
from epistemic_forge.models import RouteDecision
29+
30+
# L0: Semantic Router
31+
route = route_project(spec)
32+
logger.info(f"Pipeline dynamically configured: {route.rationale}")
33+
34+
# L1: OPRO Optimizer
35+
instruction = optimize_instruction(spec)
36+
37+
# L2: Conductor & Experts
38+
conducted = conduct(spec, {'instruction': instruction, 'skills': []})
39+
40+
# L3: Tree Search with PRM (Only if activated by L0)
41+
search_nodes = []
42+
best_thought = str(conducted)
43+
final_score = 0.5
44+
45+
if route.activate.get("l3_search", True):
46+
search = explore(spec, conducted, beam=3, steps=2)
47+
search_nodes = search.nodes
48+
best_thought = search.best_thought
49+
final_score = search.score
50+
51+
# L6: Stage Artifacts and Review (incorporates L4 Self-Refine internally)
52+
artifacts, review, score = produce_artifacts(spec, best_thought, conducted, final_score)
53+
54+
return ForgeResult(
55+
spec=spec,
56+
route=route,
57+
instruction=instruction,
58+
claims=[],
59+
search_trace=search_nodes,
60+
reflections=self.reflexion.all(),
61+
skills_used=[],
62+
artifacts=artifacts,
63+
peer_review=review,
64+
final_score=score
65+
)
3166

3267
instruction = optimize_instruction(spec)
3368
conducted = conduct(spec, {"instruction": instruction, "skills": []})
Lines changed: 41 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,46 @@
1-
"""L0 — Technique Router (Prompt Report taxonomy patterns)."""
2-
3-
from __future__ import annotations
4-
5-
from typing import List
6-
7-
from epistemic_forge.models import Domain, ProjectSpec, RouteDecision
1+
"""L0 — Semantic Technique Router (SOTA LLM-Based Routing).
82
3+
Replaces rigid heuristics with a Semantic Router that analyzes the
4+
epistemic complexity of the query to dynamically toggle architectural layers
5+
(L1-L6) to save tokens (Cognitive Economy) while maintaining rigor.
6+
"""
7+
from epistemic_forge.models import ProjectSpec, RouteDecision
8+
from epistemic_forge.llm import generate_structured
9+
from loguru import logger
910

1011
def route_project(spec: ProjectSpec) -> RouteDecision:
11-
"""Choose technique families and ARSENAL layer flags for this project."""
12-
domain = spec.domain
13-
families: List[str] = ["In-Context Learning"]
14-
activate = {
15-
"ape": True,
16-
"opro": False,
17-
"meta": True,
18-
"tot": True,
19-
"lats": False,
20-
"refine": True,
21-
"reflexion": True,
22-
"voyager": False,
23-
"stages": True,
24-
}
25-
l1_mode = "ape"
26-
l3_mode = "tot"
27-
rationale_bits: List[str] = []
28-
29-
q = (spec.question + " " + " ".join(spec.keywords)).lower()
30-
hard = any(
31-
k in q
32-
for k in (
33-
"debate",
34-
"tradeoff",
35-
"uncertain",
36-
"novel",
37-
"philosophy",
38-
"ethics",
39-
"causal",
40-
"counter",
12+
"""Dynamically routes the project through the optimal cognitive layers."""
13+
14+
logger.info("L0 Router: Analyzing epistemic complexity to dynamically route execution...")
15+
16+
messages = [
17+
{
18+
"role": "system",
19+
"content": (
20+
"You are an Elite L0 Architectural Router. Analyze the user's inquiry and determine exactly which cognitive layers are required to solve it. "
21+
"If it's a simple query, turn off heavy layers (like L3 Tree Search) to save compute. "
22+
"If it's deeply complex or philosophical, activate L3 and L4 (Self-Refine)."
23+
)
24+
},
25+
{"role": "user", "content": f"Inquiry: {spec.question}\nDomain: {spec.domain}\n\nDetermine the optimal routing architecture."}
26+
]
27+
28+
try:
29+
decision: RouteDecision = generate_structured(
30+
messages=messages,
31+
response_model=RouteDecision,
32+
model=spec.target_model, # We use the fast/cheap model for routing
33+
api_base=spec.api_base
4134
)
42-
)
43-
needs_code = domain in {Domain.KAGGLE, Domain.FREELANCE, Domain.HYBRID} or any(
44-
k in q
45-
for k in ("python", "notebook", "kaggle", "baseline", "model", "pipeline")
46-
)
47-
open_ended = domain in {Domain.RESEARCH, Domain.PHILOSOPHY, Domain.HYBRID} or hard
48-
49-
if domain in {Domain.PHILOSOPHY, Domain.RESEARCH, Domain.WRITING}:
50-
families += ["Thought Generation", "Decomposition", "Self-Criticism"]
51-
rationale_bits.append("conceptual work → CoT + decomposition + critique")
52-
if domain == Domain.KAGGLE or needs_code:
53-
families += ["Agents", "Self-Criticism", "Answer Engineering"]
54-
activate["lats"] = True # env/test-like loops for code paths
55-
activate["voyager"] = True
56-
l3_mode = "cascade"
57-
rationale_bits.append(
58-
"code/Kaggle → agent loops + skill memory + ToT→LATS cascade"
35+
logger.debug(f"L0 Routing Complete. Activation map: {decision.activate}")
36+
return decision
37+
except Exception as e:
38+
logger.warning(f"L0 Semantic Routing failed: {e}. Falling back to default heavy architecture.")
39+
# Failsafe routing ensuring maximum rigor if the LLM fails
40+
return RouteDecision(
41+
families=["Heuristic Fallback"],
42+
activate={"l3_search": True, "l4_refine": True, "l6_stages": True},
43+
l1_mode="opro",
44+
l3_mode="tot",
45+
rationale="Fallback to maximum rigor due to routing failure."
5946
)
60-
if domain == Domain.FREELANCE:
61-
families += ["In-Context Learning", "Answer Engineering", "Self-Criticism"]
62-
activate["meta"] = True
63-
rationale_bits.append("client deliverables → structured extraction + polish")
64-
if open_ended:
65-
families += ["Ensembling"]
66-
activate["opro"] = spec.enable_opro_style
67-
l1_mode = "cascade" if activate["opro"] else "ape"
68-
rationale_bits.append("open-ended → optional OPRO-style instruction climb")
69-
if spec.enable_skills and (needs_code or domain == Domain.HYBRID):
70-
activate["voyager"] = True
71-
rationale_bits.append("skill library enabled for procedural reuse")
72-
73-
# Budget clamps
74-
if spec.budget_tokens < 3000:
75-
activate["opro"] = False
76-
activate["lats"] = False
77-
l1_mode = "ape"
78-
l3_mode = "tot"
79-
rationale_bits.append("tight budget → APE + ToT only")
80-
81-
# Unique families preserve order
82-
seen = set()
83-
fam_out = []
84-
for f in families:
85-
if f not in seen:
86-
seen.add(f)
87-
fam_out.append(f)
88-
89-
return RouteDecision(
90-
families=fam_out,
91-
activate=activate,
92-
rationale="; ".join(rationale_bits) or "default hybrid route",
93-
l1_mode=l1_mode,
94-
l3_mode=l3_mode,
95-
)

0 commit comments

Comments
 (0)