Fine-Tuning, Open-Weight Models & Routing
Compare prompting/RAG, fine-tuning, and open-weight model routing across quality, cost, latency, and privacy trade-offs, and build a deterministic model router in fde-04-4 tested with pytest and GitHub Actions.
Sending every request to a single large model or jumping straight into fine-tuning before fixing retrieval and prompts creates unnecessary cost, higher latency, and avoidable infrastructure complexity.
In this module, you will build a deterministic model-routing and trade-off evaluation module in fde-04-4 that selects qualifying candidates across prompting/RAG, fine-tuned models, and open-weight/private endpoints under explicit latency, cost, and privacy constraints.
Enterprise Scenario: Northwind Freight
Northwind’s freight operations assistant handles high-volume shipment status lookups, structured customs-code extraction, and complex multi-carrier exception analysis. Some manifests contain restricted customer data that must stay inside private infrastructure, while routine lookups need low latency and low cost per run.
What You Will Build
- Routing and candidate schemas: Define strict Pydantic v2 models in
src/fde_04_4/schemas.pyfor inference approach, deployment type, independent fine-tuning status, restricted-data approval, routing decisions, and internally consistent benchmark summaries. - Constraint-aware router and batch evaluator: Implement
estimate_request_cost_usd,select_route, andevaluate_routing_batchto enforce complexity, private-hosting, restricted-data approval, latency, and precise budget constraints, then summarize cost, routed latency, route distribution, and rejection reasons. - Automated tests and CI pipeline: Add unit tests in
tests/test_router.pyand verify everything locally and in.github/workflows/tests.yml.
1. Prompting/RAG, Fine-Tuning, Open-Weight Models, and Routing
- Prompting and RAG first: Start with clear instructions, structured outputs, and grounded retrieval when behavior depends on dynamic documents or policies. Retrieval updates immediately without retraining weights.
- When fine-tuning helps: Consider fine-tuning when you have clean, representative examples and need consistent style, format, or specialized task behavior that prompting alone cannot reliably hold, while still keeping dynamic facts in retrieval or tools.
- Open-weight and self-hosted models: Inference approach describes whether the request uses prompting/RAG or direct model inference; deployment describes where the model runs; fine-tuning describes how its weights were adapted. These are independent dimensions: a fine-tuned model can be open-weight and self-hosted, or fine-tuned and served through a managed API. A self-hosted deployment is not automatically approved for restricted data: the candidate must also carry explicit approval. Self-hosting requires managing model hosting, quantization/serving trade-offs, and upgrades.
- Teaching scope boundary: This module uses deterministic candidate profiles, cost formulas, and routing rules so tests run offline in CI. Production routers pair static rules with live telemetry, quality evals, and fallback policies.
Approach and Routing Trade-Offs
| Approach | Best fit | Key trade-off |
|---|---|---|
| Prompting + RAG | Dynamic knowledge, policy lookups, fast iteration | Context length limits and retrieval quality dependence |
| Fine-tuned task model | Stable output format/style with clean training data | Training/eval upkeep and stale facts if ungrounded |
| Self-hosted open-weight | Strict data boundaries and high steady volume | Infra/GPU operations and capacity management |
| Multi-model routing | Mixed complexity and latency/cost budgets | Routing accuracy and maintaining multiple endpoints |
2. Step-by-Step Build Walkthrough
- Create the
fde-04-4repository and project scaffold:mkdir -p fde-04-4/src/fde_04_4 fde-04-4/tests fde-04-4/.github/workflows cd fde-04-4 git init cat > .gitignore <<'EOF' .venv/ .env __pycache__/ .pytest_cache/ *.egg-info/ dist/ build/ EOF cat > pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] name = "fde-04-4" version = "0.1.0" description = "Fine-tuning, open-weight model trade-offs, and deterministic model routing" requires-python = ">=3.11" dependencies = ["pydantic>=2.6,<3"] [project.optional-dependencies] dev = ["pytest>=8.0,<9"] [tool.setuptools.packages.find] where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] EOF cat > .env.example <<'EOF' # Deterministic offline model routing evaluator; no external API keys required. EOF python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Define strict Pydantic v2 schemas in
src/fde_04_4/schemas.py:"""Strict schemas for model candidates, routing requests, and benchmark summaries.""" from __future__ import annotations import math from typing import Literal from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator ApproachKind = Literal["prompt_rag", "direct_inference"] DeploymentKind = Literal["managed_api", "self_hosted_open_weight"] def _non_blank(value: str, field_name: str) -> str: cleaned = value.strip() if not cleaned: raise ValueError(f"{field_name} must not be blank") return cleaned def _positive_int(value: int, field_name: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value < 1: raise ValueError(f"{field_name} must be a positive integer") return value def _finite_non_negative(value: float, field_name: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{field_name} must be a finite number, not bool") number = float(value) if not math.isfinite(number) or number < 0: raise ValueError(f"{field_name} must be finite and non-negative") return number class ModelCandidate(BaseModel): """Inference approach, deployment, fine-tuning, pricing, and privacy are independent dimensions.""" model_config = ConfigDict(extra="forbid", strict=True) model_id: str = Field(min_length=1) approach: ApproachKind deployment: DeploymentKind is_fine_tuned: bool = False max_complexity_tier: int approved_for_restricted_data: bool = False estimated_p95_latency_ms: float input_cost_per_1k_tokens_usd: float output_cost_per_1k_tokens_usd: float @field_validator("model_id") @classmethod def validate_model_id(cls, value: str) -> str: return _non_blank(value, "model_id") @field_validator("max_complexity_tier") @classmethod def validate_tier(cls, value: int) -> int: tier = _positive_int(value, "max_complexity_tier") if tier > 5: raise ValueError("max_complexity_tier must be between 1 and 5") return tier @field_validator("estimated_p95_latency_ms", "input_cost_per_1k_tokens_usd", "output_cost_per_1k_tokens_usd") @classmethod def validate_numeric(cls, value: float, info) -> float: return _finite_non_negative(value, info.field_name) class RoutingRequest(BaseModel): """Task complexity, data classification, latency, and cost constraints.""" model_config = ConfigDict(extra="forbid", strict=True) request_id: str = Field(min_length=1) complexity_tier: int requires_private_hosting: bool = False contains_restricted_data: bool = False max_p95_latency_ms: float max_cost_usd: float estimated_input_tokens: int estimated_output_tokens: int @field_validator("request_id") @classmethod def validate_request_id(cls, value: str) -> str: return _non_blank(value, "request_id") @field_validator("complexity_tier") @classmethod def validate_complexity(cls, value: int) -> int: tier = _positive_int(value, "complexity_tier") if tier > 5: raise ValueError("complexity_tier must be between 1 and 5") return tier @field_validator("estimated_input_tokens") @classmethod def validate_input_tokens(cls, value: int) -> int: return _positive_int(value, "estimated_input_tokens") @field_validator("estimated_output_tokens") @classmethod def validate_output_tokens(cls, value: int) -> int: if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise ValueError("estimated_output_tokens must be a non-negative integer") return value @field_validator("max_p95_latency_ms", "max_cost_usd") @classmethod def validate_limits(cls, value: float, info) -> float: return _finite_non_negative(value, info.field_name) class RoutingDecision(BaseModel): """Selected route or explicit rejection.""" model_config = ConfigDict(extra="forbid", strict=True) request_id: str = Field(min_length=1) routed: bool selected_model_id: str | None = None approach: ApproachKind | None = None estimated_cost_usd: float = 0.0 estimated_p95_latency_ms: float = 0.0 reason_code: Literal["NO_CANDIDATES", "NO_ELIGIBLE_CANDIDATE"] | None = None reason: str = Field(min_length=1) reason_detail: str | None = None @field_validator("request_id", "reason") @classmethod def validate_strings(cls, value: str, info) -> str: return _non_blank(value, info.field_name) @field_validator("estimated_cost_usd", "estimated_p95_latency_ms") @classmethod def validate_metrics(cls, value: float, info) -> float: return _finite_non_negative(value, info.field_name) @model_validator(mode="after") def validate_route_state(self): if self.routed: if self.selected_model_id is None or not self.selected_model_id.strip() or self.approach is None: raise ValueError("routed decisions require a non-blank selected_model_id and an approach") if self.reason_code is not None or self.reason_detail is not None: raise ValueError("routed decisions must not contain rejection fields") else: if self.reason_code is None: raise ValueError("rejected decisions require a stable reason_code") if self.selected_model_id is not None or self.approach is not None: raise ValueError("rejected decisions must not select a model or approach") if self.estimated_cost_usd != 0.0 or self.estimated_p95_latency_ms != 0.0: raise ValueError("rejected decisions must have zero estimated cost and latency") return self class RoutingBenchmarkSummary(BaseModel): """Consistent batch counts, cost, latency, route distribution, and rejection reasons.""" model_config = ConfigDict(extra="forbid", strict=True) total_requests: int = Field(ge=1) routed_count: int = Field(ge=0) rejected_count: int = Field(ge=0) total_estimated_cost_usd: float average_routed_p95_latency_ms: float max_routed_p95_latency_ms: float approach_counts: dict[str, int] rejection_reasons: dict[str, int] decisions: list[RoutingDecision] = Field(min_length=1) @field_validator("total_estimated_cost_usd", "average_routed_p95_latency_ms", "max_routed_p95_latency_ms") @classmethod def validate_summary_metrics(cls, value: float, info) -> float: return _finite_non_negative(value, info.field_name) @model_validator(mode="after") def validate_summary(self): routed = [item for item in self.decisions if item.routed] rejected = [item for item in self.decisions if not item.routed] if self.total_requests != len(self.decisions): raise ValueError("total_requests must equal decisions length") if self.routed_count != len(routed) or self.rejected_count != len(rejected): raise ValueError("routed/rejected counts must match decisions") if self.routed_count + self.rejected_count != self.total_requests: raise ValueError("routed_count + rejected_count must equal total_requests") if len({item.request_id for item in self.decisions}) != len(self.decisions): raise ValueError("decision request_id values must be unique") expected_cost = sum(item.estimated_cost_usd for item in routed) if not math.isclose(self.total_estimated_cost_usd, expected_cost, rel_tol=1e-9, abs_tol=1e-12): raise ValueError("total estimated cost must equal routed decision costs") expected_approaches: dict[str, int] = {} for item in routed: key = item.approach expected_approaches[key] = expected_approaches.get(key, 0) + 1 if self.approach_counts != expected_approaches: raise ValueError("approach_counts must match routed decisions") expected_reasons: dict[str, int] = {} for item in rejected: expected_reasons[item.reason_code] = expected_reasons.get(item.reason_code, 0) + 1 if self.rejection_reasons != expected_reasons: raise ValueError("rejection_reasons must match rejected decisions") latencies = [item.estimated_p95_latency_ms for item in routed] expected_avg = sum(latencies) / len(latencies) if latencies else 0.0 expected_max = max(latencies, default=0.0) if not math.isclose(self.average_routed_p95_latency_ms, expected_avg, rel_tol=1e-9, abs_tol=1e-9): raise ValueError("average routed latency does not match decisions") if not math.isclose(self.max_routed_p95_latency_ms, expected_max, rel_tol=1e-9, abs_tol=1e-9): raise ValueError("maximum routed latency does not match decisions") return self - Implement candidate selection and batch evaluation in
src/fde_04_4/router.py:"""Deterministic model routing across prompting/RAG and deployment types.""" from __future__ import annotations from decimal import Decimal, localcontext from fde_04_4.schemas import ( ModelCandidate, RoutingBenchmarkSummary, RoutingDecision, RoutingRequest, ) def _estimate_cost_decimal(candidate: ModelCandidate, request: RoutingRequest) -> Decimal: # Use a high-precision local context so large token counts and fractional # per-token prices are not rounded by Decimal's default 28-digit context. with localcontext() as context: context.prec = 50 input_cost = ( Decimal(request.estimated_input_tokens) / Decimal(1000) ) * Decimal(str(candidate.input_cost_per_1k_tokens_usd)) output_cost = ( Decimal(request.estimated_output_tokens) / Decimal(1000) ) * Decimal(str(candidate.output_cost_per_1k_tokens_usd)) return input_cost + output_cost def estimate_request_cost_usd(candidate: ModelCandidate, request: RoutingRequest) -> float: """Return unrounded estimated USD cost; round only when displaying results.""" return float(_estimate_cost_decimal(candidate, request)) def select_route(request: RoutingRequest, candidates: list[ModelCandidate]) -> RoutingDecision: """Choose the lowest-cost eligible candidate without rounding budget comparisons.""" ids = [candidate.model_id for candidate in candidates] if len(ids) != len(set(ids)): raise ValueError("candidate model_id values must be unique") if not candidates: return RoutingDecision(request_id=request.request_id, routed=False, reason_code="NO_CANDIDATES", reason="No model candidates configured") qualifying = [] budget = Decimal(str(request.max_cost_usd)) for candidate in candidates: if candidate.max_complexity_tier < request.complexity_tier: continue if request.requires_private_hosting and candidate.deployment != "self_hosted_open_weight": continue if request.contains_restricted_data and not candidate.approved_for_restricted_data: continue if candidate.estimated_p95_latency_ms > request.max_p95_latency_ms: continue exact_cost = _estimate_cost_decimal(candidate, request) if exact_cost > budget: continue qualifying.append((exact_cost, candidate.estimated_p95_latency_ms, candidate)) if not qualifying: return RoutingDecision( request_id=request.request_id, routed=False, reason_code="NO_ELIGIBLE_CANDIDATE", reason="No candidate satisfied the request constraints", reason_detail=(f"tier={request.complexity_tier}; private={request.requires_private_hosting}; " f"restricted_data={request.contains_restricted_data}; " f"max_latency_ms={request.max_p95_latency_ms}; max_cost_usd={request.max_cost_usd}"), ) qualifying.sort(key=lambda item: (item[0], item[1], item[2].model_id)) exact_cost, _, chosen = qualifying[0] return RoutingDecision( request_id=request.request_id, routed=True, selected_model_id=chosen.model_id, approach=chosen.approach, estimated_cost_usd=float(exact_cost), estimated_p95_latency_ms=chosen.estimated_p95_latency_ms, reason=f"Selected lowest-cost qualifying candidate '{chosen.model_id}' ({chosen.approach})", ) def evaluate_routing_batch(requests: list[RoutingRequest], candidates: list[ModelCandidate]) -> RoutingBenchmarkSummary: """Route requests and report consistent cost, latency, distribution, and rejection metrics.""" if not requests: raise ValueError("At least one RoutingRequest is required") decisions = [select_route(req, candidates) for req in requests] routed = [item for item in decisions if item.routed] rejected = [item for item in decisions if not item.routed] latencies = [item.estimated_p95_latency_ms for item in routed] approach_counts: dict[str, int] = {} rejection_reasons: dict[str, int] = {} for item in routed: approach_counts[item.approach] = approach_counts.get(item.approach, 0) + 1 for item in rejected: rejection_reasons[item.reason_code] = rejection_reasons.get(item.reason_code, 0) + 1 return RoutingBenchmarkSummary( total_requests=len(decisions), routed_count=len(routed), rejected_count=len(rejected), total_estimated_cost_usd=sum(item.estimated_cost_usd for item in routed), average_routed_p95_latency_ms=sum(latencies) / len(latencies) if latencies else 0.0, max_routed_p95_latency_ms=max(latencies, default=0.0), approach_counts=approach_counts, rejection_reasons=rejection_reasons, decisions=decisions, ) - Add unit tests in
tests/test_router.py:"""Regression tests for privacy-aware model routing and batch benchmarks.""" from __future__ import annotations import pytest from pydantic import ValidationError from fde_04_4.router import estimate_request_cost_usd, evaluate_routing_batch, select_route from fde_04_4.schemas import ModelCandidate, RoutingDecision, RoutingRequest, RoutingBenchmarkSummary def _catalog(): return [ ModelCandidate(model_id="rag-small-fast", approach="prompt_rag", deployment="managed_api", max_complexity_tier=2, estimated_p95_latency_ms=220.0, input_cost_per_1k_tokens_usd=0.20, output_cost_per_1k_tokens_usd=0.60), ModelCandidate(model_id="ft-openweight-private", approach="direct_inference", deployment="self_hosted_open_weight", is_fine_tuned=True, max_complexity_tier=3, approved_for_restricted_data=True, estimated_p95_latency_ms=340.0, input_cost_per_1k_tokens_usd=0.35, output_cost_per_1k_tokens_usd=0.90), ModelCandidate(model_id="frontier-complex", approach="prompt_rag", deployment="managed_api", max_complexity_tier=5, estimated_p95_latency_ms=950.0, input_cost_per_1k_tokens_usd=2.50, output_cost_per_1k_tokens_usd=7.50), ] def _request(**overrides): data = dict(request_id="req-1", complexity_tier=1, max_p95_latency_ms=500.0, max_cost_usd=1.0, estimated_input_tokens=500, estimated_output_tokens=200) data.update(overrides) return RoutingRequest(**data) def test_routes_simple_request_to_cheapest_qualifying_model(): decision = select_route(_request(), _catalog()) assert decision.routed and decision.selected_model_id == "rag-small-fast" def test_private_hosting_requires_self_hosted_deployment(): decision = select_route(_request(requires_private_hosting=True, complexity_tier=2), _catalog()) assert decision.routed and decision.selected_model_id == "ft-openweight-private" def test_restricted_data_requires_explicit_approval(): decision = select_route(_request(contains_restricted_data=True), _catalog()) assert decision.routed and decision.selected_model_id == "ft-openweight-private" def test_rejects_when_no_candidate_meets_constraints(): decision = select_route(_request(complexity_tier=5, requires_private_hosting=True, max_p95_latency_ms=100.0, max_cost_usd=0.05), _catalog()) assert not decision.routed and decision.selected_model_id is None def test_cost_is_not_rounded_before_budget_comparison(): candidate = ModelCandidate(model_id="fractional", approach="prompt_rag", deployment="managed_api", max_complexity_tier=1, estimated_p95_latency_ms=10.0, input_cost_per_1k_tokens_usd=0.000001, output_cost_per_1k_tokens_usd=0.0) request = _request(max_cost_usd=0.0000000005, estimated_input_tokens=1, estimated_output_tokens=1) assert estimate_request_cost_usd(candidate, request) > request.max_cost_usd assert not select_route(request, [candidate]).routed def test_rejects_duplicate_candidate_ids(): catalog = _catalog() with pytest.raises(ValueError, match="unique"): select_route(_request(), [catalog[0], catalog[0]]) def test_decision_rejects_inconsistent_routed_state(): with pytest.raises(ValidationError): RoutingDecision(request_id="x", routed=True, reason="missing model") def test_summary_includes_latency_distribution_and_rejection_reasons(): reqs = [_request(request_id="a"), _request(request_id="b", complexity_tier=5, requires_private_hosting=True, max_p95_latency_ms=10.0)] summary = evaluate_routing_batch(reqs, _catalog()) assert summary.total_requests == 2 assert summary.routed_count == 1 and summary.rejected_count == 1 assert summary.average_routed_p95_latency_ms == 220.0 assert summary.max_routed_p95_latency_ms == 220.0 assert summary.approach_counts == {"prompt_rag": 1} assert sum(summary.rejection_reasons.values()) == 1 def test_summary_rejects_inconsistent_counts(): with pytest.raises(ValidationError): summary = evaluate_routing_batch([_request()], _catalog()) RoutingBenchmarkSummary(**{**summary.model_dump(), "routed_count": 0}) def test_latency_limit_is_inclusive(): candidate = _catalog()[0] decision = select_route(_request(max_p95_latency_ms=220.0), [candidate]) assert decision.routed def test_rejects_candidate_above_latency_limit(): candidate = _catalog()[0] decision = select_route(_request(max_p95_latency_ms=219.99), [candidate]) assert not decision.routed def test_budget_limit_is_inclusive(): candidate = _catalog()[0] request = _request(max_cost_usd=0.22) decision = select_route(request, [candidate]) assert decision.routed def test_rejected_decision_must_have_zero_metrics(): with pytest.raises(ValidationError): RoutingDecision(request_id="reject", routed=False, estimated_cost_usd=0.01, reason="No eligible candidate") def test_routed_decision_rejects_blank_model_id(): with pytest.raises(ValidationError): RoutingDecision(request_id="bad", routed=True, selected_model_id=" ", approach="prompt_rag", reason="Selected") def test_summary_rejects_duplicate_request_ids(): with pytest.raises(ValidationError): evaluate_routing_batch([_request(request_id="same"), _request(request_id="same")], _catalog()) def test_all_rejected_batch_has_zero_latency_and_cost(): summary = evaluate_routing_batch( [_request(complexity_tier=5, max_p95_latency_ms=1.0)], _catalog() ) assert summary.routed_count == 0 assert summary.total_estimated_cost_usd == 0.0 assert summary.average_routed_p95_latency_ms == 0.0 assert summary.max_routed_p95_latency_ms == 0.0 def test_restricted_data_requires_explicit_candidate_approval(): candidate = _catalog()[0].model_copy(update={"approved_for_restricted_data": False}) decision = select_route(_request(contains_restricted_data=True), [candidate]) assert not decision.routed def test_summary_rejects_non_finite_metrics(): summary = evaluate_routing_batch([_request()], _catalog()) payload = summary.model_dump() payload["average_routed_p95_latency_ms"] = float("inf") with pytest.raises(ValidationError): RoutingBenchmarkSummary(**payload) def test_fine_tuning_is_independent_of_deployment_and_approach(): candidate = ModelCandidate(model_id="managed-ft", approach="prompt_rag", deployment="managed_api", is_fine_tuned=True, max_complexity_tier=3, estimated_p95_latency_ms=100.0, input_cost_per_1k_tokens_usd=0.1, output_cost_per_1k_tokens_usd=0.2) decision = select_route(_request(), [candidate]) assert decision.routed assert decision.approach == "prompt_rag" def test_zero_output_tokens_are_valid_and_cost_no_output_tokens(): request = _request(estimated_output_tokens=0) candidate = _catalog()[0] assert request.estimated_output_tokens == 0 assert estimate_request_cost_usd(candidate, request) == 0.1 assert select_route(request, [candidate]).routed def test_negative_output_tokens_are_rejected(): with pytest.raises(ValidationError): _request(estimated_output_tokens=-1) def test_empty_candidate_catalog_uses_stable_rejection_code(): decision = select_route(_request(), []) assert not decision.routed assert decision.reason_code == "NO_CANDIDATES" summary = evaluate_routing_batch([_request()], []) assert summary.rejection_reasons == {"NO_CANDIDATES": 1} def test_rejection_reasons_are_grouped_by_stable_code(): requests = [_request(request_id="a", complexity_tier=5), _request(request_id="b", complexity_tier=5, max_cost_usd=0.01)] summary = evaluate_routing_batch(requests, _catalog()) assert summary.rejected_count == 2 assert summary.rejection_reasons == {"NO_ELIGIBLE_CANDIDATE": 2} assert all(item.reason_code == "NO_ELIGIBLE_CANDIDATE" for item in summary.decisions) assert summary.decisions[0].reason_detail is not None def test_rejects_boolean_complexity_tier(): with pytest.raises(ValidationError): _request(complexity_tier=True) - Configure GitHub Actions in
.github/workflows/tests.ymland run tests:name: Python tests on: push: pull_request: permissions: contents: read jobs: test: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" - name: Install package and test dependencies run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run tests run: python -m pytest -v
3. Common Pitfalls and Operational Hygiene
- Fine-tuning to patch retrieval or prompt gaps: Fine-tuning cannot replace missing context or unclear task instructions; verify retrieval quality and prompt contracts first.
- Bypassing privacy or residency rules for cheaper or faster models: Always filter out non-private endpoints when a request requires private hosting, and require explicit restricted-data approval when manifests contain restricted data.
- Silently routing requests that exceed budget or latency limits: Return an explicit unrouted decision with a stable reason code and clear detail rather than ignoring constraints or rounding away budget checks.
4. Completion Criteria
ModelCandidate,RoutingRequest,RoutingDecision, andRoutingBenchmarkSummaryvalidate inputs and state invariants strictly with Pydantic v2.estimate_request_cost_usd,select_route, andevaluate_routing_batchroute requests under complexity, private-hosting, restricted-data approval, latency, and exact budget rules and report consistent batch metrics.- All
pytesttests pass locally and in GitHub Actions, andfde-04-4is pushed to GitHub.
Build this
In fde-04-4, implement strict Pydantic v2 models in src/fde_04_4/schemas.py (RoutingRequest, ModelCandidate, RoutingDecision, and RoutingBenchmarkSummary) and routing plus trade-off evaluation logic in src/fde_04_4/router.py.
- Model candidate profiles across frontier/managed APIs, fine-tuned task models, and self-hosted open-weight models, accounting for task complexity, domain/privacy constraints, estimated token cost, and P95 latency budgets.
- Implement
select_routeto choose the lowest-cost qualifying candidate that satisfies complexity, latency, and privacy/residency constraints, andevaluate_routing_batchto summarize route distribution, cost, latency, and policy rejections. - Add unit tests in
tests/test_router.pycovering simple vs. complex routing, strict privacy/data-residency routing to open-weight or approved endpoints, latency/budget filtering, and infeasible request handling, then runpython -m pytest -vand pushfde-04-4(including.github/workflows/tests.yml) to GitHub.
Test your understanding
- When is fine-tuning the wrong choice compared to better retrieval (RAG), clearer prompting, or few-shot examples?
- How do open-weight or self-hosted models change trade-offs around data privacy, latency, and operational overhead?
- Why route simple or routine requests to a smaller or cheaper model while reserving larger or specialized models for harder tasks?
- What happens when no candidate model satisfies a request's latency, budget, or privacy constraints, and how should the router respond?
Reveal self-review answers (attempt the questions first)
- When fine-tuning is the wrong choice: Fine-tuning is a poor fit when the core gap is missing or rapidly changing domain knowledge (where RAG or tool lookups are needed), ambiguous task specifications, or a small/noisy dataset that risks overfitting without fixing underlying retrieval or prompt clarity.
- Open-weight / self-hosted trade-offs: Self-hosting open-weight models keeps data inside your own VPC or infrastructure boundary and avoids per-token vendor fees at high steady volume, but shifts GPU/compute capacity planning, autoscaling, and model maintenance onto your team.
- Task-based model routing: Many enterprise requests are straightforward classification, extraction, or routing tasks that do not need expensive frontier reasoning; routing easy requests to faster, cheaper models cuts unit cost and latency while keeping strong models for complex edge cases.
- Handling infeasible routing constraints: When no candidate meets the request's required privacy level, latency ceiling, or token cost budget, the router should fail explicitly with a clear rejection/unroutable decision rather than silently violating privacy or budget rules.
Questions or notes on this module?