Skip to content
AnswerWell geo Documentation

Research · 9 min read · Answerwell

Web Search API, Agent web_search Tool, Query Filters, and SDK Production

How Perplexity Search API and Agent API differ, how to filter results, and how to run the official SDKs in production with retries and async.

This page summarizes Perplexity documentation on retrieving ranked web results versus model-generated answers with search tools, tuning search requests, and operating the official Python and TypeScript SDKs in production.

Section titled “Search API vs Agent API: ranked results or answers with web_search”

The Search API exposes one endpoint, POST https://api.perplexity.ai/search, with a bearer token (PERPLEXITY_API_KEY). You send a query and receive structured ranked results—no generated answer and no token billing for generation:

The Search API is one endpoint, POST https://api.perplexity.ai/search. You send a query and get back ranked web results as structured data for your own code to filter, store, or hand to a model. There is no generated answer and no token billing.

— Perplexity, Search overview

Agent API fields such as model, effort, instructions, tools, and max_output_tokens do not belong on a search request:

The Search API request has one endpoint, POST https://api.perplexity.ai/search, and only the parameters in the API reference. Agent API fields such as model, effort, instructions, tools, and max_output_tokens are not part of a search request. The response is ranked results with titles, URLs, and extracted text; there is no generated answer. To have a model read the results, pass them to your own model or call the Agent API with the web_search tool instead.

— Perplexity, Search quickstart

The Agent API uses client.responses.create (HTTP POST https://api.perplexity.ai/v1/agent) and can attach tools. Enable live web lookup with tools=[{"type": "web_search"}]:

The Agent API provides access to a number of tools that can be used to extend the capabilities of the model.

Enable web search capabilities using the web_search tool:

— Perplexity, Agent API quickstart

Completed responses include search_results items (queries, titles, URLs, snippets) and an assistant message with synthesized text; usage records token costs and tool_calls_details.search_web invocations. For query discipline in instructions, the quickstart recommends telling the model when to search and to keep queries brief—see prompt the agent.

Goal API Client call You get
Raw URLs/snippets for your pipeline Search client.search.create(...) results[]; no assistant message
Answer + optional web_search tool loop Agent client.responses.create(..., tools=[...]) output with search_results and message
Legacy chat with grounding Sonar client.chat.completions.create(model="sonar", ...) Citations + search_results; see legacy filters

The SDK overview documents Python 3.10+ (perplexity) and Node 20+ (@perplexity-ai/perplexity_ai) clients for Search, Agent API, Embeddings, and legacy Sonar. Perplexity recommends native SDKs over raw OpenAI-compatible Sonar URLs for type safety and error handling (Sonar OpenAI compatibility).

Search API: client.search.create parameters and result fields

Section titled “Search API: client.search.create parameters and result fields”

Basic request and what each result contains

Section titled “Basic request and what each result contains”

Authenticate with Authorization: Bearer $PERPLEXITY_API_KEY and JSON Content-Type. In Python: from perplexity import Perplexity then client.search.create(query="...", max_results=5). Each hit includes title, url, snippet, date, and last_updated (Search overview). The snippet is query-relevant extracted text, trimmed by max_tokens_per_page:

Can be an empty string, so check it before you use the result.

— Perplexity, Search overview

max_results accepts values from 1 to 20 and defaults to 10 (Search quickstart).

Section titled “Regional bias, language, token budget, and fast search”

Set country to an ISO 3166-1 alpha-2 code (for example US, GB) for geographically relevant results (Search quickstart).

search_language_filter is an array of lowercase ISO 639-1 codes (for example ["en", "fr"]). Invalid codes cause API errors; the Search API allows up to 20 codes per request (Search language filter). Legacy Sonar filter docs list a 10-language cap on chat.completions.create (legacy filters).

Use max_tokens (total extracted content across all results, up to 1,000,000) and max_tokens_per_page to cap per-page extraction (Search quickstart).

For lower latency or cost, set search_type: "fast". Fast Search is priced at $1.00 per 1,000 requests in the quickstart; it requires Python library 0.43.6+ or TypeScript SDK 0.38.6+ (Search quickstart).

Search API best practices advise specific queries with context and time frames, multi-query batches (up to 5 queries in one request), requesting only needed max_results, caching non-real-time queries, and using AsyncPerplexity with batching and delays between batches.

search_language_filter, date filters, and search_recency_filter

Section titled “search_language_filter, date filters, and search_recency_filter”

Language filters work seamlessly with other search parameters for precise control.

— Perplexity, Search language filter

Use Valid Codes: Always use valid 2-letter ISO 639-1 codes. Invalid codes will result in an API error.

Lowercase Only: Language codes must be lowercase (e.g., “en” not “EN”).

— Perplexity, Search language filter

For best results, combine language filtering with other filters like search_domain_filter or search_recency_filter to narrow down your search to highly relevant, timely content in your target languages.

— Perplexity, Search language filter

The filter constrains content language, not the language of your query string—your query can be in one language while you restrict results to another.

Publication date, last updated, and recency windows

Section titled “Publication date, last updated, and recency windows”

On client.search.create, Perplexity documents (date and time filters):

Parameter Purpose
search_after_date_filter / search_before_date_filter Publication window; use one or both
last_updated_after_filter / last_updated_before_filter Content last updated in range
search_recency_filter hour, day, week, month, year without calendar dates

Examples use month/day/year strings such as 3/1/2025. For maintained pages:

This example limits search results to content that was last updated between July 1, 2025, and December 30, 2025. This is useful for finding recently maintained or refreshed content.

— Perplexity, Date and time filters

The search_recency_filter provides a convenient way to filter results by predefined time periods without specifying exact dates:

— Perplexity, Date and time filters

On legacy Sonar, date filters must use %m/%d/%Y, and search_recency_filter cannot be combined with other date filters (legacy filters).

search_domain_filter: allowlist, denylist, path, and TLD

Section titled “search_domain_filter: allowlist, denylist, path, and TLD”

Pass search_domain_filter as a string array on search.create (domain filter):

  • Allowlist hosts: ["nature.com", "science.org"] for authoritative publishers.
  • TLD: [".gov", ".edu"] for government or education sites.
  • Subdomains: wikipedia.org matches en.wikipedia.org, fr.wikipedia.org, and similar.
  • Path scope: nature.com/articles limits to that path.
  • Denylist: prefix with -, for example ["-pinterest.com", "-reddit.com"].

Domain filters work seamlessly with other search parameters for precise control.

— Perplexity, Domain filter

The Search News Monitor cookbook wires search_domain_filter, search_recency_filter, and polling; it rejects using both --domains and --exclude-domains together.

Agent API: web_search, streaming, and function calling

Section titled “Agent API: web_search, streaming, and function calling”

Enabling web_search and reading the response

Section titled “Enabling web_search and reading the response”

After client.responses.create, check response.status == "completed" (Python) and read response.output_text (Agent API quickstart). Set tool_choice: "auto" and parallel_tool_calls: true as in the documented examples.

Streaming vs non-streaming when search hits matter in the UI

Section titled “Streaming vs non-streaming when search hits matter in the UI”

Output control supports stream=True for partial response.output_text.delta events:

Streaming allows you to receive partial responses from the Perplexity API as they are generated, rather than waiting for the complete response. This is particularly useful for real-time user experiences, long responses, and interactive applications.

— Perplexity, Agent API output control

If the UI must show search results immediately:

If you need search results immediately for your user interface, consider using non-streaming requests for use cases where search result display is critical to the real-time user experience.

— Perplexity, Agent API output control

Catch APIConnectionError, RateLimitError, and APIStatusError while streaming (Agent API output control, SDK error handling).

The function calling end-to-end guide recommends returning structured errors in function_call_output ({"error": true, "message": "..."}), capping turns (for example max_turns = 10), running parallel function_call items with Promise.all or a thread pool, and never sending raw stack traces to the model.

For long Agent research jobs, async deep research limits concurrency:

Deep research queries consume significant compute resources. Keep concurrent requests to 3-5 to stay within rate limits and avoid throttling. Check your rate limits for specific thresholds.

— Perplexity, Async deep research

Production SDK: configuration, errors, retries, and throughput

Section titled “Production SDK: configuration, errors, retries, and throughput”

Environment variables and HTTP client settings

Section titled “Environment variables and HTTP client settings”

SDK best practices cover PERPLEXITY_API_KEY, optional PERPLEXITY_API_KEY_FALLBACK, and tunables such as PERPLEXITY_MAX_RETRIES, PERPLEXITY_TIMEOUT, PERPLEXITY_MAX_CONNECTIONS, and PERPLEXITY_MAX_KEEPALIVE. SDK configuration documents max_retries (default 2), granular httpx timeouts, proxies, and client.with_options(max_retries=5).

Use environment variables for configuration
Never hardcode API keys or configuration values.

— Perplexity, SDK best practices

The SDKs retry connection errors, 408, 409, 429, and 5xx twice by default, honoring Retry-After when present; Python only follows Retry-After values of 60 seconds or less (SDK error handling).

Always handle rate limits
Rate limiting is common with API usage. Always implement retry logic that waits for the Retry-After interval, with exponential backoff as a fallback.

Don’t implement aggressive retry loops without delays - this can worsen rate limiting.

— Perplexity, SDK error handling

Catch RateLimitError (429), AuthenticationError (401), and BadRequestError (400). Log X-Request-ID from APIStatusError responses. For automation, n8n integration suggests Wait nodes with exponential backoff on 429, credential checks on 401, and Retry on Fail for 500 responses.

SDK performance recommends AsyncPerplexity with asyncio.gather, semaphores for backpressure, and client.search.with_raw_response.create to read X-RateLimit-Remaining and X-RateLimit-Reset.

Type safety and legacy Sonar deep research

Section titled “Type safety and legacy Sonar deep research”

Use typed responses such as SearchCreateResponse and SearchResult from perplexity.types (Type safety). Search responses use a top-level results array; Sonar chat completions use search_results in the message payload—do not confuse the two when mapping DTOs.

For investigative reports on legacy Sonar, model: "sonar-deep-research" on POST https://api.perplexity.ai/v1/sonar supports reasoning_effort of low, medium, or high (Sonar Deep Research):

Control the computational effort dedicated to each query with the reasoning_effort parameter. This allows you to balance between speed and thoroughness while managing costs by directly impacting the amount of reasoning tokens consumed.

— Perplexity, Sonar Deep Research

Doc samples show large reasoning_tokens and num_search_queries counts driving cost; prefer Agent API or Search API for new integrations unless you explicitly need that Sonar model.

The pplx CLI prints JSON errors on stderr with error.code values such as AUTHENTICATION, RATE_LIMIT, and BAD_REQUEST (CLI overview).

  • Sending model, tools, or instructions on Search API requests.
  • Assuming every snippet is non-empty.
  • Uppercase language codes or more than 20 languages on Search requests.
  • Mixing search_recency_filter with explicit date filters on legacy Sonar.
  • Aggressive retries without backoff or ignoring Retry-After.
  • Streaming Agent responses when the UI must show search_results immediately.
  • Using both domain allowlist and exclude flags in the news monitor pattern.
  • Treating doc sample result URLs as proof that filters always exclude every other host.
  1. Set PERPLEXITY_API_KEY and call POST https://api.perplexity.ai/search with a minimal query; confirm results[].title, url, and snippet per Search quickstart and Search overview.

  2. Run one Agent API request with tools=[{"type": "web_search"}] per Agent API quickstart; verify status === "completed" and search_results in output.

  3. Repeat search with search_language_filter: ["en"], then with search_domain_filter and search_recency_filter: "week" per language filter and domain filter; inspect each hit’s host and dates.

  4. Trigger or simulate rate limiting and confirm your client respects Retry-After per SDK error handling; optionally read limit headers via SDK performance.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about so it can be corrected.