Document compressor that uses watsonx Rerank API.
To use, you should have langchain_ibm python package installed,
and the environment variable WATSONX_API_KEY set with your API key, or pass
it as a named parameter api_key to the constructor.
pip install -U langchain-ibm
# or using uv
uv add langchain-ibm
export WATSONX_API_KEY="your-api-key"
apikey and WATSONX_APIKEY are deprecated and will be removed in
version 2.0.0. Use api_key and WATSONX_API_KEY instead.
from langchain_ibm import WatsonxRerank
from ibm_watsonx_ai.foundation_models.schema import RerankParameters
parameters = RerankParameters(truncate_input_tokens=20)
ranker = WatsonxRerank(
model_id="cross-encoder/ms-marco-minilm-l-12-v2",
url="https://us-south.ml.cloud.ibm.com",
project_id="*****",
params=parameters,
# api_key="*****"
)query = "red cat chasing a laser pointer"
documents = [
"A red cat darts across the living room, pouncing on a red laser dot.",
"Two dogs play fetch in the park with a tennis ball.",
"The tabby cat naps on a sunny windowsill all afternoon.",
"A recipe for tuna casserole with crispy breadcrumbs.",
]
ranker.rerank(documents=documents, query=query)
[
{"index": 0, "relevance_score": 0.8719543218612671},
{"index": 2, "relevance_score": 0.6520894169807434},
{"index": 1, "relevance_score": 0.6270776391029358},
{"index": 3, "relevance_score": 0.4607713520526886},
]Type of model to use.
ID of the Watson Studio project.
ID of the Watson Studio space.
URL to the Watson Machine Learning or CPD instance.
API key to the Watson Machine Learning or CPD instance.
Token to the CPD instance.
Password to the CPD instance.
Username to the CPD instance.
Instance_id of the CPD instance.
Version of the CPD instance.
Model parameters to use during request generation.
You can pass one of following as verify:
Model ID validation.
Whether to stream the results or not.
Mapping of secret environment variables.
Validate that credentials and python package exists in environment.
Rerank documents.
Compress documents using watsonx's rerank API.