Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions python/packages/core/agent_framework/_in_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def _numeric_vector(value: Any, *, field_name: str) -> tuple[float, ...]:
number = float(item)
if not math.isfinite(number):
raise ValueError(f"Vector field '{field_name}' must contain only finite numbers.")
vector.append(number)
vector.append(item)
if not vector:
raise ValueError(f"Vector field '{field_name}' cannot be empty.")
return tuple(vector)
Expand All @@ -115,6 +115,11 @@ def _paired_vectors(left: Vector, right: Vector) -> tuple[tuple[float, ...], tup

def _calculate_score(left: Vector, right: Vector, distance_function: DistanceFunction) -> float:
left_values, right_values = _paired_vectors(left, right)
if distance_function == "hamming":
# Compare coordinates before float conversion can round distinct large integers to the same value.
return sum(a != b for a, b in zip(left_values, right_values, strict=True)) / len(left_values)
left_values = tuple(float(value) for value in left_values)
right_values = tuple(float(value) for value in right_values)
if distance_function in ("cosine_similarity", "cosine_distance", "DEFAULT"):
left_scale = max(abs(value) for value in left_values)
right_scale = max(abs(value) for value in right_values)
Expand All @@ -140,8 +145,6 @@ def _calculate_score(left: Vector, right: Vector, distance_function: DistanceFun
score = sum((a - b) * (a - b) for a, b in zip(left_values, right_values, strict=True))
elif distance_function == "manhattan":
score = sum(abs(a - b) for a, b in zip(left_values, right_values, strict=True))
elif distance_function == "hamming":
score = sum(a != b for a, b in zip(left_values, right_values, strict=True)) / len(left_values)
else:
raise NotImplementedError(f"Distance function '{distance_function}' is not supported by InMemoryCollection.")
if not math.isfinite(score):
Expand Down
33 changes: 33 additions & 0 deletions python/packages/core/tests/core/test_in_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,39 @@ async def test_hamming_scores_and_thresholds_use_mismatch_proportions() -> None:
]


@pytest.mark.parametrize(
("vector_type", "coordinate"),
[("int64", 2**53), ("int64", -(2**53) - 1), ("uint64", 2**64 - 2)],
)
@pytest.mark.parametrize("threshold", [None, 0.0])
async def test_hamming_preserves_large_integer_coordinates(
vector_type: str, coordinate: int, threshold: float | None
) -> None:
definition = VectorStoreCollectionDefinition(
[
VectorStoreField("key", name="id"),
VectorStoreField("vector", name="vector", type_=vector_type, dimensions=2, distance_function="hamming"),
],
collection_name="integer-hamming",
)
collection: InMemoryCollection[str, dict[str, Any]] = InMemoryCollection(dict, definition=definition)
await collection.ensure_collection_exists()
await collection.upsert(
[
{"id": "different", "vector": [coordinate + 1, 0]},
{"id": "same", "vector": [coordinate, 0]},
],
generate_vectors=False,
)

results = await collection.search(vector=[coordinate, 0], score_threshold=threshold)

expected = [("same", 0.0)]
if threshold is None:
expected.append(("different", 0.5))
assert [(result["record"]["id"], result["score"]) async for result in results] == expected


@pytest.mark.parametrize("contents", ["empty", "missing_vector", "filtered_out"])
@pytest.mark.parametrize("score_threshold", [None, 0.5])
async def test_unsupported_distance_is_rejected_independently_of_records(
Expand Down
Loading