nomic_embeddings.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. from collections.abc import Callable
  3. from typing import Any, Literal
  4. import pytest
  5. # import monkeypatch
  6. from _pytest.monkeypatch import MonkeyPatch
  7. from nomic import embed
  8. def create_embedding(texts: list[str], model: str, **kwargs: Any) -> dict:
  9. texts_len = len(texts)
  10. foo_embedding_sample = 0.123456
  11. combined = {
  12. "embeddings": [[foo_embedding_sample for _ in range(768)] for _ in range(texts_len)],
  13. "usage": {"prompt_tokens": texts_len, "total_tokens": texts_len},
  14. "model": model,
  15. "inference_mode": "remote",
  16. }
  17. return combined
  18. def mock_nomic(
  19. monkeypatch: MonkeyPatch,
  20. methods: list[Literal["text_embedding"]],
  21. ) -> Callable[[], None]:
  22. """
  23. mock nomic module
  24. :param monkeypatch: pytest monkeypatch fixture
  25. :return: unpatch function
  26. """
  27. def unpatch() -> None:
  28. monkeypatch.undo()
  29. if "text_embedding" in methods:
  30. monkeypatch.setattr(embed, "text", create_embedding)
  31. return unpatch
  32. MOCK = os.getenv("MOCK_SWITCH", "false").lower() == "true"
  33. @pytest.fixture
  34. def setup_nomic_mock(request, monkeypatch):
  35. methods = request.param if hasattr(request, "param") else []
  36. if MOCK:
  37. unpatch = mock_nomic(monkeypatch, methods=methods)
  38. yield
  39. if MOCK:
  40. unpatch()