diff --git a/docs/tiers.md b/docs/tiers.md index c2eb2c86..4babbb6c 100644 --- a/docs/tiers.md +++ b/docs/tiers.md @@ -85,6 +85,53 @@ cap also permits `resolver="fuzzy"` when explicitly selected. `max_tier="balanced"` guarantees no LLM or embedder call from the built-in tiers. A custom `extractor=`, resolver, or `reranker=` object is yours and is not capped. +## Model-backed tasks + +Set `llm_tasks` on `SelfGraph` in either SDK. Every task accepts an object with +optional `enabled` and `model` fields. The same JSON works with `--llm-tasks` +(inline or a JSON file) and `SELFGRAPH_LLM_TASKS` for CLI and MCP startup. + +```json +{ + "entities": {"model": "provider/extraction-model"}, + "preferences": {"enabled": false}, + "decisions": {"enabled": false}, + "resolution": {"enabled": true, "model": "provider/resolution-model"}, + "contradiction": {"enabled": true, "model": "provider/judge-model"}, + "seeds": {"enabled": true, "model": "provider/vector-model"} +} +``` + +Use the `provider/model` shorthand for `llm`, `embedder`, or a task's `model`. +Replace the placeholders with a provider and model installed and configured for +your SDK. Use a full LLM config object for explicit credentials or endpoint +settings. A task override uses its own connection settings. SDK callers can +also pass existing client objects or create a library-backed embedder with +`build_embedder` in Python or `buildEmbedder` in TypeScript. + +The extraction passes use `llm` as their fallback. On the LLM extraction tier +all four passes start enabled. Setting any pass to `enabled: true` selects LLM +extraction by default, so provide a model for each remaining enabled pass or +set the graph's `llm`. Configure custom extraction through `extractor`. + +Resolution and contradiction also fall back to the graph's `llm`. Seeding and +reranking fall back to `embedder`, with independent model overrides. For these +four tasks, `enabled: true` selects the model-backed tier by default. +Explicit tier selections still apply, subject to `max_tier`. Setting +`enabled: false` skips an extraction pass or limits that task to its built-in +balanced ceiling, even when a per-call option asks for its model-backed tier. + +| Task | SDK calls per operation | +|------|-------------------------| +| `entities`, `relations`, `preferences`, `decisions` | One per chunk per enabled pass. Disabling two yields two calls per chunk. At the default concurrency of four, two enabled passes allow up to eight calls in flight. | +| `resolution` | At most three per candidate by default, only for unresolved matches in the similarity band. An explicit resolver can set `max_questions`. | +| `contradiction` | At most one per new or changed relation with eligible rivals, and zero for unchanged relations. | +| `seeds` | One query embedding plus batches of up to 64 stale or uncached entity texts per scanned page. | +| `rerank` | One query embedding plus batches of up to 64 candidate context records whenever embedding reranking runs. | + +These counts apply per SDK attempt. The underlying libraries may retry +requests or split an embedding batch to meet a provider's limit. + ## Which tier ran `graph.tiers` holds the level, the cap, and each capability's effective default diff --git a/src/selfgraph/__init__.py b/src/selfgraph/__init__.py index 196a39d7..7f872dc0 100644 --- a/src/selfgraph/__init__.py +++ b/src/selfgraph/__init__.py @@ -32,7 +32,8 @@ StepOut, ) from .ids import decision_id, entity_id, normalize_rel_type, preference_id, profile_id, relation_id -from .llm import build_llm_client, build_provider +from .llm import build_embedder, build_llm_client, build_provider +from .llm.tasks import EmbeddingTask, LLMTask, LLMTasks from .models import ( AnswerabilityReport, Certification, @@ -259,7 +260,11 @@ def __dir__() -> list[str]: "DecisionsOut", "NERExtractor", "DEFAULT_PROMPTS", + "build_embedder", "build_llm_client", + "EmbeddingTask", + "LLMTask", + "LLMTasks", "entity_id", "relation_id", "preference_id", diff --git a/src/selfgraph/_install.py b/src/selfgraph/_install.py index 9401ed31..d9bc876b 100644 --- a/src/selfgraph/_install.py +++ b/src/selfgraph/_install.py @@ -88,7 +88,18 @@ def _secret(settings: Mapping[str, str]) -> str | None: @param settings (Mapping[str, str]): the settings given as flags. @return (str | None): its key, or None when none does. """ - return next((key for key, value in settings.items() if key in _SECRETS or mask_uri(value) != value), None) + for key, value in settings.items(): + if key in _SECRETS or mask_uri(value) != value: + return key + if key == "llm_tasks" and value.lstrip().startswith("{"): + tasks = parse_json(value, " in --llm-tasks", key) + for task in tasks.values(): + model = task.get("model") if isinstance(task, dict) else None + if isinstance(model, dict): + base = model.get("base_url") + if model.get("api_key") or (isinstance(base, str) and mask_uri(base) != base): + return key + return None def _skill_files() -> dict[str, str]: diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index e8a17d6d..05517405 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -785,9 +785,10 @@ def _add_globals(p: argparse.ArgumentParser, *, nested: bool = False, listed: bo ("--llm-model", {"help": "the model; a provider-prefixed one such as openai/gpt-4o-mini sets the provider"}), ("--llm-api-key", {}), ("--llm-api-key-env", {"help": "environment variable holding the LLM key"}), + ("--llm-tasks", {"help": "LLM task settings as inline JSON or a JSON file"}), ("--llm-base-url", {}), ("--llm-timeout", {"help": "seconds to wait for each LLM call (default 120)"}), - ("--llm-concurrency", {"help": "chunks to extract at once, each running four LLM calls (default 4)"}), + ("--llm-concurrency", {"help": "chunks to extract at once, each running the enabled LLM passes (default 4)"}), ("--schema", {"help": "schema JSON file applied to every insert, or inline JSON when it starts with '{'"}), ("--instructions", {"help": "extraction instructions JSON file, or inline JSON when it starts with '{'"}), ("--prompts", {"help": "extraction prompt templates JSON file, or inline JSON when it starts with '{'"}), diff --git a/src/selfgraph/client.py b/src/selfgraph/client.py index b59a553d..67d06465 100644 --- a/src/selfgraph/client.py +++ b/src/selfgraph/client.py @@ -34,7 +34,8 @@ from .extraction.prompts import check_prompts from .ids import _require_namespace, canonical_entity_id, decision_id, entity_id, type_name from .insert import Insert -from .llm.base import resolve_llm +from .llm.base import EmbedderArg, LLMArg, build_embedder, resolve_llm +from .llm.tasks import PASSES, LLMTasks, check_llm_tasks, resolved_passes, task_tier from .models import ( AnswerabilityReport, CitationReport, @@ -48,7 +49,6 @@ InsertResult, InsertWarning, JsonValue, - LLMConfig, NamespaceInfo, NeighborsResult, PathResult, @@ -59,7 +59,7 @@ as_input, check_options, ) -from .protocols import Embedder, Extractor, GraphStore, LLMClient, Provider, Reranker +from .protocols import Extractor, GraphStore, Provider, Reranker from .provenance import record_source from .resolution import ( EntityResolver, @@ -136,7 +136,8 @@ def __init__( self, store: GraphStore, *, - llm: LLMConfig | LLMClient | None = None, + llm: LLMArg | None = None, + llm_tasks: LLMTasks | None = None, instructions: ExtractionInstructions | Mapping[str, Any] | None = None, prompts: ExtractionPrompts | Mapping[str, Any] | None = None, extractor: Extractor | None = None, @@ -149,7 +150,7 @@ def __init__( max_tier: tiers.Level = "max", extraction: tiers.ExtractionTier | None = None, seeds: tiers.SeedTier | None = None, - embedder: Embedder | None = None, + embedder: EmbedderArg | None = None, rerank: tiers.RerankTier | None = None, reranker: Reranker | None = None, provider: Provider | None = None, @@ -160,6 +161,7 @@ def __init__( options, [ "llm", + "llm_tasks", "instructions", "prompts", "extractor", @@ -191,16 +193,15 @@ def __init__( llm = provider if embedder is None: embedder = provider - self._llm = resolve_llm(llm) - if level == "max" and max_tier == "max" and self._llm is None: + tasks = check_llm_tasks(llm_tasks) + self._llm_tasks = tasks + default_llm = resolve_llm(llm) + if level == "max" and max_tier == "max" and default_llm is None and not tasks: raise needs_llm("level 'max'") - if embedder is not None and not callable(getattr(embedder, "embed", None)): - raise ValidationError(f"embedder must have an embed method, got {type_name(embedder)}") if reranker is not None and not callable(getattr(reranker, "score", None)): raise ValidationError(f"reranker must have a score method, got {type_name(reranker)}") self._level: tiers.Level = level self._max_tier: tiers.Level = max_tier - self._embedder = embedder self._score_context = ( reranker.score if reranker is not None else provider.rerank if provider is not None else None ) @@ -209,24 +210,43 @@ def __init__( if extraction is not None: tiers.require_tier("extraction", extraction) elif extractor is None: - extraction = "llm" if self._llm is not None else preset["extraction"] + opted_in = default_llm is not None or any(tasks.get(name, {}).get("enabled") is True for name in PASSES) + extraction = "llm" if opted_in else preset["extraction"] self._extraction = None if extraction is None else tiers.clamp("extraction", extraction, max_tier) - if self._extraction == "llm" and self._llm is None: + self._llm = default_llm + self._passes = resolved_passes(tasks, default_llm) if self._extraction == "llm" and extractor is None else {} + if self._extraction == "llm" and extractor is not None and default_llm is None and not tasks: raise needs_llm("extraction 'llm'") + + shared_embedder = build_embedder(embedder) if embedder is not None and max_tier == "max" else None + self._embedder = self._task_model("seeds", build_embedder, shared_embedder) + self._rerank_embedder = self._task_model("rerank", build_embedder, shared_embedder) + self._judge_llm = self._task_model("contradiction", resolve_llm, default_llm) + self._resolver_llm = self._task_model("resolution", resolve_llm, default_llm) if seeds is None: - seeds = preset["seeds"] if embedder is not None or preset["seeds"] != "embeddings" else "synonyms" + seeds = self._task_default("seeds", preset["seeds"]) + if seeds == "embeddings" and self._embedder is None and tasks.get("seeds", {}).get("enabled") is not True: + seeds = "synonyms" self._seeds = self._seed_tier(seeds) self._strategy = preset["traversal"] if rerank is None and (reranker is not None or (provider is not None and max_tier == "max")): self._rerank = "custom" else: if rerank is None: - rerank = preset["rerank"] if embedder is not None or preset["rerank"] != "embeddings" else "lexical" + rerank = self._task_default("rerank", preset["rerank"]) + if ( + rerank == "embeddings" + and self._rerank_embedder is None + and tasks.get("rerank", {}).get("enabled") is not True + ): + rerank = "lexical" self._rerank = self._rerank_tier(rerank) - self._resolver_tier, self._resolver = self._resolver_for(preset["resolution"] if resolver is None else resolver) - self._contradiction: ContradictionMode = self._contradiction_tier( - preset["contradiction"] if contradiction is None else contradiction - ) + if resolver is None: + resolver = self._task_default("resolution", preset["resolution"]) + self._resolver_tier, self._resolver = self._resolver_for(resolver) + if contradiction is None: + contradiction = self._task_default("contradiction", preset["contradiction"]) + self._contradiction = self._contradiction_tier(contradiction) self._instructions = as_input(ExtractionInstructions, instructions, "instructions") self._prompts = as_input(ExtractionPrompts, prompts, "prompts") check_prompts(self._prompts) @@ -246,6 +266,26 @@ def __init__( self.content = self.insert self.code = Code(self) + def _task_model(self, name, resolve, fallback): + """Resolve the configured model for an available task. + + @param name (str): the task name. + @param resolve (Callable): the model adapter. + @param fallback (object): the graph-wide model. + @return (object | None): the task model. + """ + task = self._llm_tasks.get(name, {}) + if self._max_tier != "max" or task.get("enabled") is False: + return None + model = task.get("model") + return fallback if model is None else resolve(model) + + def _task_default(self, name: str, default: str) -> str: + return tiers.LADDERS[name][-1] if self._llm_tasks.get(name, {}).get("enabled") is True else default + + def _task_tier(self, name: str, requested: str) -> str: + return task_tier(name, requested, self._llm_tasks.get(name, {}).get("enabled"), self._max_tier) + @property def schema(self) -> Schema | None: """The graph-level schema, read-only. @@ -283,7 +323,7 @@ def _seed_tier(self, seeds: object) -> str: @return (str): the tier to seed with; raises ValidationError for embeddings without an embedder. """ tiers.require_tier("seeds", seeds) - tier = tiers.clamp("seeds", str(seeds), self._max_tier) + tier = self._task_tier("seeds", str(seeds)) if tier == "embeddings" and self._embedder is None: raise ValidationError(f"seeds 'embeddings' needs an embedder: {EMBEDDER_HINT}", code="embedder_required") return tier @@ -295,8 +335,8 @@ def _rerank_tier(self, rerank: object) -> str: @return (str): the tier to rerank with; raises ValidationError for embeddings without an embedder. """ tiers.require_tier("rerank", rerank) - tier = tiers.clamp("rerank", str(rerank), self._max_tier) - if tier == "embeddings" and self._embedder is None: + tier = self._task_tier("rerank", str(rerank)) + if tier == "embeddings" and self._rerank_embedder is None: raise ValidationError( f"rerank 'embeddings' needs an embedder: {RERANK_EMBEDDER_HINT}", code="embedder_required" ) @@ -310,9 +350,9 @@ def _resolver_for(self, resolver: EntityResolver | ResolverMode) -> tuple[str, E """ if isinstance(resolver, str): require_resolver(resolver) - tier = tiers.clamp("resolution", resolver, self._max_tier) - return tier, as_resolver(tier, self._llm) - return "custom", as_resolver(resolver, self._llm) + tier = self._task_tier("resolution", resolver) + return tier, as_resolver(tier, self._resolver_llm) + return "custom", as_resolver(resolver, self._resolver_llm) def _contradiction_tier(self, mode: object) -> ContradictionMode: """Validate a contradiction mode and lower it to the cost cap. @@ -321,8 +361,8 @@ def _contradiction_tier(self, mode: object) -> ContradictionMode: @return (ContradictionMode): the mode to apply; raises ValidationError for llm without an LLM. """ require_contradiction_mode(mode) - tier = tiers.clamp("contradiction", str(mode), self._max_tier) - if tier == "llm" and self._llm is None: + tier = self._task_tier("contradiction", str(mode)) + if tier == "llm" and self._judge_llm is None: raise needs_llm("contradiction 'llm'") return tier # type: ignore[return-value] @@ -951,12 +991,12 @@ async def create(tx: Any) -> Any: found.clear() check = self._schema_check judgment = None - if judged and self._llm is not None: + if judged and self._judge_llm is not None: planned = await _ops.create_relation( tx, self.namespace, **fields, schema_check=check, contradiction=mode, caps=caps, dry_run=True ) judgment = await judge_contradictions( - tx, self.namespace, self._llm, [planned], caps, planned.created_at + tx, self.namespace, self._judge_llm, [planned], caps, planned.created_at ) rel = await _ops.create_relation( tx, self.namespace, **fields, schema_check=check, contradiction=mode, caps=caps, warnings=found @@ -989,12 +1029,13 @@ def _build_extractor( """ if self._extractor is not None: return self._extractor - if self._extraction != "llm" or self._llm is None: + if self._extraction != "llm": from .extraction.basic import NERExtractor return NERExtractor(engine=self._extraction or "spacy") return LLMExtractor( self._llm, + llm_tasks=self._passes, prompts=self._prompts, instructions=self._instructions, call_prompts=call_prompts, @@ -1093,7 +1134,7 @@ async def _apply(tx: Any) -> InsertResult: await _ops.require_relation_identities(tx, ns, resolved.relations) await _ops.require_preference_identities(tx, ns, resolved.preferences) judgment = None - if judged and self._llm is not None: + if judged and self._judge_llm is not None: planned = await _ops.upsert_relations( tx, ns, @@ -1107,7 +1148,7 @@ async def _apply(tx: Any) -> InsertResult: judgment = await judge_contradictions( tx, ns, - self._llm, + self._judge_llm, planned, caps, created_at, diff --git a/src/selfgraph/extraction/extractor.py b/src/selfgraph/extraction/extractor.py index 5b14c1bc..6e4842fd 100644 --- a/src/selfgraph/extraction/extractor.py +++ b/src/selfgraph/extraction/extractor.py @@ -23,7 +23,8 @@ from .._tracing import traced from .._unicode import LETTER_CLASS, lower from ..errors import ExtractionError, ValidationError -from ..llm.base import summarize_error +from ..llm.base import resolve_llm, summarize_error +from ..llm.tasks import LLMTasks, check_llm_tasks, extraction_models from ..models import ( LLM_CONCURRENCY, DecisionTraceInput, @@ -312,7 +313,7 @@ def pop_warnings(self) -> list[InsertWarning]: class LLMExtractor(_WarningSink): def __init__( self, - llm: LLMClient, + llm: LLMClient | str | None, *, prompts: ExtractionPrompts | None = None, instructions: ExtractionInstructions | None = None, @@ -321,10 +322,12 @@ def __init__( schema: Schema | None = None, source_id: str | None = None, chunking: Chunking = "tokens", + llm_tasks: LLMTasks | None = None, ) -> None: check_prompts(prompts) check_prompts(call_prompts) - self._llm = llm + self._llm = resolve_llm(llm) if isinstance(llm, str) else llm + self._models = extraction_models(check_llm_tasks(llm_tasks), self._llm) self._schema = schema self._source_id = source_id self._chunking = chunking @@ -365,6 +368,10 @@ async def extract(self, document: ParsedDocument) -> Extraction: ("decisions", DecisionsOut, raw_decisions), ] + kinds = [entry for entry in kinds if self._models[entry[0]] is not None] + if not kinds: + return Extraction() + for kind, *_ in kinds: self._messages(kind, "") concurrency = getattr(self._llm, "concurrency", None) @@ -380,6 +387,8 @@ def chunk_id(chunk) -> str | None: return None if version is None else _ids.chunk_id(version, chunk.index) async def run(chunk, kind: str, schema: type[BaseModel]) -> list | InsertWarning: + model = self._models[kind] + assert model is not None async with gate: if len(chunks) > 1 and kind == kinds[0][0]: _log.info("extracting chunk %d/%d", chunk.index + 1, len(chunks)) @@ -388,7 +397,7 @@ async def run(chunk, kind: str, schema: type[BaseModel]) -> list | InsertWarning result = await traced( "selfgraph.llm", {"selfgraph.llm.task": "extraction"}, - self._llm.generate(system=system, user=user, output=schema), + model.generate(system=system, user=user, output=schema), ) return getattr(_checked_output(result, schema, kind), kind) except ExtractionError: @@ -398,7 +407,7 @@ async def run(chunk, kind: str, schema: type[BaseModel]) -> list | InsertWarning code="extraction_partial_failure", message=( f"{kind} extraction failed on chunk {chunk.index}: " - f"{summarize_error(exc, getattr(self._llm, 'base_url', None))}" + f"{summarize_error(exc, getattr(model, 'base_url', None))}" ), source_id=self._source_id, chunk_id=chunk_id(chunk), diff --git a/src/selfgraph/llm/__init__.py b/src/selfgraph/llm/__init__.py index 8079d902..82e246e1 100644 --- a/src/selfgraph/llm/__init__.py +++ b/src/selfgraph/llm/__init__.py @@ -1,3 +1,3 @@ -from .base import build_llm_client, build_provider, resolve_llm +from .base import build_embedder, build_llm_client, build_provider, resolve_llm -__all__ = ["build_llm_client", "build_provider", "resolve_llm"] +__all__ = ["build_embedder", "build_llm_client", "build_provider", "resolve_llm"] diff --git a/src/selfgraph/llm/base.py b/src/selfgraph/llm/base.py index f6deb3a0..e8b37b31 100644 --- a/src/selfgraph/llm/base.py +++ b/src/selfgraph/llm/base.py @@ -20,7 +20,10 @@ from ..models import _KNOWN_PROVIDERS, LLMConfig, as_input, did_you_mean, suggest_key from ..protocols import Embedder, LLMClient, Provider, Reranker -__all__ = ["build_llm_client", "build_provider", "resolve_llm", "summarize_error"] +__all__ = ["build_embedder", "build_llm_client", "build_provider", "resolve_llm", "summarize_error"] + +LLMArg = LLMConfig | Mapping | LLMClient | str +EmbedderArg = LLMConfig | Mapping | Embedder | str T = TypeVar("T") @@ -221,13 +224,77 @@ async def generate(self, *, system: str, user: str, output: type[T]) -> T: raise -def build_llm_client(config: LLMConfig) -> LLMClient: +def model_shorthand(value: str) -> LLMConfig: + """Parse a provider/model shorthand. + + @param value (str): the shorthand. + @return (LLMConfig): the provider and model settings. + """ + provider, _, model = value.partition("/") + if not provider or not model or any(c.isspace() for c in value) or "://" in value: + raise ValidationError("model shorthand must look like provider/model", code="invalid_setting", field="model") + return LLMConfig(provider=provider, model=value) + + +class _LibraryEmbedder: + def __init__(self, config: LLMConfig) -> None: + self._config = config + + async def embed(self, texts: list[str]) -> list[list[float]]: + """Embed a batch of texts. + + @param texts (list[str]): the input texts. + @return (list[list[float]]): the vectors in input order. + """ + try: + from litellm import aembedding + except ImportError as exc: + raise ExtractionError( + 'embeddings need the optional LLM dependencies; pip install "selfgraph[llm]"', + code="missing_package", + ) from exc + config = self._config + prefix = f"{config.provider}/" + model = config.model if config.model.lower().startswith(prefix.lower()) else f"{prefix}{config.model}" + try: + response = await aembedding( + model=model, input=texts, api_key=config.api_key, api_base=config.base_url, timeout=config.timeout + ) + return [item["embedding"] for item in sorted(response.data, key=lambda item: item["index"])] + except Exception as exc: # noqa: BLE001 + raise _fatal(exc, config, model) or ExtractionError( + f"embedding failed: {summarize_error(exc, config.base_url)}" + ) from None + + +def build_embedder(model: EmbedderArg) -> Embedder: + """Build an embedder using the optional LLM library. + + @param model (EmbedderArg): an embedder, configuration, or shorthand. + @return (Embedder): the resolved embedder. + """ + if callable(getattr(model, "embed", None)): + return model + if isinstance(model, str): + model = model_shorthand(model) + elif not isinstance(model, LLMConfig) and ( + not isinstance(model, Mapping) or not ("provider" in model or "model" in model) + ): + raise ValidationError(f"embedder must have an embed method, got {type_name(model)}") + config = as_input(LLMConfig, model, "llm config") + if config is None: + raise ValidationError("embedder needs a model", code="invalid_setting", field="model") + check_llm_config(config) + return _LibraryEmbedder(config) + + +def build_llm_client(config: LLMConfig | str) -> LLMClient: """Build a unified LLM client that routes to any provider through litellm. - @param config (LLMConfig): the provider, model, and connection settings. + @param config (LLMConfig | str): the provider, model, and connection settings. @return (LLMClient): the client. """ - return _UnifiedLLMClient(config) + return _UnifiedLLMClient(model_shorthand(config) if isinstance(config, str) else config) class _ProviderAdapter: @@ -251,16 +318,16 @@ def build_provider(llm: LLMConfig | LLMClient, embedder: Embedder, reranker: Rer return _ProviderAdapter(client, embedder, reranker) -def resolve_llm(llm: LLMConfig | Mapping | LLMClient | None) -> LLMClient | None: +def resolve_llm(llm: LLMArg | None) -> LLMClient | None: """Normalise the llm argument to an LLMClient or None. - @param llm (LLMConfig | Mapping | LLMClient | None): an LLMConfig, a mapping of its fields, or an object with + @param llm (LLMArg | None): a model shorthand, an LLMConfig, a mapping of its fields, or an object with an async ``generate(system=, user=, output=)`` method. @return (LLMClient | None): the resolved client, or None. """ if llm is None: return None - if isinstance(llm, LLMConfig): + if isinstance(llm, (LLMConfig, str)): return build_llm_client(llm) if callable(getattr(llm, "generate", None)): return llm diff --git a/src/selfgraph/llm/tasks.py b/src/selfgraph/llm/tasks.py new file mode 100644 index 00000000..f53e1076 --- /dev/null +++ b/src/selfgraph/llm/tasks.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TypedDict + +from ..errors import ValidationError, needs_llm +from ..protocols import LLMClient +from ..tiers import clamp +from .base import EmbedderArg, LLMArg, resolve_llm + +__all__ = ["LLMTasks", "LLMTask", "EmbeddingTask"] + +PASSES = ("entities", "relations", "preferences", "decisions") + + +class LLMTask(TypedDict, total=False): + enabled: bool + model: LLMArg | None + + +class EmbeddingTask(TypedDict, total=False): + enabled: bool + model: EmbedderArg | None + + +class LLMTasks(TypedDict, total=False): + entities: LLMTask + relations: LLMTask + preferences: LLMTask + decisions: LLMTask + resolution: LLMTask + contradiction: LLMTask + seeds: EmbeddingTask + rerank: EmbeddingTask + + +def check_llm_tasks(tasks: LLMTasks | None) -> LLMTasks: + """Validate task names and option shapes. + + @param tasks (LLMTasks | None): task settings. + @return (LLMTasks): the checked settings. + """ + if tasks is None: + return {} + if not isinstance(tasks, Mapping): + raise ValidationError("llm_tasks must be an object", code="invalid_setting", field="llm_tasks") + for name, task in tasks.items(): + if name not in LLMTasks.__annotations__: + raise ValidationError("llm_tasks contains an unknown task", code="invalid_setting", field="llm_tasks") + if ( + not isinstance(task, Mapping) + or task.keys() - {"enabled", "model"} + or ("enabled" in task and type(task["enabled"]) is not bool) + ): + raise ValidationError( + f"llm_tasks.{name} must be an object with optional enabled (boolean) and model fields", + code="invalid_setting", + field=f"llm_tasks.{name}", + ) + return tasks + + +def task_tier(name: str, requested: str, enabled: bool | None, cap: str) -> str: + """Apply the graph and task ceilings. + + @param name (str): the tier ladder. + @param requested (str): the requested tier. + @param enabled (bool | None): the task switch. + @param cap (str): the graph ceiling. + @return (str): the effective tier. + """ + if enabled is False and cap == "max": + cap = "balanced" + return clamp(name, requested, cap) + + +def extraction_models(tasks: LLMTasks, fallback: LLMClient | None) -> dict[str, LLMClient | None]: + """Resolve enabled extraction passes. + + @param tasks (LLMTasks): the task settings. + @param fallback (LLMClient | None): the graph LLM. + @return (dict): each pass model, or None for a disabled pass. + """ + models = {} + for name in PASSES: + task = tasks.get(name, {}) + model = None + if task.get("enabled") is not False: + override = resolve_llm(task.get("model")) + model = fallback if override is None else override + if model is None: + raise needs_llm("extraction 'llm'") + models[name] = model + return models + + +def resolved_passes(tasks: LLMTasks, fallback: LLMClient | None) -> LLMTasks: + return { + name: {"enabled": model is not None, "model": model} + for name, model in extraction_models(tasks, fallback).items() + } diff --git a/src/selfgraph/resolution.py b/src/selfgraph/resolution.py index 3737ddca..f55bc482 100644 --- a/src/selfgraph/resolution.py +++ b/src/selfgraph/resolution.py @@ -37,7 +37,7 @@ from ._unicode import DECIMAL_CLASS from .errors import ExtractionError, NotFoundError, ValidationError, needs_llm from .extraction.extractor import _FALLBACK_TYPE -from .llm.base import resolve_llm +from .llm.base import LLMArg, resolve_llm from .models import ( DecisionTraceInput, DuplicateEntityGroup, @@ -49,7 +49,6 @@ Extraction, InsertResult, InsertWarning, - LLMConfig, MergeRecord, MergeRewrite, PreferenceInput, @@ -547,7 +546,7 @@ class LLMResolver: def __init__( self, - llm: LLMConfig | LLMClient, + llm: LLMArg, *, band: tuple[float, float] = _DEFAULT_BAND, max_questions: int = _MAX_QUESTIONS, diff --git a/src/selfgraph/retrieval.py b/src/selfgraph/retrieval.py index c4a8d5c8..5d1d4c07 100644 --- a/src/selfgraph/retrieval.py +++ b/src/selfgraph/retrieval.py @@ -1187,10 +1187,10 @@ async def _rerank_scores(graph: SelfGraph, tier: str, query: str, texts: list[st terms = _stems(query_tokens) scores = [_bm25(terms, idf, doc, avgdl) for doc in docs] elif tier == "embeddings": - (target,) = await _embed(graph._embedder, [query]) + (target,) = await _embed(graph._rerank_embedder, [query]) vectors: list[list[float]] = [] for start in range(0, len(texts), _EMBED_BATCH): - vectors.extend(await _embed(graph._embedder, texts[start : start + _EMBED_BATCH])) + vectors.extend(await _embed(graph._rerank_embedder, texts[start : start + _EMBED_BATCH])) scores = [_cosine(target, v) for v in vectors] else: scores = list(await graph._score_context(query, texts)) diff --git a/src/selfgraph/runtime.py b/src/selfgraph/runtime.py index 29650cc3..fcb98a5e 100644 --- a/src/selfgraph/runtime.py +++ b/src/selfgraph/runtime.py @@ -46,6 +46,7 @@ ) from .extraction.prompts import check_prompts from .ids import _MAX_JSON_DEPTH, MAX_SAFE_INTEGER, _require_clean_json, _require_namespace, _unstorable +from .llm.tasks import LLMTasks, check_llm_tasks from .models import ( LLM_CONCURRENCY, LLM_TIMEOUT, @@ -118,6 +119,7 @@ class GraphSettings: namespace: str = "default" llm_provider: str | None = None llm_model: str | None = None + llm_tasks: LLMTasks | str | None = None llm_api_key: str | None = None llm_api_key_env: str | None = None llm_base_url: str | None = None @@ -718,8 +720,9 @@ def check_settings(settings: GraphSettings) -> GraphSettings: _llm_timeout(settings.llm_timeout) _llm_concurrency(settings.llm_concurrency) read_only = _read_only(settings.read_only) + tasks = check_llm_tasks(_json_setting(settings.llm_tasks, "llm_tasks")) llm = _build_llm(settings) - if llm is None: + if llm is None and not tasks: level = settings.level or "balanced" cap = settings.max_tier or "max" if level == "max" and cap == "max": @@ -736,7 +739,9 @@ def check_settings(settings: GraphSettings) -> GraphSettings: ) prompts = as_input(ExtractionPrompts, _json_setting(settings.prompts, "prompts"), "prompts") check_prompts(prompts) - return replace(settings, schema=schema, instructions=instructions, prompts=prompts, read_only=read_only) + return replace( + settings, schema=schema, instructions=instructions, prompts=prompts, read_only=read_only, llm_tasks=tasks + ) def build_graph(settings: GraphSettings, store: GraphStore | None = None) -> SelfGraph: @@ -754,6 +759,7 @@ def build_graph(settings: GraphSettings, store: GraphStore | None = None) -> Sel return SelfGraph( store=store, llm=_build_llm(settings), + llm_tasks=settings.llm_tasks, instructions=settings.instructions, prompts=settings.prompts, namespace=namespace, diff --git a/tests/test_tiers.py b/tests/test_tiers.py index c0730367..21a19387 100644 --- a/tests/test_tiers.py +++ b/tests/test_tiers.py @@ -1,5 +1,17 @@ import pytest -from helpers import ANN_ACME_GLOBEX, cli, fresh_graph, mcp_session, run, store_settings, utc, works_at +from helpers import ( + ANN_ACME_GLOBEX, + FakeLLM, + cli, + extracting_llm, + fresh_graph, + kuzu_main, + mcp_session, + run, + store_settings, + utc, + works_at, +) from selfgraph import Schema, ValidationError, ids from selfgraph.contradiction import _line @@ -44,6 +56,91 @@ async def embed(self, texts): return [[1.0, 0.0] if "feline" in t or "Cat" in t else [0.0, 1.0] for t in texts] +def test_llm_tasks_route_enabled_passes_and_skip_disabled_passes(): + default = FakeLLM() + entities = extracting_llm([("Person", "Ann")]) + g = fresh_graph( + llm=default, + llm_tasks={ + "entities": {"model": entities}, + "relations": {"enabled": False}, + "preferences": {"enabled": False}, + }, + ) + assert [entity.name for entity in run(g.insert.text("Ann is here.")).entities] == ["Ann"] + assert [name for name, *_ in entities.calls] == ["_EntitiesOut"] + assert [name for name, *_ in default.calls] == ["_DecisionsOut"] + + +def test_llm_tasks_route_judge_and_resolution_overrides(): + default = FakeLLM() + judge = Judge() + resolver = FakeLLM({"_SameEntity": {"same": True}}) + g = fresh_graph( + llm=default, + resolver="llm", + llm_tasks={"resolution": {"model": resolver}, "contradiction": {"enabled": True, "model": judge}}, + ) + run( + g.insert.facts( + { + "entities": [*ANN_ACME_GLOBEX, {"type": "Person", "name": "John Smith"}], + "relations": [works_at("acme", 2020)], + } + ) + ) + result = run( + g.insert.facts( + {"entities": [{"type": "Person", "name": "Jon Smyth"}], "relations": [works_at("globex", 2022)]}, + resolver="llm", + ) + ) + assert [merge.reason for merge in result.merges] == ["llm"] + assert len(resolver.calls) == len(judge.prompts) == 1 + assert [rel.id for rel in run(g.relations.list()).items] == [GLOBEX] + assert default.calls == [] + + +def test_llm_tasks_route_distinct_embedding_tasks_and_respect_the_cap(): + seeds, rerank = Embedder(), Embedder() + g = fresh_graph( + llm_tasks={"seeds": {"enabled": True, "model": seeds}, "rerank": {"enabled": True, "model": rerank}} + ) + run(g.entities.create("Cat", "Animal")) + found = run(g.retrieve("Cat")) + assert (found.tiers["seeds"], found.tiers["rerank"]) == ("embeddings", "embeddings") + assert len(seeds.calls) == len(rerank.calls) == 2 + capped = fresh_graph(max_tier="balanced", llm_tasks={"seeds": {"enabled": True, "model": "invalid"}}) + assert capped.tiers["seeds"] == "bm25" + + +def test_llm_tasks_shorthand_builds_a_batched_embedder(monkeypatch): + import sys + from types import SimpleNamespace + + from selfgraph import build_embedder + + calls = [] + + async def embed(*, model, input, **kwargs): + calls.append((model, input)) + return SimpleNamespace(data=[{"index": 1, "embedding": [2]}, {"index": 0, "embedding": [1]}]) + + monkeypatch.setitem(sys.modules, "litellm", SimpleNamespace(provider_list=["provider"], aembedding=embed)) + assert run(build_embedder("provider/vector-model").embed(["a", "b"])) == [[1], [2]] + assert calls == [("provider/vector-model", ["a", "b"])] + + +def test_llm_tasks_are_applied_by_cli_and_mcp(monkeypatch, capsys, tmp_path): + tasks = '{"resolution":{"enabled":false}}' + monkeypatch.setenv("SELFGRAPH_RESOLVER", "llm") + assert kuzu_main(tmp_path, "--llm-tasks", tasks, "init") == 0 + capsys.readouterr() + monkeypatch.setenv("SELFGRAPH_LLM_TASKS", tasks) + with mcp_session(resolver="llm", llm_tasks=tasks) as server: + assert run(server.create_entity("Ann", "Person"))["name"] == "Ann" + + def test_levels_set_every_default_and_reject_unknown_names(monkeypatch): monkeypatch.setattr("selfgraph.extraction.basic._nlp", lambda: None) assert fresh_graph("tier").tiers == { diff --git a/typescript/src/access.ts b/typescript/src/access.ts index 8042ca67..3a44bb29 100644 --- a/typescript/src/access.ts +++ b/typescript/src/access.ts @@ -9,6 +9,7 @@ import { import { activeStores, activeWriteWarnings } from "./internal/execution.js"; import { Lazy } from "./internal/lazy.js"; import { sleep } from "./internal/time.js"; +import { type LLMTasks, taskCap } from "./llm/tasks.js"; import type { InsertWarning } from "./models.js"; import { type RelationCap, type SchemaCheck, withClaims } from "./ops.js"; import type { Embedder, GraphPrimitives, GraphStore, LLMClient, Reranker } from "./protocols.js"; @@ -30,10 +31,12 @@ const CLOSED_MESSAGE = "this SelfGraph is closed; create a new SelfGraph to keep export interface TierSetup { llm: LLMClient | null; + llm_tasks: LLMTasks; max_tier: Level; seeds: SeedTier; strategy: string; embedder: Embedder | null; + rerank_embedder: Embedder | null; embeddings: Map; rerank: RerankTier | "custom"; reranker: Reranker | null; @@ -116,10 +119,12 @@ export class GraphAccess { readonly contradiction: ContradictionMode = "warn", readonly tiers: TierSetup = { llm: null, + llm_tasks: {}, max_tier: "max", seeds: "bm25", strategy: "bfs", embedder: null, + rerank_embedder: null, embeddings: new Map(), rerank: "off", reranker: null, @@ -169,7 +174,11 @@ export class GraphAccess { const mode = contradiction == null ? this.contradiction - : contradictionTier(contradiction, this.tiers.llm, this.tiers.max_tier); + : contradictionTier( + contradiction, + this.tiers.llm, + taskCap(this.tiers.llm_tasks.contradiction, this.tiers.max_tier), + ); const judged = mode === "llm"; return { contradiction: judged ? "supersede" : mode, caps: contradictionCaps(schema), judged }; } diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index c30aaa7f..c99e96c4 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -1177,9 +1177,10 @@ export function buildParser(): Command<[], GlobalOptions> { .option("--llm-model ", "the model; a provider-prefixed one such as openai/gpt-4o-mini sets the provider") .option("--llm-api-key ") .option("--llm-api-key-env ", "environment variable holding the LLM key") + .option("--llm-tasks ", "LLM task settings as inline JSON or a JSON file") .option("--llm-base-url ") .option("--llm-timeout ", "seconds to wait for each LLM call (default 120)") - .option("--llm-concurrency ", "chunks to extract at once, each running four LLM calls (default 4)") + .option("--llm-concurrency ", "chunks to extract at once, each running the enabled LLM passes (default 4)") .option("--schema ", "schema JSON file applied to every insert, or inline JSON when it starts with '{'") .option("--instructions ", "extraction instructions JSON file, or inline JSON when it starts with '{'") .option("--prompts ", "extraction prompt templates JSON file, or inline JSON when it starts with '{'") diff --git a/typescript/src/client.ts b/typescript/src/client.ts index 07d241ab..5d4bf5d4 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -18,7 +18,8 @@ import { traced, } from "./internal/tracing.js"; import { L_EVIDENCE } from "./labels.js"; -import { type LLMArg, resolveLlm } from "./llm/index.js"; +import { buildEmbedder, type EmbedderArg, type LLMArg, resolveLlm } from "./llm/index.js"; +import { checkLlmTasks, type LLMTasks, PASSES, resolvedPasses, taskCap, taskDefault, taskModel } from "./llm/tasks.js"; import { inspect, scanEntities, scanRelations } from "./maintenance.js"; import { type AnswerabilityReport, @@ -126,6 +127,7 @@ const SUGGEST_KEYS = keysOf({ extend: true, min_count: tru export interface SelfGraphOptions { llm?: LLMArg; + llm_tasks?: LLMTasks | null; instructions?: ExtractionInstructions | null; prompts?: ExtractionPrompts | null; extractor?: Extractor | null; @@ -138,7 +140,7 @@ export interface SelfGraphOptions { max_tier?: Level; extraction?: ExtractionTier | null; seeds?: SeedTier | null; - embedder?: Embedder | null; + embedder?: EmbedderArg | null; rerank?: RerankTier | null; reranker?: Reranker | null; provider?: Provider | null; @@ -146,6 +148,7 @@ export interface SelfGraphOptions { const OPTION_KEYS = keysOf({ llm: true, + llm_tasks: true, instructions: true, prompts: true, extractor: true, @@ -208,12 +211,16 @@ export class SelfGraph { ) { throw new ValidationError("provider must have generate, embed, and rerank methods", { field: "provider" }); } + const tasks = checkLlmTasks(options.llm_tasks); const llm = resolveLlm(options.llm ?? provider); - if (level === "max" && maxTier === "max" && llm === null) throw needsLlm("level 'max'"); - const embedder = options.embedder ?? provider; - if (embedder !== null && typeof (embedder as { embed?: unknown }).embed !== "function") { - throw new ValidationError(`embedder must have an embed method, got ${typeName(embedder)}`); - } + if (level === "max" && maxTier === "max" && llm === null && !Object.keys(tasks).length) + throw needsLlm("level 'max'"); + const embedderArg = options.embedder ?? provider; + const sharedEmbedder = embedderArg != null && maxTier === "max" ? buildEmbedder(embedderArg) : null; + const embedder = taskModel(tasks.seeds, maxTier, buildEmbedder, sharedEmbedder); + const rerankEmbedder = taskModel(tasks.rerank, maxTier, buildEmbedder, sharedEmbedder); + const judgeLlm = taskModel(tasks.contradiction, maxTier, resolveLlm, llm); + const resolverLlm = taskModel(tasks.resolution, maxTier, resolveLlm, llm); const reranker = options.reranker ?? null; if (reranker !== null && typeof (reranker as { score?: unknown }).score !== "function") { throw new ValidationError(`reranker must have a score method, got ${typeName(reranker)}`); @@ -222,22 +229,41 @@ export class SelfGraph { const extractor = options.extractor ?? null; let extraction: string | null = options.extraction ?? null; if (extraction !== null) requireTier("extraction", extraction); - else if (extractor === null) extraction = llm !== null ? "llm" : preset.extraction; + else if (extractor === null) { + extraction = llm !== null || PASSES.some((name) => tasks[name]?.enabled === true) ? "llm" : preset.extraction; + } if (extraction !== null) extraction = clamp("extraction", extraction, maxTier); - if (extraction === "llm" && llm === null) throw needsLlm("extraction 'llm'"); - this.extraction = extractor !== null ? null : extraction === "spacy" ? "regex" : extraction; - const seeds = options.seeds ?? (embedder !== null || preset.seeds !== "embeddings" ? preset.seeds : "synonyms"); - const seeding = seedTier(seeds, embedder, maxTier); + const models = extraction === "llm" && extractor === null ? resolvedPasses(tasks, llm) : undefined; + if (extraction === "llm" && extractor !== null && llm === null && !Object.keys(tasks).length) { + throw needsLlm("extraction 'llm'"); + } + + const seedsDefault = embedder === null && preset.seeds === "embeddings" ? "synonyms" : preset.seeds; + const rerankDefault = rerankEmbedder === null && preset.rerank === "embeddings" ? "lexical" : preset.rerank; + const seeding = seedTier( + options.seeds ?? taskDefault(tasks, "seeds", seedsDefault), + embedder, + taskCap(tasks.seeds, maxTier), + ); const rerank = options.rerank == null && (reranker !== null || (provider !== null && maxTier === "max")) ? "custom" : rerankTier( - options.rerank ?? (embedder !== null || preset.rerank !== "embeddings" ? preset.rerank : "lexical"), - embedder, - maxTier, + options.rerank ?? taskDefault(tasks, "rerank", rerankDefault), + rerankEmbedder, + taskCap(tasks.rerank, maxTier), ); - const [resolution, resolver] = resolverFor(options.resolver ?? (preset.resolution as ResolverMode), llm, maxTier); - const contradiction = contradictionTier(options.contradiction ?? preset.contradiction, llm, maxTier); + const [resolution, resolver] = resolverFor( + options.resolver ?? (taskDefault(tasks, "resolution", preset.resolution) as ResolverMode), + resolverLlm, + taskCap(tasks.resolution, maxTier), + ); + const contradiction = contradictionTier( + options.contradiction ?? taskDefault(tasks, "contradiction", preset.contradiction), + judgeLlm, + taskCap(tasks.contradiction, maxTier), + ); + this.extraction = extractor !== null ? null : extraction === "spacy" ? "regex" : extraction; const instructions = asInput(ExtractionInstructions, options.instructions, "instructions"); const prompts = asInput(ExtractionPrompts, options.prompts, "prompts"); checkPrompts(prompts); @@ -248,11 +274,13 @@ export class SelfGraph { this.schema = asSchema(options.schema); requireSchemaForMode(schemaMode, this.schema); this.graph = new GraphAccess(store, namespace, this.schema, schemaMode, contradiction, { - llm, + llm: judgeLlm, + llm_tasks: tasks, max_tier: maxTier, seeds: seeding, strategy: preset.traversal, embedder, + rerank_embedder: rerankEmbedder, embeddings: new Map(), rerank, reranker: reranker ?? (provider === null ? null : { score: provider.rerank.bind(provider) }), @@ -264,6 +292,8 @@ export class SelfGraph { this.maintenance = new Maintenance(this.graph); this.insert = new Insert(this.graph, { llm, + passes: models, + resolver_llm: resolverLlm, resolver, resolver_tier: resolution, extraction: this.extraction, @@ -611,6 +641,7 @@ export function buildGraph(value: GraphSettings, reuse: GraphStore | null = null try { return new SelfGraph(store, { llm: buildLlm(settings), + llm_tasks: settings.llm_tasks as LLMTasks, instructions: settings.instructions as ExtractionInstructions | null, prompts: settings.prompts as ExtractionPrompts | null, namespace, diff --git a/typescript/src/extraction/extractor.ts b/typescript/src/extraction/extractor.ts index c053a65f..01e7eaa9 100644 --- a/typescript/src/extraction/extractor.ts +++ b/typescript/src/extraction/extractor.ts @@ -8,7 +8,8 @@ import { parseIso, toIso } from "../internal/time.js"; import { traced } from "../internal/tracing.js"; import { LETTER_CLASS, lower } from "../internal/unicode.js"; import { EDGE_TYPES, preferenceStanceOf } from "../labels.js"; -import { summarizeError } from "../llm/index.js"; +import { resolveLlm, summarizeError } from "../llm/index.js"; +import { checkLlmTasks, extractionTasks, type LLMTask } from "../llm/tasks.js"; import { Extraction, ExtractionInstructions, @@ -554,6 +555,7 @@ export function assembleExtraction( } export interface LLMExtractorOptions { + llm_tasks?: Partial>; prompts?: ExtractionPrompts | null; instructions?: ExtractionInstructions | null; call_prompts?: ExtractionPrompts | null; @@ -564,6 +566,7 @@ export interface LLMExtractorOptions { } const OPTION_KEYS = keysOf({ + llm_tasks: true, prompts: true, instructions: true, call_prompts: true, @@ -584,6 +587,8 @@ export class WarningSink { } export class LLMExtractor extends WarningSink implements Extractor { + private readonly llm: LLMClient | null; + private readonly models: Record; private readonly catalogs: Partial>; private readonly options: LLMExtractorOptions; private readonly sourceId: string | null; @@ -593,15 +598,14 @@ export class LLMExtractor extends WarningSink implements Extractor { /** * Extract entities, relations, preferences, and decisions from text with an LLM, chunk by chunk. * - * @param llm (LLMClient): the LLM client. + * @param llm (LLMClient | string | null): the default client or model shorthand. * @param options (LLMExtractorOptions): client-level and per-call prompts, instructions, and schema guidance. */ - constructor( - private readonly llm: LLMClient, - options: LLMExtractorOptions = {}, - ) { + constructor(llm: LLMClient | string | null, options: LLMExtractorOptions = {}) { super(); checkOptions("LLMExtractor", options, OPTION_KEYS); + this.llm = typeof llm === "string" ? resolveLlm(llm) : llm; + this.models = extractionTasks(checkLlmTasks(options.llm_tasks), this.llm); this.options = { prompts: parseOrThrow(ExtractionPrompts.nullish(), options.prompts, "prompts"), instructions: parseOrThrow(ExtractionInstructions.nullish(), options.instructions, "instructions"), @@ -644,10 +648,11 @@ export class LLMExtractor extends WarningSink implements Extractor { checked: z.ZodType = schema as unknown as z.ZodType, ) => ({ kind, + model: this.models[kind], run: async (text: string) => { const [system, user] = this.messages(kind, text); const result = await traced("selfgraph.llm", { "selfgraph.llm.task": "extraction" }, () => - this.llm.generate({ system, user, output: schema }), + this.models[kind]!.generate({ system, user, output: schema }), ); const parsed = checked.safeParse(result); if (!parsed.success) { @@ -700,10 +705,10 @@ export class LLMExtractor extends WarningSink implements Extractor { })), ), ), - ]; + ].filter(({ model }) => model !== null); for (const { kind } of steps) this.messages(kind, ""); - const calls = chunks.flatMap((chunk) => steps.map(({ kind, run }) => ({ chunk, kind, run }))); + const calls = chunks.flatMap((chunk) => steps.map(({ kind, run, model }) => ({ chunk, kind, run, model }))); const outcomes: Array<{ apply: (evidence: ChunkEvidence | null) => void } | { error: unknown }> = []; let next = 0; let fatal: ExtractionError | null = null; @@ -722,7 +727,7 @@ export class LLMExtractor extends WarningSink implements Extractor { ); } }; - const { concurrency } = this.llm as { concurrency?: unknown }; + const concurrency = (this.llm as (LLMClient & { concurrency?: unknown }) | null)?.concurrency; const chunksAtOnce = typeof concurrency === "number" && Number.isSafeInteger(concurrency) && concurrency > 0 ? concurrency @@ -732,8 +737,8 @@ export class LLMExtractor extends WarningSink implements Extractor { const version = this.sourceId === null ? null : ids.sourceVersionId(this.sourceId, ids.contentHash(utf8(document.text))); - const baseUrl = (this.llm as { base_url?: string | null }).base_url ?? null; - calls.forEach(({ chunk, kind }, i) => { + calls.forEach(({ chunk, kind, model }, i) => { + const baseUrl = (model as { base_url?: string | null }).base_url ?? null; const outcome = outcomes[i]!; const chunkId = version === null ? null : ids.chunkId(version, chunk.index); if ("apply" in outcome) { diff --git a/typescript/src/index.ts b/typescript/src/index.ts index bb46e058..d442121a 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -55,7 +55,8 @@ export * as ids from "./ids.js"; export { decisionId, entityId, normalizeRelType, preferenceId, profileId, relationId } from "./ids.js"; export type { InsertFactsOptions, InsertTextOptions } from "./insert.js"; export { type Logger, type LogLevel, setLogger } from "./internal/log.js"; -export { buildLlmClient, buildProvider, type LLMArg } from "./llm/index.js"; +export { buildEmbedder, buildLlmClient, buildProvider, type EmbedderArg, type LLMArg } from "./llm/index.js"; +export type { EmbeddingTask, LLMTask, LLMTasks } from "./llm/tasks.js"; export { type AnswerabilityReport, type Certification, diff --git a/typescript/src/insert.ts b/typescript/src/insert.ts index b755787e..9087e1f0 100644 --- a/typescript/src/insert.ts +++ b/typescript/src/insert.ts @@ -8,6 +8,7 @@ import * as ids from "./ids.js"; import { comparePy, isPlainObject, pyRepr, pyStrip, utf8 } from "./internal/py.js"; import { insertAttributes, syncAttributes, traced } from "./internal/tracing.js"; import { L_TRACE } from "./labels.js"; +import { type ExtractionTasks, taskCap } from "./llm/tasks.js"; import { asInput, type DateTimeInput, @@ -170,6 +171,8 @@ function restated( export interface ExtractionSetup { llm: LLMClient | null; + passes?: ExtractionTasks; + resolver_llm: LLMClient | null; instructions: ExtractionInstructions | null; prompts: ExtractionPrompts | null; extractor: Extractor | null; @@ -198,6 +201,11 @@ export class Insert { private readonly setup: ExtractionSetup, ) {} + private resolverFor(resolver: EntityResolver | ResolverMode): [string, EntityResolver | null] { + const { llm_tasks, max_tier } = this.graph.tiers; + return resolverFor(resolver, this.setup.resolver_llm, taskCap(llm_tasks.resolution, max_tier)); + } + /** * Choose the extractor for one insert: custom, then LLM when the extraction tier is llm, then the LLM-free fallback. * @@ -215,10 +223,11 @@ export class Insert { sourceId: string | null, chunking: Chunking, ): Extractor { - const { extractor, llm, prompts, instructions, extraction } = this.setup; + const { extractor, llm, passes, prompts, instructions, extraction } = this.setup; if (extractor !== null) return extractor; - if (extraction !== "llm" || llm === null) return new NERExtractor(); + if (extraction !== "llm") return new NERExtractor(); return new LLMExtractor(llm, { + llm_tasks: passes, prompts, instructions, call_prompts: callPrompts, @@ -259,9 +268,9 @@ export class Insert { const mode = schemaMode ?? this.graph.schemaMode; requireSchemaMode(mode); requireSchemaForMode(mode, activeSchema); - const { llm, max_tier: maxTier } = this.graph.tiers; + const { llm } = this.graph.tiers; const [resolverTier, activeResolver] = - resolver === null ? [this.setup.resolver_tier, this.setup.resolver] : resolverFor(resolver, llm, maxTier); + resolver === null ? [this.setup.resolver_tier, this.setup.resolver] : this.resolverFor(resolver); const { contradiction: conflicts, caps, judged } = this.graph.contradictionFor(contradiction, activeSchema); const used: Record = { ...(extraction !== null && { extraction }), @@ -493,7 +502,7 @@ export class Insert { throw new ValidationError("replace_source needs a source_id: it replaces that source's earlier versions"); } requireJsonMapping("metadata", options.metadata); - if (options.resolver != null) resolverFor(options.resolver, this.graph.tiers.llm, this.graph.tiers.max_tier); + if (options.resolver != null) this.resolverFor(options.resolver); const eventTime = parseTime(options.event_time, "event_time"); if (!pyStrip(text)) throw new ValidationError("text cannot be empty or whitespace"); const activeSchema = asSchema(options.schema); diff --git a/typescript/src/install.ts b/typescript/src/install.ts index f1003031..9b41e11e 100644 --- a/typescript/src/install.ts +++ b/typescript/src/install.ts @@ -71,7 +71,20 @@ export type Change = { * @return (string | undefined): its key, or undefined when none does. */ function secretOf(settings: Record): string | undefined { - return Object.entries(settings).find(([key, value]) => SECRETS.includes(key) || maskUri(value) !== value)?.[0]; + for (const [key, value] of Object.entries(settings)) { + if (SECRETS.includes(key) || maskUri(value) !== value) return key; + if (key !== "llm_tasks" || !value.trimStart().startsWith("{")) continue; + const tasks = parseJson(value, " in --llm-tasks", key) as Record; + for (const task of Object.values(tasks)) { + const model = isPlainObject(task) ? task.model : null; + if ( + isPlainObject(model) && + (model.api_key || (typeof model.base_url === "string" && maskUri(model.base_url) !== model.base_url)) + ) + return key; + } + } + return undefined; } /** Read the packaged skill directory. @return (Record): relative paths and text. */ diff --git a/typescript/src/llm/index.ts b/typescript/src/llm/index.ts index 26d0a613..1defd75f 100644 --- a/typescript/src/llm/index.ts +++ b/typescript/src/llm/index.ts @@ -227,7 +227,11 @@ function recordingFetch(record: (error: unknown) => void): typeof fetch { * @param record ((error: unknown) => void): receives each call's connection error, or null. * @return (Promise): the language model. */ -async function resolveModel(config: ParsedLLMConfig, record: (error: unknown) => void): Promise { +async function resolveModel( + config: ParsedLLMConfig, + record: (error: unknown) => void, + embedding = false, +): Promise { const provider = config.provider.toLowerCase(); const prefix = `${config.provider}/`; const modelId = config.model.startsWith(prefix) ? config.model.slice(prefix.length) : config.model; @@ -252,7 +256,16 @@ async function resolveModel(config: ParsedLLMConfig, record: (error: unknown) => ); const factory = mod[factoryName] as Factory | undefined; if (typeof factory !== "function") throw new ExtractionError(`${pkg} does not export ${factoryName}`); - const instance = factory(settings) as ((modelId: string) => unknown) & { chat?: (modelId: string) => unknown }; + const instance = factory(settings) as ((modelId: string) => unknown) & { + chat?: (modelId: string) => unknown; + embeddingModel?: (modelId: string) => unknown; + }; + if (embedding) { + if (typeof instance.embeddingModel !== "function") { + throw new ExtractionError("the configured provider does not expose embedding models"); + } + return instance.embeddingModel(modelId); + } if (provider === "openai" && config.base_url != null && typeof instance.chat === "function") { return instance.chat(modelId); } @@ -370,14 +383,62 @@ export function checkLlmConfig(config: LLMConfig): ParsedLLMConfig { return parsed; } +/** Parse a model shorthand. @param value (string) The shorthand. @return (LLMConfig) The model settings. */ +export function modelShorthand(value: string): LLMConfig { + const slash = value.indexOf("/"); + if (slash < 1 || slash === value.length - 1 || /\s/.test(value) || value.includes("://")) { + throw new ValidationError("model shorthand must look like provider/model", { + code: "invalid_setting", + field: "model", + }); + } + return { provider: value.slice(0, slash), model: value }; +} + +export type EmbedderArg = Embedder | LLMConfig | string; + +/** Build an embedder. @param model (EmbedderArg) The model or embedder. @return (Embedder) The embedder. */ +export function buildEmbedder(model: EmbedderArg): Embedder { + if (typeof model === "object" && typeof (model as Embedder)?.embed === "function") return model as Embedder; + if ( + typeof model !== "string" && + (model == null || typeof model !== "object" || !("provider" in model || "model" in model)) + ) { + throw new ValidationError(`embedder must have an embed method, got ${typeName(model)}`); + } + const config = checkLlmConfig(typeof model === "string" ? modelShorthand(model) : (model as LLMConfig)); + const embedding = new Lazy(() => resolveModel(config, () => undefined, true)); + return { + async embed(texts: string[]): Promise { + const { embedMany } = await loadOptional<{ + embedMany: (options: Record) => Promise<{ embeddings: number[][] }>; + }>("ai", "embeddings need the optional 'ai' package; npm install ai", ExtractionError); + const model = await embedding.get(); + try { + const result = await embedMany({ + model, + values: texts, + maxRetries: config.max_retries, + abortSignal: config.timeout === null ? undefined : AbortSignal.timeout(config.timeout * 1000), + }); + return result.embeddings; + } catch (exc) { + throw ( + fatalError(exc, config) ?? new ExtractionError(`embedding failed: ${summarizeError(exc, config.base_url)}`) + ); + } + }, + }; +} + /** * Build an LLM client that routes to any provider through the matching AI SDK package. * - * @param config (LLMConfig): the provider, model, and connection settings. + * @param config (LLMConfig | string): the provider, model, and connection settings. * @return (LLMClient): the client. */ -export function buildLlmClient(config: LLMConfig): LLMClient { - const parsed = checkLlmConfig(config); +export function buildLlmClient(config: LLMConfig | string): LLMClient { + const parsed = checkLlmConfig(typeof config === "string" ? modelShorthand(config) : config); return new AISDKClient( { config: parsed }, parsed.temperature, @@ -408,7 +469,7 @@ export function buildProvider(llm: LLMConfig | LLMClient, embedder: Embedder, re return provider; } -export type LLMArg = LLMConfig | LLMClient | object | null | undefined; +export type LLMArg = LLMConfig | LLMClient | object | string | null | undefined; /** * Normalise the llm argument: an LLMConfig, an LLMClient, or an AI SDK model object. @@ -418,6 +479,7 @@ export type LLMArg = LLMConfig | LLMClient | object | null | undefined; */ export function resolveLlm(llm: LLMArg): LLMClient | null { if (llm == null) return null; + if (typeof llm === "string") return buildLlmClient(llm); if (typeof llm === "object" && isLlmClient(llm)) return llm; if (isLanguageModel(llm)) { const { provider, modelId } = llm as { provider?: unknown; modelId?: unknown }; diff --git a/typescript/src/llm/tasks.ts b/typescript/src/llm/tasks.ts new file mode 100644 index 00000000..89790495 --- /dev/null +++ b/typescript/src/llm/tasks.ts @@ -0,0 +1,89 @@ +import { needsLlm, ValidationError } from "../errors.js"; +import type { LLMClient } from "../protocols.js"; +import { LADDERS, type Level } from "../tiers.js"; +import { type EmbedderArg, type LLMArg, resolveLlm } from "./index.js"; + +export const PASSES = ["entities", "relations", "preferences", "decisions"] as const; +const TASKS = [...PASSES, "resolution", "contradiction", "seeds", "rerank"] as const; +type Pass = (typeof PASSES)[number]; +type Task = Exclude<(typeof TASKS)[number], Pass>; + +export interface LLMTask { + enabled?: boolean; + model?: Model; +} + +export type EmbeddingTask = LLMTask; +export type LLMTasks = Partial< + Record & Record<"seeds" | "rerank", EmbeddingTask> +>; +export type ExtractionTasks = Partial>; + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** Validate task settings. @param value (unknown) The settings. @return (LLMTasks) The checked tasks. */ +export function checkLlmTasks(value: unknown): LLMTasks { + if (value == null) return {}; + if (!isObject(value)) { + throw new ValidationError("llm_tasks must be an object", { code: "invalid_setting", field: "llm_tasks" }); + } + for (const [name, task] of Object.entries(value)) { + if (!(TASKS as readonly string[]).includes(name)) { + throw new ValidationError("llm_tasks contains an unknown task", { code: "invalid_setting", field: "llm_tasks" }); + } + if ( + !isObject(task) || + Object.keys(task).some((key) => key !== "model" && key !== "enabled") || + ("enabled" in task && typeof task.enabled !== "boolean") + ) { + throw new ValidationError( + `llm_tasks.${name} must be an object with optional enabled (boolean) and model fields`, + { code: "invalid_setting", field: `llm_tasks.${name}` }, + ); + } + } + return value as LLMTasks; +} + +/** Select the default tier. @param tasks (LLMTasks) Task settings. @param name (Task) The task. @param fallback (string) The preset tier. @return (string) The selected tier. */ +export function taskDefault(tasks: LLMTasks, name: Task, fallback: string): string { + return tasks[name]?.enabled === true ? LADDERS[name].at(-1)! : fallback; +} + +/** Apply the task switch. @param task (LLMTask) The task options. @param cap (Level) The graph ceiling. @return (Level) The effective ceiling. */ +export function taskCap(task: Pick | undefined, cap: Level): Level { + return cap === "max" && task?.enabled === false ? "balanced" : cap; +} + +/** Resolve a task model. @param task (LLMTask) Task options. @param cap (Level) The ceiling. @param resolve (function) The adapter. @param fallback (Client | null) The graph model. @return (Client | null) The resolved model. */ +export function taskModel( + task: LLMTask | undefined, + cap: Level, + resolve: (model: Model) => Client, + fallback: Client | null, +): Client | null { + if (taskCap(task, cap) !== "max") return null; + return task?.model == null ? fallback : resolve(task.model); +} + +/** Resolve extraction pass models. @param tasks (ExtractionTasks) Pass options. @param fallback (LLMClient | null) The graph LLM. @return (Record) The active models by pass. */ +export function extractionTasks(tasks: ExtractionTasks, fallback: LLMClient | null): Record { + return Object.fromEntries( + PASSES.map((name) => { + const task = tasks[name]; + if (task?.enabled === false) return [name, null]; + const model = resolveLlm(task?.model) ?? fallback; + if (model === null) throw needsLlm("extraction 'llm'"); + return [name, model]; + }), + ) as Record; +} + +/** Reuse resolved pass models. @param tasks (ExtractionTasks) Pass options. @param fallback (LLMClient | null) The graph LLM. @return (ExtractionTasks) Resolved pass options. */ +export function resolvedPasses(tasks: ExtractionTasks, fallback: LLMClient | null): ExtractionTasks { + return Object.fromEntries( + Object.entries(extractionTasks(tasks, fallback)).map(([name, model]) => [name, { enabled: model !== null, model }]), + ); +} diff --git a/typescript/src/retrieval.ts b/typescript/src/retrieval.ts index e105b653..ae4b47bb 100644 --- a/typescript/src/retrieval.ts +++ b/typescript/src/retrieval.ts @@ -26,6 +26,7 @@ import { preferenceEdgeType, R_HAS_CHUNK, } from "./labels.js"; +import { taskCap } from "./llm/tasks.js"; import { scanEntities, scanRelations } from "./maintenance.js"; import type { AnswerabilityReport, @@ -1255,7 +1256,7 @@ async function rerankScores(graph: GraphAccess, tier: string, query: string, tex const terms = stemSet(queryTokens); scores = docs.map((doc) => bm25(terms, idf, doc, avgdl)); } else if (tier === "embeddings") { - const embedder = graph.tiers.embedder!; + const embedder = graph.tiers.rerank_embedder!; const [target] = await embed(embedder, [query]); const vectors: number[][] = []; for (let start = 0; start < texts.length; start += EMBED_BATCH) { @@ -1499,9 +1500,13 @@ export async function retrieve( } else if (!pyStrip(query)) { throw new ValidationError("query cannot be empty"); } - const { embedder, max_tier: maxTier } = graph.tiers; - const seeds = options.seeds == null ? graph.tiers.seeds : seedTier(options.seeds, embedder, maxTier); - const rerank = options.rerank == null ? graph.tiers.rerank : rerankTier(options.rerank, embedder, maxTier); + const { embedder, rerank_embedder, llm_tasks, max_tier: maxTier } = graph.tiers; + const seeds = + options.seeds == null ? graph.tiers.seeds : seedTier(options.seeds, embedder, taskCap(llm_tasks.seeds, maxTier)); + const rerank = + options.rerank == null + ? graph.tiers.rerank + : rerankTier(options.rerank, rerank_embedder, taskCap(llm_tasks.rerank, maxTier)); if (options.strategy != null && typeof options.strategy !== "string") { throw new ValidationError(`strategy must be a string, got ${typeName(options.strategy)}`); } @@ -1835,9 +1840,13 @@ export async function search(graph: GraphAccess, query: string, options: SearchO const k = options.k ?? RETRIEVE_DEFAULTS.k; requireInt("k", k); if (k < 1) throw new ValidationError(`k must be >= 1, got ${k}`, { field: "k" }); - const { embedder, max_tier: maxTier } = graph.tiers; - const seeds = options.seeds == null ? graph.tiers.seeds : seedTier(options.seeds, embedder, maxTier); - const rerank = options.rerank == null ? graph.tiers.rerank : rerankTier(options.rerank, embedder, maxTier); + const { embedder, rerank_embedder, llm_tasks, max_tier: maxTier } = graph.tiers; + const seeds = + options.seeds == null ? graph.tiers.seeds : seedTier(options.seeds, embedder, taskCap(llm_tasks.seeds, maxTier)); + const rerank = + options.rerank == null + ? graph.tiers.rerank + : rerankTier(options.rerank, rerank_embedder, taskCap(llm_tasks.rerank, maxTier)); const asOf = ops.parseAsOf(options.as_of, options.known_at); const wanted = kinds ?? KINDS; return graph.read(async (store, ns) => { diff --git a/typescript/src/runtime.ts b/typescript/src/runtime.ts index 3a45f7e9..f546e6d1 100644 --- a/typescript/src/runtime.ts +++ b/typescript/src/runtime.ts @@ -23,6 +23,7 @@ import { blankLexicalTokens } from "./internal/cypherGuard.js"; import { log } from "./internal/log.js"; import { comparePy, PY_WORD_CLASS, PY_WS_CLASS, pyRepr, pySplit, pyStrip } from "./internal/py.js"; import { EDGE_TYPES, LABELS, PREFERENCE_EDGE_TYPES } from "./labels.js"; +import { checkLlmTasks, type LLMTasks } from "./llm/tasks.js"; import { scanEntities, scanRelations } from "./maintenance.js"; import { asInput, @@ -73,6 +74,7 @@ export interface GraphSettings { namespace: string; llm_provider: string | null; llm_model: string | null; + llm_tasks?: LLMTasks | string | null; llm_api_key: string | null; llm_api_key_env: string | null; llm_base_url: string | null; @@ -97,6 +99,7 @@ export const DEFAULT_SETTINGS: Readonly = Object.freeze({ namespace: "default", llm_provider: null, llm_model: null, + llm_tasks: null, llm_api_key: null, llm_api_key_env: null, llm_base_url: null, @@ -903,8 +906,9 @@ export function checkSettings(settings: GraphSettings): GraphSettings { llmTimeout(settings.llm_timeout); llmConcurrency(settings.llm_concurrency); const read_only = readOnlySetting(settings.read_only); + const tasks = checkLlmTasks(jsonSetting(settings.llm_tasks ?? null, "llm_tasks")); const llm = buildLlm(settings); - if (llm === null) { + if (llm === null && !Object.keys(tasks).length) { const level = (settings.level || "balanced") as Level; const cap = (settings.max_tier || "max") as Level; if (level === "max" && cap === "max") throw needsLlm("level 'max'"); @@ -925,5 +929,5 @@ export function checkSettings(settings: GraphSettings): GraphSettings { ); const prompts = asInput(ExtractionPrompts, jsonSetting(settings.prompts, "prompts"), "prompts"); checkPrompts(prompts); - return { ...settings, schema, instructions, prompts, read_only }; + return { ...settings, schema, instructions, prompts, read_only, llm_tasks: tasks }; } diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 6ed06ec9..b7ade823 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -74,6 +74,7 @@ _StepOut, ) from selfgraph.extraction.prompts import DEFAULT_PROMPTS +from selfgraph.llm.base import model_shorthand from selfgraph.mcp import server as mcp_server from selfgraph.models import ( EntityMatch, @@ -556,6 +557,16 @@ def deep_property_errors(): ] +def llm_task_settings(): + result = [model_shorthand("openai/group/model").model_dump(include={"provider", "model"})] + for value in ('{"entities":{"enabled":false}}', '{"seeds":{"enabled":"false"}}', '{"unknown":{}}'): + try: + result.append(check_settings(GraphSettings(store="kuzu", llm_tasks=value)).llm_tasks) + except ValidationError as exc: + result.append([exc.code, exc.field, str(exc)]) + return result + + def llm_setting_errors(): """Parse the LLM timeout and concurrency settings from text. @@ -1038,6 +1049,7 @@ def endpoint_outcome(spec): "llm_endpoint_aliases": llm_endpoint_aliases(), "deep_property_errors": deep_property_errors(), "llm_setting_errors": llm_setting_errors(), + "llm_task_settings": llm_task_settings(), "mcp_read_only": mcp_read_only(), "iso_times": iso_times(), "relative_times": relative_times(), diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index ddf4f50a..7583338b 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -93,6 +93,7 @@ import { syncAttributes, } from "../../src/internal/tracing.js"; import { ALNUM_CLASS, DECIMAL_CLASS, LETTER_CLASS, lower, upper } from "../../src/internal/unicode.js"; +import { modelShorthand } from "../../src/llm/index.js"; import { callTool, httpOptions, httpRefusal, isBlockedQuery, servedTools } from "../../src/mcp.js"; import { EntityInput, @@ -610,6 +611,20 @@ const LLM_SETTING_VALUES: Record<"timeout" | "concurrency", string[]> = { ], }; +function llmTaskSettings(): unknown[] { + return [ + modelShorthand("openai/group/model"), + ...['{"entities":{"enabled":false}}', '{"seeds":{"enabled":"false"}}', '{"unknown":{}}'].map((value) => { + try { + return checkSettings({ ...DEFAULT_SETTINGS, store: "kuzu", llm_tasks: value }).llm_tasks; + } catch (exc) { + if (!(exc instanceof ValidationError)) throw exc; + return [exc.code, exc.field, exc.message]; + } + }), + ]; +} + /** * Parse the LLM timeout and concurrency settings from text. * @@ -928,6 +943,7 @@ export function schemaWarnings(): { llm_endpoint_aliases: unknown[]; deep_property_errors: unknown[]; llm_setting_errors: unknown[]; + llm_task_settings: unknown[]; mcp_read_only: { settings: unknown[]; tools: string[] }; iso_times: string[]; relative_times: string[]; @@ -1167,6 +1183,7 @@ export function schemaWarnings(): { llm_endpoint_aliases: llmEndpointAliases(), deep_property_errors: deepPropertyErrors(), llm_setting_errors: llmSettingErrors(), + llm_task_settings: llmTaskSettings(), mcp_read_only: mcpReadOnly(), error_hints: HINTS, extraction_prompts: DEFAULT_PROMPTS, diff --git a/typescript/test/tiers.test.ts b/typescript/test/tiers.test.ts index 8973552b..e6f58fe2 100644 --- a/typescript/test/tiers.test.ts +++ b/typescript/test/tiers.test.ts @@ -1,7 +1,8 @@ -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import type { z } from "zod"; import { + buildEmbedder, buildGraph, DEFAULT_SETTINGS, type Embedder, @@ -97,6 +98,95 @@ const numberedLines = (prompt: string): string[] => pySplitLines(prompt).filter( function suite(spec: StoreSpec): void { const open = freshGraphs(spec, "tier"); + it("routes enabled extraction passes and skips disabled passes", async () => { + const generate = + (reply: object): LLMClient["generate"] => + async ({ output }) => + output.parse(reply); + const defaultModel = vi.fn(generate({ decisions: [] })); + const entities = vi.fn(generate({ entities: [{ type: "Person", name: "Ann" }] })); + const g = open({ + llm: { generate: defaultModel }, + llm_tasks: { + entities: { model: { generate: entities } }, + relations: { enabled: false }, + preferences: { enabled: false }, + }, + }); + const result = await g.insert.text("Ann is here."); + expect(result.entities.map((entity) => entity.name)).toEqual(["Ann"]); + expect(entities).toHaveBeenCalledTimes(1); + expect(defaultModel).toHaveBeenCalledTimes(1); + }); + + it("routes separate judge and resolution overrides", async () => { + const judge = new Judge(); + const same: LLMClient["generate"] = async ({ output }) => output.parse({ same: true }); + const resolver = vi.fn(same); + const defaultModel = new Judge(); + const g = open({ + llm: defaultModel, + resolver: "llm", + llm_tasks: { resolution: { model: { generate: resolver } }, contradiction: { enabled: true, model: judge } }, + }); + await g.insert.facts({ + entities: [...ANN_ACME_GLOBEX, { type: "Person", name: "John Smith" }], + relations: [annAt("acme", 2020)], + }); + const result = await g.insert.facts( + { entities: [{ type: "Person", name: "Jon Smyth" }], relations: [annAt("globex", 2022)] }, + { resolver: "llm" }, + ); + expect(result.merges.map((merge) => merge.reason)).toEqual(["llm"]); + expect(resolver).toHaveBeenCalledTimes(1); + expect(judge.prompts).toHaveLength(1); + expect((await g.relations.list()).items.map((relation) => relation.id)).toEqual([GLOBEX]); + expect(defaultModel.prompts).toEqual([]); + }); + + it("routes distinct embedding tasks and respects the cap", async () => { + const seeds = new FakeEmbedder(); + const rerank = new FakeEmbedder(); + const g = open({ llm_tasks: { seeds: { enabled: true, model: seeds }, rerank: { enabled: true, model: rerank } } }); + await g.entities.create("Cat", "Animal"); + const found = await g.retrieve("Cat"); + expect([found.tiers.seeds, found.tiers.rerank]).toEqual(["embeddings", "embeddings"]); + expect(seeds.calls).toHaveLength(2); + expect(rerank.calls).toHaveLength(2); + const capped = open({ max_tier: "balanced", llm_tasks: { seeds: { enabled: true, model: "invalid" } } }); + expect(capped.tiers.seeds).toBe("bm25"); + }); + + it("builds a library-backed embedder and sends one batch", async () => { + const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response( + JSON.stringify({ + data: [ + { embedding: [1], index: 0 }, + { embedding: [2], index: 1 }, + ], + }), + { headers: { "content-type": "application/json" } }, + ), + ); + try { + const embedder = buildEmbedder({ + provider: "provider", + model: "vector-model", + base_url: "https://vectors.invalid", + api_key: "test-key", + }); + await expect(embedder.embed(["a", "b"])).resolves.toEqual([[1], [2]]); + expect(fetch).toHaveBeenCalledTimes(1); + expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body))).toMatchObject({ + model: "vector-model", + input: ["a", "b"], + }); + } finally { + fetch.mockRestore(); + } + }); + it("levels set every default and reject unknown names", () => { expect(open().tiers).toEqual({ level: "balanced", @@ -668,6 +758,14 @@ describe("tiers over the CLI, MCP, and settings", () => { beforeAll(buildCli); afterAll(closeMcp); + it("applies task settings through CLI and MCP", async () => { + const tasks = '{"resolution":{"enabled":false}}'; + const flags = ["--store", "kuzu", "--uri", tempKuzu("selfgraph-tasks-cli-"), "--resolver", "llm"]; + expect(runCli([...flags, "--llm-tasks", tasks, "init"]).code).toBe(0); + await configureMcp(settings({ resolver: "llm", llm_tasks: tasks })); + expect((await callTool("create_entity", { name: "Ann", type: "Person" })).isError).toBe(false); + }); + it("the CLI, MCP, and settings carry the level", async () => { const env = { SELFGRAPH_STORE: "", SELFGRAPH_URI: undefined, SELFGRAPH_LEVEL: undefined }; const flags = ["--store", "kuzu", "--uri", tempKuzu("selfgraph-tiers-cli-"), "--namespace", "tier"];