The routing node (routerAgentNode) in the LangGraph architecture utilizes a four-tier cascade routing design (Tiered Routing Cascade) to minimize response latency and LLM Token expenditure while maintaining high classification precision.
+-------------------------------+
| Incoming User Message |
+---------------+---------------+
|
v
+-------------------------------+
| Tier 1: Rule Short-Circuit |
| hasUnprocessedFile? |
+---------------+---------------+
|
+--------+--------+
| |
(Yes) (No)
| |
v v
+-------------------+ +-------------------------------+
| Route: kbAgent | | Tier 2: Keyword Short-Circuit |
| source: "rule" | | matchKeywordRoute() |
+-------------------+ +---------------+---------------+
|
+--------+--------+
| |
(Match) (Miss)
| |
v v
+-------------------+ +-------------------------------+
| Target Agent | | Tier 3: Clef-flash System-One |
| source: "keyword" | | Decision Model (Confidence>0.7|
+-------------------+ +---------------+---------------+
|
+--------+--------+
| |
(Match) (Miss)
| |
v v
+-------------------+ +-------------------------------+
| Target Agent | | Tier 4: LLM Fallback Classifier|
| source: "decision"| | withStructuredOutput |
+-------------------+ +---------------+---------------+
|
v
+-------------------+
| Target Agent |
| source: "llm" |
+-------------------+
- Trigger: Evaluates if the current conversation history contains any unprocessed file/document upload (
hasUnprocessedFile). - Target Agent:
kbAgent - Latency:
< 1ms(Zero I/O, Zero LLM overhead)
- Trigger: Evaluates the trailing user message against priority-ordered keyword and regex rule groups via
lib/router/keywords.ts. - Priority Groups:
codeAgent: Matches Markdown code blocks (```ts), code writing/refactoring phrases, runtime stack traces, and data format conversions (JSON -> CSV).cryptoAgent: Matches unambiguous tickers (BTC,ETH,USDT,SOL), cryptocurrency terms, and wallet/swap intent.weatherAgent: Matches meteorological terms (weather,forecast,celsius,air quality,AQI).
- Target Agents:
codeAgent|cryptoAgent|weatherAgent - Metadata: Includes
source: "keyword"and the exact matched rule string (matchedKey). - Latency:
< 1ms
- Trigger: Triggered when Tier 1 (Rules) and Tier 2 (Keywords) miss, and decision model configuration is available.
- Provider Resolution Hierarchy:
- Route A (DB Provider Priority): Queries Postgres
providertable for any enabled provider with a model flagged withkind: ["decision"]. ExtractsbaseUrl, decrypted Bearer key, and model name. - Route B (Generic Env Fallback): If no DB decision model is configured, reads generic environment variables:
DECISION_MODEL_BASE_URL(Cloudflare Workers AI endpoint, AI Gateway URL, or private inference proxy)DECISION_MODEL_API_KEY(Standard Bearer token)DECISION_MODEL_NAME(Defaults to@cf/cloudflare/clef-flash)
- Route C (Chat Fallback): If neither Route A nor Route B exists, Tier 3 is skipped and execution proceeds directly to Tier 4 with
source: "llm".
- Route A (DB Provider Priority): Queries Postgres
- Mechanism: Calls Cloudflare Workers AI
@cf/cloudflare/clef-flash(or Jev-compatible System-One decision model) using typed question schemas (questions.route: { type: "choice", instructions, criteria }). Instead of autoregressive text generation, it evaluates probabilities across allowable options directly against the input state. - Criteria Definition:
weatherAgent: Meteorological conditions, temperature, rain, forecast, air quality.cryptoAgent: Cryptocurrency, tokens, market prices, BTC, ETH, swap, wallet.codeAgent: Programming code, scripts, algorithms, data conversion, precise math formulas.chatAgent: General conversation, translation, explanation, knowledge Q&A, writing, fallback.
- Confidence Gate: Requires calibrated confidence
confidence >= 0.70. If confidence drops below 0.70 or the decision call encounters network errors, the router gracefully falls back to Tier 4 without interrupting the user. - Latency & Resource Profile:
- Latency:
150ms - 300ms - Output tokens:
0(Zero token generation waste) - Input tokens: Typically
~230tokens (only user message + question criteria)
- Latency:
- Trigger: Triggered when Tiers 1-3 pass without a conclusive match, or when the decision model is unconfigured / below confidence threshold.
- Mechanism: Invokes structured decision model with
withStructuredOutput(InvokeRouteDecisionSchema)for deep semantic intent classification. - Target Agents:
weatherAgent|cryptoAgent|codeAgent|chatAgent(default fallback) - Latency:
500ms - 2.5s
Every invocation of the decision model is captured by CapturingHandler and surfaced in the Observability waterfall:
▼ SystemMessage: Full classification instructions and the complete list of candidate sub-agents with their respective criteria.▼ HumanMessage: The user's input prompt.▼ AiMessage: Complete decision result containingchoice,confidence, and the fullprobabilitiesbreakdown.FIELDSSidebar: Structured key-value display ofchoice,source: "decision", andconfidence.- Diagnostic Fallback Tracing: When a fallback occurs, the trace records
status: "fallback_to_chat"along with the explicit reason (e.g.low_confidence (0.65 < 0.70)orclef_request_null_or_error).
When a user session is active (userId present):
- Clef decision model executions are recorded in
credit_usage_logwithagentName: "routerAgent"andmodelName: "@cf/cloudflare/clef-flash". - Credits are deducted using the provider's configured rate (
computeCredits(usage, rate)). If the provider rates are set to0, the usage is logged for audit without billing the user.
export const RouteDecisionSchema = z.object({
next: z.enum(["weatherAgent", "chatAgent", "cryptoAgent", "codeAgent", "kbAgent"]),
source: z.enum(["rule", "keyword", "decision", "llm"]).optional(),
matchedKey: z.string().optional(),
confidence: z.number().optional(),
probabilities: z.record(z.string(), z.number()).optional(),
});langgraph-app/
├── backend/
│ └── node/
│ └── router-agent-node.ts # 4-tier intent classification node
├── lib/
│ ├── provider/
│ │ ├── decision.ts # Generic System-One / Jev / Clef decision client
│ │ ├── model-registry.ts # Multi-pool model registry (kind: ["decision"])
│ │ └── schema.ts # Provider & ModelKind type definitions
│ └── router/
│ └── keywords.ts # Tier 2 priority keyword rules & match engine
├── tests/
│ ├── backend/
│ │ └── node/
│ │ └── router-agent-node.test.ts # Node cascading logic & observability tests
│ └── lib/
│ ├── provider/
│ │ └── decision.test.ts # Decision model client unit tests
│ └── router/
│ └── keywords.test.ts # Regex & keyword precedence tests
└── docs/
└── ROUTING.md # Architecture & operational specification
- Routing Node:
backend/node/router-agent-node.ts - Decision Client (System-One / Jev / Clef):
lib/provider/decision.ts - Keyword Matching Engine:
lib/router/keywords.ts - Documentation:
docs/ROUTING.md - Unit Tests:
tests/lib/provider/decision.test.tstests/lib/router/keywords.test.tstests/backend/node/router-agent-node.test.ts