> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Building Agents with Exa Web Search

> Create intelligent agents with real-time web search capabilities using Exa integration

This guide covers how to build AI agents with powerful web search capabilities using Exa integration. Exa provides semantic search that understands the meaning of queries, enabling agents to find highly relevant, up-to-date information from across the web.

> [!NOTE]
>
> Exa-powered agents can search the web semantically, find current information, and cite sources—making them ideal for research, fact-checking, and knowledge-intensive tasks.

## Quick Start

> [tab] Python
>
> ```python theme={null}
> import requests
> import os
>
> API_KEY = os.getenv("SWARMS_API_KEY")
> BASE_URL = "https://api.swarms.world"
>
> headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json"
> }
>
> payload = {
>     "agent_config": {
>         "agent_name": "Research Agent",
>         "description": "AI research assistant with web search capabilities",
>         "system_prompt": """You are an expert research assistant with access to web search.
>         When answering questions:
>         1. Search for relevant, current information
>         2. Synthesize findings from multiple sources
>         3. Cite your sources clearly
>         4. Distinguish between facts and analysis""",
>         "model_name": "gpt-4.1",
>         "max_tokens": 4096,
>         "temperature": 0.3
>     },
>     "task": "What are the latest breakthroughs in nuclear fusion energy in 2024?",
>     "tools_enabled": ["auto_search"]
> }
>
> response = requests.post(
>     f"{BASE_URL}/v1/agent/completions",
>     headers=headers,
>     json=payload
> )
>
> result = response.json()
> print(result['outputs'])
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const API_KEY = process.env.SWARMS_API_KEY;
> const BASE_URL = "https://api.swarms.world";
>
> const headers = {
>     "x-api-key": API_KEY,
>     "Content-Type": "application/json"
> };
>
> const payload = {
>     agent_config: {
>         agent_name: "Research Agent",
>         description: "AI research assistant with web search capabilities",
>         system_prompt: `You are an expert research assistant with access to web search.
>         When answering questions:
>         1. Search for relevant, current information
>         2. Synthesize findings from multiple sources
>         3. Cite your sources clearly
>         4. Distinguish between facts and analysis`,
>         model_name: "gpt-4.1",
>         max_tokens: 4096,
>         temperature: 0.3
>     },
>     task: "What are the latest breakthroughs in nuclear fusion energy in 2024?",
>     tools_enabled: ["auto_search"]
> };
>
> fetch(`${BASE_URL}/v1/agent/completions`, {
>     method: 'POST',
>     headers: headers,
>     body: JSON.stringify(payload)
> })
> .then(response => response.json())
> .then(data => {
>     console.log("Research Results:", data.outputs);
> })
> .catch(error => console.error('Error:', error));
> ```

> [tab] cURL
>
> ```bash theme={null}
> curl -X POST "https://api.swarms.world/v1/agent/completions" \
>   -H "x-api-key: your-api-key" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "agent_config": {
>       "agent_name": "Research Agent",
>       "description": "AI research assistant with web search capabilities",
>       "system_prompt": "You are an expert research assistant with access to web search. Search for relevant information, synthesize findings, and cite sources.",
>       "model_name": "gpt-4.1",
>       "max_tokens": 4096,
>       "temperature": 0.3
>     },
>     "task": "What are the latest breakthroughs in nuclear fusion energy in 2024?",
>     "tools_enabled": ["auto_search"]
>   }'
> ```

## Exa Search Configuration

Exa provides semantic search capabilities that go beyond keyword matching. Web search is enabled per-request by adding `"auto_search"` to the `tools_enabled` list on the agent completion body (a sibling of `agent_config`, not a field inside it).

### Configuration Options

| Parameter | Type | Default | Description |
| - | - | - | - |
| `tools_enabled` | array of strings | `null` | List of tools to enable. Include `"auto_search"` to give the agent Exa-powered web search. |

Search depth and result formatting are controlled by the agent itself (via its `system_prompt` and reasoning), not by request-level parameters — there are no `exa_search_num_results` or `exa_search_max_characters` fields to tune.

### Recommended Configuration

Enable search the same way regardless of how much research the task needs — depth is a function of the task and system prompt, not a tunable request parameter:

```python theme={null}
{
    "tools_enabled": ["auto_search"]
}
```

## Use Cases

### Market Research Agent

```python theme={null}
payload = {
    "agent_config": {
        "agent_name": "Market Research Analyst",
        "description": "Analyzes market trends and competitive landscape",
        "system_prompt": """You are a senior market research analyst.
        Research current market conditions, identify trends, and provide
        data-driven insights. Always cite sources and distinguish between
        confirmed data and market speculation.""",
        "model_name": "gpt-4.1",
        "max_tokens": 4096,
        "temperature": 0.2
    },
    "task": "Analyze the current state of the electric vehicle market in Europe, including major players, market share, and growth projections.",
    "tools_enabled": ["auto_search"]
}
```

### Technical Documentation Research

```python theme={null}
payload = {
    "agent_config": {
        "agent_name": "Technical Researcher",
        "description": "Researches technical topics and documentation",
        "system_prompt": """You are a technical research specialist.
        Find accurate, up-to-date technical information from official
        documentation, reputable tech publications, and authoritative sources.
        Provide code examples when relevant.""",
        "model_name": "gpt-4.1",
        "max_tokens": 4096,
        "temperature": 0.1
    },
    "task": "What are the new features in Python 3.12 and how do they improve performance?",
    "tools_enabled": ["auto_search"]
}
```

### News and Current Events

```python theme={null}
payload = {
    "agent_config": {
        "agent_name": "News Analyst",
        "description": "Analyzes current events and news",
        "system_prompt": """You are a news analyst who provides balanced,
        factual summaries of current events. Cross-reference multiple sources,
        note any conflicting reports, and clearly separate facts from opinions.""",
        "model_name": "gpt-4.1",
        "max_tokens": 3000,
        "temperature": 0.3
    },
    "task": "What are the latest developments in AI regulation globally?",
    "tools_enabled": ["auto_search"]
}
```

### Academic Research Assistant

```python theme={null}
payload = {
    "agent_config": {
        "agent_name": "Academic Research Assistant",
        "description": "Assists with academic research and literature review",
        "system_prompt": """You are an academic research assistant.
        Find peer-reviewed sources, academic papers, and scholarly articles.
        Summarize key findings, note methodologies, and identify research gaps.
        Always provide proper citations.""",
        "model_name": "gpt-4.1",
        "max_tokens": 5000,
        "temperature": 0.2
    },
    "task": "What does recent research say about the effectiveness of spaced repetition for language learning?",
    "tools_enabled": ["auto_search"]
}
```

## Using Exa with Multi-Agent Systems

Combine Exa search with multi-agent architectures for sophisticated research workflows.

> [!NOTE]
>
> `tools_enabled` (and therefore `auto_search`) is only available on `/v1/agent/completions` (single-agent runs). The `/v1/swarm/completions` endpoint has no `tools_enabled` field, so web search cannot be enabled directly on a swarm — give individual agents search-oriented system prompts, or run a search-enabled single agent as a preprocessing step and feed its findings into the swarm's task.

### Research Team with Specialized Agents

```python theme={null}
from swarms_client import SwarmsClient
import os

client = SwarmsClient(api_key=os.getenv("SWARMS_API_KEY"))

research_team = client.swarms.run(
    name="Comprehensive Research Team",
    description="Multi-agent research system with web search",
    swarm_type="SequentialWorkflow",
    task="Analyze the potential impact of quantum computing on cybersecurity over the next decade.",
    agents=[
        {
            "agent_name": "Technical Researcher",
            "description": "Researches technical aspects and current state",
            "system_prompt": """Research the current state of quantum computing,
            focusing on technical capabilities, limitations, and timeline projections.
            Use web search to find the latest developments.""",
            "model_name": "gpt-4.1",
            "role": "researcher",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.2
        },
        {
            "agent_name": "Security Analyst",
            "description": "Analyzes cybersecurity implications",
            "system_prompt": """Analyze cybersecurity implications based on the
            technical research provided. Identify vulnerabilities, potential threats,
            and required adaptations in security protocols.""",
            "model_name": "gpt-4.1",
            "role": "analyst",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.3
        },
        {
            "agent_name": "Strategic Advisor",
            "description": "Synthesizes findings into recommendations",
            "system_prompt": """Synthesize the technical research and security analysis
            into actionable strategic recommendations. Provide a timeline for action
            and prioritize recommendations by urgency and impact.""",
            "model_name": "gpt-4.1",
            "role": "advisor",
            "max_loops": 1,
            "max_tokens": 5000,
            "temperature": 0.4
        }
    ]
)

print(research_team)
```

## Best Practices

### 1. Craft Effective Search-Oriented Prompts

Structure your system prompts to leverage search capabilities:

```python theme={null}
system_prompt = """You are a research assistant with web search capabilities.

When responding to queries:
1. SEARCH: First search for relevant, current information
2. VERIFY: Cross-reference findings across multiple sources
3. SYNTHESIZE: Combine information into a coherent response
4. CITE: Always mention your sources
5. QUALIFY: Note any uncertainties or conflicting information

Prioritize recent sources (within the last year) for time-sensitive topics."""
```

### 2. Match Prompt Depth to Task Complexity

Since `auto_search` has no tunable result-count or snippet-length parameters, control research depth through the system prompt instead — instruct the agent how many sources to consult and how thoroughly to synthesize them for the task at hand (quick fact lookup vs. comprehensive analysis).

### 3. Use Appropriate Temperature Settings

* **Factual research** (0.1-0.2): When accuracy is critical
* **Balanced analysis** (0.3-0.4): For synthesis and interpretation
* **Creative exploration** (0.5-0.7): For brainstorming and ideation

### 4. Handle Time-Sensitive Information

For topics where recency matters, include temporal context in your task:

```python theme={null}
"task": "What are the latest AI safety developments from the past 3 months?"
```

### 5. Request Source Citations

Include citation requirements in your system prompt:

```python theme={null}
system_prompt = """...
Always cite sources in your response using this format:
- [Source Name](URL) - Key finding from this source

End your response with a 'Sources' section listing all references."""
```

## Error Handling

```python theme={null}
import requests
import time

def search_with_retry(payload, headers, max_retries=3):
    """Execute search request with exponential backoff retry."""
    base_url = "https://api.swarms.world"

    for attempt in range(max_retries):
        try:
            response = requests.post(
                f"{base_url}/v1/agent/completions",
                headers=headers,
                json=payload,
                timeout=120  # Longer timeout for search operations
            )

            if response.status_code == 200:
                result = response.json()
                return {
                    "success": True,
                    "outputs": result.get("outputs"),
                    "usage": result.get("usage")
                }

            elif response.status_code == 429:
                # Rate limited - wait and retry
                wait_time = 2 ** attempt
                print(f"Rate limited. Waiting {wait_time}s before retry...")
                time.sleep(wait_time)
                continue

            elif response.status_code == 503:
                # Service temporarily unavailable
                wait_time = 5 * (attempt + 1)
                print(f"Service unavailable. Waiting {wait_time}s...")
                time.sleep(wait_time)
                continue

            else:
                return {
                    "success": False,
                    "error": f"HTTP {response.status_code}: {response.text}"
                }

        except requests.exceptions.Timeout:
            print(f"Request timed out. Attempt {attempt + 1}/{max_retries}")
            continue

        except requests.exceptions.ConnectionError:
            print(f"Connection error. Attempt {attempt + 1}/{max_retries}")
            time.sleep(2 ** attempt)
            continue

    return {
        "success": False,
        "error": "Max retries exceeded"
    }

# Usage
result = search_with_retry(payload, headers)
if result["success"]:
    print(result["outputs"])
else:
    print(f"Error: {result['error']}")
```

## Response Format

Search-enabled agents return the standard `/v1/agent/completions` response shape. The `outputs` field contains the agent's final synthesized answer (including any citations the agent chose to include in its text) — there is no separate structured `search_results` array; source handling happens inside the agent's tool call and reasoning, not as a distinct response field.

```json theme={null}
{
  "job_id": "agent-...",
  "success": true,
  "name": "Research Agent",
  "outputs": "Your comprehensive research response with synthesized information...",
  "usage": {
    "input_tokens": 500,
    "output_tokens": 1200,
    "total_tokens": 1700,
    "image_count": 0,
    "img_cost": 0.0,
    "flash_sale_applied": false,
    "total_cost": 0.05219
  },
  "timestamp": "2024-01-15T00:00:00Z"
}
```

Note: the `total_cost` in `usage` is the whole charge for the request: the token cost at the agent's model price (15% service fee included; the sample above assumes `gpt-4.1`, so \$0.01219 of tokens), plus any image fees, plus the flat \$0.04 `auto_search` fee. The search fee is billed in the same charge as the tokens, after the run succeeds; a failed run isn't charged it.

## Cost Optimization

Enabling `auto_search` costs a flat \$0.04 (`search_cost`) once per request, however many searches the agent runs (including none), on top of normal token costs. It is charged together with the tokens only after a successful run, and is included in `usage.total_cost`. Optimize usage with these strategies:

1. **Only enable search when needed**: Omit `tools_enabled` (or leave `auto_search` out of it) for tasks that don't require live web data — you'll skip the \$0.04 fee entirely.
2. **Cache research results**: Store responses for repeated similar queries instead of re-running search.
3. **Use appropriate models**: Each model bills at its own price; `gpt-4.1-mini` costs a fifth of `gpt-4.1` per token at the time of writing, so use it for simpler research tasks. Check prices with `GET /v1/models/pricing` (see [Pricing](https://docs.swarms.ai/docs/documentation/resources/pricing.md)).
4. **Limit output length**: Set a smaller `max_tokens` on `agent_config` to control response length and cost.

```python theme={null}
# Cost-efficient configuration for simple queries
efficient_config = {
    "agent_config": {
        "model_name": "gpt-4.1-mini",  # Lower cost model
        "max_tokens": 2000             # Limit output length
    },
    "tools_enabled": ["auto_search"]
}
```

## Related Resources

* [Search-Enabled Agents](https://docs.swarms.ai/docs/examples/examples/search-enabled.md) - Basic search configuration
* [Multi-Agent Workflows](https://docs.swarms.ai/docs/documentation/multi-agent/available-architectures.md) - Combining search with swarms


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