> ## 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 Gemini with the Interactions API

> Give Gemini web search and page fetch as function tools on the Interactions API: Keenable's definitions in Gemini's format and a loop in Python and TypeScript.

Gemini decides when to search the web or read a page, and your code runs each call with the Keenable SDK. This page uses the Interactions API in Google's Gen AI SDKs, `google-genai` for Python and `@google/genai` for TypeScript.

## How the loop works

1. Your code sends the question and the Keenable tools to `client.interactions.create`.
2. If Gemini wants the web, `interaction.steps` holds one `function_call` step per call, each with a `name`, an `id` and an `arguments` object.
3. Your code runs each call with `run_tool_call` and sends one `function_result` item per call, with `call_id` set to the step's `id`, in a new request that sets `previous_interaction_id`.
4. When the steps hold no `function_call`, `interaction.output_text` is the answer.

## Prerequisites

* A Gemini API key in `GEMINI_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)

Interactions API function tools are flat: `name`, `description` and `parameters` sit next to `type: "function"`. These are the Keenable SDK's definitions in that shape:

```json Gemini Interactions 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"
      ]
    }
  },
  {
    "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"
      ]
    }
  }
]
```

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 Google's Gen AI SDK:

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

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

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

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import { GoogleGenAI } from "@google/genai";
import { Keenable, KeenableError, TOOLS, runToolCall } from "keenable";

const keenable = new Keenable();
const client = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const model = "gemini-4-hydrogen";

// Interactions API function tools are flat: no nested "function" object.
const tools = TOOLS.map((tool) => ({
  type: "function" as const,
  name: tool.function.name,
  description: tool.function.description,
  parameters: tool.function.parameters,
}));

let interaction = await client.interactions.create({
  model,
  tools,
  input: "What changed in the latest Node.js LTS release? Cite your sources.",
});

while (true) {
  const calls = (interaction.steps ?? []).filter((step) => step.type === "function_call");
  if (calls.length === 0) {
    console.log(interaction.output_text);
    break;
  }

  const results = [];
  for (const call of calls) {
    try {
      const text = await runToolCall(keenable, call.name, call.arguments);
      results.push({ type: "function_result" as const, name: call.name, call_id: call.id, result: [{ type: "text" as const, text }] });
    } catch (error) {
      const text = `Tool call failed: ${error instanceof KeenableError ? error.message : error}`;
      results.push({ type: "function_result" as const, name: call.name, call_id: call.id, result: [{ type: "text" as const, text }], is_error: true });
    }
  }
  // The server keeps the conversation: send only the results and the previous interaction's ID.
  interaction = await client.interactions.create({
    model,
    tools,
    input: results,
    previous_interaction_id: interaction.id,
  });
}
```

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

from google import genai
from keenable import TOOLS, Keenable, KeenableError, run_tool_call

keenable = Keenable()
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
model = "gemini-4-hydrogen"

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

interaction = client.interactions.create(
    model=model,
    tools=tools,
    input="What changed in the latest Node.js LTS release? Cite your sources.",
)

while True:
    calls = [step for step in (interaction.steps or []) if step.type == "function_call"]
    if not calls:
        print(interaction.output_text)
        break

    results = []
    for call in calls:
        result = {"type": "function_result", "name": call.name, "call_id": call.id}
        try:
            text = run_tool_call(keenable, call.name, call.arguments)
        except KeenableError as exc:
            text = f"Tool call failed: {exc}"
            result["is_error"] = True
        result["result"] = [{"type": "text", "text": text}]
        results.append(result)
    # The server keeps the conversation: send only the results and the previous interaction's ID.
    interaction = client.interactions.create(
        model=model,
        tools=tools,
        input=results,
        previous_interaction_id=interaction.id,
    )
```

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

Each `function_result` carries the Keenable text as a single `text` part. If a tool call fails, the loop sets `is_error: true` and sends the error message, so Gemini can try another query or URL. [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 Interactions API |
| - | - |
| [Anthropic](https://docs.keenable.ai/tool-calling/anthropic.md) | The schema goes under `parameters`. Gemini keeps the conversation through `previous_interaction_id`, so you send only the new results. |
| [OpenAI](https://docs.keenable.ai/tool-calling/openai.md) | Same flat tool shape. Arguments arrive as an object rather than a JSON string, a result is a list of content parts rather than one string, and a failed call can carry `is_error`. |
| [Mistral](https://docs.keenable.ai/tool-calling/mistral.md) | Mistral takes the SDK's `TOOLS` unchanged. Gemini needs the flat shape above, and results go back as `function_result` items, not `tool` messages. |
| [Open models](https://docs.keenable.ai/tool-calling/open-models.md) | Ollama and vLLM run on your own machine and take the SDK's `TOOLS` unchanged. You keep the whole conversation on your side. |


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