Skip to main content

langchain-relevan

A LangChain retriever for Relevan search, with Relevan's feedback loop built in.

Relevan is managed search that learns from what happens after a search. This package lets a LangChain app or agent search a Relevan index, and then report back which results were useful, so that signal reaches Relevan without any extra plumbing.

Community integration. Not an official Relevan package.

Installation

pip install -U langchain-relevan

Setup

Create an API key in the Relevan console and set it as an environment variable:

export RELEVAN_API_KEY="..."          # macOS / Linux
$env:RELEVAN_API_KEY = "..."          # Windows PowerShell

You can also pass api_key= to the retriever.

Instantiation

from langchain_relevan import RelevanRetriever

retriever = RelevanRetriever(index="products", k=5)
Parameter Default What it does
index required Name of the Relevan index to search
k 4 Number of results, 1 to 100
filters None Filters, ANDed together (see below)
org_id looked up Organization id or slug. Looked up from your key once and cached when not given
content_fields all fields Fields to put in page_content, in order. By default the index's title field comes first, then the rest
api_key RELEVAN_API_KEY Relevan API key
client / async_client built on first use Pass your own relevan.Client / relevan.AsyncClient if you already have one

Usage

docs = retriever.invoke("turquoise velvet chair")

for doc in docs:
    print(doc.metadata["title"])
    print(doc.metadata["explanation"])  # why Relevan matched this result

Relevan returns each hit's full document, so there is no second fetch. page_content is the document's fields as field: value lines, title first.

Each Document also carries this metadata:

Key Meaning
id Document id in the index
position Rank in this response, starting at 0
score Relevan's score
explanation Human readable reason the document matched
matched_fields, matched_terms Which fields and words contributed
query_id, session_id Identify this search, used for feedback
index, org_id Where the document came from
title Value of the index's title field
fields The raw document

Async works the same way:

docs = await retriever.ainvoke("turquoise velvet chair")

Filters

Pass plain dicts. Filters work on fields your index mapping marks as filterable. To see which fields those are, and their most common values, call client.search.filter_values(org_id, index) on a relevan.Client.

retriever = RelevanRetriever(
    index="products",
    filters=[
        {"field": "category", "value": "Accent Chairs"},       # exact match
        {"field": "color", "values": ["blue", "turquoise"]},  # any of
        {"field": "price", "gte": 100, "lte": 400},           # range
    ],
)

Use within a chain

RelevanRetriever is a normal LangChain retriever, so it composes with |:

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

prompt = ChatPromptTemplate.from_template(
    "Recommend one product for: {question}\n\nProducts:\n{context}"
)

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

chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm  # any LangChain chat model
    | StrOutputParser()
)

chain.invoke("a turquoise velvet chair for a small living room")

Feedback

This is the part that is specific to Relevan. Every document already carries the ids Relevan needs, so reporting what happened is one call:

docs = retriever.invoke("turquoise velvet chair")

retriever.send_click(docs[1])                     # a user opened this result
retriever.send_judgment(docs[0], 0)               # grade one result: 0, 1 or 2
retriever.send_conversion(docs[1], "purchase")    # a closing event
retriever.send_search_judgment(docs, [0, 2, 2])   # grade the whole search

Grades are 0 (not useful), 1 (a little useful), 2 (very useful). send_judgment and send_search_judgment also take an optional description (up to 2000 characters) explaining what was wanted.

Every method has an async twin: asend_click, asend_judgment, asend_conversion, asend_search_judgment.

Things to know:

  • Relevan accepts one send_search_judgment per search. A second one for the same query_id is rejected.
  • Pass source="eval" for test suites and benchmarks, so Relevan can tell that traffic apart from real users. The default is production.
  • Feedback goes to Relevan's beta endpoint, so the Relevan SDK emits a RelevanBetaWarning on each call. To silence it:
import warnings
from relevan import RelevanBetaWarning

warnings.filterwarnings("ignore", category=RelevanBetaWarning)

Closing connections

The retriever opens an HTTP connection on first use. Use it as a context manager, or call close(), to close it:

with RelevanRetriever(index="products") as retriever:
    docs = retriever.invoke("turquoise velvet chair")

async with RelevanRetriever(index="products") as retriever:
    docs = await retriever.ainvoke("turquoise velvet chair")

Only clients the retriever built are closed. A client you passed in stays yours to close.

Example

examples/wands_feedback_loop.py runs product queries against an index built from the WANDS dataset, prints each result with Relevan's explanation, grades the results with a simple rule and sends the grades back as feedback.

python examples/wands_feedback_loop.py --dry-run   # search only
python examples/wands_feedback_loop.py             # search and send feedback

Development

pip install -e ".[test]"
pytest                    # unit tests, no network
pytest -m integration     # live tests, needs RELEVAN_API_KEY

Live tests use the index in RELEVAN_TEST_INDEX (default wands-bench) and send feedback with source="eval". The filter test needs an index with at least one filterable field and skips otherwise.

Tested against relevan 0.2.1 on Python 3.11 (Windows) and 3.13 (Linux).

License

Apache-2.0

Metadata

Release files for langchain-relevan 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-relevan 0.1.0
File Size Uploaded Provenance Actions
langchain_relevan-0.1.0.tar.gz 23.4 kB Without provenance Details for langchain_relevan-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for langchain-relevan 0.1.0
File Interpreter ABI Platform Actions
langchain_relevan-0.1.0-py3-none-any.whl Python 3 none any Details for langchain_relevan-0.1.0-py3-none-any.whl

Total release size: 37.3 kB

Release files / langchain_relevan-0.1.0.tar.gz

Download URL langchain_relevan-0.1.0.tar.gz
Size 23.4 kB
Tags Source
SHA-256 checksum
How to use checksums
aac1b98752ed80347996d04aacff33860069ad18121b1dd02539afdde8d7cef5
BLAKE2b-256 checksum
How to use checksums
a8d5ecedb60184573579fb71dc830dcfbbff36d98084c0c8d500cb9878e62e4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / langchain_relevan-0.1.0-py3-none-any.whl

Download URL langchain_relevan-0.1.0-py3-none-any.whl
Size 13.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
866d32f1acb46d7c2aa02aff442c0063d3972f925a9773a8e10db32d6b77de8f
BLAKE2b-256 checksum
How to use checksums
1e5328a94f9029f15d9cb543bf89f19d89dabff823711f0da4662997242ef553
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for langchain-relevan 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page