fix(langchain): search() crashes with TypeError when score is None (#5072)
Co-authored-by: Kartik <kartik.labhshetwar@mem0.ai>
This commit is contained in:
@@ -107,7 +107,7 @@ def score_and_rank(
|
||||
if mem_id is None:
|
||||
continue
|
||||
|
||||
semantic_score = result.get("score", 0.0)
|
||||
semantic_score = result.get("score") or 0.0
|
||||
if semantic_score < threshold:
|
||||
continue
|
||||
|
||||
|
||||
@@ -21,6 +21,16 @@ class OutputData(BaseModel):
|
||||
payload: Optional[Dict] # metadata
|
||||
|
||||
|
||||
# Methods that accept a pre-computed embedding and return (Document, float) pairs.
|
||||
# Tried in order; first match wins. Not part of the base VectorStore contract,
|
||||
# but exposed by several concrete implementations.
|
||||
_SCORED_BY_VECTOR_METHODS = [
|
||||
"similarity_search_by_vector_with_relevance_scores", # Chroma
|
||||
"similarity_search_with_score_by_vector", # FAISS, Qdrant
|
||||
"similarity_search_by_vector_with_score", # Pinecone, YDB
|
||||
]
|
||||
|
||||
|
||||
class Langchain(VectorStoreBase):
|
||||
def __init__(self, client: VectorStore, collection_name: str = "mem0"):
|
||||
self.client = client
|
||||
@@ -95,14 +105,40 @@ class Langchain(VectorStoreBase):
|
||||
"""
|
||||
Search for similar vectors in LangChain.
|
||||
"""
|
||||
# For each vector, perform a similarity search
|
||||
kwargs = {"embedding": vectors, "k": top_k}
|
||||
if filters:
|
||||
results = self.client.similarity_search_by_vector(embedding=vectors, k=top_k, filter=filters)
|
||||
else:
|
||||
results = self.client.similarity_search_by_vector(embedding=vectors, k=top_k)
|
||||
kwargs["filter"] = filters
|
||||
|
||||
final_results = self._parse_output(results)
|
||||
return final_results
|
||||
# Try methods that return (Document, float) pairs — not in the base contract
|
||||
# but available on several concrete implementations.
|
||||
for method_name in _SCORED_BY_VECTOR_METHODS:
|
||||
method = getattr(self.client, method_name, None)
|
||||
if method is None:
|
||||
continue
|
||||
try:
|
||||
results = method(**kwargs)
|
||||
return [
|
||||
OutputData(
|
||||
id=getattr(doc, "id", None),
|
||||
score=float(score),
|
||||
payload=getattr(doc, "metadata", {}),
|
||||
)
|
||||
for doc, score in results
|
||||
]
|
||||
except (NotImplementedError, TypeError):
|
||||
continue
|
||||
|
||||
# Fallback: similarity_search_by_vector returns List[Document] with no scores.
|
||||
# Assign 1.0 so score_and_rank never receives None (None < threshold crashes).
|
||||
docs = self.client.similarity_search_by_vector(**kwargs)
|
||||
return [
|
||||
OutputData(
|
||||
id=getattr(doc, "id", None),
|
||||
score=1.0,
|
||||
payload=getattr(doc, "metadata", {}),
|
||||
)
|
||||
for doc in docs
|
||||
]
|
||||
|
||||
def delete(self, vector_id):
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user