> ## Documentation Index
> Fetch the complete documentation index at: https://docs.keenable.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Every page is listed in https://docs.keenable.ai/llms.txt. To pick a product for a job, read https://docs.keenable.ai/choose.md
> Setup steps for agents, covering the SDKs, the MCP server and the CLI: https://docs.keenable.ai/skill.md
> Keenable search and fetch work without an API key. To add them to code, use the official SDK for the project's language: https://docs.keenable.ai/sdks.md
> Without a key, call POST https://api.keenable.ai/v1/search/public or GET https://api.keenable.ai/v1/fetch/public with an X-Keenable-Title header that names your app.
> With a key, send it in the X-API-Key header and read it from the KEENABLE_API_KEY environment variable. Never ask a user to paste a key into chat. Every access method: https://docs.keenable.ai/auth.md
> To get an API key without the console, use device login: https://docs.keenable.ai/authentication.md#device-login
> MCP server: https://api.keenable.ai/mcp (no key, or X-API-Key; keyless Codex uses https://api.keenable.ai/mcp-public), or https://api.keenable.ai/mcp-oauth for OAuth sign-in. These docs are an MCP server at https://docs.keenable.ai/mcp and the OpenAPI spec is at https://docs.keenable.ai/api-reference/openapi.json
> Keenable searches and fetches public web pages. If a question needs no web information, skip the call.
> On 402 with an API key (code insufficient_credits), stop and ask a human to add credits; don't retry. On 429, wait the number of seconds in Retry-After, then retry. Before you ship, follow https://docs.keenable.ai/production.md
> Every error, with its cause and fix, is in https://docs.keenable.ai/errors.md and moving from another search API is covered in https://docs.keenable.ai/migrate.md
> Before you compare Keenable with another search API, read https://docs.keenable.ai/guides/evaluate-search-apis.md

# Web search and fetch as LLM tools

> Give an LLM web search and page fetch as tools. Pass the SDK's TOOLS to any OpenAI-compatible chat completions client and run each call with run_tool_call.

Your model decides when to search the web or read a page, and your code runs the call with one helper. The SDKs ship the tool definitions and the helper, so you write only the loop.

## What you get

`TOOLS` is a list of two tool definitions in OpenAI function-calling format. Pass it as `tools` to any chat completions client that accepts that format.

| Tool | What the model can do | Arguments |
| - | - | - |
| `keenable_search` | Search the web. The model gets ranked pages with title, URL and extracted page text. | `query` (required) and optional filters, listed in [Tool arguments](#tool-arguments) |
| `keenable_fetch` | Read one page as markdown. | `url` (required) |

`run_tool_call` runs whichever of the two tools the model picked and returns the text to send back. Each SDK names the pieces in its own style:

| | TypeScript | Python | Go (package `keenable`) | Rust (crate `keenable`) |
| - | - | - | - | - |
| Both definitions | `TOOLS` | `TOOLS` | `Tools` | `tools()` |
| One definition | `SEARCH_TOOL`, `FETCH_TOOL` | `SEARCH_TOOL`, `FETCH_TOOL` | `SearchTool`, `FetchTool` | `search_tool()`, `fetch_tool()` |
| Run a tool call | `runToolCall` | `run_tool_call` (`arun_tool_call` with `AsyncKeenable`) | `RunToolCall` | `client.run_tool_call` |

The programs on this page are in TypeScript and Python. In Go, `keenable.RunToolCall(ctx, client, name, arguments)` returns `(string, error)` and takes the same tool names and arguments. In Rust, `client.run_tool_call(name, arguments).await` returns `Result<String, keenable::Error>`, where `arguments` is the JSON text the model sent. For each SDK's client settings and error classes, see the [TypeScript](https://docs.keenable.ai/sdks/typescript.md), [Python](https://docs.keenable.ai/sdks/python.md), [Go](https://docs.keenable.ai/sdks/go.md) and [Rust](https://docs.keenable.ai/sdks/rust.md) pages.

## Provider pages

Each provider page has the tool definitions in that provider's own format and a complete loop in TypeScript and Python with the provider's official SDK:

| Provider | API on the page | Tool format |
| - | - | - |
| [Anthropic](https://docs.keenable.ai/tool-calling/anthropic.md) | Messages API | `name`, `description`, `input_schema` |
| [OpenAI](https://docs.keenable.ai/tool-calling/openai.md) | Responses API | Flat `type: "function"` tools |
| [Gemini](https://docs.keenable.ai/tool-calling/gemini.md) | Interactions API | Flat `type: "function"` tools |
| [Mistral](https://docs.keenable.ai/tool-calling/mistral.md) | Chat completion | The SDK's `TOOLS`, unchanged |
| [Open models](https://docs.keenable.ai/tool-calling/open-models.md) | Ollama, and vLLM's OpenAI-compatible server | The SDK's `TOOLS`, unchanged |

For any other provider with an OpenAI-compatible Chat Completions endpoint, use the loop below. For the Vercel AI SDK, see [Vercel AI SDK](https://docs.keenable.ai/integrations/vercel.md).

## Run the tool-calling loop

The program below asks a question, lets the model call the Keenable tools as often as it needs, and prints the final answer. It uses the official `openai` client, which works with any provider that has an OpenAI-compatible chat completions endpoint. Keenable needs no API key here.

**1. Install the packages**

Install the Keenable SDK and the `openai` client:

```bash TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
npm install keenable openai
```

```bash Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
pip install keenable openai
```

**2. Point the client at your LLM provider**

The `openai` client reads the key and the base URL from the environment. The program reads the model name from `OPENAI_MODEL`. Use your provider's values:

```bash theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
export OPENAI_API_KEY=<your_provider_key>
export OPENAI_BASE_URL=<your_provider_base_url>
export OPENAI_MODEL=<a_model_that_supports_tool_calling>
```

To call OpenAI itself, leave `OPENAI_BASE_URL` unset. For Cerebras's own Python and Node clients, see [Cerebras](https://docs.keenable.ai/integrations/cerebras.md).

**3. Save the program**

Save this program as `tool-calling.mts` or `tool_calling.py`:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import { Keenable, KeenableError, TOOLS, runToolCall } from "keenable";
import OpenAI from "openai";

const keenable = new Keenable();
const llm = new OpenAI(); // reads OPENAI_API_KEY and OPENAI_BASE_URL

const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
  {
    role: "system",
    content:
      "Use the web tools when the answer depends on recent information. " +
      "Cite sources by their number, like [1].",
  },
  { role: "user", content: "What is the latest version of the Model Context Protocol specification?" },
];

while (true) {
  const completion = await llm.chat.completions.create({
    model: process.env.OPENAI_MODEL!,
    messages,
    tools: TOOLS,
  });
  const message = completion.choices[0].message;
  if (!message.tool_calls?.length) {
    console.log(message.content);
    break;
  }

  messages.push(message);
  for (const call of message.tool_calls) {
    if (call.type !== "function") continue;
    let output: string;
    try {
      output = await runToolCall(keenable, call.function.name, call.function.arguments);
    } catch (error) {
      output = `Tool call failed: ${error instanceof KeenableError ? error.message : error}`;
    }
    messages.push({ role: "tool", tool_call_id: call.id, content: output });
  }
}
```

```python Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import os

from keenable import TOOLS, Keenable, KeenableError, run_tool_call
from openai import OpenAI

keenable = Keenable()
llm = OpenAI()  # reads OPENAI_API_KEY and OPENAI_BASE_URL

messages = [
    {
        "role": "system",
        "content": "Use the web tools when the answer depends on recent "
        "information. Cite sources by their number, like [1].",
    },
    {"role": "user", "content": "What is the latest version of the Model Context Protocol specification?"},
]

while True:
    completion = llm.chat.completions.create(
        model=os.environ["OPENAI_MODEL"], messages=messages, tools=TOOLS
    )
    message = completion.choices[0].message
    if not message.tool_calls:
        print(message.content)
        break

    messages.append(message)
    for call in message.tool_calls:
        try:
            output = run_tool_call(keenable, call.function.name, call.function.arguments)
        except KeenableError as exc:
            output = f"Tool call failed: {exc}"
        messages.append({"role": "tool", "tool_call_id": call.id, "content": output})
```

Each pass of the loop does three things:

1. Sends the conversation and `TOOLS` to the model.
2. If the model answers without a tool call, prints the answer and stops.
3. Otherwise runs every tool call with `run_tool_call` and appends each result as a `role: "tool"` message with the matching `tool_call_id`.

**4. Run it**

```bash TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
npx tsx tool-calling.mts
```

```bash Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
python tool_calling.py
```

The program prints the model's final message. The system prompt asks the model to cite the tool results by number, such as `[1]`.

## What a tool call returns

`run_tool_call` takes the client, the tool name and the arguments, and returns one string. The arguments can be the raw JSON string from the model or an already-decoded object.

This program runs a search tool call by hand, with no model and no key:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import { Keenable, runToolCall } from "keenable";

const output = await runToolCall(
  new Keenable(),
  "keenable_search",
  '{"query": "Model Context Protocol specification", "site": "modelcontextprotocol.io"}',
);
console.log(output);
```

```python Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
from keenable import Keenable, run_tool_call

output = run_tool_call(
    Keenable(),
    "keenable_search",
    '{"query": "Model Context Protocol specification", "site": "modelcontextprotocol.io"}',
)
print(output)
```

You see the same numbered block that `to_context()` renders, one `[n] Title (url)` header per result followed by the page text:

```text Example output · results vary theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
[1] Specification (https://modelcontextprotocol.io/specification/2025-03-26) - published 2025-03-26T00:00:00Z
[Model Context Protocol](https://modelcontextprotocol.io) (MCP) is an open protocol that…

[2] Overview (https://modelcontextprotocol.io/specification/2025-03-26/basic) - published 2025-03-26T00:00:00Z
The Model Context Protocol consists of several key components that work together: …

[3] Tools (https://modelcontextprotocol.io/specification/2025-11-25/server/tools) - published 2025-11-25T00:00:00Z
…
```

A `keenable_fetch` call returns the same shape with a single `[1] Title (url)` entry, so the model cites a fetched page the way it cites a search result. Both blocks are limited to 12,000 characters. See [Context size](https://docs.keenable.ai/sdks.md#context-size).

For `keenable_search`, the helper passes on only the arguments its own `TOOLS` lists. It drops any other argument the model sends.

## Tool arguments

These are the arguments the SDK's definitions offer the model. The SDK column is the first SDK version whose `TOOLS` and `run_tool_call` include the argument:

| Tool | Argument | Type | Required | SDK | Description the model sees |
| - | - | - | - | - | - |
| `keenable_search` | `query` | string | Yes | 0.1.0 or later | What to look for, described in natural language rather than keywords. |
| `keenable_search` | `site` | string | No | 0.1.0 or later | Optional. Restrict results to one domain, e.g. 'arxiv.org'. |
| `keenable_search` | `exclude_domains` | array of string | No | 0.1.5 or later | Optional. Never return results from these hosts or their subdomains, e.g. 'pinterest.com'. Hosts only, no paths or wildcards. Up to 1,000. |
| `keenable_search` | `published_after` | string | No | 0.1.0 or later | Optional. Only pages published on or after this date (YYYY-MM-DD). |
| `keenable_search` | `objective` | string | No | 0.2.0 or later | Optional. Two or three natural sentences, with no field labels and no line breaks, that cover: the exact facts, entities, numbers, dates or names a useful page must contain; task context the query does not state (who, where, when, eligibility, date window); which kinds of sources count or must be excluded; what is already established from earlier steps; and what is still unknown. Every sentence must be self-contained: name the entities, places, dates and figures explicitly, and never refer to 'the task', 'the clue', 'the question', 'above' or earlier results. Do not paste the conversation, and do not include personal, confidential or sensitive information. At most 1,000 characters. |
| `keenable_search` | `disable_cards` | boolean | No | 0.1.5 or later | Optional. true returns ordinary web pages in place of Keenable's cards (results Keenable writes for prices, exchange rates or company facts, whose URLs expire after one day). Default false. |
| `keenable_fetch` | `url` | string | Yes | 0.1.0 or later | The URL of the page to read. |

SDK 0.2.0 is not yet on npm or PyPI. PyPI has 0.1.5 and the Go module is tagged v0.1.5, which offer every argument except `objective`. npm has 0.1.4, which offers only `site` and `published_after` of the optional ones.

## Errors inside a tool call

`run_tool_call` raises a `KeenableError` instead of returning an error string. The loop above catches it and sends the message back as the tool result, so the model can retry with other arguments or another URL.

| When | Error | Example message (Python) |
| - | - | - |
| The model names a tool other than the two | `KeenableInvalidRequestError` | `unknown Keenable tool: 'web_search'` |
| The arguments are not a JSON object | `KeenableInvalidRequestError` | `tool call arguments are not valid JSON: 'not json'` |
| `query` or `url` is missing or empty | `KeenableInvalidRequestError` | `keenable_search needs a 'query'` |
| The API returns an error, such as a page that can't be fetched | `KeenableAPIError` and the other [SDK error classes](https://docs.keenable.ai/sdks.md#errors) | `Keenable API error (502): …` |

In the first three cases the SDK sends no request. If the API returns `429`, see [Rate limits](https://docs.keenable.ai/rate-limits.md). An [API key](https://docs.keenable.ai/api-keys.md) removes the keyless hourly cap.

## Ground an answer without tool calling

If your model has no tool calling, or you want one search per question, search first and put the `to_context()` block in the prompt. For questions about recent events, see [RAG with fresh web results](https://docs.keenable.ai/recipes/rag-with-fresh-web-results.md). This program uses the same environment variables as the tool-calling loop:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import { Keenable } from "keenable";
import OpenAI from "openai";

const question = "What is the latest version of the Model Context Protocol specification?";

const results = await new Keenable().search(question);
const llm = new OpenAI(); // reads OPENAI_API_KEY and OPENAI_BASE_URL

const completion = await llm.chat.completions.create({
  model: process.env.OPENAI_MODEL!,
  messages: [
    {
      role: "system",
      content:
        "Answer using only the sources provided. Cite them by their number, " +
        "like [1]. If the sources do not answer the question, say so.",
    },
    { role: "user", content: `${results.toContext()}\n\nQuestion: ${question}` },
  ],
});
console.log(completion.choices[0].message.content);

console.log("\nSources:");
results.cited().forEach((result, index) => {
  console.log(`[${index + 1}] ${result.title} - ${result.url}`);
});
```

```python Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import os

from keenable import Keenable
from openai import OpenAI

question = "What is the latest version of the Model Context Protocol specification?"

results = Keenable().search(question)
llm = OpenAI()  # reads OPENAI_API_KEY and OPENAI_BASE_URL

completion = llm.chat.completions.create(
    model=os.environ["OPENAI_MODEL"],
    messages=[
        {
            "role": "system",
            "content": "Answer using only the sources provided. Cite them by "
            "their number, like [1]. If the sources do not answer the "
            "question, say so.",
        },
        {"role": "user", "content": f"{results.to_context()}\n\nQuestion: {question}"},
    ],
)
print(completion.choices[0].message.content)

print("\nSources:")
for index, result in enumerate(results.cited(), start=1):
    print(f"[{index}] {result.title} - {result.url}")
```

The program prints the model's answer, then the sources behind each `[n]` marker:

```text Example output · results vary theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
<the model's answer>

Sources:
[1] Specification - https://modelcontextprotocol.info/specification
[2] The New MCP Roadmap - https://blog.modelcontextprotocol.io/posts/mcp-roadmap
[3] Model Context Protocol Blog - https://blog.modelcontextprotocol.io
…
```

`cited()` returns the results that `to_context()` kept, in the same order, so the list always matches the numbers the model saw. To narrow the search, pass the [Search parameters](https://docs.keenable.ai/products/search.md#key-parameters) to `search`.

## Related pages

> [card] [Tavus](https://docs.keenable.ai/integrations/tavus.md)
>
> Give a Tavus PAL live web search with one API tool that calls Keenable, so it can answer questions about current events mid-conversation.

> [card] [Fetch quickstart](https://docs.keenable.ai/products/fetch.md)
>
> Turn any URL into clean markdown your model can read, or get only the part a prompt asks for. Try it with no API key. Code, cost per call and gotchas.

> [card] [Connect your agent (MCP)](https://docs.keenable.ai/mcp-server.md)
>
> Connect the Keenable MCP server to Claude Code, Cursor, Codex and other clients for web search and fetch with no key. Sign in for higher limits and Monitors.

> [card] [LangChain](https://docs.keenable.ai/integrations/langchain.md)
>
> Give LangChain agents web search and page fetch with langchain-keenable: the KeenableSearch and KeenableFetch tools.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.