Skip to main content
Integrations

LangChain

langchain-kaer connects LangChain agents and chains to Kaer 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 in sync and async code.

Package
langchain-kaer on PyPI
Scope
search
Price
Each query is billed like POST /v1/search, see Search pricing

#Before you begin

  • A key with the search scope. See Authentication.
  • Search open on your account: add a card in Billing, which comes with 1,000 free web searches, or make a first top-up of $5 or more. Until then a search returns 403 tier_required.
  • Python 3.10 or later.

#Install the package

Shell
pip install -U langchain-kaer

export KAER_API_KEY="kaer_live_..."

The package reads your key from KAER_API_KEY. You can also pass it in code: KaerSearch(kaer_api_key="...").

#Search with the 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, on the deep lane, the page's main text and text_truncated. An instant answer and any warnings come with them when the API sends them.

#Give the tool to an agent

The agent and chain examples also need LangChain and a model package, installed in their first line. Any chat model that supports tool calling works.

Python
# pip install -U langchain langchain-anthropic
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.

#Set what the model can choose

The model sets these arguments on each call. Values it sets override the defaults you gave the tool.

querystringRequired

What to search for, 1 to 512 characters.

lanestring

web, fast, deep or auto.

include_domainsstring[]

Only return results from these host names or their subdomains.

exclude_domainsstring[]

Never return results from these host names.

You fix these settings when you create the tool:

max_resultsintegerDefault 5

Results per query, 1 to 25.

lanestringDefault auto

The lane used when the model does not choose one.

allow_model_lanebooleanDefault True

Set False to always use lane, which keeps the price per query fixed.

include_domainsstring[]

Default host names to search within.

exclude_domainsstring[]

Default host names to leave out.

kaer_api_keystringDefault KAER_API_KEY

Your key. Read from the environment variable when you leave it out.

timeoutnumberDefault 60

Seconds to wait for a response.

#Choose a lane

LaneWhat it doesPer queryTimeout
webKaer's own index alone. Fastest and cheapest.$0.00056 s
fastKaer's index racing the live web.$0.00112 s
deepEvery lane, re-ranked. Results carry the page's main text, up to 4,000 characters, when the page could be read.$0.00340 s
autoKaer picks a lane for each query and bills the lane that served it.As served40 s

A search that fails or times out is not charged.

#Retrieve documents

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 served_lane and, when the result has them, title, url, snippet, source, published_date, text_truncated and text_source.

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). To answer from the documents, pipe the retriever into a prompt and a model:

Python: answer from search results
# pip install -U langchain langchain-anthropic
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 of Search, 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= to the wrapper, then hand the wrapper to the tool or retriever: KaerSearch(api_wrapper=KaerSearchAPIWrapper(client=my_client)).

#Handle errors

KaerSearchAPIWrapper checks the query, lane, domain lists and paging before it sends anything, and raises ValueError when one is out of range. An error from the API 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. When no response arrives, status_code is None, and code is timeout if the request timed out. The tool catches both errors and returns them to the model as an error ToolMessage, so an agent can recover. The retriever raises them.

StatusCodeWhat it means
401invalid_api_keyThe key is malformed, unknown, revoked or expired.
402insufficient_creditsYour balance cannot cover the call's hold. Free credit never pays for mail.
403tier_requiredYour tier does not include this service yet.
403insufficient_scopeThe key does not have the endpoint's scope.
429rate_limit_exceededToo many requests this minute for the key or the account, or too many invalid keys from your address.
429too_many_concurrent_searchesYour account already has its maximum of searches in flight: your tier's figure, or your search plan's when that is higher.
502search_failedThe search service failed. Nothing was charged.
504search_timeoutSearch ran out of time. Nothing was charged.

Every code, with its fix, is in Errors.