intent-router 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- intent_router/__init__.py +87 -0
- intent_router/adapters.py +38 -0
- intent_router/cli.py +144 -0
- intent_router/config.py +279 -0
- intent_router/embedders/__init__.py +73 -0
- intent_router/embedders/artifacts.py +168 -0
- intent_router/embedders/base.py +67 -0
- intent_router/embedders/http.py +153 -0
- intent_router/embedders/onnx.py +120 -0
- intent_router/errors.py +62 -0
- intent_router/models.py +50 -0
- intent_router/py.typed +1 -0
- intent_router/router.py +499 -0
- intent_router/storage.py +404 -0
- intent_router/vectors.py +62 -0
- intent_router-0.2.0.dist-info/METADATA +223 -0
- intent_router-0.2.0.dist-info/RECORD +20 -0
- intent_router-0.2.0.dist-info/WHEEL +4 -0
- intent_router-0.2.0.dist-info/entry_points.txt +2 -0
- intent_router-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Configuration-driven hybrid SQLite RAG intent router for AI agent tool selection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .adapters import extract_tool_name
|
|
6
|
+
from .config import (
|
|
7
|
+
EmbedderConfig,
|
|
8
|
+
RetrievalMode,
|
|
9
|
+
RouterConfig,
|
|
10
|
+
RoutingConfig,
|
|
11
|
+
StorageConfig,
|
|
12
|
+
ToolDefinition,
|
|
13
|
+
export_json_schema,
|
|
14
|
+
load_config,
|
|
15
|
+
load_config_dict,
|
|
16
|
+
)
|
|
17
|
+
from .embedders import (
|
|
18
|
+
EMBEDDING_REVISION,
|
|
19
|
+
MULTILINGUAL_E5_SMALL_ARTIFACTS,
|
|
20
|
+
CallableEmbedder,
|
|
21
|
+
Embedder,
|
|
22
|
+
ModelArtifact,
|
|
23
|
+
OllamaEmbedder,
|
|
24
|
+
OnnxE5Embedder,
|
|
25
|
+
OpenAICompatibleEmbedder,
|
|
26
|
+
create_embedder,
|
|
27
|
+
provision_models,
|
|
28
|
+
verify_artifact,
|
|
29
|
+
verify_models,
|
|
30
|
+
)
|
|
31
|
+
from .errors import (
|
|
32
|
+
ArtifactError,
|
|
33
|
+
ConfigError,
|
|
34
|
+
EmbedderError,
|
|
35
|
+
IntentRouterError,
|
|
36
|
+
RouterNotReadyError,
|
|
37
|
+
StorageError,
|
|
38
|
+
)
|
|
39
|
+
from .models import MatchedAnchor, RoutingResult, ToolScore
|
|
40
|
+
from .router import IntentRouter
|
|
41
|
+
from .storage import IndexedAnchor, SQLiteToolStore, StoredTool
|
|
42
|
+
from .vectors import cosine_similarity, pack_vector, unit_vector, unpack_vector
|
|
43
|
+
|
|
44
|
+
__version__ = "0.2.0"
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"EMBEDDING_REVISION",
|
|
48
|
+
"MULTILINGUAL_E5_SMALL_ARTIFACTS",
|
|
49
|
+
"ArtifactError",
|
|
50
|
+
"CallableEmbedder",
|
|
51
|
+
"ConfigError",
|
|
52
|
+
"Embedder",
|
|
53
|
+
"EmbedderConfig",
|
|
54
|
+
"EmbedderError",
|
|
55
|
+
"IndexedAnchor",
|
|
56
|
+
"IntentRouter",
|
|
57
|
+
"IntentRouterError",
|
|
58
|
+
"MatchedAnchor",
|
|
59
|
+
"ModelArtifact",
|
|
60
|
+
"OllamaEmbedder",
|
|
61
|
+
"OnnxE5Embedder",
|
|
62
|
+
"OpenAICompatibleEmbedder",
|
|
63
|
+
"RetrievalMode",
|
|
64
|
+
"RouterConfig",
|
|
65
|
+
"RouterNotReadyError",
|
|
66
|
+
"RoutingConfig",
|
|
67
|
+
"RoutingResult",
|
|
68
|
+
"SQLiteToolStore",
|
|
69
|
+
"StorageConfig",
|
|
70
|
+
"StorageError",
|
|
71
|
+
"StoredTool",
|
|
72
|
+
"ToolDefinition",
|
|
73
|
+
"ToolScore",
|
|
74
|
+
"__version__",
|
|
75
|
+
"cosine_similarity",
|
|
76
|
+
"create_embedder",
|
|
77
|
+
"export_json_schema",
|
|
78
|
+
"extract_tool_name",
|
|
79
|
+
"load_config",
|
|
80
|
+
"load_config_dict",
|
|
81
|
+
"pack_vector",
|
|
82
|
+
"provision_models",
|
|
83
|
+
"unit_vector",
|
|
84
|
+
"unpack_vector",
|
|
85
|
+
"verify_artifact",
|
|
86
|
+
"verify_models",
|
|
87
|
+
]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Framework-agnostic tool name extraction helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def extract_tool_name(tool: Any) -> str:
|
|
10
|
+
"""Extract a tool identifier/name from callables, OpenAI/Anthropic dicts, or objects."""
|
|
11
|
+
if isinstance(tool, str):
|
|
12
|
+
name = tool.strip()
|
|
13
|
+
if name:
|
|
14
|
+
return name
|
|
15
|
+
raise TypeError("Tool string name must not be empty.")
|
|
16
|
+
|
|
17
|
+
if isinstance(tool, Mapping):
|
|
18
|
+
# OpenAI function tool schema: {"type": "function", "function": {"name": "..."}}
|
|
19
|
+
fn_block = tool.get("function")
|
|
20
|
+
if isinstance(fn_block, Mapping):
|
|
21
|
+
fn_name = fn_block.get("name")
|
|
22
|
+
if isinstance(fn_name, str) and fn_name.strip():
|
|
23
|
+
return fn_name.strip()
|
|
24
|
+
|
|
25
|
+
# Flat tool schema (Anthropic, MCP JSON, custom dict)
|
|
26
|
+
for field in ("name", "id"):
|
|
27
|
+
value = tool.get(field)
|
|
28
|
+
if isinstance(value, str) and value.strip():
|
|
29
|
+
return value.strip()
|
|
30
|
+
|
|
31
|
+
raise TypeError(f"Could not extract tool name from mapping keys: {list(tool.keys())}")
|
|
32
|
+
|
|
33
|
+
for attr in ("name", "id", "__name__"):
|
|
34
|
+
value = getattr(tool, attr, None)
|
|
35
|
+
if isinstance(value, str) and value.strip():
|
|
36
|
+
return value.strip()
|
|
37
|
+
|
|
38
|
+
raise TypeError(f"Unsupported tool object of type {type(tool).__name__}: missing name/id/__name__.")
|
intent_router/cli.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Command-line interface for intent-router-py."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
|
|
10
|
+
from .config import RetrievalMode, export_json_schema, load_config
|
|
11
|
+
from .embedders import provision_models, verify_models
|
|
12
|
+
from .errors import IntentRouterError
|
|
13
|
+
from .router import IntentRouter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
prog="intent-router",
|
|
19
|
+
description="Configuration-driven hybrid SQLite RAG intent router CLI.",
|
|
20
|
+
)
|
|
21
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
22
|
+
|
|
23
|
+
validate_cmd = sub.add_parser("validate", help="Validate a router configuration file.")
|
|
24
|
+
validate_cmd.add_argument("config", help="Path to YAML, JSON, or TOML config file.")
|
|
25
|
+
|
|
26
|
+
index_cmd = sub.add_parser("index", help="Build or sync the SQLite RAG tool index.")
|
|
27
|
+
index_cmd.add_argument("config", help="Path to YAML, JSON, or TOML config file.")
|
|
28
|
+
index_cmd.add_argument("--force", action="store_true", help="Force re-indexing even on cache hit.")
|
|
29
|
+
|
|
30
|
+
route_cmd = sub.add_parser("route", help="Route a query against a configured router.")
|
|
31
|
+
route_cmd.add_argument("config", help="Path to YAML, JSON, or TOML config file.")
|
|
32
|
+
route_cmd.add_argument("query", help="Natural-language query to route.")
|
|
33
|
+
route_cmd.add_argument("--top-k", type=int, default=None, help="Maximum tools to select.")
|
|
34
|
+
route_cmd.add_argument("--threshold", type=float, default=None, help="Minimum score threshold.")
|
|
35
|
+
route_cmd.add_argument(
|
|
36
|
+
"--mode",
|
|
37
|
+
choices=[m.value for m in RetrievalMode],
|
|
38
|
+
default=None,
|
|
39
|
+
help="Override retrieval mode.",
|
|
40
|
+
)
|
|
41
|
+
route_cmd.add_argument(
|
|
42
|
+
"--tags",
|
|
43
|
+
default=None,
|
|
44
|
+
help="Comma-separated tag filter.",
|
|
45
|
+
)
|
|
46
|
+
route_cmd.add_argument(
|
|
47
|
+
"--locale",
|
|
48
|
+
default=None,
|
|
49
|
+
help="Optional anchor locale filter (e.g. en, cs).",
|
|
50
|
+
)
|
|
51
|
+
route_cmd.add_argument("--json", action="store_true", dest="as_json", help="Print JSON output.")
|
|
52
|
+
|
|
53
|
+
sub.add_parser("schema", help="Export the JSON Schema for RouterConfig.")
|
|
54
|
+
|
|
55
|
+
prov_cmd = sub.add_parser(
|
|
56
|
+
"provision-models",
|
|
57
|
+
help="Download and verify pinned Xenova/multilingual-e5-small ONNX artifacts.",
|
|
58
|
+
)
|
|
59
|
+
prov_cmd.add_argument("--dir", default="./models", help="Target models directory.")
|
|
60
|
+
|
|
61
|
+
verify_cmd = sub.add_parser(
|
|
62
|
+
"verify-models",
|
|
63
|
+
help="Verify SHA-256 checksums for pinned ONNX artifacts.",
|
|
64
|
+
)
|
|
65
|
+
verify_cmd.add_argument("--dir", default="./models", help="Models directory to verify.")
|
|
66
|
+
|
|
67
|
+
return parser
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
71
|
+
"""Entry point for the ``intent-router`` CLI."""
|
|
72
|
+
parser = _build_parser()
|
|
73
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
if args.command == "validate":
|
|
77
|
+
config = load_config(args.config)
|
|
78
|
+
enabled = config.enabled_tools()
|
|
79
|
+
print(
|
|
80
|
+
f"Valid configuration: {len(enabled)} enabled tools "
|
|
81
|
+
f"({len(config.tools)} total), mode={config.routing.mode.value}, "
|
|
82
|
+
f"fingerprint={config.fingerprint()[:12]}"
|
|
83
|
+
)
|
|
84
|
+
return 0
|
|
85
|
+
|
|
86
|
+
if args.command == "index":
|
|
87
|
+
with IntentRouter.from_config(args.config) as router:
|
|
88
|
+
rebuilt = router.warm(force=args.force)
|
|
89
|
+
status = "re-indexed" if rebuilt else "cache-hit"
|
|
90
|
+
print(
|
|
91
|
+
f"Index ready ({status}): storage={router.store.path}, "
|
|
92
|
+
f"cache_key={router.cache_key[:12]}"
|
|
93
|
+
)
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
if args.command == "route":
|
|
97
|
+
tags = [t.strip() for t in args.tags.split(",") if t.strip()] if args.tags else None
|
|
98
|
+
config = load_config(args.config)
|
|
99
|
+
if args.mode is not None:
|
|
100
|
+
config.routing.mode = RetrievalMode(args.mode)
|
|
101
|
+
if config.routing.mode == RetrievalMode.LEXICAL:
|
|
102
|
+
config.embedder.provider = "none"
|
|
103
|
+
with IntentRouter(config) as router:
|
|
104
|
+
router.warm()
|
|
105
|
+
result = router.route(
|
|
106
|
+
args.query,
|
|
107
|
+
top_k=args.top_k,
|
|
108
|
+
threshold=args.threshold,
|
|
109
|
+
mode=args.mode,
|
|
110
|
+
tags=tags,
|
|
111
|
+
locale=args.locale,
|
|
112
|
+
)
|
|
113
|
+
if args.as_json:
|
|
114
|
+
print(result.model_dump_json(indent=2))
|
|
115
|
+
else:
|
|
116
|
+
if not result.tools:
|
|
117
|
+
print("No tools matched threshold.")
|
|
118
|
+
for idx, tool in enumerate(result.tools, start=1):
|
|
119
|
+
flag = " [always]" if tool.always_included else ""
|
|
120
|
+
print(f"{idx}. {tool.tool_id} (score={tool.score:.4f}){flag}")
|
|
121
|
+
return 0
|
|
122
|
+
|
|
123
|
+
if args.command == "schema":
|
|
124
|
+
print(json.dumps(export_json_schema(), indent=2))
|
|
125
|
+
return 0
|
|
126
|
+
|
|
127
|
+
if args.command == "provision-models":
|
|
128
|
+
paths = provision_models(args.dir)
|
|
129
|
+
print(f"Provisioned and verified {len(paths)} artifacts in {args.dir}.")
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
if args.command == "verify-models":
|
|
133
|
+
verify_models(args.dir)
|
|
134
|
+
print(f"All pinned model checksums match in {args.dir}.")
|
|
135
|
+
return 0
|
|
136
|
+
|
|
137
|
+
return 1
|
|
138
|
+
except IntentRouterError as exc:
|
|
139
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
140
|
+
return 2
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
raise SystemExit(main())
|
intent_router/config.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Configuration models and YAML/JSON/TOML loaders for intent-router-py."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import tomllib
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from enum import StrEnum
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
15
|
+
|
|
16
|
+
from .errors import ConfigError
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RetrievalMode(StrEnum):
|
|
20
|
+
"""Supported retrieval strategies for tool routing."""
|
|
21
|
+
|
|
22
|
+
HYBRID = "hybrid"
|
|
23
|
+
SEMANTIC = "semantic"
|
|
24
|
+
LEXICAL = "lexical"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ToolDefinition(BaseModel):
|
|
28
|
+
"""Declarative definition of a routable tool and its intent anchors."""
|
|
29
|
+
|
|
30
|
+
model_config = ConfigDict(extra="forbid")
|
|
31
|
+
|
|
32
|
+
id: str = Field(..., min_length=1, description="Unique identifier of the tool.")
|
|
33
|
+
name: str | None = Field(
|
|
34
|
+
default=None,
|
|
35
|
+
description="Optional display or callable name; defaults to id.",
|
|
36
|
+
)
|
|
37
|
+
description: str = Field(..., min_length=1, description="Human-readable tool description.")
|
|
38
|
+
anchors: dict[str, list[str]] | list[str] = Field(
|
|
39
|
+
default_factory=dict,
|
|
40
|
+
description="Representative user utterances (flat list or locale-keyed mapping).",
|
|
41
|
+
)
|
|
42
|
+
tags: list[str] = Field(default_factory=list, description="Optional tags for filtering.")
|
|
43
|
+
always_include: bool = Field(
|
|
44
|
+
default=False,
|
|
45
|
+
description="If true, include this tool even when its score is below threshold.",
|
|
46
|
+
)
|
|
47
|
+
enabled: bool = Field(default=True, description="Whether this tool participates in routing.")
|
|
48
|
+
metadata: dict[str, Any] = Field(
|
|
49
|
+
default_factory=dict,
|
|
50
|
+
description="Arbitrary metadata returned with routing results.",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@field_validator("id", "description")
|
|
54
|
+
@classmethod
|
|
55
|
+
def _strip_required(cls, value: str) -> str:
|
|
56
|
+
stripped = value.strip()
|
|
57
|
+
if not stripped:
|
|
58
|
+
raise ValueError("Value must not be empty or whitespace.")
|
|
59
|
+
return stripped
|
|
60
|
+
|
|
61
|
+
@field_validator("name")
|
|
62
|
+
@classmethod
|
|
63
|
+
def _strip_optional_name(cls, value: str | None) -> str | None:
|
|
64
|
+
if value is None:
|
|
65
|
+
return None
|
|
66
|
+
stripped = value.strip()
|
|
67
|
+
return stripped or None
|
|
68
|
+
|
|
69
|
+
@field_validator("tags")
|
|
70
|
+
@classmethod
|
|
71
|
+
def _normalize_tags(cls, value: list[str]) -> list[str]:
|
|
72
|
+
seen: set[str] = set()
|
|
73
|
+
result: list[str] = []
|
|
74
|
+
for item in value:
|
|
75
|
+
cleaned = item.strip()
|
|
76
|
+
if cleaned and cleaned not in seen:
|
|
77
|
+
seen.add(cleaned)
|
|
78
|
+
result.append(cleaned)
|
|
79
|
+
return result
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def display_name(self) -> str:
|
|
83
|
+
"""Return the tool name, falling back to its id."""
|
|
84
|
+
return self.name or self.id
|
|
85
|
+
|
|
86
|
+
def iter_anchors(self, *, include_description: bool = True) -> list[tuple[str, str, str]]:
|
|
87
|
+
"""Return deduplicated ``(locale, kind, text)`` tuples for indexing."""
|
|
88
|
+
collected: list[tuple[str, str, str]] = []
|
|
89
|
+
seen: set[tuple[str, str, str]] = set()
|
|
90
|
+
|
|
91
|
+
def _add(locale: str, kind: str, raw_text: str) -> None:
|
|
92
|
+
text = raw_text.strip()
|
|
93
|
+
if not text:
|
|
94
|
+
return
|
|
95
|
+
item = (locale, kind, text)
|
|
96
|
+
if item not in seen:
|
|
97
|
+
seen.add(item)
|
|
98
|
+
collected.append(item)
|
|
99
|
+
|
|
100
|
+
if isinstance(self.anchors, list):
|
|
101
|
+
for text in self.anchors:
|
|
102
|
+
_add("default", "anchor", text)
|
|
103
|
+
else:
|
|
104
|
+
for locale, texts in self.anchors.items():
|
|
105
|
+
loc = locale.strip() or "default"
|
|
106
|
+
for text in texts:
|
|
107
|
+
_add(loc, "anchor", text)
|
|
108
|
+
|
|
109
|
+
if include_description:
|
|
110
|
+
_add("default", "description", f"{self.display_name}: {self.description}")
|
|
111
|
+
|
|
112
|
+
return collected
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RoutingConfig(BaseModel):
|
|
116
|
+
"""Scoring, thresholding, and candidate cap settings."""
|
|
117
|
+
|
|
118
|
+
model_config = ConfigDict(extra="forbid")
|
|
119
|
+
|
|
120
|
+
mode: RetrievalMode = Field(default=RetrievalMode.HYBRID)
|
|
121
|
+
threshold: float = Field(default=0.45, ge=0.0, lt=1.0)
|
|
122
|
+
max_tools: int = Field(default=5, ge=1, le=100)
|
|
123
|
+
min_tools: int = Field(default=0, ge=0, le=100)
|
|
124
|
+
semantic_weight: float = Field(default=0.7, ge=0.0, le=1.0)
|
|
125
|
+
lexical_weight: float = Field(default=0.3, ge=0.0, le=1.0)
|
|
126
|
+
include_description_as_anchor: bool = Field(default=True)
|
|
127
|
+
query_prefix: str = Field(default="query: ")
|
|
128
|
+
anchor_prefix: str = Field(default="query: ")
|
|
129
|
+
|
|
130
|
+
@model_validator(mode="after")
|
|
131
|
+
def _validate_bounds(self) -> RoutingConfig:
|
|
132
|
+
if self.min_tools > self.max_tools:
|
|
133
|
+
raise ValueError("min_tools cannot be greater than max_tools.")
|
|
134
|
+
if self.mode == RetrievalMode.HYBRID and (self.semantic_weight + self.lexical_weight) <= 0.0:
|
|
135
|
+
raise ValueError("Hybrid mode requires semantic_weight + lexical_weight > 0.")
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class StorageConfig(BaseModel):
|
|
140
|
+
"""SQLite RAG storage settings."""
|
|
141
|
+
|
|
142
|
+
model_config = ConfigDict(extra="forbid")
|
|
143
|
+
|
|
144
|
+
path: str = Field(default=":memory:")
|
|
145
|
+
auto_sync: bool = Field(default=True)
|
|
146
|
+
wal_mode: bool = Field(default=True)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class EmbedderConfig(BaseModel):
|
|
150
|
+
"""Embedding backend configuration."""
|
|
151
|
+
|
|
152
|
+
model_config = ConfigDict(extra="forbid")
|
|
153
|
+
|
|
154
|
+
provider: Literal["onnx", "openai", "ollama", "none", "custom"] = Field(default="none")
|
|
155
|
+
model: str | None = Field(default=None)
|
|
156
|
+
model_dir: str | None = Field(default=None)
|
|
157
|
+
base_url: str | None = Field(default=None)
|
|
158
|
+
api_key_env: str | None = Field(default=None)
|
|
159
|
+
dimension: int | None = Field(default=None, ge=1)
|
|
160
|
+
max_tokens: int = Field(default=512, ge=1)
|
|
161
|
+
timeout_seconds: float = Field(default=30.0, gt=0.0)
|
|
162
|
+
threads: int = Field(default=1, ge=1)
|
|
163
|
+
verify_checksums: bool = Field(default=True)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class RouterConfig(BaseModel):
|
|
167
|
+
"""Top-level configuration object defining tools, storage, embedder, and routing rules."""
|
|
168
|
+
|
|
169
|
+
model_config = ConfigDict(extra="forbid")
|
|
170
|
+
|
|
171
|
+
version: str = Field(default="1")
|
|
172
|
+
routing: RoutingConfig = Field(default_factory=RoutingConfig)
|
|
173
|
+
storage: StorageConfig = Field(default_factory=StorageConfig)
|
|
174
|
+
embedder: EmbedderConfig = Field(default_factory=EmbedderConfig)
|
|
175
|
+
tools: list[ToolDefinition] = Field(..., min_length=1)
|
|
176
|
+
|
|
177
|
+
@model_validator(mode="after")
|
|
178
|
+
def _validate_unique_tool_ids(self) -> RouterConfig:
|
|
179
|
+
seen: set[str] = set()
|
|
180
|
+
duplicates: list[str] = []
|
|
181
|
+
for tool in self.tools:
|
|
182
|
+
if tool.id in seen:
|
|
183
|
+
duplicates.append(tool.id)
|
|
184
|
+
seen.add(tool.id)
|
|
185
|
+
if duplicates:
|
|
186
|
+
raise ValueError(f"Duplicate tool ids found: {', '.join(sorted(set(duplicates)))}")
|
|
187
|
+
return self
|
|
188
|
+
|
|
189
|
+
def enabled_tools(self) -> list[ToolDefinition]:
|
|
190
|
+
"""Return only enabled tool definitions in declaration order."""
|
|
191
|
+
return [tool for tool in self.tools if tool.enabled]
|
|
192
|
+
|
|
193
|
+
def fingerprint(self, embedder_id: str | None = None) -> str:
|
|
194
|
+
"""Compute a deterministic SHA-256 fingerprint for index cache validation."""
|
|
195
|
+
payload = {
|
|
196
|
+
"version": self.version,
|
|
197
|
+
"embedder_id": embedder_id,
|
|
198
|
+
"anchor_prefix": self.routing.anchor_prefix,
|
|
199
|
+
"include_description_as_anchor": self.routing.include_description_as_anchor,
|
|
200
|
+
"tools": [
|
|
201
|
+
{
|
|
202
|
+
"id": tool.id,
|
|
203
|
+
"name": tool.display_name,
|
|
204
|
+
"description": tool.description,
|
|
205
|
+
"tags": tool.tags,
|
|
206
|
+
"always_include": tool.always_include,
|
|
207
|
+
"metadata": tool.metadata,
|
|
208
|
+
"anchors": tool.iter_anchors(
|
|
209
|
+
include_description=self.routing.include_description_as_anchor
|
|
210
|
+
),
|
|
211
|
+
}
|
|
212
|
+
for tool in sorted(self.enabled_tools(), key=lambda t: t.id)
|
|
213
|
+
],
|
|
214
|
+
}
|
|
215
|
+
canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
|
216
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def load_config_dict(data: Mapping[str, Any]) -> RouterConfig:
|
|
220
|
+
"""Validate an in-memory mapping into a ``RouterConfig``."""
|
|
221
|
+
try:
|
|
222
|
+
return RouterConfig.model_validate(dict(data))
|
|
223
|
+
except ValidationError as exc:
|
|
224
|
+
raise ConfigError(f"Configuration validation failed: {exc}") from exc
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def load_config(path: str | Path) -> RouterConfig:
|
|
228
|
+
"""Load and validate a YAML, JSON, or TOML router configuration file."""
|
|
229
|
+
config_path = Path(path).expanduser()
|
|
230
|
+
if not config_path.exists():
|
|
231
|
+
raise ConfigError(f"Configuration file not found: {config_path}", code="CONFIG_NOT_FOUND")
|
|
232
|
+
if not config_path.is_file():
|
|
233
|
+
raise ConfigError(f"Configuration path is not a file: {config_path}", code="CONFIG_INVALID")
|
|
234
|
+
|
|
235
|
+
resolved_path = config_path.resolve()
|
|
236
|
+
base_dir = resolved_path.parent
|
|
237
|
+
suffix = resolved_path.suffix.lower()
|
|
238
|
+
|
|
239
|
+
try:
|
|
240
|
+
raw_text = resolved_path.read_text(encoding="utf-8")
|
|
241
|
+
except OSError as exc:
|
|
242
|
+
raise ConfigError(f"Failed to read configuration file {resolved_path}: {exc}") from exc
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
if suffix in {".yaml", ".yml"}:
|
|
246
|
+
parsed = yaml.safe_load(raw_text)
|
|
247
|
+
elif suffix == ".json":
|
|
248
|
+
parsed = json.loads(raw_text)
|
|
249
|
+
elif suffix == ".toml":
|
|
250
|
+
parsed = tomllib.loads(raw_text)
|
|
251
|
+
else:
|
|
252
|
+
raise ConfigError(
|
|
253
|
+
f"Unsupported config format '{suffix}'. Use .yaml, .yml, .json, or .toml."
|
|
254
|
+
)
|
|
255
|
+
except (yaml.YAMLError, json.JSONDecodeError, tomllib.TOMLDecodeError) as exc:
|
|
256
|
+
raise ConfigError(f"Failed to parse {resolved_path.name}: {exc}") from exc
|
|
257
|
+
|
|
258
|
+
if not isinstance(parsed, Mapping):
|
|
259
|
+
raise ConfigError("Top-level configuration must be a mapping/object.")
|
|
260
|
+
|
|
261
|
+
config = load_config_dict(parsed)
|
|
262
|
+
|
|
263
|
+
# Resolve relative filesystem paths relative to the config file directory.
|
|
264
|
+
if config.storage.path != ":memory:":
|
|
265
|
+
storage_path = Path(config.storage.path).expanduser()
|
|
266
|
+
if not storage_path.is_absolute():
|
|
267
|
+
config.storage.path = str((base_dir / storage_path).resolve())
|
|
268
|
+
|
|
269
|
+
if config.embedder.model_dir is not None:
|
|
270
|
+
model_dir = Path(config.embedder.model_dir).expanduser()
|
|
271
|
+
if not model_dir.is_absolute():
|
|
272
|
+
config.embedder.model_dir = str((base_dir / model_dir).resolve())
|
|
273
|
+
|
|
274
|
+
return config
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def export_json_schema() -> dict[str, Any]:
|
|
278
|
+
"""Return the JSON Schema dictionary for ``RouterConfig``."""
|
|
279
|
+
return RouterConfig.model_json_schema()
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Embedder abstractions, factories, and pinned artifact utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ..config import EmbedderConfig
|
|
6
|
+
from ..errors import ConfigError
|
|
7
|
+
from .artifacts import (
|
|
8
|
+
EMBEDDING_REVISION,
|
|
9
|
+
MULTILINGUAL_E5_SMALL_ARTIFACTS,
|
|
10
|
+
ModelArtifact,
|
|
11
|
+
provision_models,
|
|
12
|
+
verify_artifact,
|
|
13
|
+
verify_models,
|
|
14
|
+
)
|
|
15
|
+
from .base import CallableEmbedder, Embedder
|
|
16
|
+
from .http import OllamaEmbedder, OpenAICompatibleEmbedder
|
|
17
|
+
from .onnx import OnnxE5Embedder
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def create_embedder(config: EmbedderConfig) -> Embedder | None:
|
|
21
|
+
"""Instantiate an ``Embedder`` from an ``EmbedderConfig``."""
|
|
22
|
+
if config.provider in {"none", "custom"}:
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
if config.provider == "onnx":
|
|
26
|
+
if not config.model_dir:
|
|
27
|
+
raise ConfigError("embedder.model_dir is required when embedder.provider is 'onnx'.")
|
|
28
|
+
return OnnxE5Embedder(
|
|
29
|
+
model_dir=config.model_dir,
|
|
30
|
+
verify_checksums=config.verify_checksums,
|
|
31
|
+
max_tokens=config.max_tokens,
|
|
32
|
+
threads=config.threads,
|
|
33
|
+
dimension=config.dimension or 384,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
if config.provider == "openai":
|
|
37
|
+
if not config.model:
|
|
38
|
+
raise ConfigError("embedder.model is required when embedder.provider is 'openai'.")
|
|
39
|
+
return OpenAICompatibleEmbedder(
|
|
40
|
+
model=config.model,
|
|
41
|
+
base_url=config.base_url or "https://api.openai.com/v1",
|
|
42
|
+
api_key_env=config.api_key_env or "OPENAI_API_KEY",
|
|
43
|
+
dimension=config.dimension,
|
|
44
|
+
timeout_seconds=config.timeout_seconds,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if config.provider == "ollama":
|
|
48
|
+
if not config.model:
|
|
49
|
+
raise ConfigError("embedder.model is required when embedder.provider is 'ollama'.")
|
|
50
|
+
return OllamaEmbedder(
|
|
51
|
+
model=config.model,
|
|
52
|
+
base_url=config.base_url or "http://127.0.0.1:11434",
|
|
53
|
+
dimension=config.dimension,
|
|
54
|
+
timeout_seconds=config.timeout_seconds,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
raise ConfigError(f"Unsupported embedder provider: {config.provider}")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"EMBEDDING_REVISION",
|
|
62
|
+
"MULTILINGUAL_E5_SMALL_ARTIFACTS",
|
|
63
|
+
"CallableEmbedder",
|
|
64
|
+
"Embedder",
|
|
65
|
+
"ModelArtifact",
|
|
66
|
+
"OllamaEmbedder",
|
|
67
|
+
"OnnxE5Embedder",
|
|
68
|
+
"OpenAICompatibleEmbedder",
|
|
69
|
+
"create_embedder",
|
|
70
|
+
"provision_models",
|
|
71
|
+
"verify_artifact",
|
|
72
|
+
"verify_models",
|
|
73
|
+
]
|