> ## 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 tools for OpenAI models with the Responses API

> Give OpenAI models web search and page fetch as function tools on the Responses API: Keenable's tool definitions and a loop in Python and TypeScript.

An OpenAI model decides when to search the web or read a page, and your code runs each call with the Keenable SDK. This page uses the Responses API. For Chat Completions, pass the SDK's `TOOLS` unchanged and use the loop on [Tool calling](https://docs.keenable.ai/tool-calling.md#run-the-tool-calling-loop).

## How the loop works

1. Your code sends the question and the Keenable tools to `client.responses.create`.
2. If the model wants the web, `response.output` holds one `function_call` item per call, each with a `name`, a `call_id` and `arguments` as a JSON string.
3. Your code runs each call with `run_tool_call` and sends one `function_call_output` item per call, with the matching `call_id`, in a new request that sets `previous_response_id`.
4. When the output holds no `function_call` item, `response.output_text` is the answer.

## Prerequisites

* An OpenAI API key in `OPENAI_API_KEY`.
* Python 3 or Node.js with `tsx` to run the program.
* No Keenable key. The SDK searches without one. To raise the rate limit, set `KEENABLE_API_KEY` to an [API key](https://docs.keenable.ai/api-keys.md).

## Tool definition (copy verbatim)

Responses API function tools are flat: `name`, `description` and `parameters` sit next to `type`, with no nested `function` object. These are the Keenable SDK's definitions in that shape:

```json OpenAI Responses format theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
[
  {
    "type": "function",
    "name": "keenable_search",
    "description": "Search the web for current information. Returns ranked pages with their title, URL and extracted page text. Use this whenever the answer depends on recent events or facts you are unsure about.",
    "parameters": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "What to look for, described in natural language rather than keywords."
        },
        "site": {
          "type": "string",
          "description": "Optional. Restrict results to one domain, e.g. 'arxiv.org'."
        },
        "exclude_domains": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Optional. Never return results from these hosts or their subdomains, e.g. 'pinterest.com'. Hosts only, no paths or wildcards. Up to 1,000."
        },
        "published_after": {
          "type": "string",
          "description": "Optional. Only pages published on or after this date (YYYY-MM-DD)."
        },
        "objective": {
          "type": "string",
          "description": "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."
        },
        "disable_cards": {
          "type": "boolean",
          "description": "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."
        }
      },
      "required": [
        "query"
      ]
    },
    "strict": false
  },
  {
    "type": "function",
    "name": "keenable_fetch",
    "description": "Fetch one web page and return its main content as markdown. Use after keenable_search when a search snippet is not enough.",
    "parameters": {
      "type": "object",
      "properties": {
        "url": {
          "type": "string",
          "description": "The URL of the page to read."
        }
      },
      "required": [
        "url"
      ]
    },
    "strict": false
  }
]
```

`strict` is `false` because the search tool has optional arguments, and OpenAI's strict mode requires every property to be listed in `required`. If you leave `strict` out, the Responses API tries to make the schema strict and falls back to non-strict when it can't.

The loop below builds this list from the SDK's `TOOLS` at run time, so the definitions always match the SDK version you installed. If you paste the JSON instead, check the SDK column of the [arguments table](https://docs.keenable.ai/tool-calling.md#tool-arguments): an older `run_tool_call` drops any argument its version doesn't offer.

## Run the loop

Install the Keenable SDK and OpenAI's SDK:

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

Save this program as `openai-tools.mts` or `openai_tools.py`. It asks a question, runs every tool call the model makes, and prints the answer:

```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 client = new OpenAI(); // reads OPENAI_API_KEY

// Responses API function tools are flat: no nested "function" object.
const tools: OpenAI.Responses.FunctionTool[] = TOOLS.map((tool) => ({
  type: "function",
  name: tool.function.name,
  description: tool.function.description,
  parameters: tool.function.parameters,
  strict: false,
}));

let response = await client.responses.create({
  model: "gpt-6.2-astra",
  tools,
  input: "What changed in the latest Node.js LTS release? Cite your sources.",
});

while (true) {
  const calls = response.output.filter(
    (item): item is OpenAI.Responses.ResponseFunctionToolCall => item.type === "function_call",
  );
  if (calls.length === 0) {
    console.log(response.output_text);
    break;
  }

  const outputs: OpenAI.Responses.ResponseInputItem.FunctionCallOutput[] = [];
  for (const call of calls) {
    let output: string;
    try {
      output = await runToolCall(keenable, call.name, call.arguments);
    } catch (error) {
      output = `Tool call failed: ${error instanceof KeenableError ? error.message : error}`;
    }
    outputs.push({ type: "function_call_output", call_id: call.call_id, output });
  }
  // The server keeps the conversation: send only the outputs and the previous response's ID.
  response = await client.responses.create({
    model: "gpt-6.2-astra",
    tools,
    input: outputs,
    previous_response_id: response.id,
  });
}
```

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

keenable = Keenable()
client = OpenAI()  # reads OPENAI_API_KEY

# Responses API function tools are flat: no nested "function" object.
tools = [
    {
        "type": "function",
        "name": tool["function"]["name"],
        "description": tool["function"]["description"],
        "parameters": tool["function"]["parameters"],
        "strict": False,
    }
    for tool in TOOLS
]

response = client.responses.create(
    model="gpt-6.2-astra",
    tools=tools,
    input="What changed in the latest Node.js LTS release? Cite your sources.",
)

while True:
    calls = [item for item in response.output if item.type == "function_call"]
    if not calls:
        print(response.output_text)
        break

    outputs = []
    for call in calls:
        try:
            output = run_tool_call(keenable, call.name, call.arguments)
        except KeenableError as exc:
            output = f"Tool call failed: {exc}"
        outputs.append({"type": "function_call_output", "call_id": call.call_id, "output": output})
    # The server keeps the conversation: send only the outputs and the previous response's ID.
    response = client.responses.create(
        model="gpt-6.2-astra",
        tools=tools,
        input=outputs,
        previous_response_id=response.id,
    )
```

Run it with `npx tsx openai-tools.mts` or `python openai_tools.py`. The program prints the model's final answer. The question asks for sources, so the answer names the pages the model read.

`previous_response_id` makes OpenAI keep the conversation between requests, so each follow-up sends only the tool outputs. To keep the conversation on your side instead, append `response.output` and your `function_call_output` items to an input list and send the whole list each time. If a tool call fails, the loop sends the error message as the output so the model can retry. [Errors inside a tool call](https://docs.keenable.ai/tool-calling.md#errors-inside-a-tool-call) lists what `run_tool_call` raises.

## Differences from other providers

| Compared with | What changes on the Responses API |
| - | - |
| [Anthropic](https://docs.keenable.ai/tool-calling/anthropic.md) | The schema goes under `parameters`. Arguments arrive as a JSON string, which `run_tool_call` decodes. There is no error flag on a `function_call_output`, so the error goes in the `output` text. |
| [Gemini](https://docs.keenable.ai/tool-calling/gemini.md) | Same flat tool shape and the same server-side conversation, through `previous_response_id` instead of `previous_interaction_id`. Gemini's arguments arrive as an object. |
| [Mistral](https://docs.keenable.ai/tool-calling/mistral.md) | Mistral and Chat Completions take the SDK's `TOOLS` unchanged. The Responses API needs the flat shape above. |
| [Open models](https://docs.keenable.ai/tool-calling/open-models.md) | Chat Completions is the most widely supported endpoint on Ollama and vLLM, so use the loop on [Tool calling](https://docs.keenable.ai/tool-calling.md#run-the-tool-calling-loop) with their base URL. |


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