solon-ai-router
2026年12月1日 下午11:01:23
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon-ai-router</artifactId>
</dependency>
1、描述
solon-ai 的扩展插件,v4.1.0 后支持。在发起聊天请求时,从一组已经构建好的 ChatModel 中选出一个,返回该模型自己的 ChatRequestDesc;之后的 options()、call()、stream() 等都由目标模型处理。只作用于 ChatModel,不接入 Agent、Flow 或 Harness。
| 类 | 描述 |
|---|---|
ChatModelRouter | 路由入口,prompt(...) 与 ChatModel 的四个入口同形(Prompt / 消息列表 / 消息数组 / 字符串) |
ChatModelRoute | 候选:(id, description, weight, chatModel) |
RoundRobinRoutingStrategy | 按注册顺序轮询 |
WeightedRoundRobinRoutingStrategy | 按 weight 平滑加权轮询 |
RuleBasedRoutingStrategy | RoutingRule(routeId, predicate) 按顺序匹配,第一个命中的胜出 |
SmartRoutingStrategy | 用一个分类模型先调用一次,按候选描述选路(多一次调用的成本与延迟) |
注意:选路发生在 prompt(...) 时(只创建请求也会消耗一次轮询位置)。路由器没有默认候选和失败转移:规则都不匹配、分类失败、路由 ID 未知时,直接抛出 RoutingException。
2、示例
import org.noear.solon.ai.chat.ChatModel;
import org.noear.solon.ai.chat.ChatResponse;
import org.noear.solon.ai.chat.prompt.Prompt;
import org.noear.solon.ai.router.ChatModelRoute;
import org.noear.solon.ai.router.ChatModelRouter;
import org.noear.solon.ai.router.RoutingRule;
import org.noear.solon.ai.router.strategy.RuleBasedRoutingStrategy;
import java.util.Arrays;
ChatModel fastModel = ..., reasoningModel = ...;
ChatModelRouter router = new ChatModelRouter(Arrays.asList(
new ChatModelRoute("fast", "常规问答", 1, fastModel),
new ChatModelRoute("reasoning", "复杂分析与多步推理", 1, reasoningModel)
), new RuleBasedRoutingStrategy(Arrays.asList(
new RoutingRule("reasoning", ctx -> {
String content = ctx.getPrompt().getUserContent();
return content != null && content.contains("分析");
}),
new RoutingRule("fast", ctx -> true) //兜底规则要显式加
)));
ChatResponse resp = router.prompt("分析这个并发问题")
.options(o -> o.temperature(0.2))
.call();
//显式指定候选(绕过策略)
Prompt prompt = Prompt.of("生成摘要").attrPut(ChatModelRouter.ATTR_ROUTE_ID, "fast");
router.prompt(prompt).call();