Metadata-Version: 2.5
Name: langchain-relevan
Version: 0.1.0
Summary: LangChain retriever for Relevan search, with feedback built in.
Project-URL: Repository, https://github.com/OsasDTEch/langchain-relevan
Author: Wisdom Omons
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: langchain,rag,relevan,retriever,search
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Requires-Dist: langchain-core<2,>=0.3
Requires-Dist: relevan<0.3,>=0.2.1
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
Requires-Dist: pytest>=8.3; extra == 'test'
Description-Content-Type: text/markdown

# langchain-relevan

A LangChain retriever for [Relevan](https://relevan.dev) 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

```bash
pip install -U langchain-relevan
```

## Setup

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

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

You can also pass `api_key=` to the retriever.

## Instantiation

```python
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

```python
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:

```python
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`.

```python
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 `|`:

```python
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:

```python
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:

```python
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:

```python
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`](examples/wands_feedback_loop.py) runs product queries against an index built from the [WANDS](https://github.com/wayfair/WANDS) dataset, prints each result with Relevan's explanation, grades the results with a simple rule and sends the grades back as feedback.

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

## Development

```bash
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
