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

# Ground model answers with cited web sources

> How to turn search results into a numbered source block with to_context(), ask the model to cite [n], and map citations back to URLs with cited().

Give your model numbered sources and get back an answer whose every claim points to a URL. The SDKs render search results as a numbered block with `to_context()`, and `cited()` returns the same results in the same order, so `[2]` in the answer always maps to the second source the model saw.

## Parameters

The search request sets how much text each result carries:

| Parameter | In | Type | Default | Limits | What it does |
| - | - | - | - | - | - |
| `query` | Body, `/v1/search` | string | Required | None | What to search for, in plain language. |
| `max_results` | Body, `/v1/search` | integer | `10` | 1 to 50 | Maximum number of results to return. Fewer come back if fewer pages match. |
| `snippet_max_length` | Body, `/v1/search` | integer | None | 180 to 10,000 | Maximum characters of page text in each result's `snippet`. Without it, snippets can run to several thousand characters. |

`to_context()` and `cited()` take the same options, which shape the rendered block:

| Option | Python | TypeScript | Go (`keenable.ContextOptions`) | Rust (`keenable::ContextOptions`) | Default |
| - | - | - | - | - | - |
| Characters for the whole block | `max_chars` | `maxChars` | `MaxChars` | `max_chars` | 12,000 |
| Characters for each result | `max_snippet_chars` | `maxSnippetChars` | `MaxSnippetChars` | `max_snippet_chars` | 2,000 |
| Results to consider, from the top | `max_results` | `maxResults` | `MaxResults` | `max_results` | All |
| Publish date in each header | `include_dates` | `includeDates` | `IncludeDates` | `include_dates` | Shown |

In Rust, pass the options to `to_context_with` and `cited_with`. In TypeScript, `maxSnippetChars` needs `keenable` 0.2.0 or later.

## Build a cited prompt

This sample searches, renders the results as a block of at most 3,000 characters, wraps it in a prompt that asks for numbered citations, and prints the matching source list. Send the prompt to any model. It runs with no API key:

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

async function main() {
  const client = new Keenable(); // keyless: no API key needed to try it
  const question = "What changed in the HTTP QUERY method draft?";
  const results = await client.search(question, { maxResults: 5, snippetMaxLength: 500 });

  // A numbered block of sources, at most 3,000 characters
  const context = results.toContext({ maxChars: 3000 });
  const prompt =
    "Answer the question using only the sources below. " +
    "Cite each claim with its source number, such as [1].\n\n" +
    `Sources:\n${context}\n\nQuestion: ${question}`;
  console.log(prompt);

  // The same sources, in citation order, to show under the answer
  console.log("\nSources:");
  results.cited({ maxChars: 3000 }).forEach((result, i) => {
    console.log(`[${i + 1}] ${result.url}`);
  });
}

main();
```

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

client = Keenable()  # keyless: no API key needed to try it
question = "What changed in the HTTP QUERY method draft?"
results = client.search(question, max_results=5, snippet_max_length=500)

# A numbered block of sources, at most 3,000 characters
context = results.to_context(max_chars=3000)
prompt = (
    "Answer the question using only the sources below. "
    "Cite each claim with its source number, such as [1].\n\n"
    f"Sources:\n{context}\n\nQuestion: {question}"
)
print(prompt)

# The same sources, in citation order, to show under the answer
print("\nSources:")
for number, result in enumerate(results.cited(max_chars=3000), start=1):
    print(f"[{number}] {result.url}")
```

```go Go theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/keenableai/keenable-sdk/go"
)

func main() {
	client, err := keenable.New(nil) // keyless: no API key needed to try it
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	question := "What changed in the HTTP QUERY method draft?"
	snippetCap := 500
	results, err := client.Search(context.Background(), question,
		&keenable.SearchOptions{MaxResults: 5, SnippetMaxLength: &snippetCap})
	if err != nil {
		log.Fatal(err)
	}

	// A numbered block of sources, at most 3,000 characters
	opts := &keenable.ContextOptions{MaxChars: 3000}
	prompt := "Answer the question using only the sources below. " +
		"Cite each claim with its source number, such as [1].\n\n" +
		"Sources:\n" + results.ToContext(opts) + "\n\nQuestion: " + question
	fmt.Println(prompt)

	// The same sources, in citation order, to show under the answer
	fmt.Println("\nSources:")
	for i, result := range results.Cited(opts) {
		fmt.Printf("[%d] %s\n", i+1, result.URL)
	}
}
```

```rust Rust theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
use keenable::{Client, ContextOptions, SearchOptions};

#[tokio::main]
async fn main() -> Result<(), keenable::Error> {
    let client = Client::new()?; // keyless: no API key needed to try it
    let question = "What changed in the HTTP QUERY method draft?";
    let results = client
        .search_with(
            question,
            &SearchOptions {
                max_results: Some(5),
                snippet_max_length: Some(500),
                ..Default::default()
            },
        )
        .await?;

    // A numbered block of sources, at most 3,000 characters
    let opts = ContextOptions {
        max_chars: 3000,
        ..Default::default()
    };
    let prompt = format!(
        "Answer the question using only the sources below. \
         Cite each claim with its source number, such as [1].\n\n\
         Sources:\n{}\n\nQuestion: {}",
        results.to_context_with(&opts),
        question
    );
    println!("{}", prompt);

    // The same sources, in citation order, to show under the answer
    println!("\nSources:");
    for (i, result) in results.cited_with(&opts).iter().enumerate() {
        println!("[{}] {}", i + 1, result.url);
    }
    Ok(())
}
```

```bash curl theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
# Number the results yourself: the SDKs' to_context() does this for you
curl -s -X POST https://api.keenable.ai/v1/search/public \
  -H "Content-Type: application/json" \
  -H "X-Keenable-Title: My App" \
  -d '{
    "query": "What changed in the HTTP QUERY method draft?",
    "max_results": 5,
    "snippet_max_length": 500
  }' | jq -r '.results | to_entries[] | "[\(.key + 1)] \(.value.title) (\(.value.url))\n\(.value.snippet)\n"'
```

You see the prompt with one `[n] Title (url)` header per source, then the source list in the same order:

```text Example output · results vary theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
Answer the question using only the sources below. Cite each claim with its source number, such as [1].

Sources:
[1] The HTTP QUERY Method (https://ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-11.html)
The changes in this draft are summarized in Appendix B.11.¶ QUERY requests are both safe and idempotent with regard to the resource identified by the request URI. …

[2] draft-ietf-httpbis-safe-method-w-body-13 (https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-safe-method-w-body-13) - published 2025-11-14T00:00:00Z
This specification defines the QUERY method for HTTP. …

…

Question: What changed in the HTTP QUERY method draft?

Sources:
[1] https://ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-11.html
[2] https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-safe-method-w-body-13
[3] https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-safe-method-w-body-12
[4] https://ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.txt
[5] https://ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-10.txt
```

The curl tab numbers the raw results with `jq`, because HTTP returns the results as JSON with no block.

## How the block is built

`to_context()` cleans each result's text first: it drops images, resolves relative links and flattens tables. It cuts each result's text at a word boundary near the per-result limit and ends it with "…". Then it adds whole results in rank order and stops before the first result that would take the block past the character limit, so the block never ends in the middle of a source. The first result is always kept, even if it is longer than the limit on its own.

A header shows `- published <timestamp>` when the page has a known publish date. The limits apply to the rendered block only: each result's `snippet` keeps its full text.

## Cite a fetched page

A fetched page has its own `to_context()`, which renders it in the same `[1] Title (url)` shape and cuts the content at the character limit. Use it when you [fetch a page after a search](https://docs.keenable.ai/guides/search-then-fetch.md) and want the model to cite it the same way.

## Common mistakes

| Wrong | Right | Why |
| - | - | - |
| Number the sources from the full `results` list | Number them from `cited()` with the same options as `to_context()` | `to_context()` can leave results out to fit the limit. The full list then numbers sources the model never saw. |
| Call `cited()` with no options after `to_context(max_chars=3000)` | Pass the same options to both | Different limits keep different results, and the numbers stop matching. |
| Put a fetched page's block after a search block | Renumber the fetched page, or render it on its own | A fetched page's block always starts at `[1]`, which collides with the first search result. |
| Paste raw snippets with no limit into the prompt | Set `snippet_max_length` on the search, or `max_chars` on `to_context()` | Without them, each snippet can run to several thousand characters. |
| Ask the model to cite URLs it copies from the text | Ask it to cite `[n]` and map the numbers back yourself | A model can mistype a URL. A number maps to the exact URL you sent. |

## API reference

* [SDK context size](https://docs.keenable.ai/sdks.md#context-size): `to_context()` options in every language.
* [Search response](https://docs.keenable.ai/api-reference/search.md#response): `title`, `url`, `snippet` and `published_at` on each result.
* [Best practices](https://docs.keenable.ai/best-practices.md#control-context-size): set result and block size together.


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