AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Building Grounded AI Agents with Perplexity Sonar API: Domain Filtering and Streaming Citations

Rubén Arteaga · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Integrating live internet retrieval into enterprise chatbots, internal copilots, and automated research agents is notoriously difficult. Building an in-house web Retrieval-Augmented Generation (RAG) pipeline—complete with headless browser scrapers, anti-bot bypass proxies, HTML DOM parsers, vector databases, and cross-encoder re-rankers—demands months of engineering effort and incurs significant operational costs. Worse, custom pipelines often struggle to align generated text with verifiable source URLs, leading to subtle hallucinations and ungrounded citations.

Perplexity AI solves this architectural bottleneck through its official Sonar API. By collapsing web crawling, real-time search indexing, document parsing, and factual synthesis into a single REST endpoint, developers can query the live internet and stream grounded responses with verifiable citations.

At 365Finds, our research recommendation is direct: for dynamic web Q&A, competitor monitoring, and market research bots, assembling a bespoke web scraping and vector RAG stack is an expensive anti-pattern. Outsource real-time web retrieval to Perplexity AI's Sonar models. However, enterprise reliability depends on two technical pillars: strictly calibrating retrieval boundaries with search_domain_filter and reliably handling the Server-Sent Events (SSE) citation streaming pipeline.


Sonar vs. Sonar Pro: Latency, Cost, and Reasoning Trade-offs

Perplexity AI provides two primary tiers for search-grounded completions:

Capability / MetricSonar (sonar)Sonar Pro (sonar-pro)
Base ArchitectureLightweight search-optimized modelFrontier reasoning model with deep search
Input Pricing$1.00 per 1M tokens$3.00 per 1M tokens
Output Pricing$1.00 per 1M tokens$15.00 per 1M tokens
Search Request Fee$5.00 per 1,000 requests (low context); $8.00 per 1,000 (medium)$6.00 per 1,000 requests (low context); $10.00–$14.00+ (medium / pro)
Context WindowUp to 127k tokensUp to 200k tokens
Max Output TokensStandard response (~4k tokens)Extended response (~8k tokens)
Query StrategySingle-pass targeted searchMulti-query decomposition; iterative retrieval
Best Used ForReal-time user Q&A; customer support; latency-sensitive botsDeep industry research; complex multi-source synthesis; compliance

365Finds Model Selection Verdict


API Authentication and Endpoints

Perplexity AI exposes its models through OpenAI-compatible interfaces as well as the native Agent API (/v1/agent or /v1/responses).

  1. Log in to the Perplexity API Portal and generate a secure API key.
  2. Set the key in your local or container environment:
    export PERPLEXITY_API_KEY="pplx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    
  3. Target the chat completions endpoint:
    • Chat Completions: https://api.perplexity.ai/chat/completions (or Orchestrator: https://api.perplexity.ai/orchestrator/v1/chat/completions)
    • Agent API: https://api.perplexity.ai/v1/agent

Mastering search_domain_filter

Unrestricted internet searches often pollute language models with SEO blog spam, forum speculation, and paywalled fluff. The search_domain_filter parameter allows backend developers to enforce strict boundary controls on what the model can crawl and cite.

Core Syntax and Rules

The search_domain_filter parameter accepts an array of strings subject to three strict constraints:

  1. Mutually Exclusive Modes: You must use either an allowlist (include only) or a denylist (exclude), but never combine them in the same request.
  2. Maximum of 20 Domains: The array cannot exceed 20 domain or path entries.
  3. No Protocol Prefixes: Always provide domains as clean hostnames (e.g., "github.com", not "https://github.com").

1. Allowlist Filtering (Precision Mode)

Use plain domain strings to restrict the retrieval engine exclusively to verified, high-trust sources:

{
  "model": "sonar",
  "messages": [
    {"role": "user", "content": "How do I configure connection pooling in async SQLAlchemy?"}
  ],
  "search_domain_filter": [
    "docs.sqlalchemy.org",
    "github.com",
    "docs.python.org"
  ]
}

Root domain definitions automatically match all subdomains. Specifying "wikipedia.org" covers en.wikipedia.org, de.wikipedia.org, and all localized variants.

2. Denylist Filtering (Noise Reduction Mode)

Prefix domain names with a hyphen (-) to exclude unverified social commentary, clickbait farms, and community forums while leaving the rest of the open web accessible:

{
  "model": "sonar",
  "messages": [
    {"role": "user", "content": "What are the latest enterprise security vulnerabilities in Kubernetes?"}
  ],
  "search_domain_filter": [
    "-reddit.com",
    "-twitter.com",
    "-x.com",
    "-quora.com",
    "-medium.com"
  ]
}

3. Path-Level and TLD Filtering

4. Recency Filtering

Combine domain controls with search_recency_filter to discard stale results:


Streaming Citations via Server-Sent Events (SSE)

When streaming is enabled ("stream": true), Perplexity AI transmits text tokens and structured metadata over an HTTP Server-Sent Events connection.

How Citations Flow in the Stream

  1. Content Deltas: As the model generates text, incremental chunks arrive via standard delta fields (choices[0].delta.content or response.output_text.delta).
  2. Inline Citation Markers: The model directly embeds bracketed numeric markers (such as [1], [2], or [1][2]) directly into the prose stream immediately following the factual claim.
  3. Structured Citation Payloads: The corresponding source URLs arrive either attached to the completion metadata (in citations array) or via dedicated response.reasoning.search_results event payloads containing id, title, and url.
  4. Resolution Rule: In multi-step research or deep reasoning modes, the search engine may trigger multiple search rounds. Always accumulate search results into an append-only registry rather than overwriting on each event; otherwise, later references like [5] will become dangling pointers.

Complete Python Production Implementation

The following production-ready script connects to the Sonar API, applies domain filtering, streams text chunks to the terminal in real time, and dynamically transforms inline [N] references into interactive Markdown hyperlinks.

import json
import os
import re
import requests

API_KEY = os.environ.get("PERPLEXITY_API_KEY")
ENDPOINT = "https://api.perplexity.ai/chat/completions"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

payload = {
    "model": "sonar",
    "messages": [
        {
            "role": "system",
            "content": "You are an expert software architect. Cite factual claims using bracketed numbers."
        },
        {
            "role": "user",
            "content": "What are the latest production features and deprecations in FastAPI?"
        }
    ],
    "search_domain_filter": [
        "fastapi.tiangolo.com",
        "github.com",
        "pypi.org"
    ],
    "search_recency_filter": "month",
    "stream": True
}

def stream_grounded_search():
    if not API_KEY:
        raise ValueError("PERPLEXITY_API_KEY environment variable is not set.")

    response = requests.post(ENDPOINT, headers=headers, json=payload, stream=True)
    response.raise_for_status()

    accumulated_text = ""
    citations_list = []

    print(">>> Streaming Response:\n")

    for line in response.iter_lines(decode_unicode=True):
        if not line or not line.startswith("data: "):
            continue

        raw_data = line[6:].strip()
        if raw_data == "[DONE]":
            break

        try:
            chunk = json.loads(raw_data)
            
            # Extract incremental text token
            delta = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
            if delta:
                accumulated_text += delta
                print(delta, end="", flush=True)

            # Capture structured citation URLs
            if "citations" in chunk and chunk["citations"]:
                citations_list = chunk["citations"]

        except json.JSONDecodeError:
            continue

    print("\n\n" + "="*50)
    print(">>> Processed References:\n")

    # Map [1], [2] markers to actual URLs
    def replace_citation(match):
        ref_idx = int(match.group(1)) - 1  # Citations are 1-indexed
        if 0 <= ref_idx < len(citations_list):
            url = citations_list[ref_idx]
            return f"[[{ref_idx + 1}]]({url})"
        return match.group(0)

    # Convert prose markers to markdown links
    resolved_markdown = re.sub(r"\[(\d+)\]", replace_citation, accumulated_text)

    # Print citation appendix
    if citations_list:
        for idx, url in enumerate(citations_list, start=1):
            print(f"- [{idx}] {url}")
    else:
        print("No external citations returned.")

    return resolved_markdown

if __name__ == "__main__":
    stream_grounded_search()

TypeScript / Node.js Streaming Implementation

For developers building on Node.js, Next.js, or cloud functions, the native OpenAI SDK connects directly to Perplexity AI:

import OpenAI from "openai";

const perplexity = new OpenAI({
  apiKey: process.env.PERPLEXITY_API_KEY || "",
  baseURL: "https://api.perplexity.ai",
});

async function runGroundedStream() {
  const stream = await perplexity.chat.completions.create({
    model: "sonar",
    messages: [
      {
        role: "system",
        content: "You are a technical research assistant. Provide concise, cited answers.",
      },
      {
        role: "user",
        content: "Explain the architecture of PyTorch 2.0 Dynamo and Inductor.",
      },
    ],
    stream: true,
    // Perplexity extensions passed via extra body options
    ...({
      search_domain_filter: ["pytorch.org", "github.com"],
      search_recency_filter: "month",
    } as any),
  });

  let fullContent = "";
  let citations: string[] = [];

  for await (const chunk of stream) {
    const delta = chunk.choices[0]?.delta?.content || "";
    if (delta) {
      fullContent += delta;
      process.stdout.write(delta);
    }

    // Perplexity attaches citations to the chunk object
    const chunkCitations = (chunk as any).citations;
    if (chunkCitations && Array.isArray(chunkCitations)) {
      citations = chunkCitations;
    }
  }

  console.log("\n\n--- Source Citations ---");
  citations.forEach((url, i) => {
    console.log(`[${i + 1}] ${url}`);
  });
}

runGroundedStream().catch(console.error);

Production Gotchas and Engineering Best Practices

When deploying Sonar API integrations into enterprise environments, keep these engineering constraints in mind:

  1. Avoid Mixing Allowlist and Denylist: Supplying ["github.com", "-reddit.com"] will trigger an immediate 400 Bad Request. Pick one strategy per intent.
  2. Prevent Filter Overload: Do not pack all 20 allowable domains into the filter unless strictly necessary. Over-constraining retrieval often deprives the model of essential context, causing fallback refusals. Maintain focused sets of 3 to 7 authoritative domains.
  3. Handle Missing Citations Gracefully: If the model answers using internal parametric knowledge rather than retrieved web documents, the citations array will be empty. Ensure your regex parser fails open and preserves the original text without crashing.
  4. Rate Limits and Overload Retries: Production code must inspect HTTP 429 errors and parse the Retry-After header. Perplexity enforces per-tier rate limits, and during upstream surges, exponential backoff with jitter is mandatory.
  5. Deterministic Testing Considerations: Even with temperature: 0, web-grounded completions are inherently dynamic because internet pages and search indices update constantly. For regression testing, mock the API layer or freeze specific response fixtures.

By pairing strict domain filtering with a robust SSE citation ingestion loop, engineering teams can deliver real-time, audit-proof AI agents without maintaining heavy crawling and vector infrastructure.


References