From e6b55176ef53266e6fe4017f78efd50d12cf76ab Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 00:28:42 +0530 Subject: [PATCH 1/2] feat(providers): gemini + ollama backends, fakes, and live smoke script (T04) - ChatBackend/EmbeddingBackend protocols, ChatResult/Usage, typed ProviderError (quota_exhausted | provider_unavailable), bounded 429 exponential backoff (max 5 retries, 1s..60s cap), L2 normalization, <=100-text batching, and prices.json (as_of 2026-11-16, per 9.8) - Gemini via google-genai (config-pinned answer/embedding models, RETRIEVAL_DOCUMENT/RETRIEVAL_QUERY task types); Ollama via httpx (qwen2.5:7b-instruct + nomic-embed-text), injectable transport - get_chat/get_embeddings factories read CALIPER_PROVIDER, GEMINI_API_KEY, OLLAMA_BASE_URL from env (11.2); 768-dim enforcement before any call - tests/fakes.py: scripted FakeChat (paraphrased-quote + refusal cases) and deterministic hash-based FakeEmbeddings (768-dim, correlated) - scripts/smoke.py: manual live smoke per backend + 429 backoff demo, exits nonzero with the 9 error envelope on failure - 30 new unit tests; pytest/ruff/mypy strict all green --- scripts/smoke.py | 241 +++++++++++++++++++++++ src/caliper/providers/__init__.py | 108 +++++++++++ src/caliper/providers/base.py | 263 ++++++++++++++++++++++++++ src/caliper/providers/gemini.py | 149 +++++++++++++++ src/caliper/providers/ollama.py | 170 +++++++++++++++++ src/caliper/providers/prices.json | 16 ++ tests/conftest.py | 14 ++ tests/fakes.py | 176 +++++++++++++++++ tests/unit/test_fakes.py | 121 ++++++++++++ tests/unit/test_providers_base.py | 242 ++++++++++++++++++++++++ tests/unit/test_providers_gemini.py | 284 ++++++++++++++++++++++++++++ tests/unit/test_providers_ollama.py | 256 +++++++++++++++++++++++++ 12 files changed, 2040 insertions(+) create mode 100644 scripts/smoke.py create mode 100644 src/caliper/providers/__init__.py create mode 100644 src/caliper/providers/base.py create mode 100644 src/caliper/providers/gemini.py create mode 100644 src/caliper/providers/ollama.py create mode 100644 src/caliper/providers/prices.json create mode 100644 tests/conftest.py create mode 100644 tests/fakes.py create mode 100644 tests/unit/test_fakes.py create mode 100644 tests/unit/test_providers_base.py create mode 100644 tests/unit/test_providers_gemini.py create mode 100644 tests/unit/test_providers_ollama.py diff --git a/scripts/smoke.py b/scripts/smoke.py new file mode 100644 index 0000000..5df4faa --- /dev/null +++ b/scripts/smoke.py @@ -0,0 +1,241 @@ +"""P0 live smoke test (T04, §14.2, §15) — run by a human, NEVER in CI. + +Exercises BOTH provider backends live: + 1. one chat call (gemini: cfg.answer.model; ollama: qwen2.5:7b-instruct), + 2. one 768-dim embedding per backend, printed with its L2 norm (≈ 1.0, + proving the client-side normalization of ADR-003), + 3. the bounded 429 backoff path (no live rate limit needed: the helper runs + against a scripted twice-429 operation and logs the same WARNING events + production calls produce). + +Reads config and GEMINI_API_KEY exactly like the runtime does — environment +variables (§11.2), optionally populated from a repo-root `.env`. Any failure +exits nonzero with the §9 error envelope on stderr. + +Usage: + uv run python scripts/smoke.py + +Setup (docs/SETUP.md lands with T22): + cp .env.example .env # then set GEMINI_API_KEY=... + # for the ollama leg: install Ollama, then + # ollama pull qwen2.5:7b-instruct && ollama pull nomic-embed-text +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import sys +from pathlib import Path + +import httpx + +from caliper.config import CaliperConfig, ConfigError, fp8, load_config +from caliper.providers.base import ( + Prices, + ProviderError, + Usage, + call_with_backoff, + estimate_cost, + gemini_api_key, + load_prices, + ollama_base_url, +) +from caliper.providers.gemini import GeminiChat, GeminiEmbeddings +from caliper.providers.ollama import ( + OLLAMA_CHAT_MODEL, + OLLAMA_EMBED_MODEL, + OLLAMA_HTTP_TIMEOUT_S, + OllamaChat, + OllamaEmbeddings, +) + +REPO_ROOT = Path(__file__).resolve().parents[1] +LOGGER = logging.getLogger("caliper.smoke") + +SMOKE_SYSTEM = "You are a documentation assistant. Answer in one short sentence." +SMOKE_QUESTION = "In one sentence: what is an Azure Functions timer trigger?" +SMOKE_EMBED_TEXT = "How do I configure retries on an Azure Functions timer trigger?" + +# §9 error envelope exit codes. +EXIT_CODES: dict[str, int] = { + "config_invalid": 2, + "provider_unavailable": 4, + "quota_exhausted": 5, +} + + +class BackendPair: + """One provider's chat + embedding backends plus its pinned chat model.""" + + def __init__( + self, + name: str, + chat: GeminiChat | OllamaChat, + embeddings: GeminiEmbeddings | OllamaEmbeddings, + chat_model: str, + ) -> None: + self.name = name + self.chat = chat + self.embeddings = embeddings + self.chat_model = chat_model + + +def _load_env_file(path: Path) -> None: + """Populate os.environ from .env (KEY=VALUE lines) without overriding.""" + if not path.is_file(): + return + for line in path.read_text(encoding="utf-8").splitlines(): + stripped = line.strip() + if not stripped or stripped.startswith("#") or "=" not in stripped: + continue + key, _, value = stripped.partition("=") + os.environ.setdefault(key.strip(), value.strip().strip("'").strip('"')) + + +def _build_backend(name: str, cfg: CaliperConfig) -> BackendPair: + """Build one backend pair directly (smoke tests BOTH, ignoring CALIPER_PROVIDER).""" + if name == "gemini": + from google import genai + + models = genai.Client(api_key=gemini_api_key()).models + return BackendPair( + name, + GeminiChat(models), + GeminiEmbeddings( + models, model=cfg.embeddings.model, dimensions=cfg.embeddings.dimensions + ), + chat_model=cfg.answer.model, + ) + client = httpx.Client(base_url=ollama_base_url(), timeout=httpx.Timeout(OLLAMA_HTTP_TIMEOUT_S)) + return BackendPair( + name, + OllamaChat(client), + OllamaEmbeddings(client, model=OLLAMA_EMBED_MODEL, dimensions=cfg.embeddings.dimensions), + chat_model=OLLAMA_CHAT_MODEL, + ) + + +def _run_backend(backend: BackendPair, prices: Prices) -> None: + """One chat call + one embed per backend; prints norms and cost (§14.2).""" + result = backend.chat.complete( + system=SMOKE_SYSTEM, + user=SMOKE_QUESTION, + model=backend.chat_model, + temperature=0.0, + seed=42, + ) + print( + f"[{backend.name}] chat ok: model={result.model} " + f"tokens(in/out)={result.prompt_tokens}/{result.completion_tokens} " + f"text={result.text!r}" + ) + if backend.chat_model in prices.entries: + cost = estimate_cost( + Usage( + prompt_tokens=result.prompt_tokens, + completion_tokens=result.completion_tokens, + ), + backend.chat_model, + prices.entries, + ) + print(f"[{backend.name}] estimated cost (prices as_of {prices.as_of}): ${cost:.6f}") + else: + print(f"[{backend.name}] estimated cost: $0.000000 (local model, no price entry)") + + vector = backend.embeddings.embed_query(SMOKE_EMBED_TEXT) + norm = math.sqrt(sum(v * v for v in vector)) + if abs(norm - 1.0) > 1e-6: + raise ProviderError( + f"[{backend.name}] embedding norm {norm:.6f} != 1.0 — client-side L2 " + "normalization (ADR-003) is broken" + ) + print( + f"[{backend.name}] embed ok: dims={len(vector)} norm={norm:.6f} (L2-normalized client-side)" + ) + + +def _demonstrate_backoff() -> None: + """Log the same WARNING events a live 429 produces, with recorded sleeps.""" + attempts = {"n": 0} + slept: list[float] = [] + + class _Simulated429(Exception): + """Stand-in for an HTTP 429 from the provider.""" + + def op() -> str: + attempts["n"] += 1 + if attempts["n"] <= 2: + raise _Simulated429("simulated HTTP 429") + return "succeeded" + + outcome = call_with_backoff( + op, + describe="smoke 429 backoff demo", + is_rate_limited=lambda exc: isinstance(exc, _Simulated429), + sleep=slept.append, + ) + print(f"429 backoff demo: {attempts['n']} attempts, sleeps={slept} -> {outcome}") + + +def _fail(code: str, message: str) -> int: + print(json.dumps({"error": {"code": code, "message": message}}), file=sys.stderr) + return EXIT_CODES[code] + + +def main() -> int: + logging.basicConfig( + level=os.environ.get("CALIPER_LOG_LEVEL", "INFO").upper(), + format="%(asctime)s %(levelname)s %(name)s %(message)s", + stream=sys.stderr, + ) + _load_env_file(REPO_ROOT / ".env") + print("== caliper live smoke (T04) ==") + + try: + user_config = Path( + os.environ.get("CALIPER_CONFIG", REPO_ROOT / "configs" / "caliper.sample.toml") + ) + cfg = load_config(user_config, REPO_ROOT / "configs" / "v1.toml") + except ConfigError as exc: + return _fail("config_invalid", str(exc)) + print(f"config fingerprint (fp8): {fp8(cfg)}") + + prices = load_prices() + print(f"price table as_of: {prices.as_of} (re-verify at P0, §9.8)") + + failures: list[ProviderError] = [] + for name in ("gemini", "ollama"): + try: + backend = _build_backend(name, cfg) + except ConfigError as exc: + failures.append(ProviderError(str(exc), code="config_invalid")) + continue + except ProviderError as exc: + failures.append(exc) + continue + try: + _run_backend(backend, prices) + except ProviderError as exc: + failures.append(exc) + + _demonstrate_backoff() + + if failures: + first = failures[0] + for extra in failures[1:]: + LOGGER.warning("additional backend failure: %s", extra) + LOGGER.debug("first failure traceback", exc_info=first) + return _fail(first.code, str(first)) + print("SMOKE OK — chat + 768-dim normalized embed per backend, backoff path logged.") + print( + "OQ1 reminder: confirm gemini-3.5-flash-lite free-tier RPD in AI Studio " + "and record the decision in the decision log." + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/caliper/providers/__init__.py b/src/caliper/providers/__init__.py new file mode 100644 index 0000000..50d330d --- /dev/null +++ b/src/caliper/providers/__init__.py @@ -0,0 +1,108 @@ +"""Provider factories (§7.2): `get_chat(cfg)` and `get_embeddings(cfg)`. + +Provider selection and endpoints come from the environment (§11.2): +CALIPER_PROVIDER (gemini|ollama, default gemini), GEMINI_API_KEY, +OLLAMA_BASE_URL. Model IDs and generation parameters come from the resolved +`CaliperConfig` (T02) — never hardcoded here. Re-exports the public surface +of the component so callers can `from caliper.providers import ...`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import httpx +from google import genai + +from caliper.config import ConfigError +from caliper.providers.base import ( + EMBEDDING_DIMENSIONS, + ChatBackend, + ChatResult, + EmbeddingBackend, + PriceEntry, + Prices, + ProviderError, + Usage, + estimate_cost, + gemini_api_key, + l2_normalize, + load_prices, + ollama_base_url, + provider_name, +) +from caliper.providers.gemini import GeminiChat, GeminiEmbeddings +from caliper.providers.ollama import ( + OLLAMA_CHAT_MODEL, + OLLAMA_EMBED_MODEL, + OLLAMA_HTTP_TIMEOUT_S, + OllamaChat, + OllamaEmbeddings, +) + +if TYPE_CHECKING: + from caliper.config import CaliperConfig + +__all__ = [ + "EMBEDDING_DIMENSIONS", + "OLLAMA_CHAT_MODEL", + "OLLAMA_EMBED_MODEL", + "OLLAMA_HTTP_TIMEOUT_S", + "ChatBackend", + "ChatResult", + "EmbeddingBackend", + "GeminiChat", + "GeminiEmbeddings", + "OllamaChat", + "OllamaEmbeddings", + "PriceEntry", + "Prices", + "ProviderError", + "Usage", + "estimate_cost", + "get_chat", + "get_embeddings", + "l2_normalize", + "load_prices", +] + + +def get_chat(cfg: CaliperConfig) -> ChatBackend: + """Build the configured chat backend (§7.2). + + The caller (answer) passes `cfg.answer.model` / temperature / seed to + `complete()` on every call; this factory only selects the transport. + """ + if provider_name() == "gemini": + genai_client = genai.Client(api_key=gemini_api_key()) + return GeminiChat(genai_client.models) + ollama_client = httpx.Client( + base_url=ollama_base_url(), timeout=httpx.Timeout(OLLAMA_HTTP_TIMEOUT_S) + ) + return OllamaChat(ollama_client) + + +def get_embeddings(cfg: CaliperConfig) -> EmbeddingBackend: + """Build the configured embedding backend (§7.2). + + Both backends must emit 768-dim, client-side-L2-normalized vectors + (ADR-003, dimension-compatible with the `vec0` schema and with the Ollama + fallback), so a different `embeddings.dimensions` is rejected here before + any model call could be made. + """ + if cfg.embeddings.dimensions != EMBEDDING_DIMENSIONS: + raise ConfigError( + f"embeddings.dimensions must be {EMBEDDING_DIMENSIONS} " + f"(ADR-003: vec0 schema + Ollama compatibility), got {cfg.embeddings.dimensions}" + ) + if provider_name() == "gemini": + genai_client = genai.Client(api_key=gemini_api_key()) + return GeminiEmbeddings( + genai_client.models, model=cfg.embeddings.model, dimensions=cfg.embeddings.dimensions + ) + ollama_client = httpx.Client( + base_url=ollama_base_url(), timeout=httpx.Timeout(OLLAMA_HTTP_TIMEOUT_S) + ) + return OllamaEmbeddings( + ollama_client, model=OLLAMA_EMBED_MODEL, dimensions=cfg.embeddings.dimensions + ) diff --git a/src/caliper/providers/base.py b/src/caliper/providers/base.py new file mode 100644 index 0000000..5c3642c --- /dev/null +++ b/src/caliper/providers/base.py @@ -0,0 +1,263 @@ +"""Provider primitives shared by every backend (§7.2). + +This file is single-owner (T04, §14.4). It defines the two backend protocols, +the result/usage dataclasses, the typed component exception, L2 normalization, +the bounded 429 backoff helper, batching, and the price table (§9.8). + +Providers are a leaf component above `config` only (§4.2): they must not know +about SQLite, prompts, or retrieval, and they never issue parallel requests. +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import time +from collections.abc import Callable, Iterator, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Literal, Protocol, TypedDict + +from caliper.config import ConfigError + +_LOGGER = logging.getLogger(__name__) + +# --- Environment contract (§11.2) -------------------------------------------- + +PROVIDER_ENV_VAR = "CALIPER_PROVIDER" +GEMINI_API_KEY_ENV_VAR = "GEMINI_API_KEY" +OLLAMA_BASE_URL_ENV_VAR = "OLLAMA_BASE_URL" +DEFAULT_OLLAMA_BASE_URL = "http://127.0.0.1:11434" + +# --- Binding constants (§7.2, ADR-003) ---------------------------------------- + +#: Every embedding is 768 dims, L2-normalized client-side before storage. +EMBEDDING_DIMENSIONS = 768 +#: Maximum texts per embedding request (§7.2 "batch ... at up to 100 texts"). +EMBED_BATCH_SIZE = 100 +#: Bounded retries on HTTP 429: max 5 retries, then raise (§7.2). +MAX_RETRIES = 5 +#: Backoff schedule 1s → 2s → 4s → ... capped at 60s (§7.4, §10.3). +BACKOFF_BASE_DELAY_S = 1.0 +BACKOFF_MAX_DELAY_S = 60.0 + + +class ProviderError(Exception): + """A provider backend failed after bounded retries (§11.3). + + `code` carries the §9 envelope code this error maps to at the CLI/web + edges: `provider_unavailable` (503/exit 4) or `quota_exhausted` + (503/exit 5, after 429 retries are exhausted). + """ + + def __init__(self, message: str, *, code: ProviderErrorCode = "provider_unavailable") -> None: + super().__init__(message) + self.code: ProviderErrorCode = code + + +ProviderErrorCode = Literal["provider_unavailable", "quota_exhausted"] + +# --- Public result types (§9.8) ------------------------------------------------ + + +@dataclass(frozen=True) +class ChatResult: + """One chat completion: answer text plus usage capture (§7.2, §9.8).""" + + text: str + prompt_tokens: int + completion_tokens: int + model: str + + +@dataclass(frozen=True) +class Usage: + """Token usage of one request, for the §11.3 cost estimator.""" + + prompt_tokens: int = 0 + completion_tokens: int = 0 + embed_tokens: int = 0 + + +# --- Backend protocols (§7.2 public interface, binding) ------------------------ + + +class ChatBackend(Protocol): + def complete( + self, *, system: str, user: str, model: str, temperature: float, seed: int | None + ) -> ChatResult: ... + + +class EmbeddingBackend(Protocol): + def embed_documents(self, texts: list[str]) -> list[list[float]]: ... + + def embed_query(self, text: str) -> list[float]: ... + + +# --- Price table (§9.8) -------------------------------------------------------- + + +class PriceEntry(TypedDict): + """USD per million tokens for one model.""" + + input_per_mtok: float + output_per_mtok: float + embed_per_mtok: float + + +@dataclass(frozen=True) +class Prices: + """The price table with its `as_of` date recorded (A3, §9.8).""" + + as_of: str + entries: dict[str, PriceEntry] + + +def _price_entry(model: str, raw: object) -> PriceEntry: + if not isinstance(raw, dict): + raise ProviderError(f"prices.json: entry for {model!r} must be an object") + values: list[float] = [] + for key in ("input_per_mtok", "output_per_mtok", "embed_per_mtok"): + value = raw.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ProviderError(f"prices.json: {model}.{key} must be a number") + values.append(float(value)) + return PriceEntry(input_per_mtok=values[0], output_per_mtok=values[1], embed_per_mtok=values[2]) + + +def load_prices() -> Prices: + """Load `prices.json` shipped next to this module (§9.8, §6.1).""" + path = Path(__file__).with_name("prices.json") + try: + raw: object = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise ProviderError(f"cannot read price table {path}: {exc}") from exc + if not isinstance(raw, dict): + raise ProviderError("prices.json: top level must be an object") + as_of = raw.get("as_of") + if not isinstance(as_of, str) or not as_of: + raise ProviderError("prices.json: 'as_of' must be a non-empty date string") + table_raw = raw.get("prices") + if not isinstance(table_raw, dict): + raise ProviderError("prices.json: 'prices' must be an object") + entries = {str(model): _price_entry(model, entry) for model, entry in table_raw.items()} + return Prices(as_of=as_of, entries=entries) + + +def estimate_cost(usage: Usage, model: str, prices: Mapping[str, PriceEntry]) -> float: + """(prompt*in + completion*out + embed*embed) / 1e6, USD (§7.2, §11.3). + + Raises ProviderError for a model missing from the table: a wrong price + figure never invalidates logged results (A3), but a missing entry is a + real gap and must fail loudly instead of logging $0.00 silently. + """ + entry = prices.get(model) + if entry is None: + raise ProviderError(f"no price entry for model {model!r} in prices.json") + total = ( + usage.prompt_tokens * entry["input_per_mtok"] + + usage.completion_tokens * entry["output_per_mtok"] + + usage.embed_tokens * entry["embed_per_mtok"] + ) + return total / 1e6 + + +# --- Vector math (ADR-003) ------------------------------------------------------ + + +def l2_normalize(vector: Sequence[float]) -> list[float]: + """Return the L2-normalized copy of `vector` (client-side, ADR-003). + + All 768-dim vectors are normalized here before storage or comparison; + only 3072-dim output would be API-normalized, and we never use it. + """ + norm = math.sqrt(sum(value * value for value in vector)) + if norm == 0.0: + raise ProviderError("cannot L2-normalize a zero vector") + return [value / norm for value in vector] + + +def iter_batches(texts: Sequence[str], size: int = EMBED_BATCH_SIZE) -> Iterator[list[str]]: + """Split `texts` into batches of at most `size` (≤100 per request, §7.2).""" + for start in range(0, len(texts), size): + yield list(texts[start : start + size]) + + +# --- Bounded 429 backoff (§7.2 binding) ----------------------------------------- + + +def call_with_backoff[T]( + op: Callable[[], T], + *, + describe: str, + is_rate_limited: Callable[[Exception], bool], + max_retries: int = MAX_RETRIES, + base_delay_s: float = BACKOFF_BASE_DELAY_S, + max_delay_s: float = BACKOFF_MAX_DELAY_S, + sleep: Callable[[float], None] = time.sleep, +) -> T: + """Run `op` with bounded exponential backoff on HTTP 429 (§7.2). + + 429 responses are retried up to `max_retries` times with delays + base*2**n capped at `max_delay_s`, then ProviderError(code=quota_exhausted) + is raised. Any other exception is wrapped immediately as + ProviderError(code=provider_unavailable) — no unbounded retries, never a + silent swallow (§16 provider discipline). Raw tracebacks stay at DEBUG. + """ + for attempt in range(max_retries + 1): + try: + return op() + except Exception as exc: # noqa: BLE001 - single typed wrap, never swallowed + if is_rate_limited(exc) and attempt < max_retries: + delay = min(base_delay_s * (2**attempt), max_delay_s) + _LOGGER.warning( + "%s: rate limited (HTTP 429); retrying in %.1fs (retry %d/%d)", + describe, + delay, + attempt + 1, + max_retries, + ) + sleep(delay) + continue + if is_rate_limited(exc): + _LOGGER.debug("%s: still rate limited after retries", describe, exc_info=True) + raise ProviderError( + f"{describe} still rate limited after {max_retries} retries", + code="quota_exhausted", + ) from exc + _LOGGER.debug("%s failed", describe, exc_info=True) + raise ProviderError(f"{describe} failed: {type(exc).__name__}: {exc}") from exc + raise AssertionError("unreachable: call_with_backoff loop is exhaustive") + + +# --- Environment accessors (§11.2) ---------------------------------------------- + + +def provider_name() -> Literal["gemini", "ollama"]: + """The selected provider from CALIPER_PROVIDER (default: gemini).""" + raw = os.environ.get(PROVIDER_ENV_VAR, "gemini").strip().lower() + if raw == "gemini": + return "gemini" + if raw == "ollama": + return "ollama" + raise ConfigError(f"{PROVIDER_ENV_VAR} must be 'gemini' or 'ollama', got {raw!r}") + + +def required_env(name: str) -> str: + """Read a required environment variable, failing with its name (§11.4).""" + value = os.environ.get(name) + if not value: + raise ConfigError(f"environment variable {name} is required but not set (see .env)") + return value + + +def gemini_api_key() -> str: + """GEMINI_API_KEY, required iff provider=gemini (§11.2). Never logged.""" + return required_env(GEMINI_API_KEY_ENV_VAR) + + +def ollama_base_url() -> str: + """OLLAMA_BASE_URL (default http://127.0.0.1:11434, §11.2).""" + return os.environ.get(OLLAMA_BASE_URL_ENV_VAR, DEFAULT_OLLAMA_BASE_URL) diff --git a/src/caliper/providers/gemini.py b/src/caliper/providers/gemini.py new file mode 100644 index 0000000..33a7b73 --- /dev/null +++ b/src/caliper/providers/gemini.py @@ -0,0 +1,149 @@ +"""Gemini backend via the `google-genai` SDK (§5, §7.2). + +Chat runs whatever model the caller passes (the config-pinned answer model, +default `gemini-3.5-flash-lite` per OQ1). Embeddings use the config-pinned +embedding model at `output_dimensionality=768` with task types +RETRIEVAL_DOCUMENT / RETRIEVAL_QUERY; every returned vector is L2-normalized +client-side (ADR-003 — only 3072-dim output is API-normalized). + +HTTP 429 responses back off exponentially, bounded at MAX_RETRIES, then raise +ProviderError(code="quota_exhausted"). Nothing here is parallel and nothing is +cached (§16 provider discipline). +""" + +from __future__ import annotations + +import time +from collections.abc import Callable, Sequence +from typing import Protocol + +from google.genai import errors as genai_errors +from google.genai import types +from google.genai.types import EmbedContentConfig, GenerateContentConfig + +from caliper.providers.base import ( + EMBEDDING_DIMENSIONS, + ChatResult, + ProviderError, + call_with_backoff, + iter_batches, + l2_normalize, +) + +GEMINI_TASK_DOCUMENT = "RETRIEVAL_DOCUMENT" +GEMINI_TASK_QUERY = "RETRIEVAL_QUERY" + + +class GeminiModels(Protocol): + """The narrow slice of `google.genai.client.Models` we use. + + The real SDK client satisfies this structurally (checked under mypy + strict); tests inject a fake with the same shape through the public + constructor — no patch() anywhere (§15). + """ + + def generate_content( + self, *, model: str, contents: str, config: GenerateContentConfig + ) -> types.GenerateContentResponse: ... + + def embed_content( + self, *, model: str, contents: Sequence[str], config: EmbedContentConfig + ) -> types.EmbedContentResponse: ... + + +def _is_rate_limited(exc: Exception) -> bool: + """True when the SDK raised an HTTP 429 (google.genai.errors.APIError).""" + return isinstance(exc, genai_errors.APIError) and exc.code == 429 + + +class GeminiChat: + """ChatBackend over the Gemini API (§7.2). Model is passed per call.""" + + def __init__( + self, models: GeminiModels, *, sleep: Callable[[float], None] = time.sleep + ) -> None: + self._models = models + self._sleep = sleep + + def complete( + self, *, system: str, user: str, model: str, temperature: float, seed: int | None + ) -> ChatResult: + config = GenerateContentConfig( + system_instruction=system, temperature=temperature, seed=seed + ) + response = call_with_backoff( + lambda: self._models.generate_content(model=model, contents=user, config=config), + describe=f"Gemini chat call ({model})", + is_rate_limited=_is_rate_limited, + sleep=self._sleep, + ) + text = response.text + if not text: + raise ProviderError(f"Gemini chat returned no text for model {model}") + usage = response.usage_metadata + return ChatResult( + text=text, + prompt_tokens=int(usage.prompt_token_count or 0) if usage else 0, + completion_tokens=int(usage.candidates_token_count or 0) if usage else 0, + model=model, + ) + + +class GeminiEmbeddings: + """EmbeddingBackend over the Gemini API, batched at ≤100 texts (§7.2).""" + + def __init__( + self, + models: GeminiModels, + *, + model: str, + dimensions: int = EMBEDDING_DIMENSIONS, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + self._models = models + self._model = model + self._dimensions = dimensions + self._sleep = sleep + + def embed_documents(self, texts: list[str]) -> list[list[float]]: + vectors: list[list[float]] = [] + for batch in iter_batches(texts): + vectors.extend(self._embed_batch(batch, GEMINI_TASK_DOCUMENT)) + return vectors + + def embed_query(self, text: str) -> list[float]: + return self._embed_batch([text], GEMINI_TASK_QUERY)[0] + + def _embed_batch(self, batch: Sequence[str], task_type: str) -> list[list[float]]: + if not batch: + return [] + response = call_with_backoff( + lambda: self._models.embed_content( + model=self._model, + contents=batch, + config=EmbedContentConfig( + task_type=task_type, output_dimensionality=self._dimensions + ), + ), + describe=f"Gemini embed call ({self._model}, {len(batch)} texts, {task_type})", + is_rate_limited=_is_rate_limited, + sleep=self._sleep, + ) + embeddings = response.embeddings + if embeddings is None or len(embeddings) != len(batch): + found = len(embeddings) if embeddings is not None else 0 + raise ProviderError( + f"Gemini embedding response has {found} vectors for {len(batch)} inputs" + ) + vectors: list[list[float]] = [] + for embedding in embeddings: + values = embedding.values + if values is None: + raise ProviderError("Gemini embedding response is missing values") + if len(values) != self._dimensions: + raise ProviderError( + f"Gemini embedding returned {len(values)} dims, expected {self._dimensions}" + ) + # Client-side L2 normalization: mandatory at 768 dims (ADR-003). + vectors.append(l2_normalize(values)) + return vectors diff --git a/src/caliper/providers/ollama.py b/src/caliper/providers/ollama.py new file mode 100644 index 0000000..82c6681 --- /dev/null +++ b/src/caliper/providers/ollama.py @@ -0,0 +1,170 @@ +"""Ollama backend: the local $0 fallback (§5, §7.2). + +Uses `qwen2.5:7b-instruct` for chat and `nomic-embed-text` (768 dims) for +embeddings — the two pinned Ollama models (§7.2 binding). Same protocol, same +client-side L2 normalization, same bounded 429 backoff as the Gemini backend. +Transport errors (Ollama not running) raise ProviderError(code= +"provider_unavailable") immediately — only HTTP 429 is retried. + +httpx.Client is injected through the public constructor, so tests drive this +backend with `httpx.MockTransport` (an injectable transport, §15) and never +touch the network or patch internals. +""" + +from __future__ import annotations + +import time +from collections.abc import Callable, Mapping, Sequence + +import httpx + +from caliper.providers.base import ( + EMBEDDING_DIMENSIONS, + ChatResult, + ProviderError, + call_with_backoff, + iter_batches, + l2_normalize, +) + +#: §7.2 pin — the Ollama answer model (override answer.model in caliper.toml +#: when switching providers; the fingerprint gate catches any drift, FR-10). +OLLAMA_CHAT_MODEL = "qwen2.5:7b-instruct" +#: §7.2 pin — the Ollama embedding model, dimension-compatible at 768 (ADR-003). +OLLAMA_EMBED_MODEL = "nomic-embed-text" + +#: Local model calls can be slow on CPU; generous but bounded. +OLLAMA_HTTP_TIMEOUT_S = 120.0 + + +def _is_rate_limited(exc: Exception) -> bool: + """True when httpx saw an HTTP 429 status.""" + return isinstance(exc, httpx.HTTPStatusError) and exc.response.status_code == 429 + + +def _token_count(data: Mapping[str, object], key: str) -> int: + """Read an optional integer token-count field, defaulting to 0.""" + value = data.get(key) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return 0 + return int(value) + + +def _vector_list( + data: Mapping[str, object], key: str, batch_len: int, dimensions: int, describe: str +) -> list[list[float]]: + """Extract, validate, and L2-normalize an embeddings list (ADR-003).""" + raw = data.get(key) + if not isinstance(raw, list): + raise ProviderError(f"{describe}: response is missing a '{key}' list") + if len(raw) != batch_len: + raise ProviderError(f"{describe}: response has {len(raw)} vectors for {batch_len} inputs") + vectors: list[list[float]] = [] + for item in raw: + if not isinstance(item, list): + raise ProviderError(f"{describe}: '{key}' entries must be lists of numbers") + values: list[float] = [] + for value in item: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ProviderError(f"{describe}: '{key}' entries must be lists of numbers") + values.append(float(value)) + if len(values) != dimensions: + raise ProviderError(f"{describe}: vector has {len(values)} dims, expected {dimensions}") + vectors.append(l2_normalize(values)) + return vectors + + +def _post_json( + client: httpx.Client, + path: str, + payload: Mapping[str, object], + *, + describe: str, + sleep: Callable[[float], None], +) -> dict[str, object]: + """POST `payload` and return the decoded JSON object, with bounded 429 backoff.""" + + def op() -> object: + response = client.post(path, json=payload) + response.raise_for_status() + raw: object = response.json() + return raw + + data = call_with_backoff(op, describe=describe, is_rate_limited=_is_rate_limited, sleep=sleep) + if not isinstance(data, dict): + raise ProviderError(f"{describe}: response body is not a JSON object") + return data + + +class OllamaChat: + """ChatBackend over Ollama's /api/chat (§7.2).""" + + def __init__( + self, client: httpx.Client, *, sleep: Callable[[float], None] = time.sleep + ) -> None: + self._client = client + self._sleep = sleep + + def complete( + self, *, system: str, user: str, model: str, temperature: float, seed: int | None + ) -> ChatResult: + options: dict[str, float | int] = {"temperature": temperature} + if seed is not None: + options["seed"] = seed + payload: dict[str, object] = { + "model": model, + "messages": [ + {"role": "system", "content": system}, + {"role": "user", "content": user}, + ], + "stream": False, + "options": options, + } + describe = f"Ollama chat call ({model})" + data = _post_json(self._client, "/api/chat", payload, describe=describe, sleep=self._sleep) + message = data.get("message") + if not isinstance(message, dict): + raise ProviderError("Ollama chat response is missing 'message'") + text = message.get("content") + if not isinstance(text, str) or not text: + raise ProviderError("Ollama chat response has no 'message.content' text") + return ChatResult( + text=text, + prompt_tokens=_token_count(data, "prompt_eval_count"), + completion_tokens=_token_count(data, "eval_count"), + model=model, + ) + + +class OllamaEmbeddings: + """EmbeddingBackend over Ollama's batched /api/embed (§7.2).""" + + def __init__( + self, + client: httpx.Client, + *, + model: str = OLLAMA_EMBED_MODEL, + dimensions: int = EMBEDDING_DIMENSIONS, + sleep: Callable[[float], None] = time.sleep, + ) -> None: + self._client = client + self._model = model + self._dimensions = dimensions + self._sleep = sleep + + def embed_documents(self, texts: list[str]) -> list[list[float]]: + vectors: list[list[float]] = [] + for batch in iter_batches(texts): + vectors.extend(self._embed(batch)) + return vectors + + def embed_query(self, text: str) -> list[float]: + return self._embed([text])[0] + + def _embed(self, batch: Sequence[str]) -> list[list[float]]: + if not batch: + return [] + payload: dict[str, object] = {"model": self._model, "input": list(batch)} + describe = f"Ollama embed call ({self._model}, {len(batch)} texts)" + data = _post_json(self._client, "/api/embed", payload, describe=describe, sleep=self._sleep) + return _vector_list(data, "embeddings", len(batch), self._dimensions, describe) diff --git a/src/caliper/providers/prices.json b/src/caliper/providers/prices.json new file mode 100644 index 0000000..8685bc0 --- /dev/null +++ b/src/caliper/providers/prices.json @@ -0,0 +1,16 @@ +{ + "as_of": "2026-11-16", + "note": "USD per million tokens, as published Nov 2026 (\u00a79.8, A3). Figures are re-verified at the P0 live smoke test; free-tier traffic logs $0.00 with full token counts, so a corrected figure recomputes costs from logs without re-running.", + "prices": { + "gemini-3.5-flash-lite": { + "input_per_mtok": 0.10, + "output_per_mtok": 0.40, + "embed_per_mtok": 0.0 + }, + "gemini-embedding-001": { + "input_per_mtok": 0.15, + "output_per_mtok": 0.0, + "embed_per_mtok": 0.15 + } + } +} diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..6fed408 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,14 @@ +"""Pytest bootstrap: make tests/fakes.py importable from subdirectories (§15). + +tests/fakes.py lives at tests/ level while unit/integration tests live in +subdirectories; with pytest's default import mode those subdirectories — not +tests/ itself — go on sys.path. Adding tests/ here lets every test import the +two fake backends as `fakes` (the suite's only mocks). +""" + +import sys +from pathlib import Path + +_TESTS_DIR = Path(__file__).resolve().parent +if str(_TESTS_DIR) not in sys.path: + sys.path.insert(0, str(_TESTS_DIR)) diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..ebfae36 --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,176 @@ +"""Fake backends for offline tests (§15) — the ONLY mocks in this suite. + +Two implementations, both stable public seams for later tasks (T09–T14): + +- `FakeChat`: a ChatBackend with a scripted response list. Callers push the + responses they need, in order; every call is recorded. Includes a + paraphrased-quote case and a refusal case (§15) shaped like the §7.7 reply + schema, so answer/quote-verification tests can script them directly. +- `FakeEmbeddings`: an EmbeddingBackend with deterministic hash-based + embeddings (768-dim by default). Vectors are derived per-token (a small + hashing-trick projection), so texts sharing vocabulary get correlated + vectors — retrieval tests can rely on relatedness, not just determinism. + +No network, no patch(), no knowledge of any component's internals. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from collections.abc import Sequence +from dataclasses import dataclass, field + +from caliper.providers.base import EMBEDDING_DIMENSIONS, ChatResult, l2_normalize + +_TOKEN_RE = re.compile(r"[a-z0-9]+") + +# --- FakeChat ------------------------------------------------------------------- + + +@dataclass(frozen=True) +class CompleteCall: + """One recorded complete() call.""" + + system: str + user: str + model: str + temperature: float + seed: int | None + + +@dataclass +class FakeChat: + """Scripted ChatBackend: pops one response per complete() call, in order.""" + + responses: list[ChatResult] + calls: list[CompleteCall] = field(default_factory=list) + + def complete( + self, *, system: str, user: str, model: str, temperature: float, seed: int | None + ) -> ChatResult: + self.calls.append( + CompleteCall(system=system, user=user, model=model, temperature=temperature, seed=seed) + ) + if not self.responses: + raise RuntimeError("FakeChat: scripted responses exhausted") + return self.responses.pop(0) + + +def chat_result( + text: str, + *, + model: str = "fake-chat-model", + prompt_tokens: int = 120, + completion_tokens: int = 40, +) -> ChatResult: + """Build a ChatResult with plausible default token counts.""" + return ChatResult( + text=text, + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + model=model, + ) + + +def scripted_chat(*responses: ChatResult) -> FakeChat: + """A FakeChat playing the given responses in order.""" + return FakeChat(responses=list(responses)) + + +def paraphrased_quote_result( + *, model: str = "fake-chat-model", prompt_tokens: int = 120, completion_tokens: int = 40 +) -> ChatResult: + """Scripted answer whose citation quote PARAPHRASES the passage (§15). + + Downstream quote verification (T11) must retry/drop this one — the quote + is not a verbatim substring of any chunk body. + """ + text = json.dumps( + { + "answer": "Set the retry policy on a timer trigger via the retry block.", + "citations": [{"chunk": 1, "quote": "you can configure a fixed retry delay"}], + "refused": False, + } + ) + return chat_result( + text, model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens + ) + + +def refusal_result( + *, model: str = "fake-chat-model", prompt_tokens: int = 120, completion_tokens: int = 15 +) -> ChatResult: + """Scripted refusal per §7.7 mechanism (1): `refused: true`, no citations.""" + text = json.dumps( + { + "answer": "Not found in the provided passages.", + "citations": [], + "refused": True, + } + ) + return chat_result( + text, model=model, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens + ) + + +# --- FakeEmbeddings -------------------------------------------------------------- + + +@dataclass(frozen=True) +class EmbedCall: + """One recorded embed call: the input texts and the task kind.""" + + texts: tuple[str, ...] + task_type: str # "document" (embed_documents) or "query" (embed_query) + + +def _token_positions(token: str, dimensions: int) -> list[tuple[int, float]]: + """Deterministic (index, sign) projections for one token (hashing trick).""" + digest = hashlib.sha256(token.encode("utf-8")).digest() + positions: list[tuple[int, float]] = [] + for half in (digest[:8], digest[8:16]): + value = int.from_bytes(half, "big") + index = value % dimensions + sign = 1.0 if (value >> 63) & 1 else -1.0 + positions.append((index, sign)) + return positions + + +def fake_embedding(text: str, dimensions: int = EMBEDDING_DIMENSIONS) -> list[float]: + """Deterministic 768-dim embedding of `text`, L2-normalized. + + Tokens sharing vocabulary land on the same coordinates, so texts about + the same topic have cosine > 0 and unrelated texts ≈ 0. Same text always + yields the same vector (stable across runs and processes). + """ + accumulated = [0.0] * dimensions + tokens = _TOKEN_RE.findall(text.lower()) or [""] + for token in tokens: + for index, sign in _token_positions(token, dimensions): + accumulated[index] += sign + return l2_normalize(accumulated) + + +def cosine(a: Sequence[float], b: Sequence[float]) -> float: + """Cosine similarity of two equal-length vectors (unit test helper).""" + numerator = sum(x * y for x, y in zip(a, b, strict=True)) + return numerator / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))) + + +@dataclass +class FakeEmbeddings: + """Deterministic hash-based EmbeddingBackend (§15).""" + + dimensions: int = EMBEDDING_DIMENSIONS + calls: list[EmbedCall] = field(default_factory=list) + + def embed_documents(self, texts: list[str]) -> list[list[float]]: + self.calls.append(EmbedCall(texts=tuple(texts), task_type="document")) + return [fake_embedding(text, self.dimensions) for text in texts] + + def embed_query(self, text: str) -> list[float]: + self.calls.append(EmbedCall(texts=(text,), task_type="query")) + return fake_embedding(text, self.dimensions) diff --git a/tests/unit/test_fakes.py b/tests/unit/test_fakes.py new file mode 100644 index 0000000..a8985d8 --- /dev/null +++ b/tests/unit/test_fakes.py @@ -0,0 +1,121 @@ +"""Unit tests: tests/fakes.py — the suite's two (and only) mock backends (§15). + +Verifies the contract later tasks (T09–T14) rely on: scripted chat responses +including the paraphrased-quote and refusal cases, plus deterministic, +L2-normalized, semantically-correlated hash embeddings. +""" + +import json + +import pytest +from fakes import ( + EmbedCall, + FakeChat, + FakeEmbeddings, + chat_result, + cosine, + fake_embedding, + paraphrased_quote_result, + refusal_result, + scripted_chat, +) + +# --- FakeChat --------------------------------------------------------------------- + + +def test_fake_chat_plays_scripted_responses_in_order() -> None: + first = chat_result("one") + second = chat_result("two") + chat = scripted_chat(first, second) + + assert chat.complete(system="s", user="u", model="m", temperature=0.0, seed=1) is first + assert chat.complete(system="s", user="u", model="m", temperature=0.0, seed=1) is second + + +def test_fake_chat_records_every_call() -> None: + chat = scripted_chat(chat_result("ok")) + chat.complete(system="sys", user="usr", model="m1", temperature=0.0, seed=42) + + (call,) = chat.calls + assert call.system == "sys" + assert call.user == "usr" + assert call.model == "m1" + assert call.temperature == 0.0 + assert call.seed == 42 + + +def test_fake_chat_raises_when_script_exhausted() -> None: + chat = scripted_chat(chat_result("only")) + chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + with pytest.raises(RuntimeError, match="exhausted"): + chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + + +def test_fake_chat_can_be_scripted_empty_for_protocol_shaped_use() -> None: + chat: FakeChat = scripted_chat() + assert chat.responses == [] + + +def test_paraphrased_quote_case_is_a_paraphrasing_citation() -> None: + result = paraphrased_quote_result() + payload = json.loads(result.text) + assert payload["refused"] is False + (citation,) = payload["citations"] + # §15: this quote must NOT be trusted verbatim by downstream verification. + assert isinstance(citation["quote"], str) + assert "fixed retry delay" in citation["quote"] + + +def test_refusal_case_refuses_with_no_citations() -> None: + result = refusal_result() + payload = json.loads(result.text) + assert payload["refused"] is True + assert payload["citations"] == [] + + +# --- FakeEmbeddings ---------------------------------------------------------------- + + +def test_fake_embedding_is_deterministic_and_unit_norm() -> None: + first = fake_embedding("How do I configure retries on a timer trigger?") + second = fake_embedding("How do I configure retries on a timer trigger?") + + assert len(first) == 768 + assert first == second + assert sum(v * v for v in first) == pytest.approx(1.0) + + +def test_fake_embedding_related_texts_are_closer_than_unrelated() -> None: + question = "How do I configure retries on a timer trigger?" + related = "retry configuration for timer triggers" + unrelated = "blob storage account properties" + + assert cosine(fake_embedding(question), fake_embedding(related)) > cosine( + fake_embedding(question), fake_embedding(unrelated) + ) + + +def test_fake_embedding_empty_text_still_unit_norm() -> None: + vector = fake_embedding("") + assert sum(v * v for v in vector) == pytest.approx(1.0) + + +def test_fake_embeddings_records_batches_with_task_kind() -> None: + embeddings = FakeEmbeddings() + vectors = embeddings.embed_documents(["alpha", "beta"]) + query = embeddings.embed_query("gamma") + + assert len(vectors) == 2 + assert vectors[0] == fake_embedding("alpha") + assert query == fake_embedding("gamma") + assert embeddings.calls == [ + EmbedCall(texts=("alpha", "beta"), task_type="document"), + EmbedCall(texts=("gamma",), task_type="query"), + ] + + +def test_fake_embeddings_custom_dimensions() -> None: + embeddings = FakeEmbeddings(dimensions=64) + (vector,) = embeddings.embed_documents(["text"]) + assert len(vector) == 64 + assert sum(v * v for v in vector) == pytest.approx(1.0) diff --git a/tests/unit/test_providers_base.py b/tests/unit/test_providers_base.py new file mode 100644 index 0000000..4036574 --- /dev/null +++ b/tests/unit/test_providers_base.py @@ -0,0 +1,242 @@ +"""Unit tests: providers/base.py — cost estimation, normalization, batching, +bounded 429 backoff, factories, and env handling (§7.2, §9.8, §11.3).""" + +import pytest + +from caliper.config import CaliperConfig, ConfigError +from caliper.providers import ( + EMBEDDING_DIMENSIONS, + OLLAMA_EMBED_MODEL, + GeminiChat, + GeminiEmbeddings, + OllamaChat, + OllamaEmbeddings, + ProviderError, + Usage, + estimate_cost, + get_chat, + get_embeddings, + l2_normalize, + load_prices, +) +from caliper.providers import base as base_module + +# --- estimate_cost (§9.8 figures) ----------------------------------------------- + + +def test_estimate_cost_combines_input_and_output_per_mtok() -> None: + prices = load_prices().entries + usage = Usage(prompt_tokens=1_000_000, completion_tokens=1_000_000) + # §9.8: gemini-3.5-flash-lite $0.10/M in, $0.40/M out. + assert estimate_cost(usage, "gemini-3.5-flash-lite", prices) == pytest.approx(0.50) + + +def test_estimate_cost_uses_embed_price_for_embed_tokens() -> None: + prices = load_prices().entries + usage = Usage(embed_tokens=1_000_000) + # §9.8: gemini-embedding-001 $0.15/M in. + assert estimate_cost(usage, "gemini-embedding-001", prices) == pytest.approx(0.15) + + +def test_estimate_cost_unknown_model_raises_provider_error() -> None: + with pytest.raises(ProviderError, match="no price entry"): + estimate_cost(Usage(prompt_tokens=1), "totally-unknown-model", load_prices().entries) + + +def test_load_prices_records_as_of_and_binding_figures() -> None: + prices = load_prices() + assert prices.as_of # §9.8: as_of recorded + flash_lite = prices.entries["gemini-3.5-flash-lite"] + assert flash_lite["input_per_mtok"] == pytest.approx(0.10) + assert flash_lite["output_per_mtok"] == pytest.approx(0.40) + embedding = prices.entries["gemini-embedding-001"] + assert embedding["embed_per_mtok"] == pytest.approx(0.15) + + +# --- l2_normalize (ADR-003) ------------------------------------------------------- + + +def test_l2_normalize_scales_to_unit_norm_preserving_direction() -> None: + normalized = l2_normalize([3.0, 4.0]) + assert normalized == pytest.approx([0.6, 0.8]) + assert sum(value * value for value in normalized) == pytest.approx(1.0) + + +def test_l2_normalize_zero_vector_raises() -> None: + with pytest.raises(ProviderError, match="zero vector"): + l2_normalize([0.0, 0.0, 0.0]) + + +# --- iter_batches (§7.2: ≤100 texts per request) ----------------------------------- + + +def test_iter_batches_caps_batch_size_at_100() -> None: + batches = list(base_module.iter_batches([f"t{i}" for i in range(250)])) + assert [len(batch) for batch in batches] == [100, 100, 50] + + +def test_iter_batches_empty_input_yields_nothing() -> None: + assert list(base_module.iter_batches([])) == [] + + +def test_iter_batches_custom_size() -> None: + assert [len(b) for b in base_module.iter_batches(["a", "b", "c"], size=2)] == [2, 1] + + +# --- call_with_backoff (§7.2: max 5 retries on 429) --------------------------------- + + +class _Fake429(Exception): + """Stand-in for an HTTP 429 error from either SDK.""" + + +def _is_fake_429(exc: Exception) -> bool: + return isinstance(exc, _Fake429) + + +def test_call_with_backoff_retries_429_with_exponential_delays() -> None: + sleeps: list[float] = [] + attempts = {"n": 0} + + def op() -> str: + attempts["n"] += 1 + if attempts["n"] <= 2: + raise _Fake429("429") + return "ok" + + result = base_module.call_with_backoff( + op, describe="demo", is_rate_limited=_is_fake_429, sleep=sleeps.append + ) + assert result == "ok" + assert attempts["n"] == 3 + assert sleeps == [1.0, 2.0] + + +def test_call_with_backoff_raises_quota_exhausted_after_max_retries() -> None: + sleeps: list[float] = [] + attempts = {"n": 0} + + def op() -> str: + attempts["n"] += 1 + raise _Fake429("429") + + with pytest.raises(ProviderError, match="rate limited") as excinfo: + base_module.call_with_backoff( + op, describe="demo", is_rate_limited=_is_fake_429, sleep=sleeps.append + ) + assert excinfo.value.code == "quota_exhausted" + # 1 initial attempt + MAX_RETRIES retries; 1s → 2s → 4s → 8s → 16s. + assert attempts["n"] == 1 + base_module.MAX_RETRIES + assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0] + + +def test_call_with_backoff_backoff_delay_is_capped() -> None: + sleeps: list[float] = [] + + def op() -> str: + raise _Fake429("429") + + with pytest.raises(ProviderError): + base_module.call_with_backoff( + op, + describe="demo", + is_rate_limited=_is_fake_429, + base_delay_s=30.0, + max_delay_s=60.0, + sleep=sleeps.append, + ) + assert all(delay <= 60.0 for delay in sleeps) + + +def test_call_with_backoff_wraps_other_errors_without_retry() -> None: + sleeps: list[float] = [] + attempts = {"n": 0} + + def op() -> str: + attempts["n"] += 1 + raise ValueError("boom") + + with pytest.raises(ProviderError, match="ValueError: boom") as excinfo: + base_module.call_with_backoff( + op, describe="demo", is_rate_limited=_is_fake_429, sleep=sleeps.append + ) + assert excinfo.value.code == "provider_unavailable" + assert attempts["n"] == 1 + assert sleeps == [] + + +# --- provider selection + factories via environment (§11.2) ------------------------ + + +@pytest.fixture +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("CALIPER_PROVIDER", raising=False) + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + monkeypatch.delenv("OLLAMA_BASE_URL", raising=False) + + +def test_provider_name_defaults_to_gemini(clean_env: None) -> None: + assert base_module.provider_name() == "gemini" + + +def test_provider_name_reads_and_normalizes_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CALIPER_PROVIDER", " Ollama ") + assert base_module.provider_name() == "ollama" + + +def test_provider_name_rejects_unknown_value(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CALIPER_PROVIDER", "openai") + with pytest.raises(ConfigError, match="CALIPER_PROVIDER"): + base_module.provider_name() + + +def test_get_chat_gemini_requires_api_key(clean_env: None) -> None: + with pytest.raises(ConfigError, match="GEMINI_API_KEY"): + get_chat(CaliperConfig()) + + +def test_get_chat_gemini_builds_gemini_backend( + clean_env: None, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GEMINI_API_KEY", "test-key") + assert isinstance(get_chat(CaliperConfig()), GeminiChat) + + +def test_get_chat_ollama_builds_ollama_backend( + clean_env: None, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("CALIPER_PROVIDER", "ollama") + assert isinstance(get_chat(CaliperConfig()), OllamaChat) + + +def test_get_embeddings_rejects_non_768_dimensions_before_any_env_access( + clean_env: None, +) -> None: + cfg = CaliperConfig() + broken = cfg.model_copy( + update={"embeddings": cfg.embeddings.model_copy(update={"dimensions": 512})} + ) + with pytest.raises(ConfigError, match="embeddings.dimensions"): + get_embeddings(broken) + + +def test_get_embeddings_gemini_uses_config_model( + clean_env: None, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GEMINI_API_KEY", "test-key") + embeddings = get_embeddings(CaliperConfig()) + assert isinstance(embeddings, GeminiEmbeddings) + # Reading the config flow that was passed in (single underscore attrs are + # the backend's captured settings; ruff SLF rules are not enabled). + assert embeddings._model == "gemini-embedding-001" + assert embeddings._dimensions == EMBEDDING_DIMENSIONS + + +def test_get_embeddings_ollama_uses_pinned_ollama_model( + clean_env: None, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("CALIPER_PROVIDER", "ollama") + embeddings = get_embeddings(CaliperConfig()) + assert isinstance(embeddings, OllamaEmbeddings) + assert embeddings._model == OLLAMA_EMBED_MODEL + assert embeddings._dimensions == EMBEDDING_DIMENSIONS diff --git a/tests/unit/test_providers_gemini.py b/tests/unit/test_providers_gemini.py new file mode 100644 index 0000000..e85fe5d --- /dev/null +++ b/tests/unit/test_providers_gemini.py @@ -0,0 +1,284 @@ +"""Unit tests: providers/gemini.py — chat parameters/usage, embedding batching +(≤100), task types, client-side normalization, and 429 backoff. + +The SDK client seam is injected through the public constructor (§15): a fake +`GeminiModels` object with scripted responses and exceptions. No network, no +patch() on internals. +""" + +import math + +import pytest +from google.genai import errors as genai_errors +from google.genai import types + +from caliper.providers import EMBEDDING_DIMENSIONS, ProviderError +from caliper.providers.gemini import ( + GEMINI_TASK_DOCUMENT, + GEMINI_TASK_QUERY, + GeminiChat, + GeminiEmbeddings, +) + +# --- test doubles (constructor-injected, like tests/fakes.py but SDK-shaped) ----- + + +def _chat_response( + text: str, *, prompt_tokens: int = 10, completion_tokens: int = 5 +) -> types.GenerateContentResponse: + return types.GenerateContentResponse.model_construct( + candidates=[ + types.Candidate.model_construct( + content=types.Content.model_construct(parts=[types.Part.model_construct(text=text)]) + ) + ], + usage_metadata=types.GenerateContentResponseUsageMetadata.model_construct( + prompt_token_count=prompt_tokens, candidates_token_count=completion_tokens + ), + model_version="fake", + ) + + +def _empty_chat_response() -> types.GenerateContentResponse: + return types.GenerateContentResponse.model_construct(candidates=[]) + + +def _embed_response(vectors: list[list[float]]) -> types.EmbedContentResponse: + return types.EmbedContentResponse.model_construct( + embeddings=[types.ContentEmbedding(values=vector) for vector in vectors] + ) + + +def _rate_limited() -> genai_errors.APIError: + return genai_errors.APIError(429, {"message": "quota exceeded", "status": "RESOURCE_EXHAUSTED"}) + + +def _server_error() -> genai_errors.APIError: + return genai_errors.APIError(500, {"message": "internal", "status": "INTERNAL"}) + + +def _sleep_recorder() -> tuple[list[float], object]: + sleeps: list[float] = [] + + def record(seconds: float) -> None: + sleeps.append(seconds) + + return sleeps, record + + +class FakeGeminiModels: + """Fake of the narrow `GeminiModels` protocol with scripted results. + + Unscripted calls auto-reply: chat with a canned text response, embeddings + with a 768-dim constant vector per input (so normalization is a no-op). + """ + + def __init__(self) -> None: + self.generate_calls: list[dict[str, object]] = [] + self.embed_calls: list[dict[str, object]] = [] + self.generate_results: list[object] = [] # responses or exceptions + self.embed_results: list[object] = [] + + def generate_content( + self, *, model: str, contents: str, config: types.GenerateContentConfig + ) -> types.GenerateContentResponse: + self.generate_calls.append({"model": model, "contents": contents, "config": config}) + if self.generate_results: + item = self.generate_results.pop(0) + if isinstance(item, Exception): + raise item + assert isinstance(item, types.GenerateContentResponse) + return item + return _chat_response("auto reply") + + def embed_content( + self, *, model: str, contents: list[str], config: types.EmbedContentConfig + ) -> types.EmbedContentResponse: + self.embed_calls.append({"model": model, "contents": list(contents), "config": config}) + if self.embed_results: + item = self.embed_results.pop(0) + if isinstance(item, Exception): + raise item + assert isinstance(item, types.EmbedContentResponse) + return item + return _embed_response([[2.0] * EMBEDDING_DIMENSIONS for _ in contents]) + + +# --- chat (§7.2 complete) --------------------------------------------------------- + + +def test_complete_sends_system_temperature_seed_and_returns_usage() -> None: + models = FakeGeminiModels() + models.generate_results = [ + _chat_response("the answer", prompt_tokens=321, completion_tokens=44) + ] + chat = GeminiChat(models) + + result = chat.complete( + system="be terse", + user="question text", + model="gemini-3.5-flash-lite", + temperature=0.0, + seed=42, + ) + + assert result.text == "the answer" + assert result.prompt_tokens == 321 + assert result.completion_tokens == 44 + assert result.model == "gemini-3.5-flash-lite" + assert len(models.generate_calls) == 1 + call = models.generate_calls[0] + assert call["model"] == "gemini-3.5-flash-lite" + assert call["contents"] == "question text" + config = call["config"] + assert isinstance(config, types.GenerateContentConfig) + assert config.system_instruction == "be terse" + assert config.temperature == 0.0 + assert config.seed == 42 + + +def test_complete_seed_none_is_passed_through() -> None: + models = FakeGeminiModels() + chat = GeminiChat(models) + chat.complete(system="s", user="u", model="m", temperature=0.7, seed=None) + config = models.generate_calls[0]["config"] + assert isinstance(config, types.GenerateContentConfig) + assert config.seed is None + + +def test_complete_empty_response_raises_provider_error() -> None: + models = FakeGeminiModels() + models.generate_results = [_empty_chat_response()] + chat = GeminiChat(models) + with pytest.raises(ProviderError, match="no text"): + chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + + +def test_complete_retries_429_once_then_succeeds() -> None: + models = FakeGeminiModels() + models.generate_results = [_rate_limited(), _chat_response("recovered")] + sleeps, sleep = _sleep_recorder() + chat = GeminiChat(models, sleep=sleep) + + result = chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + + assert result.text == "recovered" + assert len(models.generate_calls) == 2 + assert sleeps == [1.0] + + +def test_complete_raises_quota_exhausted_after_max_retries() -> None: + models = FakeGeminiModels() + models.generate_results = [_rate_limited()] * 10 + sleeps, sleep = _sleep_recorder() + chat = GeminiChat(models, sleep=sleep) + + with pytest.raises(ProviderError, match="rate limited") as excinfo: + chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + + assert excinfo.value.code == "quota_exhausted" + assert len(models.generate_calls) == 6 # 1 initial + 5 retries + assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0] + + +def test_complete_does_not_retry_non_429_errors() -> None: + models = FakeGeminiModels() + models.generate_results = [_server_error()] + sleeps, sleep = _sleep_recorder() + chat = GeminiChat(models, sleep=sleep) + + with pytest.raises(ProviderError) as excinfo: + chat.complete(system="s", user="u", model="m", temperature=0.0, seed=None) + + assert excinfo.value.code == "provider_unavailable" + assert len(models.generate_calls) == 1 + assert sleeps == [] + + +# --- embeddings (§7.2 binding: batch ≤100, task types, client-side normalization) -- + + +def test_embed_documents_batches_at_most_100_per_request() -> None: + models = FakeGeminiModels() + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + + vectors = embeddings.embed_documents([f"text {i}" for i in range(250)]) + + assert len(models.embed_calls) == 3 + batch_sizes = [len(call["contents"]) for call in models.embed_calls] # type: ignore[arg-type] + assert batch_sizes == [100, 100, 50] + assert len(vectors) == 250 + + +def test_embed_documents_uses_retrieval_document_task_and_768_dimensions() -> None: + models = FakeGeminiModels() + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + embeddings.embed_documents(["chunk body"]) + + config = models.embed_calls[0]["config"] + assert isinstance(config, types.EmbedContentConfig) + assert config.task_type == GEMINI_TASK_DOCUMENT == "RETRIEVAL_DOCUMENT" + assert config.output_dimensionality == EMBEDDING_DIMENSIONS == 768 + assert models.embed_calls[0]["model"] == "gemini-embedding-001" + + +def test_embed_documents_output_is_l2_normalized() -> None: + models = FakeGeminiModels() + models.embed_results = [_embed_response([[3.0, 4.0] + [0.0] * 766])] + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + + (vector,) = embeddings.embed_documents(["chunk body"]) + + assert vector[0] == pytest.approx(0.6) + assert vector[1] == pytest.approx(0.8) + assert sum(value * value for value in vector) == pytest.approx(1.0) + + +def test_embed_documents_empty_input_makes_no_calls() -> None: + models = FakeGeminiModels() + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + assert embeddings.embed_documents([]) == [] + assert models.embed_calls == [] + + +def test_embed_query_uses_retrieval_query_task_type() -> None: + models = FakeGeminiModels() + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + + vector = embeddings.embed_query("how do retries work?") + + config = models.embed_calls[0]["config"] + assert isinstance(config, types.EmbedContentConfig) + assert config.task_type == GEMINI_TASK_QUERY == "RETRIEVAL_QUERY" + assert models.embed_calls[0]["contents"] == ["how do retries work?"] + assert len(vector) == EMBEDDING_DIMENSIONS + assert sum(value * value for value in vector) == pytest.approx(1.0) + + +def test_embed_wrong_dimensionality_raises_provider_error() -> None: + models = FakeGeminiModels() + models.embed_results = [_embed_response([[2.0] * 512])] + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + with pytest.raises(ProviderError, match="512 dims, expected 768"): + embeddings.embed_query("q") + + +def test_embed_vector_count_mismatch_raises_provider_error() -> None: + models = FakeGeminiModels() + models.embed_results = [_embed_response([[2.0] * EMBEDDING_DIMENSIONS])] + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001") + with pytest.raises(ProviderError, match="1 vectors for 2 inputs"): + embeddings.embed_documents(["a", "b"]) + + +def test_embed_retries_429_with_backoff_then_succeeds() -> None: + models = FakeGeminiModels() + models.embed_results = [_rate_limited(), _rate_limited(), _embed_response([[2.0] * 768])] + sleeps, sleep = _sleep_recorder() + embeddings = GeminiEmbeddings(models, model="gemini-embedding-001", sleep=sleep) + + vector = embeddings.embed_query("q") + + assert len(models.embed_calls) == 3 + assert sleeps == [1.0, 2.0] + assert math.isclose(sum(v * v for v in vector), 1.0) diff --git a/tests/unit/test_providers_ollama.py b/tests/unit/test_providers_ollama.py new file mode 100644 index 0000000..2b2540e --- /dev/null +++ b/tests/unit/test_providers_ollama.py @@ -0,0 +1,256 @@ +"""Unit tests: providers/ollama.py — chat payload/usage parsing, embed +batching/normalization, 429 backoff, and transport-error mapping. + +Network is exercised through httpx's injectable MockTransport (§15) — no real +requests, no patch() on internals. +""" + +import json +from collections.abc import Callable + +import httpx +import pytest + +from caliper.providers import EMBEDDING_DIMENSIONS, ProviderError +from caliper.providers.ollama import ( + OLLAMA_CHAT_MODEL, + OLLAMA_EMBED_MODEL, + OllamaChat, + OllamaEmbeddings, +) + +BASE_URL = "http://ollama.test" + + +def _client(handler: Callable[[httpx.Request], httpx.Response]) -> httpx.Client: + return httpx.Client(transport=httpx.MockTransport(handler), base_url=BASE_URL) + + +def _sleep_recorder() -> tuple[list[float], object]: + sleeps: list[float] = [] + + def record(seconds: float) -> None: + sleeps.append(seconds) + + return sleeps, record + + +def _chat_handler( + content: str, *, prompt_eval_count: int = 21, eval_count: int = 7 +) -> Callable[[httpx.Request], httpx.Response]: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, + json={ + "message": {"role": "assistant", "content": content}, + "prompt_eval_count": prompt_eval_count, + "eval_count": eval_count, + }, + request=request, + ) + + return handler + + +def _embed_handler() -> Callable[[httpx.Request], httpx.Response]: + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content.decode("utf-8")) + return httpx.Response( + 200, + json={"embeddings": [[1.0] * EMBEDDING_DIMENSIONS for _ in body["input"]]}, + request=request, + ) + + return handler + + +# --- chat (§7.2 complete) --------------------------------------------------------- + + +def test_complete_posts_chat_payload_and_parses_usage() -> None: + seen: dict[str, object] = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["path"] = request.url.path + seen["body"] = json.loads(request.content.decode("utf-8")) + return _chat_handler("Set the retry block.")(request) + + chat = OllamaChat(_client(handler)) + result = chat.complete( + system="be terse", + user="question text", + model=OLLAMA_CHAT_MODEL, + temperature=0.0, + seed=42, + ) + + assert result.text == "Set the retry block." + assert result.prompt_tokens == 21 + assert result.completion_tokens == 7 + assert result.model == OLLAMA_CHAT_MODEL + assert seen["path"] == "/api/chat" + body = seen["body"] + assert isinstance(body, dict) + assert body["model"] == OLLAMA_CHAT_MODEL + assert body["stream"] is False + assert body["messages"] == [ + {"role": "system", "content": "be terse"}, + {"role": "user", "content": "question text"}, + ] + assert body["options"] == {"temperature": 0.0, "seed": 42} + + +def test_complete_omits_seed_when_none() -> None: + seen: dict[str, object] = {} + + def handler(request: httpx.Request) -> httpx.Response: + seen["body"] = json.loads(request.content.decode("utf-8")) + return _chat_handler("ok")(request) + + chat = OllamaChat(_client(handler)) + chat.complete(system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.5, seed=None) + body = seen["body"] + assert isinstance(body, dict) + assert body["options"] == {"temperature": 0.5} + + +def test_complete_missing_content_raises_provider_error() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"message": {}}, request=request) + + chat = OllamaChat(_client(handler)) + with pytest.raises(ProviderError, match="message.content"): + chat.complete(system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.0, seed=None) + + +# --- embeddings (§7.2 binding) ----------------------------------------------------- + + +def test_embed_documents_batches_at_most_100_and_normalizes() -> None: + requests: list[int] = [] + + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content.decode("utf-8")) + requests.append(len(body["input"])) + assert request.url.path == "/api/embed" + assert body["model"] == OLLAMA_EMBED_MODEL + return httpx.Response( + 200, + json={"embeddings": [[3.0, 4.0] + [0.0] * 766 for _ in body["input"]]}, + request=request, + ) + + embeddings = OllamaEmbeddings(_client(handler)) + vectors = embeddings.embed_documents([f"text {i}" for i in range(250)]) + + assert requests == [100, 100, 50] + assert len(vectors) == 250 + assert vectors[0][0] == pytest.approx(0.6) + assert vectors[0][1] == pytest.approx(0.8) + assert sum(v * v for v in vectors[0]) == pytest.approx(1.0) + + +def test_embed_query_sends_single_text_and_normalizes() -> None: + embeddings = OllamaEmbeddings(_client(_embed_handler())) + vector = embeddings.embed_query("how do retries work?") + assert len(vector) == EMBEDDING_DIMENSIONS + assert sum(v * v for v in vector) == pytest.approx(1.0) + + +def test_embed_documents_empty_input_makes_no_requests() -> None: + count = {"n": 0} + + def handler(request: httpx.Request) -> httpx.Response: + count["n"] += 1 + return _embed_handler()(request) + + embeddings = OllamaEmbeddings(_client(handler)) + assert embeddings.embed_documents([]) == [] + assert count["n"] == 0 + + +def test_embed_wrong_dimensionality_raises_provider_error() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"embeddings": [[1.0] * 512]}, request=request) + + embeddings = OllamaEmbeddings(_client(handler)) + with pytest.raises(ProviderError, match="512 dims, expected 768"): + embeddings.embed_query("q") + + +# --- backoff + error mapping (§7.2, §10.1) ------------------------------------------ + + +def test_complete_retries_429_with_backoff_then_succeeds() -> None: + state = {"n": 0} + sleeps, sleep = _sleep_recorder() + + def handler(request: httpx.Request) -> httpx.Response: + state["n"] += 1 + if state["n"] <= 2: + return httpx.Response(429, json={"error": "rate limited"}, request=request) + return _chat_handler("recovered")(request) + + chat = OllamaChat(_client(handler), sleep=sleep) + result = chat.complete( + system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.0, seed=None + ) + + assert result.text == "recovered" + assert state["n"] == 3 + assert sleeps == [1.0, 2.0] + + +def test_complete_raises_quota_exhausted_after_max_retries() -> None: + state = {"n": 0} + sleeps, sleep = _sleep_recorder() + + def handler(request: httpx.Request) -> httpx.Response: + state["n"] += 1 + return httpx.Response(429, json={"error": "rate limited"}, request=request) + + chat = OllamaChat(_client(handler), sleep=sleep) + with pytest.raises(ProviderError, match="rate limited") as excinfo: + chat.complete(system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.0, seed=None) + + assert excinfo.value.code == "quota_exhausted" + assert state["n"] == 6 # 1 initial + 5 retries + assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0] + + +def test_transport_error_maps_to_provider_unavailable_without_retry() -> None: + state = {"n": 0} + + def handler(request: httpx.Request) -> httpx.Response: + state["n"] += 1 + raise httpx.ConnectError("connection refused") + + chat = OllamaChat(_client(handler)) + with pytest.raises(ProviderError, match="connection refused") as excinfo: + chat.complete(system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.0, seed=None) + + assert excinfo.value.code == "provider_unavailable" + assert state["n"] == 1 + + +def test_http_500_maps_to_provider_unavailable_without_retry() -> None: + state = {"n": 0} + + def handler(request: httpx.Request) -> httpx.Response: + state["n"] += 1 + return httpx.Response(500, json={"error": "boom"}, request=request) + + chat = OllamaChat(_client(handler)) + with pytest.raises(ProviderError, match="500"): + chat.complete(system="s", user="u", model=OLLAMA_CHAT_MODEL, temperature=0.0, seed=None) + + assert state["n"] == 1 + + +def test_unexpected_json_shape_raises_provider_error() -> None: + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(200, json={"unexpected": True}, request=request) + + embeddings = OllamaEmbeddings(_client(handler)) + with pytest.raises(ProviderError, match="embeddings"): + embeddings.embed_query("q") From 89e5423c2bed07bc06fd9d18e075a8e49495274d Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 00:33:20 +0530 Subject: [PATCH 2/2] fix(providers): keep genai client alive via GeminiSession google-genai's Models object holds only a weak reference to its Client: dropping the Client makes every request fail with 'Cannot send a request, as the client has been closed'. get_chat/get_embeddings and scripts/smoke.py now build a GeminiSession that owns the Client, and the Gemini backends store it (keepalive slot). Found by the live smoke run; proven by the gemini leg passing (chat + 768-dim normalized embed + cost + backoff demo). --- scripts/smoke.py | 13 +++++++------ src/caliper/providers/__init__.py | 15 +++++++++------ src/caliper/providers/gemini.py | 29 ++++++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/scripts/smoke.py b/scripts/smoke.py index 5df4faa..32a7295 100644 --- a/scripts/smoke.py +++ b/scripts/smoke.py @@ -43,7 +43,7 @@ load_prices, ollama_base_url, ) -from caliper.providers.gemini import GeminiChat, GeminiEmbeddings +from caliper.providers.gemini import GeminiChat, GeminiEmbeddings, GeminiSession from caliper.providers.ollama import ( OLLAMA_CHAT_MODEL, OLLAMA_EMBED_MODEL, @@ -98,14 +98,15 @@ def _load_env_file(path: Path) -> None: def _build_backend(name: str, cfg: CaliperConfig) -> BackendPair: """Build one backend pair directly (smoke tests BOTH, ignoring CALIPER_PROVIDER).""" if name == "gemini": - from google import genai - - models = genai.Client(api_key=gemini_api_key()).models + session = GeminiSession(gemini_api_key()) return BackendPair( name, - GeminiChat(models), + GeminiChat(session.models, keepalive=session), GeminiEmbeddings( - models, model=cfg.embeddings.model, dimensions=cfg.embeddings.dimensions + session.models, + model=cfg.embeddings.model, + dimensions=cfg.embeddings.dimensions, + keepalive=session, ), chat_model=cfg.answer.model, ) diff --git a/src/caliper/providers/__init__.py b/src/caliper/providers/__init__.py index 50d330d..e79dd68 100644 --- a/src/caliper/providers/__init__.py +++ b/src/caliper/providers/__init__.py @@ -12,7 +12,6 @@ from typing import TYPE_CHECKING import httpx -from google import genai from caliper.config import ConfigError from caliper.providers.base import ( @@ -31,7 +30,7 @@ ollama_base_url, provider_name, ) -from caliper.providers.gemini import GeminiChat, GeminiEmbeddings +from caliper.providers.gemini import GeminiChat, GeminiEmbeddings, GeminiSession from caliper.providers.ollama import ( OLLAMA_CHAT_MODEL, OLLAMA_EMBED_MODEL, @@ -53,6 +52,7 @@ "EmbeddingBackend", "GeminiChat", "GeminiEmbeddings", + "GeminiSession", "OllamaChat", "OllamaEmbeddings", "PriceEntry", @@ -74,8 +74,8 @@ def get_chat(cfg: CaliperConfig) -> ChatBackend: `complete()` on every call; this factory only selects the transport. """ if provider_name() == "gemini": - genai_client = genai.Client(api_key=gemini_api_key()) - return GeminiChat(genai_client.models) + session = GeminiSession(gemini_api_key()) + return GeminiChat(session.models, keepalive=session) ollama_client = httpx.Client( base_url=ollama_base_url(), timeout=httpx.Timeout(OLLAMA_HTTP_TIMEOUT_S) ) @@ -96,9 +96,12 @@ def get_embeddings(cfg: CaliperConfig) -> EmbeddingBackend: f"(ADR-003: vec0 schema + Ollama compatibility), got {cfg.embeddings.dimensions}" ) if provider_name() == "gemini": - genai_client = genai.Client(api_key=gemini_api_key()) + session = GeminiSession(gemini_api_key()) return GeminiEmbeddings( - genai_client.models, model=cfg.embeddings.model, dimensions=cfg.embeddings.dimensions + session.models, + model=cfg.embeddings.model, + dimensions=cfg.embeddings.dimensions, + keepalive=session, ) ollama_client = httpx.Client( base_url=ollama_base_url(), timeout=httpx.Timeout(OLLAMA_HTTP_TIMEOUT_S) diff --git a/src/caliper/providers/gemini.py b/src/caliper/providers/gemini.py index 33a7b73..4a0b1e2 100644 --- a/src/caliper/providers/gemini.py +++ b/src/caliper/providers/gemini.py @@ -17,6 +17,7 @@ from collections.abc import Callable, Sequence from typing import Protocol +from google import genai from google.genai import errors as genai_errors from google.genai import types from google.genai.types import EmbedContentConfig, GenerateContentConfig @@ -56,14 +57,36 @@ def _is_rate_limited(exc: Exception) -> bool: return isinstance(exc, genai_errors.APIError) and exc.code == 429 +class GeminiSession: + """Owns a `genai.Client` so its `.models` handle stays usable (§7.2). + + The google-genai SDK's `Models` object holds only a weak reference to its + `Client`: once the `Client` is garbage-collected, every request fails with + "Cannot send a request, as the client has been closed". Factories and the + smoke script therefore build a `GeminiSession` and hand it to the backends, + which store it — keeping the client alive for the backend's lifetime. + """ + + def __init__(self, api_key: str) -> None: + self.client = genai.Client(api_key=api_key) + self.models = self.client.models + + class GeminiChat: """ChatBackend over the Gemini API (§7.2). Model is passed per call.""" def __init__( - self, models: GeminiModels, *, sleep: Callable[[float], None] = time.sleep + self, + models: GeminiModels, + *, + sleep: Callable[[float], None] = time.sleep, + keepalive: object | None = None, ) -> None: self._models = models self._sleep = sleep + # Holds the GeminiSession (and thus the genai.Client) referenced for + # this backend's lifetime; see GeminiSession's docstring. + self._keepalive = keepalive def complete( self, *, system: str, user: str, model: str, temperature: float, seed: int | None @@ -99,11 +122,15 @@ def __init__( model: str, dimensions: int = EMBEDDING_DIMENSIONS, sleep: Callable[[float], None] = time.sleep, + keepalive: object | None = None, ) -> None: self._models = models self._model = model self._dimensions = dimensions self._sleep = sleep + # Holds the GeminiSession (and thus the genai.Client) referenced for + # this backend's lifetime; see GeminiSession's docstring. + self._keepalive = keepalive def embed_documents(self, texts: list[str]) -> list[list[float]]: vectors: list[list[float]] = []