# LangChain

> Add live flight, hotel, and rental car search to a LangChain agent: seven tools for Python (langchain-ktemia) and JavaScript (@ktemia/langchain) across 100+ providers.

Canonical: https://www.ktemia.com/docs/langchain/

[`langchain-ktemia`](https://pypi.org/project/langchain-ktemia/) gives an agent built with [LangChain](https://docs.langchain.com/) live travel prices: flight search, hotel search, and car rental search across 100+ providers. The model looks up the place, runs the search, and answers from real prices with each seller's booking link.

Ktemia compares prices; it does not book. The traveller books on the seller's site.

For JavaScript and TypeScript, the same tools are [`@ktemia/langchain`](https://www.npmjs.com/package/@ktemia/langchain) on npm; see [LangChain.js](#langchainjs) below.

Source: [Ktemiaa/ktemia-agent-toolkit](https://github.com/Ktemiaa/ktemia-agent-toolkit) on GitHub, MIT licensed.

## Install

```bash
pip install langchain-ktemia
```

The quick start below also uses `langchain` for `create_agent` and a model package, for example `pip install langchain langchain-openai`.

Create an API key at [app.ktemia.com/api-keys](https://app.ktemia.com/api-keys). It is free, needs no card, and the Free plan includes 100 requests a month. Put it in your environment:

```bash
export KTEMIA_API_KEY=your-key
```

## Quick start

```python
from langchain.agents import create_agent
from langchain_ktemia import KtemiaToolkit

agent = create_agent("openai:gpt-5-mini", tools=KtemiaToolkit().get_tools())

result = agent.invoke(
    {"messages": [("user", "What is the cheapest flight from Los Angeles to London on 2027-03-14?")]}
)
print(result["messages"][-1].content)
```

A typical run takes three steps. The model calls `ktemia_lookup` to resolve "London" to `LON`, calls `ktemia_search_flights`, then writes the answer from the fares it got back.

Any chat model with tool calling works. Pass a model string such as `"anthropic:claude-sonnet-5-5"`, or a chat model object from `langchain-openai`, `langchain-anthropic`, or `langchain-google-genai`.

## Tools

`KtemiaToolkit().get_tools()` returns all seven tools, sharing one client. The `name` is what the model sees.

| Tool | Class | Use it for | Cost |
| ---- | ----- | ---------- | ---- |
| `ktemia_lookup` | `KtemiaLookup` | Airport and city codes, airline codes, hotel and car location ids | 1 request |
| `ktemia_search_flights` | `KtemiaSearchFlights` | One-way, round trip, and multi-city fares | 2 requests, then 1 per page |
| `ktemia_search_hotels` | `KtemiaSearchHotels` | Stays, with stars, rating, price, and amenity filters | 2 requests, then 1 per page |
| `ktemia_search_cars` | `KtemiaSearchCars` | Rentals at a city or airport, with one-way drop-off | 2 requests, then 1 per page |
| `ktemia_get_details` | `KtemiaGetDetails` | Every price and booking link for one chosen result | 1 request |
| `ktemia_get_hotel_reviews` | `KtemiaHotelReviews` | Guest reviews, by traveller type, month, or phrase | 1 request |
| `ktemia_key_status` | `KtemiaKeyStatus` | Plan and requests left this month | Free |

The tool descriptions are the same ones the [Ktemia MCP server](https://www.ktemia.com/docs/mcp/) and the [Vercel AI SDK tools](https://www.ktemia.com/docs/vercel-ai-sdk/) use. They tell the model to resolve codes before searching, to ask for missing dates instead of guessing, and how to read the next page.

To give the model fewer tools, pick the classes you need:

```python
from langchain_ktemia import KtemiaHotelReviews, KtemiaLookup, KtemiaSearchHotels

tools = [KtemiaLookup(), KtemiaSearchHotels(), KtemiaHotelReviews()]
```

Keep all three together when you narrow the set like this. The descriptions refer to each other by name, for example "use ktemia_lookup with kind='hotelLocation' first".

A tool also works on its own, outside an agent:

```python
from langchain_ktemia import KtemiaLookup

print(KtemiaLookup().invoke({"kind": "airport", "query": "London"}))
```

## A hotel agent

A system prompt keeps the agent on task. Put today's date in it: models do not know it, and a search needs a future date.

```python
from datetime import date

from langchain.agents import create_agent
from langchain_ktemia import KtemiaHotelReviews, KtemiaLookup, KtemiaSearchHotels

agent = create_agent(
    "openai:gpt-5-mini",
    tools=[KtemiaLookup(), KtemiaSearchHotels(), KtemiaHotelReviews()],
    system_prompt=(
        f"Today is {date.today()}. You compare hotels. Resolve the city with ktemia_lookup "
        "(kind hotelLocation), search, then read reviews for the top two before recommending one. "
        "Ask for missing dates instead of guessing."
    ),
)

result = agent.invoke(
    {"messages": [("user", "A quiet 4-star hotel in Lisbon, April 10 to 13, for two adults. Which one?")]}
)
```

## Async

Every tool implements `ainvoke`, so the same tools run in async agents and LangGraph graphs without blocking:

```python
result = await agent.ainvoke({"messages": [("user", "Rental cars at Lisbon airport, May 2 to 5")]})
```

## Options

The toolkit and every tool take the same options:

```python
from ktemia import AsyncKtemia, Ktemia
from langchain_ktemia import KtemiaSearchFlights, KtemiaToolkit

KtemiaToolkit(api_key="...")  # default: KTEMIA_API_KEY

# Share configured clients with the rest of your app
client = Ktemia(timeout=60.0, max_retries=2)
toolkit = KtemiaToolkit(client=client, async_client=AsyncKtemia())
flights = KtemiaSearchFlights(client=client)
```

`api_key` is stored as a `SecretStr` and left out of the tool's serialized fields. Building the tools never fails, even without a key, so creating them at import time is safe. A missing key shows up on the first call, as an error the model can read.

## Errors the model can act on

When Ktemia refuses a call, the tool returns the reason to the model as JSON instead of raising, so the agent can recover:

```json
{ "error": { "code": "INVALID_INPUT", "param": "departureDate", "retryable": false,
  "message": "departureDate 2025-03-14 is in the past. Ask the user for a future date. Nothing was sent to Ktemia, so no quota was used." } }
```

| Case | What happens |
| ---- | ------------ |
| Past date, city name in a code field, 40-night stay, return before departure | Rejected before sending. No quota spent. |
| `RATE_LIMIT_EXCEEDED` | Retried automatically after `Retry-After`, up to `max_retries`. |
| `QUOTA_EXCEEDED` | Never retried. The month's allowance is gone; `ktemia_key_status` shows the reset date. |
| No results | An empty page with a `pagingHint` to try other dates, a nearby airport, or fewer filters. |

Arguments outside the API's limits, such as `maxStops` above 2 or more than 16 hotel guests, fail LangChain's schema check before the tool runs. Errors that are not Ktemia's, such as a bug in your code, are still raised.

## Paging and details

A search returns the first page and a `nextToken`. The model reads the next page by calling the same tool with only `nextToken`; each result carries a `pagingHint` that says so. Each page also carries its own `token`; `ktemia_get_details` takes that token and a result `id` and returns every price and booking link for that result. Tokens expire one hour after the search starts. See [pagination](https://www.ktemia.com/docs/api/#pagination).

## Without LangChain

The client underneath is [`ktemia`](https://pypi.org/project/ktemia/) on PyPI, with sync and async versions. It works in any Python project:

```python
from ktemia import Ktemia

kt = Ktemia()  # reads KTEMIA_API_KEY
page = kt.flights.search(origin="LAX", destination="LON", departureDate="2027-03-14")
details = kt.flights.details(page["token"], page["flights"][0]["id"])
```

Field names are the API's own (`departureDate`, `pickupLocation`). A failed call raises `KtemiaError` with the API's `code`, `status`, `param`, and `retryable`.

## LangChain.js

The same seven tools for JavaScript and TypeScript are [`@ktemia/langchain`](https://www.npmjs.com/package/@ktemia/langchain) on npm. It needs Node 20+, `@langchain/core` 1.x, and zod 3.25 or 4:

```bash
npm install @ktemia/langchain @langchain/core zod
```

```ts
import { createAgent } from "langchain";
import { ktemiaTools } from "@ktemia/langchain";

const agent = createAgent({ model: "openai:gpt-5-mini", tools: ktemiaTools() });

const result = await agent.invoke({
  messages: [{ role: "user", content: "What is the cheapest flight from Los Angeles to London on 2027-03-14?" }],
});
console.log(result.messages.at(-1)?.content);
```

`ktemiaTools()` returns all seven tools, and `new KtemiaToolkit().getTools()` returns the same set as a LangChain toolkit. To give the model fewer, use the factories: `lookup()`, `searchFlights()`, `searchHotels()`, `searchCars()`, `getDetails()`, `hotelReviews()`, and `keyStatus()`. Options match the Python package, in camelCase:

```ts
import { Ktemia } from "ktemia";
import { hotelReviews, ktemiaTools, lookup, searchHotels } from "@ktemia/langchain";

ktemiaTools({ apiKey: process.env.MY_KTEMIA_KEY, timeoutMs: 60_000, maxRetries: 2 });
const tools = [lookup(), searchHotels(), hotelReviews()];
const shared = ktemiaTools({ client: new Ktemia() });
```

Errors, paging, and quota behave as described above. Run the tools on the server, so the API key never reaches a browser.

## Related

- [MCP server](https://www.ktemia.com/docs/mcp/): the same tools for Cursor, Claude, Codex, and VS Code
- [Vercel AI SDK](https://www.ktemia.com/docs/vercel-ai-sdk/): the same tools for TypeScript agents
- [API reference](https://www.ktemia.com/docs/api/): every endpoint, field, and error code
- [Build an AI travel deal finder](https://www.ktemia.com/blog/ai-travel-deal-finder/)
- [Flight search API](https://www.ktemia.com/blog/flight-search-api/)

## Questions

**What is langchain-ktemia?**

A Python package that gives a LangChain agent seven travel tools. They search and compare flights, hotels, and rental cars across 100+ providers, look up airport codes and location ids, read hotel reviews, and return each provider's booking link. @ktemia/langchain is the same seven tools for LangChain.js.

**Does it book flights or hotels?**

No. Every tool is read-only. Ktemia compares prices and returns the provider's link, and the traveller books on the provider's site.

**Which LangChain versions and models does it support?**

LangChain 1.x (langchain-core 1.0 or later) on Python 3.10+, and LangChain.js 1.x (@langchain/core 1.x) on Node 20+. It works with any chat model that supports tool calling, such as OpenAI, Anthropic, or Google models. Every Python tool also implements ainvoke, so it runs in async agents and LangGraph graphs.

**Is it free?**

The package is MIT licensed. Calls use your Ktemia API key, and the Free plan includes 100 requests a month with no card. A search costs two requests, each further page or detail one, and ktemia_key_status is free.

**How is it different from the Ktemia MCP server?**

Same seven tools, same descriptions, same quota. The MCP server is for clients like Cursor and Claude. langchain-ktemia is for agents you write in Python, with no MCP connection to run.
