@@ -37,6 +37,26 @@ def search_one(cls, vector, meta_conditions, top) -> List[Tuple[int, float]]:
37
37
if "hnsw_ef" in cls .search_params :
38
38
cls .cur .execute (f"SET hnsw.ef_search = { cls .search_params ['hnsw_ef' ]} " )
39
39
40
+ # Ensure vector is in the correct format for pgvector
41
+ try :
42
+ if isinstance (vector , bytes ):
43
+ # If vector is bytes, it might be serialized - try to convert
44
+ # First try to interpret as float32 bytes
45
+ try :
46
+ import struct
47
+ num_floats = len (vector ) // 4 # 4 bytes per float32
48
+ vector_array = np .array (struct .unpack (f'{ num_floats } f' , vector ), dtype = np .float32 )
49
+ except struct .error :
50
+ # If that fails, try to decode as numpy array
51
+ vector_array = np .frombuffer (vector , dtype = np .float32 )
52
+ elif isinstance (vector , np .ndarray ):
53
+ vector_array = vector .astype (np .float32 )
54
+ else :
55
+ # Convert list to numpy array
56
+ vector_array = np .array (vector , dtype = np .float32 )
57
+ except Exception as e :
58
+ raise ValueError (f"Failed to convert vector to proper format. Vector type: { type (vector )} , Error: { e } " )
59
+
40
60
if cls .distance == Distance .COSINE :
41
61
query = f"SELECT id, embedding <=> %s AS _score FROM items ORDER BY _score LIMIT { top } ;"
42
62
elif cls .distance == Distance .L2 :
@@ -46,7 +66,7 @@ def search_one(cls, vector, meta_conditions, top) -> List[Tuple[int, float]]:
46
66
47
67
cls .cur .execute (
48
68
query ,
49
- (np . array ( vector ) ,),
69
+ (vector_array ,),
50
70
)
51
71
return cls .cur .fetchall ()
52
72
0 commit comments