semantic_router.routers.base
the routing contract. a router scores every route for a query; everything else is shared.
run
def run(coro: Coroutine[object, object, T]) -> Trun a coroutine from sync code, including from inside a running loop (notebooks).
every sync call shares one background loop, so pooled connections survive between calls
instead of being torn down with a fresh asyncio.run each time.
in_sync_call
def in_sync_call() -> booltrue while a sync method's coroutine runs on the shared background loop.
routers use their clients' sync APIs there: an async client used on that loop binds to it, and then fails when the caller later awaits on a loop of their own.
FitReport Objects
@dataclass(frozen=True)
class FitReport()accuracy
top-1 accuracy on queries that have a route, before any threshold
ece
calibration error of the stated confidences
QueryResult Objects
@dataclass(frozen=True)
class QueryResult()what scoring one query gives: the raw score per route, and the matches behind it.
Arguments:
scores: The raw score for every route, higher means more likely.matched_utterances: The stored utterances that matched, per route, when asked for and the router can say.Nonewhen it can't.
BaseRouter Objects
class BaseRouter(ABC)concurrency
cap on in-flight requests when scoring many queries
acall
async def acall(
query: str,
limit: int | None = 1,
threshold: float | None = None,
return_utterances: bool = False) -> RouteChoice | list[RouteChoice]route one query.
Arguments:
query: The text to route.limit: How many choices to return, best first:1gives one choice,Noneevery route that clears its threshold.threshold: A confidence threshold for this call only, over every route's and the router's.return_utterances: Also fill each choice'smatched_utteranceswith the stored utterances that matched the query, where the router can say.
afit
async def afit(X: Sequence[str],
y: Sequence[str | None],
method: Method = "platt") -> FitReportcalibrate on labelled queries. a label of None means no route should match.
aevaluate
async def aevaluate(X: Sequence[str], y: Sequence[str | None]) -> floatend-to-end accuracy with the threshold applied; None labels are right when nothing passes.
to_yaml
def to_yaml(path: str | Path) -> Nonesave the router to a yaml file; load_router reads it back. keys are never written.
to_json
def to_json(path: str | Path) -> Nonesave the router to a json file; load_router reads it back. keys are never written.