> ## Documentation Index
> Fetch the complete documentation index at: https://perplexity-cf-proxied-beta.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tools

> Web search, URL fetching, and function calling tools for the Agent API

## Overview

The Agent API provides tools that extend model capabilities beyond their training data. Tools must be explicitly configured in your API request—once enabled, models autonomously decide when to use them based on your instructions.

| Type         | Tools                     | Use Case                                   |
| ------------ | ------------------------- | ------------------------------------------ |
| **Built-in** | `web_search`, `fetch_url` | Real-time web information retrieval        |
| **Custom**   | Your functions            | Connect to databases, APIs, business logic |

Enable tools by adding them to the `tools` array in your request:

<CodeGroup>
  ```python Python theme={null}
  from perplexity import Perplexity

  client = Perplexity()

  response = client.responses.create(
      model="openai/gpt-5.2",
      input="What are the latest AI developments?",
      tools=[
          {"type": "web_search"},
          {"type": "fetch_url"}
      ],
      instructions="Use web_search for current information. Use fetch_url when you need full article content."
  )

  print(response.output_text)
  ```

  ```typescript TypeScript theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  const response = await client.responses.create({
      model: "openai/gpt-5.2",
      input: "What are the latest AI developments?",
      tools: [
          { type: "web_search" as const },
          { type: "fetch_url" as const }
      ],
      instructions: "Use web_search for current information. Use fetch_url when you need full article content."
  });

  console.log(response.output_text);
  ```
</CodeGroup>

## Web Search Tool

The `web_search` tool allows models to perform web searches with advanced filtering capabilities. Use it when you need current information, news, or data beyond the model's training cutoff.

**Pricing:** \$5.00 per 1,000 search calls (\$0.005 per search), plus token costs.

### Example

<CodeGroup>
  ```python Python theme={null}
  from perplexity import Perplexity

  client = Perplexity()

  response = client.responses.create(
      model="openai/gpt-5.2",
      input="What are recent academic findings on renewable energy?",
      tools=[
          {
              "type": "web_search",
              "filters": {
                  "search_domain_filter": ["nature.com", "science.org", ".edu"],
                  "search_recency_filter": "month"
              }
          }
      ],
      instructions="Search for recent English-language academic publications."
  )

  print(response.output_text)
  ```

  ```typescript TypeScript theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  const response = await client.responses.create({
      model: "openai/gpt-5.2",
      input: "What are recent academic findings on renewable energy?",
      tools: [
          {
              type: "web_search" as const,
              filters: {
                  search_domain_filter: ["nature.com", "science.org", ".edu"],
                  search_recency_filter: "month"
              }
          }
      ],
      instructions: "Search for recent English-language academic publications."
  });

  console.log(response.output_text);
  ```
</CodeGroup>

### Key Parameters

| Filter                  | Type             | Description                                                        | Limit          |
| ----------------------- | ---------------- | ------------------------------------------------------------------ | -------------- |
| `search_domain_filter`  | Array of strings | Filter by specific domains (allowlist or denylist with `-` prefix) | Max 20 domains |
| `search_recency_filter` | String           | Filter by time period: `"day"`, `"week"`, `"month"`, `"year"`      | -              |
| `search_after_date`     | String           | Filter results published after this date (format: `"M/D/YYYY"`)    | -              |
| `search_before_date`    | String           | Filter results published before this date (format: `"M/D/YYYY"`)   | -              |
| `max_tokens_per_page`   | Integer          | Control the amount of content retrieved per search result          | -              |

<Tip>
  Use `-` prefix to exclude domains: `"-reddit.com"` excludes Reddit from results. Lower `max_tokens_per_page` to reduce context token costs.
</Tip>

## Fetch URL Tool

The `fetch_url` tool fetches and extracts content from specific URLs. Use it when you need the full content of a particular web page, article, or document rather than search results.

**Pricing:** \$0.50 per 1,000 requests (\$0.0005 per fetch), plus token costs.

### Example

<CodeGroup>
  ```python Python theme={null}
  from perplexity import Perplexity

  client = Perplexity()

  response = client.responses.create(
      model="openai/gpt-5.2",
      input="Summarize the content at https://example.com/article",
      tools=[
          {
              "type": "fetch_url"
          }
      ],
      instructions="Use fetch_url to retrieve and summarize the article."
  )

  print(response.output_text)
  ```

  ```typescript TypeScript theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  const response = await client.responses.create({
      model: "openai/gpt-5.2",
      input: "Summarize the content at https://example.com/article",
      tools: [
          {
              type: "fetch_url" as const
          }
      ],
      instructions: "Use fetch_url to retrieve and summarize the article."
  });

  console.log(response.output_text);
  ```
</CodeGroup>

### When to Use

| Use `fetch_url` when...         | Use `web_search` when...                |
| ------------------------------- | --------------------------------------- |
| You have a specific URL         | You need to find relevant pages         |
| You need full page content      | You need snippets from multiple sources |
| Analyzing a particular document | Researching a broad topic               |
| Verifying specific claims       | Finding current news or events          |

<Tip>
  Combine `web_search` and `fetch_url` for comprehensive research: search to find relevant pages, then fetch full content from the most relevant results.
</Tip>

## Function Calling

Function calling allows you to define custom functions that models can invoke during a conversation. Unlike built-in tools, custom functions let you connect the model to your own systems—databases, APIs, business logic, or any external service.

**Pricing:** No additional cost (standard token pricing applies).

### How It Works

Function calling follows a multi-turn conversation pattern:

1. Define functions with names, descriptions, and parameter schemas
2. Send your prompt with function definitions
3. Model returns a `function_call` item if it needs to call a function
4. Execute the function in your code
5. Return results as a `function_call_output` item
6. Model uses the results to generate its final response

### Example

<CodeGroup>
  ```python Python theme={null}
  from perplexity import Perplexity
  import json

  client = Perplexity()

  # Define your function tools
  tools = [
      {
          "type": "function",
          "name": "get_horoscope",
          "description": "Get today's horoscope for an astrological sign.",
          "parameters": {
              "type": "object",
              "properties": {
                  "sign": {
                      "type": "string",
                      "description": "An astrological sign like Taurus or Aquarius"
                  }
              },
              "required": ["sign"]
          }
      }
  ]

  # Your actual function implementation
  def get_horoscope(sign: str) -> str:
      return f"{sign}: Today brings new opportunities for growth."

  # Send initial request with tools
  response = client.responses.create(
      model="openai/gpt-5.2",
      tools=tools,
      input="What is my horoscope? I am an Aquarius."
  )

  # Process the response and handle function calls
  next_input = [item.model_dump() for item in response.output]

  for item in response.output:
      if item.type == "function_call":
          # Execute the function
          args = json.loads(item.arguments)
          result = get_horoscope(args["sign"])

          # Add the function result to the input
          next_input.append({
              "type": "function_call_output",
              "call_id": item.call_id,
              "output": json.dumps({"horoscope": result})
          })

  # Send the function results back to get the final response
  final_response = client.responses.create(
      model="openai/gpt-5.2",
      input=next_input
  )

  print(final_response.output_text)
  ```

  ```typescript TypeScript theme={null}
  import Perplexity from '@perplexity-ai/perplexity_ai';

  const client = new Perplexity();

  // Define your function tools
  const tools = [
      {
          type: "function" as const,
          name: "get_horoscope",
          description: "Get today's horoscope for an astrological sign.",
          parameters: {
              type: "object",
              properties: {
                  sign: {
                      type: "string",
                      description: "An astrological sign like Taurus or Aquarius"
                  }
              },
              required: ["sign"]
          }
      }
  ];

  // Your actual function implementation
  function getHoroscope(sign: string): string {
      return `${sign}: Today brings new opportunities for growth.`;
  }

  // Send initial request with tools
  const response = await client.responses.create({
      model: "openai/gpt-5.2",
      tools: tools,
      input: "What is my horoscope? I am an Aquarius."
  });

  // Process the response and handle function calls
  const nextInput: any[] = response.output.map(item => ({ ...item }));

  for (const item of response.output) {
      if (item.type === "function_call") {
          // Execute the function
          const args = JSON.parse(item.arguments);
          const result = getHoroscope(args.sign);

          // Add the function result to the input
          nextInput.push({
              type: "function_call_output",
              call_id: item.call_id,
              output: JSON.stringify({ horoscope: result })
          });
      }
  }

  // Send the function results back to get the final response
  const finalResponse = await client.responses.create({
      model: "openai/gpt-5.2",
      input: nextInput
  });

  console.log(finalResponse.output_text);
  ```
</CodeGroup>

### Key Properties

| Property      | Type    | Required | Description                                                    |
| ------------- | ------- | -------- | -------------------------------------------------------------- |
| `type`        | string  | Yes      | Must be `"function"`                                           |
| `name`        | string  | Yes      | Function name the model will use to call it                    |
| `description` | string  | Yes      | Clear description of what the function does and when to use it |
| `parameters`  | object  | Yes      | JSON Schema defining the function's parameters                 |
| `strict`      | boolean | No       | Enable strict schema validation                                |

<Warning>
  The `arguments` field in function calls is a JSON string, not a parsed object. Always use `json.loads()` (Python) or `JSON.parse()` (JavaScript) to parse it.
</Warning>

<Tip>
  Write clear, specific function descriptions. The model uses these to decide when to call each function. Include details about what the function returns and any constraints.
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="Agent API Quickstart" icon="rocket" href="/docs/agent-api/quickstart">
    Get started with the Agent API.
  </Card>

  <Card title="Models" icon="brain" href="/docs/agent-api/models">
    Explore direct model selection and third-party models.
  </Card>

  <Card title="API Reference" icon="code-circle" href="/api-reference/responses-post">
    View complete endpoint documentation.
  </Card>

  <Card title="Output Control" icon="indent-decrease" href="/docs/agent-api/output-control">
    Configure streaming responses and structured outputs with JSON schema.
  </Card>
</CardGroup>
