diff --git a/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md b/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md new file mode 100644 index 000000000..8325e54c2 --- /dev/null +++ b/dokimi/changelog.d/20261205_221923_nikolay.a.petrov_pipeline-settings.md @@ -0,0 +1,8 @@ + + +### Added + +- **`EvaluationPipeline` accepts an `EvaluationSettings` object.** Python callers can pass the same run settings as one object with `EvaluationPipeline(settings=...)`. Existing positional and keyword arguments still work. diff --git a/dokimi/dokimi/commands/benchmark.py b/dokimi/dokimi/commands/benchmark.py index 591dc1fd4..5d58a0847 100644 --- a/dokimi/dokimi/commands/benchmark.py +++ b/dokimi/dokimi/commands/benchmark.py @@ -52,7 +52,7 @@ def _refuse_judge_sampling(args: argparse.Namespace) -> None: def _run_single_library(entry, output_dir: str, model: str, provider: str, judge_model: str, judge_provider: str = DEFAULT_JUDGE_PROVIDER, doc_source_override=None, max_tokens_per_question: int = DEFAULT_MAX_TOKENS_PER_QUESTION, force_regen: bool = False, concurrency: int = DEFAULT_CONCURRENCY, questions_from=None, questions_root=None, judge_temperature=None, judge_placeholder=False, registry=None) -> dict: """Run full evaluation pipeline for one ProductEntry. Returns result dict.""" from dokimi.commands.arms import pipeline_checkpoint - from dokimi.orchestrator import EvaluationPipeline + from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings from pathlib import Path as _Path doc_source = doc_source_override or (entry.doc_sources[0] if entry.doc_sources else "context7") @@ -72,7 +72,7 @@ def _run_single_library(entry, output_dir: str, model: str, provider: str, judge context=f"benchmark:{entry.key}", ) - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product=entry.name, repo=entry.repo, description=entry.description, @@ -94,7 +94,7 @@ def _run_single_library(entry, output_dir: str, model: str, provider: str, judge registry=registry, questions_root=_Path(questions_root) if questions_root else None, checkpoint=pipeline_checkpoint, # the answered questions, until the answers file is saved (#1004) - ) + )) result = pipeline.run(concurrency=concurrency) return {"library": entry.key, "name": entry.name, "status": "ok", "result": result} diff --git a/dokimi/dokimi/commands/orchestrate.py b/dokimi/dokimi/commands/orchestrate.py index 4cbcf66e7..7d5b19908 100644 --- a/dokimi/dokimi/commands/orchestrate.py +++ b/dokimi/dokimi/commands/orchestrate.py @@ -31,7 +31,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: """Run full evaluation pipeline (orchestrator).""" from dokimi.commands.arms import pipeline_checkpoint from dokimi.mcp.factory import require_local_doc_source - from dokimi.orchestrator import EvaluationPipeline + from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings if not getattr(args, "repo", None) and not getattr(args, "description", None): raise InputError("either --repo or --description must be provided.") @@ -65,7 +65,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: require_local_doc_source(getattr(args, "doc_source", "context7")) # Create pipeline; it checks --questions and creates the output directories try: - pipeline = EvaluationPipeline( + pipeline = EvaluationPipeline(settings=EvaluationSettings( product=args.product, repo=getattr(args, "repo", None), description=getattr(args, "description", None), @@ -87,7 +87,7 @@ def cmd_evaluate(args: argparse.Namespace) -> None: doc_source=getattr(args, "doc_source", "context7"), context7_id=getattr(args, "context7_id", None), checkpoint=pipeline_checkpoint, # the answered questions, until the answers file is saved (#1004) - ) + )) except OSError as exc: # a missing --questions file, an unusable --out-dir raise InputError(str(exc)) from exc diff --git a/dokimi/dokimi/orchestrator/__init__.py b/dokimi/dokimi/orchestrator/__init__.py index 6556a867b..aff240299 100644 --- a/dokimi/dokimi/orchestrator/__init__.py +++ b/dokimi/dokimi/orchestrator/__init__.py @@ -4,5 +4,6 @@ """Pipeline orchestration module.""" from .pipeline import EvaluationPipeline +from .pipeline_settings import EvaluationSettings -__all__ = ["EvaluationPipeline"] +__all__ = ["EvaluationPipeline", "EvaluationSettings"] diff --git a/dokimi/dokimi/orchestrator/pipeline.py b/dokimi/dokimi/orchestrator/pipeline.py index 19a78ceac..c48754fc0 100644 --- a/dokimi/dokimi/orchestrator/pipeline.py +++ b/dokimi/dokimi/orchestrator/pipeline.py @@ -13,14 +13,13 @@ from dokimi.artifacts import save_artifact from dokimi.atomic_write import write_bytes_in_place_or_atomic from dokimi.process_io import text_file_bytes -from dokimi.defaults import (DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER, DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, - DEFAULT_RETRIEVAL_TOP_K) from dokimi.eval.stats import paired_summary from dokimi.mcp.factory import create_doc_source_client, require_local_doc_source, resolve_library_id_for_product from dokimi.orchestrator.arm_answering import Checkpoint, PipelineArms from dokimi.files import InputError, read_json_input, refuse_device from dokimi.digest import key_bytes +from dokimi.orchestrator.pipeline_settings import EvaluationSettings from dokimi.orchestrator.question_source import warn_unpinned_questions from dokimi.orchestrator.question_sets import ( compute_question_set_hash, load_questions_payload, resolve_questions_from_path) @@ -98,118 +97,58 @@ class EvaluationPipeline: 6. Generate report """ - def __init__( - self, - product: str, - output_dir: Path, - repo: Optional[str] = None, - description: Optional[str] = None, - custom_questions_path: Optional[Path] = None, - model: str = DEFAULT_ANSWER_MODEL, - provider: str = DEFAULT_ANSWER_PROVIDER, - judge_model: str = DEFAULT_JUDGE_MODEL, - judge_provider: str = DEFAULT_JUDGE_PROVIDER, - judge_temperature: Optional[float] = None, - personas_count: int = 5, - questions_per_topic: int = 2, - top_k: int = DEFAULT_RETRIEVAL_TOP_K, - rerank_threshold: float = 0.3, - debug_retrieval: bool = False, - doc_source: str = "context7", - context7_id: Optional[str] = None, - max_tokens_per_question: int = 4000, - force_regen: bool = False, - questions_from: Optional[Path] = None, - product_key: Optional[str] = None, - questions_root: Optional[Path] = None, - registry: Optional[Any] = None, - judge_placeholder: bool = False, - checkpoint: Optional[Callable[[Path], Checkpoint]] = None, - ): + def __init__(self, *args: Any, settings: Optional[EvaluationSettings] = None, **kwargs: Any): """ Initialize pipeline. - Args: - product: Product name (e.g., "oneDNN") - output_dir: Base directory for outputs - repo: GitHub repo (e.g., "oneapi-src/oneDNN"). Optional — when - omitted, ``description`` must be provided so the LLM can - generate personas without GitHub data. - description: Plain-text description of the product. Used as the - sole signal for persona generation when ``repo`` is not given. - Also useful to supplement GitHub data. - custom_questions_path: Optional path to manual questions JSON - model: LLM model for generation/answering - provider: Provider for generation/answering - judge_model: LLM model for evaluation - judge_provider: Provider for evaluation - judge_temperature: Optional judge sampling temperature; unset leaves - the provider default - personas_count: Target number of personas - questions_per_topic: Questions per topic per persona - top_k: Docs to retrieve before reranking - rerank_threshold: Min relevance score - debug_retrieval: Include retrieval metadata - doc_source: Documentation source descriptor — 'context7' (default), - 'local:', or 'url:' - context7_id: Explicit Context7 library ID (e.g., 'intel/mkl-dnn'). - Overrides the auto-resolved ID when doc_source is 'context7'. - questions_from: Reuse an existing question set (file, or a run - directory holding questions/.json). - product_key: Registry key used for output file names and golden - question-set lookup (defaults to ``product``). - questions_root: Directory holding golden question sets named - ``_golden.json``, for example a checkout of the - evaluation-content repository. When given and the file is - present it is the run's whole question set and generation is - skipped; when it is absent a warning is logged and questions are - generated. Without this argument (and without - ``custom_questions_path``) the run has no golden set. - registry: ProductRegistry used to find the declared context7_id - (default: the bundled products.yaml) - judge_placeholder: No effect, warned: since method version 4 the - context arm answers a question with no document found with the - plain prompt, and that answer is judged (#228 step 4c) - checkpoint: Makes the file the answered questions are kept in until - the answers file is saved, from the answers path - (``commands.arms.pipeline_checkpoint``); none by default + Takes the run's inputs as an :class:`EvaluationSettings` (``settings=``), or as + the same fields given as keyword arguments, which build one. The fields are + described on :class:`EvaluationSettings`. The fields may also be given + positionally, in field order, as the keyword signature always allowed. """ - if not repo and not description: + if settings is None: + try: + settings = EvaluationSettings(*args, **kwargs) + except TypeError as exc: # preserve the original parameter binding error under the pipeline name + raise TypeError(str(exc).replace("EvaluationSettings.__init__()", "EvaluationPipeline.__init__()", 1)) from None + elif args or kwargs: + raise TypeError("EvaluationPipeline() takes settings or keyword arguments, not both") + if not settings.repo and not settings.description: raise ValueError( "Either 'repo' or 'description' must be provided. " "Supply 'repo' for GitHub-based persona discovery, or " "'description' for products without a public repository." ) - self.product = product - self.product_key = product_key or product - self.repo = repo - self.description = description - self.output_dir = Path(output_dir) - - self.questions_root = Path(questions_root) if questions_root else None - self._resolve_question_source(custom_questions_path, questions_from, force_regen) - - self.model = model - self.provider = provider - self.judge_model = judge_model - self.judge_provider = judge_provider - self.judge_temperature = judge_temperature - _warn_judge_placeholder(judge_placeholder) - - self.personas_count = personas_count - self.questions_per_topic = questions_per_topic - self.top_k = top_k - self.rerank_threshold = rerank_threshold - self.debug_retrieval = debug_retrieval - self.doc_source = doc_source - self.context7_id = context7_id + self.product = settings.product + self.product_key = settings.product_key or settings.product + self.repo = settings.repo + self.description = settings.description + self.output_dir = Path(settings.output_dir) + + self.questions_root = Path(settings.questions_root) if settings.questions_root else None + self._resolve_question_source(settings.custom_questions_path, settings.questions_from, settings.force_regen) + + self.model = settings.model + self.provider = settings.provider + self.judge_model = settings.judge_model + self.judge_provider = settings.judge_provider + self.judge_temperature = settings.judge_temperature + _warn_judge_placeholder(settings.judge_placeholder) + + self.personas_count = settings.personas_count + self.questions_per_topic = settings.questions_per_topic + self.top_k = settings.top_k + self.rerank_threshold = settings.rerank_threshold + self.debug_retrieval = settings.debug_retrieval + self.doc_source = settings.doc_source + self.context7_id = settings.context7_id # Product registry for the library id (defaults to the bundled products.yaml). - self.registry = registry - self.max_tokens_per_question = max_tokens_per_question - self.force_regen = force_regen + self.registry = settings.registry + self.max_tokens_per_question = settings.max_tokens_per_question + self.force_regen = settings.force_regen - self._resolve_external_questions(questions_from) + self._resolve_external_questions(settings.questions_from) # Output paths self.personas_path = self.output_dir / "personas" / f"{self.product_key}.json" @@ -221,7 +160,7 @@ def __init__( # Create output dirs for path in [self.personas_path, self.questions_path, self.answers_path, self.eval_path, self.report_path]: path.parent.mkdir(parents=True, exist_ok=True) - self.checkpoint = _open_checkpoint(checkpoint, self.answers_path) + self.checkpoint = _open_checkpoint(settings.checkpoint, self.answers_path) def _resolve_question_source(self, custom_questions_path: Optional[Path], questions_from: Optional[Path], force_regen: bool) -> None: diff --git a/dokimi/dokimi/orchestrator/pipeline_settings.py b/dokimi/dokimi/orchestrator/pipeline_settings.py new file mode 100644 index 000000000..fdee207ce --- /dev/null +++ b/dokimi/dokimi/orchestrator/pipeline_settings.py @@ -0,0 +1,95 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Settings for one run of :class:`~dokimi.orchestrator.pipeline.EvaluationPipeline`.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Optional + +from dokimi.defaults import (DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER, DEFAULT_JUDGE_MODEL, DEFAULT_JUDGE_PROVIDER, + DEFAULT_RETRIEVAL_TOP_K) +from dokimi.orchestrator.arm_answering import Checkpoint + + +@dataclass(frozen=True) +class EvaluationSettings: + """ + The inputs of one pipeline run. ``EvaluationPipeline(settings=...)`` takes this + object; ``EvaluationPipeline(**fields)`` builds it from the same fields. + + Fields: + product: Product name (e.g., "oneDNN") + output_dir: Base directory for outputs + repo: GitHub repo (e.g., "oneapi-src/oneDNN"). Optional — when + omitted, ``description`` must be provided so the LLM can + generate personas without GitHub data. + description: Plain-text description of the product. Used as the + sole signal for persona generation when ``repo`` is not given. + Also useful to supplement GitHub data. + custom_questions_path: Optional path to manual questions JSON + model: LLM model for generation/answering + provider: Provider for generation/answering + judge_model: LLM model for evaluation + judge_provider: Provider for evaluation + judge_temperature: Optional judge sampling temperature; unset leaves + the provider default + personas_count: Target number of personas + questions_per_topic: Questions per topic per persona + top_k: Docs to retrieve before reranking + rerank_threshold: Min relevance score + debug_retrieval: Include retrieval metadata + doc_source: Documentation source descriptor — 'context7' (default), + 'local:', or 'url:' + context7_id: Explicit Context7 library ID (e.g., 'intel/mkl-dnn'). + Overrides the auto-resolved ID when doc_source is 'context7'. + max_tokens_per_question: Token budget for documentation retrieved per question + force_regen: Regenerate the question set even when a cached one exists + questions_from: Reuse an existing question set (file, or a run + directory holding questions/.json). + product_key: Registry key used for output file names and golden + question-set lookup (defaults to ``product``). + questions_root: Directory holding golden question sets named + ``_golden.json``, for example a checkout of the + evaluation-content repository. When given and the file is + present it is the run's whole question set and generation is + skipped; when it is absent a warning is logged and questions are + generated. Without this argument (and without + ``custom_questions_path``) the run has no golden set. + registry: ProductRegistry used to find the declared context7_id + (default: the bundled products.yaml) + judge_placeholder: No effect, warned: since method version 4 the + context arm answers a question with no document found with the + plain prompt, and that answer is judged (#228 step 4c) + checkpoint: Makes the file the answered questions are kept in until + the answers file is saved, from the answers path + (``commands.arms.pipeline_checkpoint``); none by default + """ + + product: str + output_dir: Path + repo: Optional[str] = None + description: Optional[str] = None + custom_questions_path: Optional[Path] = None + model: str = DEFAULT_ANSWER_MODEL + provider: str = DEFAULT_ANSWER_PROVIDER + judge_model: str = DEFAULT_JUDGE_MODEL + judge_provider: str = DEFAULT_JUDGE_PROVIDER + judge_temperature: Optional[float] = None + personas_count: int = 5 + questions_per_topic: int = 2 + top_k: int = DEFAULT_RETRIEVAL_TOP_K + rerank_threshold: float = 0.3 + debug_retrieval: bool = False + doc_source: str = "context7" + context7_id: Optional[str] = None + max_tokens_per_question: int = 4000 + force_regen: bool = False + questions_from: Optional[Path] = None + product_key: Optional[str] = None + questions_root: Optional[Path] = None + registry: Optional[Any] = None + judge_placeholder: bool = False + checkpoint: Optional[Callable[[Path], Checkpoint]] = None diff --git a/dokimi/tests/test_answering_stack_p_step2.py b/dokimi/tests/test_answering_stack_p_step2.py index f9a53ae63..5b8a836e4 100644 --- a/dokimi/tests/test_answering_stack_p_step2.py +++ b/dokimi/tests/test_answering_stack_p_step2.py @@ -26,7 +26,8 @@ class _FakePipeline: built: list = [] - def __init__(self, **kwargs): + def __init__(self, settings): + kwargs = vars(settings) _FakePipeline.built.append(kwargs) self.answers_path = kwargs["output_dir"] / "answers" / f"{kwargs['product_key']}.json" diff --git a/dokimi/tests/test_benchmark_command_question_set.py b/dokimi/tests/test_benchmark_command_question_set.py index d96892ecd..9d6fea90e 100644 --- a/dokimi/tests/test_benchmark_command_question_set.py +++ b/dokimi/tests/test_benchmark_command_question_set.py @@ -161,8 +161,8 @@ def test_questions_root_reaches_the_pipeline(monkeypatch, tmp_path): seen: dict[str, object] = {} class FakePipeline: - def __init__(self, **kwargs): - seen.update(kwargs) + def __init__(self, settings): + seen.update(vars(settings)) def run(self, concurrency=5): return {} diff --git a/dokimi/tests/test_benchmark_registry_wiring.py b/dokimi/tests/test_benchmark_registry_wiring.py index 3ce13f3fa..05b324455 100644 --- a/dokimi/tests/test_benchmark_registry_wiring.py +++ b/dokimi/tests/test_benchmark_registry_wiring.py @@ -48,7 +48,8 @@ class _Spy: built: list = [] - def __init__(self, **kwargs): + def __init__(self, settings): + kwargs = vars(settings) # every field is also a keyword: EvaluationPipeline(**kwargs) takes them back self.kwargs = kwargs _Spy.built.append(kwargs) diff --git a/dokimi/tests/test_pipeline_question_set.py b/dokimi/tests/test_pipeline_question_set.py index 8166a6c17..57f063f2f 100644 --- a/dokimi/tests/test_pipeline_question_set.py +++ b/dokimi/tests/test_pipeline_question_set.py @@ -228,8 +228,8 @@ def test_evaluate_command_forwards_questions_root(tmp_path, monkeypatch): seen: dict[str, object] = {} class FakePipeline: - def __init__(self, **kwargs): - seen.update(kwargs) + def __init__(self, settings): + seen.update(vars(settings)) def run(self, concurrency=5): return { diff --git a/dokimi/tests/test_pipeline_settings.py b/dokimi/tests/test_pipeline_settings.py new file mode 100644 index 000000000..d1bb7ebd7 --- /dev/null +++ b/dokimi/tests/test_pipeline_settings.py @@ -0,0 +1,74 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""EvaluationPipeline takes its inputs as an EvaluationSettings, or as the same fields as keywords.""" + +from dataclasses import fields +from pathlib import Path + +import pytest + +from dokimi.orchestrator import EvaluationPipeline, EvaluationSettings + + +def _attrs(pipe): + return {k: v for k, v in sorted(vars(pipe).items()) if not callable(v)} + + +def test_settings_and_keywords_build_the_same_pipeline(tmp_path): + kwargs = dict(product="oneTBB", output_dir=tmp_path / "run", description="d", model="m", top_k=7) + by_keywords = EvaluationPipeline(**kwargs) + by_settings = EvaluationPipeline(settings=EvaluationSettings(**kwargs)) + assert _attrs(by_settings) == _attrs(by_keywords) + + +def test_positional_arguments_fill_the_fields_in_order(tmp_path): + by_position = EvaluationPipeline("oneTBB", tmp_path / "run", "oneapi-src/oneTBB", description=None) + by_keyword = EvaluationPipeline(product="oneTBB", output_dir=tmp_path / "run", repo="oneapi-src/oneTBB", + description=None) + assert _attrs(by_position) == _attrs(by_keyword) + + +def test_a_positional_argument_repeated_as_a_keyword_is_refused(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline("oneTBB", tmp_path, product="x", description="d") + assert str(exc.value) == "EvaluationPipeline.__init__() got multiple values for argument 'product'" + + +@pytest.mark.parametrize(("kwargs", "message"), [ + ({"product": "other"}, "got multiple values for argument 'product'"), + ({"bogus": True}, "got an unexpected keyword argument 'bogus'"), +]) +def test_constructor_reports_bad_keywords_before_excess_positional_arguments(kwargs, message): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(*([None] * 26), **kwargs) + assert str(exc.value) == f"EvaluationPipeline.__init__() {message}" + + +def test_the_settings_fields_are_the_constructor_keywords(): + names = {f.name for f in fields(EvaluationSettings)} + assert {"product", "output_dir", "questions_root", "checkpoint", "judge_placeholder"} <= names + assert "settings" not in names + + +def test_settings_and_keywords_together_are_refused(tmp_path): + settings = EvaluationSettings(product="oneTBB", output_dir=tmp_path, description="d") + with pytest.raises(TypeError, match="takes settings or keyword arguments, not both"): + EvaluationPipeline(settings=settings, model="m") + + +def test_an_unknown_keyword_is_refused_under_the_pipeline_name(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(product="oneTBB", output_dir=tmp_path, description="d", bogus=1) + assert str(exc.value) == "EvaluationPipeline.__init__() got an unexpected keyword argument 'bogus'" + + +def test_a_missing_required_field_is_refused_under_the_pipeline_name(tmp_path): + with pytest.raises(TypeError) as exc: + EvaluationPipeline(output_dir=tmp_path, description="d") + assert str(exc.value) == "EvaluationPipeline.__init__() missing 1 required positional argument: 'product'" + + +def test_the_settings_are_not_stored_on_the_pipeline(tmp_path): + pipe = EvaluationPipeline(settings=EvaluationSettings(product="oneTBB", output_dir=Path(tmp_path), description="d")) + assert not any(isinstance(v, EvaluationSettings) for v in vars(pipe).values())