aw.routing¶
Configurable routing and decision chains for agentic workflows.
This module provides tools for building extensible, inspectable routing chains that follow the open-closed principle. Users can:
Use default configurations out of the box
Inspect all routing rules and mappings
Customize individual components
Extend with new routing strategies
The key pattern is: provide sensible defaults, make them visible, keep them mutable.
Functions
|
Use explicit extension if provided. |
|
Extract extension from URL path. |
|
Factory for content-type based detection. |
|
Factory for magic bytes based detection. |
Classes
|
Router with short-circuit conditions. |
|
A routing strategy backed by a ranked search: answer only when the ranking is clear. |
|
Context for extension detection. |
|
Route extension detection through configurable strategies. |
|
Router based on a lookup mapping. |
|
Route through strategies in priority order, short-circuiting on first match. |
|
Protocol for routing strategies. |
- class aw.routing.ConditionalRouter(strategies=list(), short_circuit=None)[source]¶
Bases:
PriorityRouterRouter with short-circuit conditions.
Only accepts results that match the short-circuit condition, otherwise continues to next strategy.
>>> def try_url(x): return x.get('url_ext') >>> def try_type(x): return x.get('content_type_ext') >>> >>> # Only accept .pdf or .md, otherwise keep trying >>> router = ConditionalRouter( ... [try_url, try_type], ... short_circuit=lambda r: r in {'.pdf', '.md'} ... ) >>> >>> # .pdf matches short-circuit, return immediately >>> router({'url_ext': '.pdf', 'content_type_ext': '.html'}) '.pdf' >>> >>> # .jpg doesn't match, try next strategy, .md matches >>> router({'url_ext': '.jpg', 'content_type_ext': '.md'}) '.md'
- class aw.routing.ConfidentRetrievalStrategy(search, floor=0.0, gap=0.0, rel_gap=None, require_boundary=True, dedup_key=None)[source]¶
Bases:
objectA routing strategy backed by a ranked search: answer only when the ranking is clear.
search(context)returns(candidate, score)pairs, best first (any retrieval engine:ir.discover, a BM25 index, a dict lookup). The strategy returns the top candidate when its score reachesfloorand beats the runner-up bygap(absolute) or keeps it at or belowrel_gaptimes its own score (relative); otherwise it returnsNoneso aPriorityRoutercan fall through to the next, more expensive, strategy (an LLM adjudicator, a human). That is the “cheap-first, escalate on ambiguity” shape: no model in the hot path for the clear cases, abstention rather than a guess for the close ones.Until a boundary is configured the strategy abstains (
require_boundary): an uncalibrated search must not route. Setfloor,gaporrel_gap, or passrequire_boundary=Falseto take the top candidate of any ranking.dedup_keycollapses copies of one candidate ('name@base'records of the same skill) to the best-scoring one before the gap test, so twins cannot tie.>>> ranked = {'open an issue': [('ge-write-issue', 0.9), ('ge', 0.4)], ... 'do the thing': [('a', 0.5), ('b', 0.48)], ... 'nothing': []} >>> route = ConfidentRetrievalStrategy(search=ranked.get, floor=0.3, gap=0.1) >>> route('open an issue') 'ge-write-issue' >>> route('do the thing') is None # too close to call: escalate True >>> route('nothing') is None True >>> router = PriorityRouter([route, lambda q: 'ask-the-llm']) >>> router('do the thing') 'ask-the-llm'
explaintells a caller why a query fell through, for calibration logs:>>> route.explain('do the thing') 'ambiguous: a=0.5 over b=0.48 is below gap 0.1' >>> ConfidentRetrievalStrategy(search=ranked.get).explain('open an issue') 'abstained: no boundary configured (set floor, gap or rel_gap)' >>> copies = lambda q: [('x@a', 10.0), ('x@b', 10.0), ('y', 7.0)] >>> ConfidentRetrievalStrategy(search=copies, rel_gap=0.9, dedup_key=lambda c: c.split('@')[0])('q') 'x@a'
- class aw.routing.ExtensionContext(url, content=b'', content_type='', explicit_extension=None)[source]¶
Bases:
objectContext for extension detection.
>>> ctx = ExtensionContext( ... url='https://example.com/file.pdf', ... content=b'%PDF-1.5', ... content_type='text/html' ... ) >>> ctx.url 'https://example.com/file.pdf'
- class aw.routing.ExtensionRouter(priority_extensions=<factory>, content_type_map=<factory>, magic_bytes_map=<factory>)[source]¶
Bases:
objectRoute extension detection through configurable strategies.
This router implements the default logic for detecting file extensions, but every component is visible and customizable.
Examples
>>> # Use with defaults >>> router = ExtensionRouter() >>> ctx = ExtensionContext('https://example.com/file.pdf', b'%PDF-1.5') >>> router(ctx) '.pdf' >>> >>> # URL without extension, falls back to magic bytes >>> ctx = ExtensionContext('https://example.com/download', b'%PDF-1.5') >>> router(ctx) '.pdf' >>> >>> # Priority extensions short-circuit >>> ctx = ExtensionContext('https://example.com/file.pdf', b'<html>') >>> router(ctx) # .pdf from URL wins even though content is HTML '.pdf' >>> >>> # Customize content type mapping >>> router.content_type_map['.txt'] = 'text/x-log' >>> >>> # Add custom detector >>> def my_detector(ctx): return '.custom' if 'special' in ctx.url else None >>> router = router.with_prepended_strategy(my_detector)
- with_appended_strategy(strategy)[source]¶
Create new router with added strategy at lowest priority.
- Return type:
- class aw.routing.MappingRouter(mapping=dict(), default=None, key_transform=None)[source]¶
Bases:
objectRouter based on a lookup mapping.
Provides a clean interface for switch-case style routing with:
Visible, mutable mapping
Optional default value or factory
Easy extension via dict interface
>>> # Content-Type to extension mapping >>> ct_map = { ... 'application/pdf': '.pdf', ... 'text/html': '.html', ... 'application/json': '.json', ... } >>> router = MappingRouter(ct_map) >>> >>> router('application/pdf') '.pdf' >>> router('text/plain') is None # No default True >>> >>> # With default >>> router_with_default = MappingRouter(ct_map, default='.bin') >>> router_with_default('text/plain') '.bin'
- class aw.routing.PriorityRouter(strategies=list())[source]¶
Bases:
objectRoute through strategies in priority order, short-circuiting on first match.
This is a simpler, more specialized version of i2.routing_forest that’s optimized for the common case of “try these in order, stop at first success”.
>>> def try_a(x): return 'A' if x > 10 else None >>> def try_b(x): return 'B' if x > 5 else None >>> def try_c(x): return 'C' >>> >>> router = PriorityRouter([try_a, try_b, try_c]) >>> router(15) 'A' >>> router(8) 'B' >>> router(3) 'C'
- class aw.routing.RoutingStrategy(*args, **kwargs)[source]¶
Bases:
ProtocolProtocol for routing strategies.
A routing strategy takes a context and returns a result or None.
- aw.routing.detect_explicit(ctx)[source]¶
Use explicit extension if provided.
>>> ctx = ExtensionContext('', explicit_extension='pdf') >>> detect_explicit(ctx) '.pdf' >>> ctx = ExtensionContext('', explicit_extension='.json') >>> detect_explicit(ctx) '.json'
- aw.routing.detect_from_url(ctx)[source]¶
Extract extension from URL path.
>>> ctx = ExtensionContext('https://example.com/file.pdf') >>> detect_from_url(ctx) '.pdf' >>> ctx = ExtensionContext('https://example.com/file') >>> detect_from_url(ctx) is None True
- aw.routing.make_content_type_detector(content_type_map=None)[source]¶
Factory for content-type based detection.
Returns a detector function with the given mapping. Users can create custom detectors with different mappings.
>>> # Use default mapping >>> detector = make_content_type_detector() >>> ctx = ExtensionContext('', content_type='application/pdf') >>> detector(ctx) '.pdf' >>> >>> # Custom mapping >>> custom_map = {'text/plain': '.log'} >>> custom_detector = make_content_type_detector(custom_map) >>> ctx = ExtensionContext('', content_type='text/plain') >>> custom_detector(ctx) '.log'
- Return type:
- aw.routing.make_magic_bytes_detector(magic_bytes_map=None)[source]¶
Factory for magic bytes based detection.
>>> detector = make_magic_bytes_detector() >>> ctx = ExtensionContext('', content=b'%PDF-1.5...') >>> detector(ctx) '.pdf' >>> ctx = ExtensionContext('', content=b'<html>...') >>> detector(ctx) '.html'
- Return type: