mirror of
https://github.com/hwchase17/langchain.git
synced 2025-09-14 05:56:40 +00:00
Implemented Milvus translator for self-querying (#10162)
- Implemented the MilvusTranslator for self-querying using Milvus vector store - Made unit tests to test its functionality - Documented the Milvus self-querying
This commit is contained in:
@@ -12,6 +12,7 @@ from langchain.retrievers.self_query.chroma import ChromaTranslator
|
||||
from langchain.retrievers.self_query.dashvector import DashvectorTranslator
|
||||
from langchain.retrievers.self_query.deeplake import DeepLakeTranslator
|
||||
from langchain.retrievers.self_query.elasticsearch import ElasticsearchTranslator
|
||||
from langchain.retrievers.self_query.milvus import MilvusTranslator
|
||||
from langchain.retrievers.self_query.myscale import MyScaleTranslator
|
||||
from langchain.retrievers.self_query.pinecone import PineconeTranslator
|
||||
from langchain.retrievers.self_query.qdrant import QdrantTranslator
|
||||
@@ -23,6 +24,7 @@ from langchain.vectorstores import (
|
||||
DashVector,
|
||||
DeepLake,
|
||||
ElasticsearchStore,
|
||||
Milvus,
|
||||
MyScale,
|
||||
Pinecone,
|
||||
Qdrant,
|
||||
@@ -43,6 +45,7 @@ def _get_builtin_translator(vectorstore: VectorStore) -> Visitor:
|
||||
MyScale: MyScaleTranslator,
|
||||
DeepLake: DeepLakeTranslator,
|
||||
ElasticsearchStore: ElasticsearchTranslator,
|
||||
Milvus: MilvusTranslator,
|
||||
}
|
||||
if vectorstore_cls not in BUILTIN_TRANSLATORS:
|
||||
raise ValueError(
|
||||
|
83
libs/langchain/langchain/retrievers/self_query/milvus.py
Normal file
83
libs/langchain/langchain/retrievers/self_query/milvus.py
Normal file
@@ -0,0 +1,83 @@
|
||||
"""Logic for converting internal query language to a valid Milvus query."""
|
||||
from typing import Tuple, Union
|
||||
|
||||
from langchain.chains.query_constructor.ir import (
|
||||
Comparator,
|
||||
Comparison,
|
||||
Operation,
|
||||
Operator,
|
||||
StructuredQuery,
|
||||
Visitor,
|
||||
)
|
||||
|
||||
COMPARATOR_TO_BER = {
|
||||
Comparator.EQ: "==",
|
||||
Comparator.GT: ">",
|
||||
Comparator.GTE: ">=",
|
||||
Comparator.LT: "<",
|
||||
Comparator.LTE: "<=",
|
||||
}
|
||||
|
||||
UNARY_OPERATORS = [Operator.NOT]
|
||||
|
||||
|
||||
def process_value(value: Union[int, float, str]) -> str:
|
||||
# required for comparators involving strings
|
||||
if isinstance(value, str):
|
||||
# If the value is already a string, add double quotes
|
||||
return f'"{value}"'
|
||||
else:
|
||||
# If the valueis not a string, convert it to a string without double quotes
|
||||
return str(value)
|
||||
|
||||
|
||||
class MilvusTranslator(Visitor):
|
||||
"""Translate Milvus internal query language elements to valid filters."""
|
||||
|
||||
"""Subset of allowed logical operators."""
|
||||
allowed_operators = [Operator.AND, Operator.NOT, Operator.OR]
|
||||
|
||||
"""Subset of allowed logical comparators."""
|
||||
allowed_comparators = [
|
||||
Comparator.EQ,
|
||||
Comparator.GT,
|
||||
Comparator.GTE,
|
||||
Comparator.LT,
|
||||
Comparator.LTE,
|
||||
]
|
||||
|
||||
def _format_func(self, func: Union[Operator, Comparator]) -> str:
|
||||
self._validate_func(func)
|
||||
value = func.value
|
||||
if isinstance(func, Comparator):
|
||||
value = COMPARATOR_TO_BER[func]
|
||||
return f"{value}"
|
||||
|
||||
def visit_operation(self, operation: Operation) -> str:
|
||||
if operation.operator in UNARY_OPERATORS and len(operation.arguments) == 1:
|
||||
operator = self._format_func(operation.operator)
|
||||
return operator + "(" + operation.arguments[0].accept(self) + ")"
|
||||
elif operation.operator in UNARY_OPERATORS:
|
||||
raise ValueError(
|
||||
f'"{operation.operator.value}" can have only one argument in Milvus'
|
||||
)
|
||||
else:
|
||||
args = [arg.accept(self) for arg in operation.arguments]
|
||||
operator = self._format_func(operation.operator)
|
||||
return "(" + (" " + operator + " ").join(args) + ")"
|
||||
|
||||
def visit_comparison(self, comparison: Comparison) -> str:
|
||||
comparator = self._format_func(comparison.comparator)
|
||||
processed_value = process_value(comparison.value)
|
||||
attribute = comparison.attribute
|
||||
|
||||
return "( " + attribute + " " + comparator + " " + processed_value + " )"
|
||||
|
||||
def visit_structured_query(
|
||||
self, structured_query: StructuredQuery
|
||||
) -> Tuple[str, dict]:
|
||||
if structured_query.filter is None:
|
||||
kwargs = {}
|
||||
else:
|
||||
kwargs = {"expr": structured_query.filter.accept(self)}
|
||||
return structured_query.query, kwargs
|
@@ -0,0 +1,116 @@
|
||||
from typing import Dict, Tuple
|
||||
|
||||
from langchain.chains.query_constructor.ir import (
|
||||
Comparator,
|
||||
Comparison,
|
||||
Operation,
|
||||
Operator,
|
||||
StructuredQuery,
|
||||
)
|
||||
from langchain.retrievers.self_query.milvus import MilvusTranslator
|
||||
|
||||
DEFAULT_TRANSLATOR = MilvusTranslator()
|
||||
|
||||
|
||||
def test_visit_comparison() -> None:
|
||||
comp = Comparison(comparator=Comparator.LT, attribute="foo", value=4)
|
||||
expected = "( foo < 4 )"
|
||||
actual = DEFAULT_TRANSLATOR.visit_comparison(comp)
|
||||
|
||||
assert expected == actual
|
||||
|
||||
|
||||
def test_visit_operation() -> None:
|
||||
# Non-Unary operator
|
||||
|
||||
op = Operation(
|
||||
operator=Operator.AND,
|
||||
arguments=[
|
||||
Comparison(comparator=Comparator.LT, attribute="foo", value=2),
|
||||
Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
|
||||
Comparison(comparator=Comparator.LT, attribute="abc", value="4"),
|
||||
],
|
||||
)
|
||||
|
||||
expected = '(( foo < 2 ) and ( bar == "baz" ) ' 'and ( abc < "4" ))'
|
||||
actual = DEFAULT_TRANSLATOR.visit_operation(op)
|
||||
|
||||
assert expected == actual
|
||||
|
||||
# Unary operator: normal execution
|
||||
op = Operation(
|
||||
operator=Operator.NOT,
|
||||
arguments=[
|
||||
Comparison(comparator=Comparator.LT, attribute="foo", value=2),
|
||||
],
|
||||
)
|
||||
|
||||
expected = "not(( foo < 2 ))"
|
||||
actual = DEFAULT_TRANSLATOR.visit_operation(op)
|
||||
|
||||
assert expected == actual
|
||||
|
||||
# Unary operator: error
|
||||
op = Operation(
|
||||
operator=Operator.NOT,
|
||||
arguments=[
|
||||
Comparison(comparator=Comparator.LT, attribute="foo", value=2),
|
||||
Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
|
||||
Comparison(comparator=Comparator.LT, attribute="abc", value="4"),
|
||||
],
|
||||
)
|
||||
|
||||
try:
|
||||
DEFAULT_TRANSLATOR.visit_operation(op)
|
||||
except ValueError as e:
|
||||
assert str(e) == '"not" can have only one argument in Milvus'
|
||||
else:
|
||||
assert False, "Expected exception not raised" # No exception -> test failed
|
||||
|
||||
|
||||
def test_visit_structured_query() -> None:
|
||||
query = "What is the capital of France?"
|
||||
structured_query = StructuredQuery(
|
||||
query=query,
|
||||
filter=None,
|
||||
)
|
||||
expected: Tuple[str, Dict] = (query, {})
|
||||
|
||||
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
|
||||
assert expected == actual
|
||||
|
||||
comp = Comparison(comparator=Comparator.LT, attribute="foo", value=454)
|
||||
structured_query = StructuredQuery(
|
||||
query=query,
|
||||
filter=comp,
|
||||
)
|
||||
|
||||
expected = (
|
||||
query,
|
||||
{"expr": "( foo < 454 )"},
|
||||
)
|
||||
|
||||
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
|
||||
assert expected == actual
|
||||
|
||||
op = Operation(
|
||||
operator=Operator.AND,
|
||||
arguments=[
|
||||
Comparison(comparator=Comparator.LT, attribute="foo", value=2),
|
||||
Comparison(comparator=Comparator.EQ, attribute="bar", value="baz"),
|
||||
Comparison(comparator=Comparator.LT, attribute="abc", value=50),
|
||||
],
|
||||
)
|
||||
|
||||
structured_query = StructuredQuery(
|
||||
query=query,
|
||||
filter=op,
|
||||
)
|
||||
|
||||
expected = (
|
||||
query,
|
||||
{"expr": "(( foo < 2 ) " 'and ( bar == "baz" ) ' "and ( abc < 50 ))"},
|
||||
)
|
||||
|
||||
actual = DEFAULT_TRANSLATOR.visit_structured_query(structured_query)
|
||||
assert expected == actual
|
Reference in New Issue
Block a user