Metadata-Version: 2.5
Name: langchain-kaer
Version: 0.1.0
Summary: LangChain tool and retriever for the Kaer Search API.
Project-URL: Homepage, https://api.kaer.ai
Project-URL: Documentation, https://github.com/Kaer-AI/langchain-kaer#readme
Project-URL: API reference, https://api.kaer.ai/docs/search
Project-URL: Source, https://github.com/Kaer-AI/langchain-kaer
Project-URL: Issues, https://github.com/Kaer-AI/langchain-kaer/issues
Author-email: Kaer Labs Ltd <support@kaer.ai>
License-Expression: MIT
License-File: LICENSE
Keywords: agents,kaer,langchain,retriever,search,tool,web search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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 :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: <4.0,>=3.10
Requires-Dist: httpx<1.0.0,>=0.25.0
Requires-Dist: langchain-core<2.0.0,>=0.3.15
Requires-Dist: pydantic<3.0.0,>=2.7.4
Description-Content-Type: text/markdown

# langchain-kaer

`langchain-kaer` connects LangChain agents and chains to the [Kaer Search API](https://api.kaer.ai/docs/search). It provides `KaerSearch`, a tool a model can call to search the web, and `KaerSearchRetriever`, which returns search results as LangChain documents. Both send one `POST /v1/search` request per query and work with sync and async code.

## Install

```bash
pip install -U langchain-kaer
```

## Get an API key

1. Sign up at [api.kaer.ai](https://api.kaer.ai).
2. Create a key in the dashboard and tick the `search` scope.
3. Add credit. Search opens after your account's first top-up; adding a card in Billing first gives you free web searches. See [Search pricing](https://api.kaer.ai/docs/search-pricing) for the price per query on each lane.

```bash
export KAER_API_KEY="kaer_live_..."
```

You can also pass the key in code: `KaerSearch(kaer_api_key="...")`.

## Use the search tool

```python
from langchain_kaer import KaerSearch

tool = KaerSearch(max_results=5)

tool.invoke({"query": "latest results on perovskite solar cells"})
```

The tool returns the query, the lane that served it and a list of results. Each result has a `title`, `url` and `snippet`, plus `published_date` when it is known and the page's main `text` on the `deep` lane.

### Give the tool to an agent

The agent and chain examples below also need LangChain and a model package:

```bash
pip install -U langchain langchain-anthropic
```

```python
from langchain.agents import create_agent
from langchain_kaer import KaerSearch

agent = create_agent(
    model="anthropic:claude-sonnet-5-5",
    tools=[KaerSearch(max_results=5)],
)

result = agent.invoke(
    {
        "messages": [
            {"role": "user", "content": "What changed in the EU AI Act this month?"}
        ]
    }
)
print(result["messages"][-1].content)
```

When a model calls the tool, the `ToolMessage` content holds compact results for the model to read. Its `artifact` holds the full API response, including `kaer.request_id` and `kaer.cost_usd`, so your code can log what each search cost.

### What the model can set

| Argument | Type | Description |
| --- | --- | --- |
| `query` | string | What to search for, 1 to 512 characters. Required. |
| `lane` | string | `web`, `fast`, `deep` or `auto`. Optional. |
| `include_domains` | list of strings | Only return results from these host names or their subdomains. Optional. |
| `exclude_domains` | list of strings | Never return results from these host names. Optional. |

### Settings you fix when you create the tool

| Setting | Default | Description |
| --- | --- | --- |
| `max_results` | `5` | Results per query, 1 to 25. |
| `lane` | `"auto"` | The lane used when the model does not choose one. |
| `allow_model_lane` | `True` | Set `False` to always use `lane`, which keeps the price per query fixed. |
| `include_domains` | `None` | Default host names to search within. |
| `exclude_domains` | `None` | Default host names to leave out. |
| `kaer_api_key` | `KAER_API_KEY` | Your key. |
| `timeout` | `60` | Seconds to wait for a response. |

## Choose a lane

| Lane | What it does | Timeout |
| --- | --- | --- |
| `web` | Searches Kaer's own index. Fastest and cheapest. | 6 s |
| `fast` | Races Kaer's index against the live web. | 12 s |
| `deep` | Runs every lane and re-ranks the results. Each result carries the page's main text, up to 4,000 characters, when the page could be read. | 40 s |
| `auto` | Kaer picks a lane for each query. You pay for the lane that served it. | 40 s |

A search that fails or times out is not charged.

## Use the retriever

`KaerSearchRetriever` returns a list of `Document` objects. On the `deep` lane, `page_content` is the page's main text; on the other lanes it is the result snippet. `metadata` holds `title`, `url`, `snippet`, `source`, `published_date` and `served_lane`.

```python
from langchain_kaer import KaerSearchRetriever

retriever = KaerSearchRetriever(k=5, lane="deep")

docs = retriever.invoke("How do heat pumps work in cold climates?")
for doc in docs:
    print(doc.metadata["title"], doc.metadata["url"])
```

Pass `k` at call time to change how many documents come back: `retriever.invoke(query, k=3)`.

### Use the retriever in a chain

```python
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain.chat_models import init_chat_model
from langchain_kaer import KaerSearchRetriever

retriever = KaerSearchRetriever(k=5, lane="deep")
llm = init_chat_model("anthropic:claude-sonnet-5-5")

prompt = ChatPromptTemplate.from_template(
    "Answer from the sources and cite their URLs.\n\n"
    "Sources:\n{context}\n\nQuestion: {question}"
)


def format_docs(docs):
    return "\n\n".join(f"{d.metadata['url']}\n{d.page_content}" for d in docs)


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

print(chain.invoke("How do heat pumps work in cold climates?"))
```

## Call the API directly

`KaerSearchAPIWrapper` sends the request and returns the API's JSON response. It accepts every request field the API documents, including `offset` and `page` for paging on the `web` and `fast` lanes, and `fields` to choose which result keys come back.

```python
from langchain_kaer import KaerSearchAPIWrapper

search = KaerSearchAPIWrapper()
data = search.search(
    "solar panel efficiency records", lane="fast", num_results=10, offset=10
)
print(data["served_lane"], data["kaer"]["cost_usd"])
```

Use `await search.asearch(...)` in async code. To send requests through your own `httpx` client, for a proxy or retries, pass `client=` or `async_client=`.

## Handle errors

`KaerSearchAPIWrapper` raises `KaerAPIError`, with the HTTP `status_code`, the API's error `code`, its `message`, the `request_id` and `retry_after` when the API sent one. The tool catches these errors and returns them to the model as an error `ToolMessage`, so an agent can recover. The retriever raises them.

| Status | Code | What to do |
| --- | --- | --- |
| 401 | `invalid_api_key` | Check the key, or create a new one. |
| 402 | `insufficient_credits` | Add credit. |
| 403 | `tier_required` | Search opens after your account's first top-up. |
| 403 | `insufficient_scope` | Add the `search` scope to the key. |
| 429 | `rate_limit_exceeded` | Wait for `retry_after` seconds, then retry. |
| 504 | `search_timeout` | Retry, or use a faster lane. |

The full list is in the [error reference](https://api.kaer.ai/docs/errors).

## Development

```bash
make test               # unit tests, no network
make integration_tests  # live tests, needs KAER_API_KEY
make lint
```

Set `KAER_BASE_URL` to send requests to another base URL, for example a proxy in front of the API.

## Links

- [Kaer Search API reference](https://api.kaer.ai/docs/search)
- [Search pricing](https://api.kaer.ai/docs/search-pricing)
- [Kaer API dashboard](https://api.kaer.ai)
- [Issues](https://github.com/Kaer-AI/langchain-kaer/issues)

## Licence

MIT. See [LICENSE](LICENSE).
