|
| 1 | +"""Opt-in live LiteLLM provider checks against real embedding APIs. |
| 2 | +
|
| 3 | +These tests intentionally do not run in normal CI. Enable them with |
| 4 | +``BASIC_MEMORY_RUN_LITELLM_INTEGRATION=1`` and provider API keys when validating |
| 5 | +new LiteLLM model support before merging or releasing. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +import math |
| 12 | +import os |
| 13 | +from dataclasses import dataclass |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +import pytest |
| 17 | + |
| 18 | +from basic_memory.repository.litellm_provider import LiteLLMEmbeddingProvider |
| 19 | + |
| 20 | + |
| 21 | +pytestmark = [ |
| 22 | + pytest.mark.semantic, |
| 23 | + pytest.mark.slow, |
| 24 | + pytest.mark.live, |
| 25 | + pytest.mark.skipif( |
| 26 | + os.getenv("BASIC_MEMORY_RUN_LITELLM_INTEGRATION") != "1", |
| 27 | + reason="Set BASIC_MEMORY_RUN_LITELLM_INTEGRATION=1 to run live LiteLLM tests", |
| 28 | + ), |
| 29 | +] |
| 30 | + |
| 31 | + |
| 32 | +@dataclass(frozen=True) |
| 33 | +class LiteLLMLiveCase: |
| 34 | + """A real LiteLLM embedding model to exercise end-to-end.""" |
| 35 | + |
| 36 | + name: str |
| 37 | + model: str |
| 38 | + dimensions: int |
| 39 | + api_key_env: str | None = None |
| 40 | + document_input_type: str | None = None |
| 41 | + query_input_type: str | None = None |
| 42 | + |
| 43 | + |
| 44 | +def _custom_cases() -> list[LiteLLMLiveCase]: |
| 45 | + """Load additional live model cases from BASIC_MEMORY_TEST_LITELLM_CASES.""" |
| 46 | + raw = os.getenv("BASIC_MEMORY_TEST_LITELLM_CASES") |
| 47 | + if not raw: |
| 48 | + return [] |
| 49 | + |
| 50 | + values = json.loads(raw) |
| 51 | + if not isinstance(values, list): |
| 52 | + raise ValueError("BASIC_MEMORY_TEST_LITELLM_CASES must be a JSON array") |
| 53 | + |
| 54 | + cases: list[LiteLLMLiveCase] = [] |
| 55 | + for value in values: |
| 56 | + if not isinstance(value, dict): |
| 57 | + raise ValueError("Each LiteLLM live case must be a JSON object") |
| 58 | + case_data: dict[str, Any] = value |
| 59 | + cases.append( |
| 60 | + LiteLLMLiveCase( |
| 61 | + name=str(case_data["name"]), |
| 62 | + model=str(case_data["model"]), |
| 63 | + dimensions=int(case_data["dimensions"]), |
| 64 | + api_key_env=case_data.get("api_key_env"), |
| 65 | + document_input_type=case_data.get("document_input_type"), |
| 66 | + query_input_type=case_data.get("query_input_type"), |
| 67 | + ) |
| 68 | + ) |
| 69 | + return cases |
| 70 | + |
| 71 | + |
| 72 | +def _live_cases() -> list[LiteLLMLiveCase | Any]: |
| 73 | + """Return built-in and user-supplied live cases whose credentials are available.""" |
| 74 | + cases: list[LiteLLMLiveCase] = [] |
| 75 | + |
| 76 | + if os.getenv("OPENAI_API_KEY"): |
| 77 | + cases.append( |
| 78 | + LiteLLMLiveCase( |
| 79 | + name="openai-text-embedding-3-small", |
| 80 | + model="openai/text-embedding-3-small", |
| 81 | + dimensions=1536, |
| 82 | + api_key_env="OPENAI_API_KEY", |
| 83 | + ) |
| 84 | + ) |
| 85 | + |
| 86 | + if os.getenv("COHERE_API_KEY"): |
| 87 | + cases.append( |
| 88 | + LiteLLMLiveCase( |
| 89 | + name="cohere-embed-english-v3", |
| 90 | + model="cohere/embed-english-v3.0", |
| 91 | + dimensions=1024, |
| 92 | + api_key_env="COHERE_API_KEY", |
| 93 | + ) |
| 94 | + ) |
| 95 | + |
| 96 | + cases.extend(_custom_cases()) |
| 97 | + if cases: |
| 98 | + return cases |
| 99 | + |
| 100 | + return [ |
| 101 | + pytest.param( |
| 102 | + None, |
| 103 | + marks=pytest.mark.skip( |
| 104 | + reason=( |
| 105 | + "No LiteLLM live cases configured. Set OPENAI_API_KEY, " |
| 106 | + "COHERE_API_KEY, or BASIC_MEMORY_TEST_LITELLM_CASES." |
| 107 | + ) |
| 108 | + ), |
| 109 | + ) |
| 110 | + ] |
| 111 | + |
| 112 | + |
| 113 | +def _cosine(a: list[float], b: list[float]) -> float: |
| 114 | + """Compute cosine similarity for live ranking sanity checks.""" |
| 115 | + dot = sum(x * y for x, y in zip(a, b, strict=True)) |
| 116 | + norm_a = math.sqrt(sum(x * x for x in a)) |
| 117 | + norm_b = math.sqrt(sum(y * y for y in b)) |
| 118 | + if norm_a == 0 or norm_b == 0: |
| 119 | + return 0.0 |
| 120 | + return dot / (norm_a * norm_b) |
| 121 | + |
| 122 | + |
| 123 | +def _assert_valid_vector(vector: list[float], dimensions: int) -> None: |
| 124 | + """Assert provider output is a usable normalized vector.""" |
| 125 | + assert len(vector) == dimensions |
| 126 | + assert all(math.isfinite(value) for value in vector) |
| 127 | + norm = math.sqrt(sum(value * value for value in vector)) |
| 128 | + assert norm == pytest.approx(1.0, abs=1e-6) |
| 129 | + |
| 130 | + |
| 131 | +@pytest.mark.asyncio |
| 132 | +@pytest.mark.parametrize( |
| 133 | + "case", |
| 134 | + _live_cases(), |
| 135 | + ids=lambda case: case.name if isinstance(case, LiteLLMLiveCase) else "no-live-cases", |
| 136 | +) |
| 137 | +async def test_litellm_live_model_embeds_documents_and_queries( |
| 138 | + case: LiteLLMLiveCase, |
| 139 | +) -> None: |
| 140 | + """A live LiteLLM model should embed documents and rank a related query higher.""" |
| 141 | + api_key = os.getenv(case.api_key_env) if case.api_key_env else None |
| 142 | + provider = LiteLLMEmbeddingProvider( |
| 143 | + model_name=case.model, |
| 144 | + dimensions=case.dimensions, |
| 145 | + batch_size=2, |
| 146 | + api_key=api_key, |
| 147 | + timeout=60.0, |
| 148 | + document_input_type=case.document_input_type, |
| 149 | + query_input_type=case.query_input_type, |
| 150 | + ) |
| 151 | + |
| 152 | + documents = [ |
| 153 | + "OAuth login refresh tokens keep an authenticated web session active.", |
| 154 | + "A sourdough starter ferments flour and water before bread baking.", |
| 155 | + ] |
| 156 | + vectors = await provider.embed_documents(documents) |
| 157 | + query_vector = await provider.embed_query("authentication login token flow") |
| 158 | + |
| 159 | + assert len(vectors) == 2 |
| 160 | + for vector in [*vectors, query_vector]: |
| 161 | + _assert_valid_vector(vector, case.dimensions) |
| 162 | + |
| 163 | + assert _cosine(query_vector, vectors[0]) > _cosine(query_vector, vectors[1]) |
0 commit comments