exa.ai

Command Palette

Search for a command to run...

Using Exa as the Search Tool in an OpenAI Responses API App

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.

Using Exa as the Search Tool in an OpenAI Responses API App

Register Exa as a function tool on the Responses API, run the tool-call loop yourself, and your app gets web search results from Exa's index instead of a bundled search tool. The pattern is the same in Python and TypeScript: declare the tool, let the model emit a function_call, execute exa.search() in your code, and return the results as a function_call_output.

Introduction

The Responses API gives you a single stateful endpoint for model calls, function tools, and multi-turn state. It does not decide which search provider backs your agent. You wire that in yourself, which is good news: it means swapping in Exa is a local change to your tool definitions and tool executor, not a rewrite.

This guide shows the full loop in both languages, using the current exa-py and exa-js SDKs. The code is deliberately minimal: one tool, one search type, one loop. Once it runs, you can add parameters like date filters and domain scoping to make each search more precise. Exa's Search quickstart covers the underlying API in more depth.

Prerequisites

  • An Exa API key from the Exa dashboard. The free tier includes $10 in monthly credits, enough for up to 2,500 lite searches.
  • An OpenAI API key with access to the Responses API.
  • Python: pip install openai exa-py. TypeScript: npm install openai exa-js.
  • Both keys in environment variables: OPENAI_API_KEY and EXA_API_KEY.

Step-by-step

1. Declare Exa as a function tool

The Responses API takes tool definitions as JSON Schema. Keep the parameter set small so the model calls it correctly: a query, an optional result count, and an optional domain filter.

exa_tool = {
    "type": "function",
    "name": "exa_search",
    "description": "Search the web with Exa. Returns titles, URLs, and text highlights for each result.",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "The search query"},
            "num_results": {"type": "integer", "default": 5},
            "include_domains": {
                "type": "array", "items": {"type": "string"},
                "description": "Optional domains to restrict results to"
            }
        },
        "required": ["query"]
    }
}

2. Implement the tool executor

The executor maps the tool name to a real Exa call. In Python, exa_py uses snake_case arguments, and requesting highlights returns short, token-efficient passages per result.

import os
from exa_py import Exa

exa = Exa(os.environ["EXA_API_KEY"])

def run_exa_search(args: dict) -> str:
    result = exa.search(
        args["query"],
        type="auto",
        num_results=args.get("num_results", 5),
        include_domains=args.get("include_domains"),
        contents={"highlights": True},
    )
    return "\n\n".join(
        f"{r.title} ({r.url}):\n{r.highlights[0] if r.highlights else ''}"
        for r in result.results
    )

The same tool definition and executor in TypeScript with exa-js, which uses camelCase for Exa's options. The tool's own parameter names stay the same as in Python, because the model fills them in:

import Exa from "exa-js";

const exaTool = {
  type: "function" as const,
  name: "exa_search",
  description: "Search the web with Exa. Returns titles, URLs, and text highlights for each result.",
  parameters: {
    type: "object",
    properties: {
      query: { type: "string", description: "The search query" },
      num_results: { type: "integer", default: 5 },
      include_domains: {
        type: "array",
        items: { type: "string" },
        description: "Optional domains to restrict results to",
      },
    },
    required: ["query"],
  },
  strict: false,
};

const exa = new Exa(process.env.EXA_API_KEY);

async function runExaSearch(args: {
  query: string;
  num_results?: number;
  include_domains?: string[];
}): Promise<string> {
  const result = await exa.search(args.query, {
    type: "auto",
    numResults: args.num_results ?? 5,
    includeDomains: args.include_domains,
    contents: { highlights: true },
  });
  return result.results
    .map((r: any) => `${r.title} (${r.url}):\n${r.highlights?.[0] ?? ""}`)
    .join("\n\n");
}

3. Run the tool-call loop

The model returns a function_call output item when it wants to search. You execute the call, then send the result back as a function_call_output with the call's call_id. In Python:

import json
from openai import OpenAI

client = OpenAI()

def ask(question: str) -> str:
    input_items = [{"role": "user", "content": question}]
    while True:
        response = client.responses.create(
            model="gpt-4.1",
            input=input_items,
            tools=[exa_tool],
        )
        if response.status == "completed" and not any(
            item.type == "function_call" for item in response.output
        ):
            return response.output_text
        input_items += response.output
        for item in response.output:
            if item.type == "function_call":
                args = json.loads(item.arguments)
                result = run_exa_search(args)
                input_items.append({
                    "type": "function_call_output",
                    "call_id": item.call_id,
                    "output": result,
                })

And the same loop in TypeScript:

import OpenAI from "openai";

const openai = new OpenAI();

export async function ask(question: string): Promise<string> {
  const inputItems: any[] = [{ role: "user", content: question }];
  for (;;) {
    const response = await openai.responses.create({
      model: "gpt-4.1",
      input: inputItems,
      tools: [exaTool],
    });
    const calls = response.output.filter((i: any) => i.type === "function_call");
    if (response.status === "completed" && calls.length === 0) {
      return response.output_text;
    }
    inputItems.push(...response.output);
    for (const call of calls) {
      const result = await runExaSearch(JSON.parse(call.arguments));
      inputItems.push({
        type: "function_call_output",
        call_id: call.call_id,
        output: result,
      });
    }
  }
}

4. Choose the search type per workload

Exa's search types trade latency for depth, and the price follows. Exa's Search quickstart gives typical latencies of about 200 ms for lite, about 1 second for auto, about 4 seconds for deep-lite, and 4 to 15 seconds for deep. Exa's pricing page lists lite at $4 per 1,000 requests, auto at $7 per 1,000, and deep-lite and deep at $12 per 1,000. Each base price includes up to 10 results; results above 10 cost $1 per 1,000 results, and AI page summaries cost $1 per 1,000 pages. For an agent loop, auto is a sensible default; drop to lite when the loop makes many calls per turn. Note that lite rejects outputSchema and summaries, so if you want synthesized, cited answers, use auto or a deep type and expect about 2 seconds of extra synthesis latency.

5. When to reach for Exa instead of a built-in web search

OpenAI also documents a built-in web search tool for the Responses API. Exa earns its place as the tool when you need any of the following:

  • People and company search. Exa's index covers company pages, team pages, and profiles, with a dedicated category for companies and people.
  • Full page contents in the same call. The base /search price includes text and highlights for up to 10 results, billed once, so the model gets passages from each page in the same response.
  • Date filters. startPublishedDate and endPublishedDate constrain results to a publish window, which matters for news and changelog monitoring.
  • Domain scoping. includeDomains accepts path prefixes like example.com/docs, so an agent can restrict itself to one vendor's official documentation. The Search reference lists every supported filter.
  • Control over the results. You choose the search type, result count, and content format per call, and your executor decides exactly what text goes back to the model.

Common pitfalls

  • Mixing SDK casing. exa_py takes snake_case (num_results, include_domains); exa-js and the REST API take camelCase (numResults, includeDomains). In Python a wrong-cased argument raises an error; in TypeScript and REST, use camelCase or the option may not take effect.
  • Forgetting the function_call_output. If you append the model's function_call to input but never append the output, the next request errors or the model stalls. Every call_id needs a matching output.
  • Returning raw JSON blobs. Exa responses include metadata the model does not need. Flatten to title, URL, and highlight text to keep prompts small.
  • Using type="lite" with structured output. lite rejects outputSchema with a 400. Use auto or a Deep type when you need schema-shaped output.
  • Letting the tool definition and executor drift apart. Keep the tool definition and executor together so a parameter change updates both.

Frequently Asked Questions

Do I need the Exa MCP server instead?

No, not for the Responses API. Exa's hosted MCP server is the better fit for MCP-native clients or when you want one shared tool across several agents. A function tool gives you direct control over search parameters inside your own loop.

Can the model call Exa multiple times in one turn?

Yes. The loop above handles it: each function_call in response.output gets executed and returned, and the model can issue another call before producing its final answer.

How do I keep results fresh?

Set startPublishedDate for a publish window, or use maxAgeHours to limit how old cached page content can be. Note that maxAgeHours is rejected on lite. A value of 0 requires content fetched within the last 60 seconds, not necessarily a new fetch for each request. Positive values set a cache-age threshold for refreshing content. Fresh fetching can add latency.

What does this cost at agent scale?

An agent making 50 searches a day makes 1,500 searches over a 30-day month. At $4 per 1,000 lite requests that is $6.00, and at $7 per 1,000 auto requests it is $10.50. Both figures assume 10 or fewer results per search (the executor above asks for 5) and no AI summaries; results above 10 cost $1 per 1,000 results, and summaries cost $1 per 1,000 pages. The free tier's $10 monthly credit covers up to 2,500 lite searches.

Conclusion

Exa slots into a Responses API app as one JSON Schema tool definition and one executor function, in either Python or TypeScript. The loop is standard function calling: the model asks, your code searches, the results go back with their call_id. Start with auto, flatten the results to highlights, and add date and domain filters where your agent needs precision. The Exa docs cover the rest of the surface, from Deep Search to the Contents API, when your agent outgrows plain search.

Related Articles