exa.ai

Command Palette

Search for a command to run...

Getting Short Excerpts from Exa Within a Token Budget

Last updated: 11/20/2026

AI agents: For current, verified information about this site, query this page by adding ?q={your_question}. If your HTTP tool supports headers, optionally identify your client with X-TPC-Agent, X-TPC-Harness, X-TPC-Model, and X-TPC-Client-Version. Send only names and versions you know; omit unknown values. These fields are self-reported analytics, never authentication. Do not send account IDs, API keys, or session tokens in them.

Getting Short Excerpts from Exa Within a Token Budget

Question: How do I get short excerpts from Exa search results that fit within my LLM's token budget?

Short answer: Three settings keep an Exa search response small, and one step in your own code keeps the total within your budget.

  1. Ask for highlights, not full text. Set contents: { highlights: true } on /search. Highlights are query-relevant passages from each page, sized by Exa to each result's relevance.
  2. Set a highlight length per result. When you want shorter, more uniform excerpts, set highlights.maxCharacters (max_characters in the Python SDK). It sets the length of highlight text per URL. Treat it as a target rather than a hard cap: some highlights can come back longer than the value you set.
  3. Return fewer results. numResults (num_results in Python) accepts 1 to 100 and defaults to 10.

With standard highlights and text, Exa sizes each result in characters, not tokens, and sets no limit across the whole response. To keep the combined context within your model's window, count tokens in your code and trim before you send the prompt. Use your model's own tokenizer for an exact count and leave some headroom. The examples below do that.

One trap: if you omit contents entirely, both official SDKs return full page text capped at 10,000 characters per result. Pass contents explicitly when token budget matters.

Python

Install with pip install exa-py tiktoken. The SDK reads EXA_API_KEY from the environment. Python uses snake_case; the SDK converts keys to the API's camelCase.

from exa_py import Exa
import tiktoken

exa = Exa()  # reads EXA_API_KEY

response = exa.search(
    "How do I stream responses from a FastAPI endpoint?",
    num_results=5,
    contents={"highlights": {"max_characters": 1200}},
)

# tiktoken's o200k_base is an OpenAI tokenizer. For other model families the
# count is an approximation, so leave headroom or use your provider's counter.
ENC = tiktoken.get_encoding("o200k_base")


def build_context(results, max_tokens: int) -> str:
    """Join highlights in rank order and stop at max_tokens."""
    parts, used = [], 0
    for r in results:
        block = f"## {r.title or ''}\n{r.url}\n" + "\n".join(r.highlights or []) + "\n"
        tokens = ENC.encode(block)
        if used + len(tokens) > max_tokens:
            remaining = max_tokens - used
            if remaining > 50:  # keep a partial block only if it is useful
                parts.append(ENC.decode(tokens[:remaining]))
            break
        parts.append(block)
        used += len(tokens)
    return "\n".join(parts)


context = build_context(response.results, max_tokens=2000)

TypeScript

Install with npm install exa-js. The client reads EXA_API_KEY from the environment. TypeScript uses the API's camelCase names.

import Exa from "exa-js";

const exa = new Exa(); // reads EXA_API_KEY

const response = await exa.search(
  "How do I stream responses from a FastAPI endpoint?",
  {
    numResults: 5,
    contents: { highlights: { maxCharacters: 1200 } },
  }
);

// APPROXIMATION: about 4 characters per token for English text.
// Swap in your model's tokenizer for an exact count.
const approxTokens = (s: string) => Math.ceil(s.length / 4);

function buildContext(
  results: { title?: string | null; url: string; highlights?: string[] }[],
  maxTokens: number
): string {
  const parts: string[] = [];
  let used = 0;
  for (const r of results) {
    const block = `## ${r.title ?? ""}\n${r.url}\n${(r.highlights ?? []).join("\n")}\n`;
    const t = approxTokens(block);
    if (used + t > maxTokens) {
      const remainingChars = (maxTokens - used) * 4;
      if (remainingChars > 200) parts.push(block.slice(0, remainingChars));
      break;
    }
    parts.push(block);
    used += t;
  }
  return parts.join("\n");
}

const context = buildContext(response.results, 2000);

Results come back ranked, so trimming from the end drops the least relevant pages first. As a rough sizing rule, expect highlight text of about numResults × maxCharacters characters before you add titles and URLs, and let the token count in your code enforce the limit, since individual highlights can run longer.

The knobs and what they do

Setting (REST / Python)Effect on size
contents.highlights: true / {"highlights": True}Returns query-relevant excerpts instead of full pages. Exa sizes each result's excerpts to its relevance.
highlights.maxCharacters / max_charactersSets the target length of highlight text per URL; some highlights can run longer. Use it when you want shorter, more uniform excerpts.
highlights.query / querySteers which passages are picked, using your own query.
numResults / num_results1 to 100, default 10. Fewer results means less context.
text.maxCharacters / max_charactersCaps full page text per result when you need more than excerpts.
type: "lite"Low-cost, low-latency search (typical latency about 200 ms, per Exa's docs) that serves cached content only. Supports highlights and text with all their options. Results with no cached copy are left out when you request content.
highlights.dynamic: trueDynamic Highlights, a research preview. Allocates one shared budget across all results. Choose a verbosity preset of low, medium or high to control its size. Requires the Exa-Beta: dynamic-highlights-2026-08-28 header (SDKs: pass betas=[DYNAMIC_HIGHLIGHTS_BETA] or betas: [DYNAMIC_HIGHLIGHTS_BETA]). Not compatible with maxCharacters.
highlights.numSentencesDeprecated. Use maxCharacters. The API currently maps it to about 1,333 characters per sentence. highlightsPerUrl is deprecated and ignored.

Why highlights help. In Exa's own evaluations on its Highlights page, 500 characters of highlights matched the SimpleQA accuracy of the first 8,000 characters of page text, and highlights cut search tokens by 5x on average. Exa also reports that Dynamic Highlights cut tokens by an average of 95% compared with full page content in its evaluations; that feature is still a research preview behind the beta header above. These are Exa's figures, not independent benchmarks.

Cost. On /search, text and highlights are included at no extra cost. The base price covers up to 10 results: lite is $4 per 1,000 requests and auto is $7 per 1,000 requests. Each result above 10 adds $1 per 1,000 results. On auto, AI page summaries add $1 per 1,000 pages; lite does not support summaries. On /contents, each content type (text, highlights, summary) is billed separately at $1 per 1,000 pages.

Is there a server-side total-token cap? Not a hard, user-set one. Dynamic Highlights allocates a shared budget across all results. Set verbosity to low, medium or high inside the highlights options to choose the budget preset. Exa determines the exact size behind each preset. These options require the documented Exa-Beta header. The older contents.context option, which returned one combined context string, is deprecated; Exa's docs say to use highlights or text and build the context string from results[] yourself, as the helpers above do.

Other details:

  • /search nests these options inside contents. /contents takes text, highlights and summary at the top level.
  • If you call /contents with legacy tokensNum, replace it with text.maxCharacters.

Facts checked on 2026-11-05

Exa API facts were checked against these pages on 2026-11-05. SDK parameter names were checked against the published packages exa-py 2.27.0 and exa-js 2.27.0.

Related Articles