milvus-logo
LFAI
Home
  • Integrações

Milvus Hybrid Search Retriever

Visão geral

O Milvus é uma base de dados vetorial de código aberto criada para potenciar a incorporação de aplicações de pesquisa por semelhança e de IA. O Milvus torna a pesquisa de dados não estruturados mais acessível e proporciona uma experiência de utilizador consistente, independentemente do ambiente de implementação.

Isto irá ajudá-lo a começar a utilizar o recuperador Milvus Hybrid Search, que combina os pontos fortes da pesquisa vetorial densa e esparsa. Para obter documentação detalhada de todos os recursos e configurações do MilvusCollectionHybridSearchRetriever, acesse a referência da API.

Consulte também a documentação da Pesquisa multi-vetorial Milvus.

Detalhes da integração

RecuperadorAuto-hospedagemOferta na nuvemPacote
MilvusCollectionHybridSearchRetrieverlangchain_milvus

Configuração

Se quiser obter rastreio automatizado de consultas individuais, também pode definir a sua chave da API LangSmith descomentando abaixo:

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

Instalação

Este retriever reside no pacote langchain-milvus. Este guia requer as seguintes dependências:

%pip install --upgrade --quiet pymilvus[model] langchain-milvus langchain-openai
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_milvus.retrievers import MilvusCollectionHybridSearchRetriever
from langchain_milvus.utils.sparse import BM25SparseEmbedding
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from pymilvus import (
    Collection,
    CollectionSchema,
    DataType,
    FieldSchema,
    WeightedRanker,
    connections,
)

Iniciar o serviço Milvus

Consulte a documentação do Milvus para iniciar o serviço Milvus.

Depois de iniciar o milvus, é necessário especificar o URI de conexão do milvus.

CONNECTION_URI = "http://localhost:19530"

Preparar a chave da API do OpenAI

Consulte a documentação do OpenAI para obter a chave da API do OpenAI e defina-a como uma variável de ambiente.

export OPENAI_API_KEY=<your_api_key>

Preparar funções de incorporação densas e esparsas

Vamos ficcionar 10 descrições falsas de romances. Na produção real, pode tratar-se de uma grande quantidade de dados de texto.

texts = [
    "In 'The Whispering Walls' by Ava Moreno, a young journalist named Sophia uncovers a decades-old conspiracy hidden within the crumbling walls of an ancient mansion, where the whispers of the past threaten to destroy her own sanity.",
    "In 'The Last Refuge' by Ethan Blackwood, a group of survivors must band together to escape a post-apocalyptic wasteland, where the last remnants of humanity cling to life in a desperate bid for survival.",
    "In 'The Memory Thief' by Lila Rose, a charismatic thief with the ability to steal and manipulate memories is hired by a mysterious client to pull off a daring heist, but soon finds themselves trapped in a web of deceit and betrayal.",
    "In 'The City of Echoes' by Julian Saint Clair, a brilliant detective must navigate a labyrinthine metropolis where time is currency, and the rich can live forever, but at a terrible cost to the poor.",
    "In 'The Starlight Serenade' by Ruby Flynn, a shy astronomer discovers a mysterious melody emanating from a distant star, which leads her on a journey to uncover the secrets of the universe and her own heart.",
    "In 'The Shadow Weaver' by Piper Redding, a young orphan discovers she has the ability to weave powerful illusions, but soon finds herself at the center of a deadly game of cat and mouse between rival factions vying for control of the mystical arts.",
    "In 'The Lost Expedition' by Caspian Grey, a team of explorers ventures into the heart of the Amazon rainforest in search of a lost city, but soon finds themselves hunted by a ruthless treasure hunter and the treacherous jungle itself.",
    "In 'The Clockwork Kingdom' by Augusta Wynter, a brilliant inventor discovers a hidden world of clockwork machines and ancient magic, where a rebellion is brewing against the tyrannical ruler of the land.",
    "In 'The Phantom Pilgrim' by Rowan Welles, a charismatic smuggler is hired by a mysterious organization to transport a valuable artifact across a war-torn continent, but soon finds themselves pursued by deadly assassins and rival factions.",
    "In 'The Dreamwalker's Journey' by Lyra Snow, a young dreamwalker discovers she has the ability to enter people's dreams, but soon finds herself trapped in a surreal world of nightmares and illusions, where the boundaries between reality and fantasy blur.",
]

Utilizaremos o OpenAI Embedding para gerar vectores densos e o algoritmo BM25 para gerar vectores esparsos.

Inicializar a função de incorporação densa e obter a dimensão

dense_embedding_func = OpenAIEmbeddings()
dense_dim = len(dense_embedding_func.embed_query(texts[1]))
dense_dim
1536

Inicializar a função de incorporação esparsa.

Note que o resultado da incorporação esparsa é um conjunto de vectores esparsos, que representam o índice e o peso das palavras-chave do texto de entrada.

sparse_embedding_func = BM25SparseEmbedding(corpus=texts)
sparse_embedding_func.embed_query(texts[1])
{0: 0.4270424944042204,
 21: 1.845826690498331,
 22: 1.845826690498331,
 23: 1.845826690498331,
 24: 1.845826690498331,
 25: 1.845826690498331,
 26: 1.845826690498331,
 27: 1.2237754316221157,
 28: 1.845826690498331,
 29: 1.845826690498331,
 30: 1.845826690498331,
 31: 1.845826690498331,
 32: 1.845826690498331,
 33: 1.845826690498331,
 34: 1.845826690498331,
 35: 1.845826690498331,
 36: 1.845826690498331,
 37: 1.845826690498331,
 38: 1.845826690498331,
 39: 1.845826690498331}

Criar a coleção Milvus e carregar dados

Inicializar o URI de ligação e estabelecer a ligação

connections.connect(uri=CONNECTION_URI)

Definir os nomes dos campos e os respectivos tipos de dados

pk_field = "doc_id"
dense_field = "dense_vector"
sparse_field = "sparse_vector"
text_field = "text"
fields = [
    FieldSchema(
        name=pk_field,
        dtype=DataType.VARCHAR,
        is_primary=True,
        auto_id=True,
        max_length=100,
    ),
    FieldSchema(name=dense_field, dtype=DataType.FLOAT_VECTOR, dim=dense_dim),
    FieldSchema(name=sparse_field, dtype=DataType.SPARSE_FLOAT_VECTOR),
    FieldSchema(name=text_field, dtype=DataType.VARCHAR, max_length=65_535),
]

Criar uma coleção com o esquema definido

schema = CollectionSchema(fields=fields, enable_dynamic_field=False)
collection = Collection(
    name="IntroductionToTheNovels", schema=schema, consistency_level="Strong"
)

Definir índices para vectores densos e esparsos

dense_index = {"index_type": "FLAT", "metric_type": "IP"}
collection.create_index("dense_vector", dense_index)
sparse_index = {"index_type": "SPARSE_INVERTED_INDEX", "metric_type": "IP"}
collection.create_index("sparse_vector", sparse_index)
collection.flush()

Inserir entidades na coleção e carregar a coleção

entities = []
for text in texts:
    entity = {
        dense_field: dense_embedding_func.embed_documents([text])[0],
        sparse_field: sparse_embedding_func.embed_documents([text])[0],
        text_field: text,
    }
    entities.append(entity)
collection.insert(entities)
collection.load()

Instanciação

Agora podemos instanciar o nosso recuperador, definindo parâmetros de pesquisa para campos esparsos e densos:

sparse_search_params = {"metric_type": "IP"}
dense_search_params = {"metric_type": "IP", "params": {}}
retriever = MilvusCollectionHybridSearchRetriever(
    collection=collection,
    rerank=WeightedRanker(0.5, 0.5),
    anns_fields=[dense_field, sparse_field],
    field_embeddings=[dense_embedding_func, sparse_embedding_func],
    field_search_params=[dense_search_params, sparse_search_params],
    top_k=3,
    text_field=text_field,
)

Nos parâmetros de entrada deste recuperador, usamos uma incorporação densa e uma incorporação esparsa para efetuar uma pesquisa híbrida nos dois campos desta coleção, e usamos o WeightedRanker para a classificação. Finalmente, serão devolvidos 3 documentos top-K.

Utilização

retriever.invoke("What are the story about ventures?")
[Document(page_content="In 'The Lost Expedition' by Caspian Grey, a team of explorers ventures into the heart of the Amazon rainforest in search of a lost city, but soon finds themselves hunted by a ruthless treasure hunter and the treacherous jungle itself.", metadata={'doc_id': '449281835035545843'}),
 Document(page_content="In 'The Phantom Pilgrim' by Rowan Welles, a charismatic smuggler is hired by a mysterious organization to transport a valuable artifact across a war-torn continent, but soon finds themselves pursued by deadly assassins and rival factions.", metadata={'doc_id': '449281835035545845'}),
 Document(page_content="In 'The Dreamwalker's Journey' by Lyra Snow, a young dreamwalker discovers she has the ability to enter people's dreams, but soon finds herself trapped in a surreal world of nightmares and illusions, where the boundaries between reality and fantasy blur.", metadata={'doc_id': '449281835035545846'})]

Utilização numa cadeia

Inicializar o ChatOpenAI e definir um modelo de prompt

llm = ChatOpenAI()

PROMPT_TEMPLATE = """
Human: You are an AI assistant, and provides answers to questions by using fact based and statistical information when possible.
Use the following pieces of information to provide a concise answer to the question enclosed in <question> tags.

<context>
{context}
</context>

<question>
{question}
</question>

Assistant:"""

prompt = PromptTemplate(
    template=PROMPT_TEMPLATE, input_variables=["context", "question"]
)

Definir uma função para formatar documentos

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

Definir uma cadeia usando o recuperador e outros componentes

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

Executar uma consulta usando a cadeia definida

rag_chain.invoke("What novels has Lila written and what are their contents?")
"Lila Rose has written 'The Memory Thief,' which follows a charismatic thief with the ability to steal and manipulate memories as they navigate a daring heist and a web of deceit and betrayal."

Soltar a coleção

collection.drop()

Referência da API

Para obter documentação pormenorizada de todas as caraterísticas e configurações de MilvusCollectionHybridSearchRetriever, consulte a referência da API.

Traduzido porDeepLogo

Try Zilliz Cloud for Free

Zilliz Cloud is hassle-free, powered by Milvus and 10x faster.

Get Started
Feedback

Esta página foi útil?