Skip to main content

Localai reranker integration

还没翻译译自英文(docs.langchain.com)本页 5 段都还没译

Info

langchain-localai is a 3rd party integration package for LocalAI. It provides a simple way to use LocalAI services in LangChain.

The source code is available on GitHub

This notebook shows how to use LocalAI Reranker API for document compression and retrieval.

Let's load the LocalAIRerank class. In order to use the LocalAIRerank class, you need to have the LocalAI service hosted somewhere and configure the reranker. See the documentation at localai.io/basics/getting_started/index.html and localai.io/features/reranker/index.html.

pip install -U langchain-localai
import os
from langchain_localai import LocalAIRerank
from langchain_core.documents import Document

# Set your LocalAI/OpenAI API key as an environment variable for security.
# For example, in your shell: export OPENAI_API_KEY="your-key-here"
reranker = LocalAIRerank(
    openai_api_key=os.environ.get("OPENAI_API_KEY"),
    model="bge-reranker-v2-m3",
    openai_api_base="http://localhost:8080",
)
reranked_docs = reranker.compress_documents(
    documents=[
        Document(page_content="Green tea is rich in antioxidants and may improve brain function."),
        Document(page_content="Coffee contains caffeine and can increase alertness."),
        Document(page_content="Black tea has a strong flavor and contains various polyphenols."),
    ],
    query="What are the health benefits of green tea?"
)