test_embedding_index.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import numpy as np
  2. import pytest
  3. from agent_ai.embedding_index import build_faiss_index, search_faiss
  4. def test_build_and_search_faiss_index():
  5. embeddings = np.array([
  6. [1.0, 0.0, 0.0, 0.0],
  7. [0.9, 0.1, 0.0, 0.0],
  8. [0.0, 1.0, 0.0, 0.0],
  9. [0.0, 0.9, 0.1, 0.0],
  10. [0.0, 0.0, 1.0, 0.0]
  11. ], dtype=np.float32)
  12. # Construire l'index
  13. index = build_faiss_index(embeddings)
  14. # Requête : un vecteur proche du premier
  15. query = np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float32)
  16. distances, indices = search_faiss(index, query, top_k=3)
  17. # Vérifier la forme des résultats
  18. assert distances.shape == (1, 3)
  19. assert indices.shape == (1, 3)
  20. # Le vecteur le plus proche doit être lui-même (distance max = 1 après normalisation)
  21. assert indices[0, 0] == 0
  22. assert np.isclose(distances[0, 0], 0.0, atol=1e-5)
  23. # Les distances doivent être décroissantes (cosine similarity décroissante)
  24. assert distances[0, 0] <= distances[0, 1] <= distances[0, 2]
  25. def test_search_batch_queries():
  26. embeddings = np.random.rand(10, 8).astype(np.float32)
  27. index = build_faiss_index(embeddings)
  28. queries = np.array([
  29. embeddings[0],
  30. embeddings[1]
  31. ])
  32. distances, indices = search_faiss(index, queries, top_k=2)
  33. assert distances.shape == (2, 2)
  34. assert indices.shape == (2, 2)