Skip to main content

Perplexity Search API tool for Strands Agents - enables real-time web search with citations

Project description

Strands Perplexity

A Strands Agents tool for performing real-time web searches using the Perplexity Search API.

Features

  • 🔍 Real-time web search - Access ranked web search results from Perplexity's continuously refreshed index
  • 📝 Citations included - Every result includes URLs for proper attribution
  • 🌍 Regional search - Filter results by country using ISO country codes
  • 🔤 Language filtering - Filter results by language using ISO 639-1 codes
  • 🌐 Domain filtering - Include or exclude specific domains from results
  • 📊 Multi-query support - Execute up to 5 related queries in a single request

Installation

pip install strands-perplexity

Configuration

Set your Perplexity API key as an environment variable:

export PERPLEXITY_API_KEY="your_api_key_here"

You can get an API key from the Perplexity API Settings.

Usage

Basic Usage with Strands Agent

from strands import Agent
from strands_perplexity import perplexity_search

# Create an agent with the Perplexity search tool
agent = Agent(tools=[perplexity_search])

# The agent can now search the web
response = agent("What are the latest developments in AI?")
print(response)

Direct Tool Usage

from strands_perplexity import perplexity_search, perplexity_multi_search

# Basic search
results = perplexity_search(query="artificial intelligence trends 2024")
for result in results["results"]:
    print(f"{result['title']}: {result['url']}")

# Search with domain filter (allowlist)
results = perplexity_search(
    query="climate change research",
    search_domain_filter=["science.org", "nature.com", "cell.com"],
    max_results=10
)

# Search with domain filter (denylist)
results = perplexity_search(
    query="renewable energy innovations",
    search_domain_filter=["-pinterest.com", "-reddit.com", "-quora.com"]
)

# Regional search
results = perplexity_search(
    query="government policies on renewable energy",
    country="US",
    max_results=5
)

# Language-filtered search
results = perplexity_search(
    query="latest AI news",
    search_language_filter=["en", "fr", "de"]
)

# Multi-query search for comprehensive research
results = perplexity_multi_search(
    queries=[
        "artificial intelligence trends 2024",
        "machine learning breakthroughs recent",
        "AI applications in healthcare"
    ],
    max_results=5
)

API Reference

perplexity_search

Search the web using Perplexity's Search API.

Parameters:

Parameter Type Default Description
query str Required The search query string
max_results int 5 Maximum results to return (1-20)
max_tokens_per_page int 2048 Maximum tokens to extract per webpage
max_tokens int 25000 Maximum total tokens across all results
search_domain_filter list[str] None Domains to include or exclude (max 20)
search_language_filter list[str] None ISO 639-1 language codes (max 10)
country str None ISO 3166-1 alpha-2 country code

Returns:

{
    "query": "your search query",
    "search_id": "unique-search-id",
    "results": [
        {
            "title": "Page Title",
            "url": "https://example.com/page",
            "snippet": "Extracted content from the page...",
            "date": "2024-01-15",
            "last_updated": "2024-01-20"
        },
        # ... more results
    ],
    "result_count": 5
}

perplexity_multi_search

Execute multiple search queries in a single request.

Parameters:

Same as perplexity_search, except:

Parameter Type Default Description
queries list[str] Required List of search queries (max 5)

Returns:

{
    "queries": ["query1", "query2", "query3"],
    "search_id": "unique-search-id",
    "results": [
        [  # Results for query1
            {"title": "...", "url": "...", "snippet": "..."},
            # ...
        ],
        [  # Results for query2
            {"title": "...", "url": "...", "snippet": "..."},
            # ...
        ],
        # ...
    ],
    "result_count": 15  # Total across all queries
}

Domain Filtering

The search_domain_filter parameter supports two modes:

Allowlist Mode (include only specified domains)

results = perplexity_search(
    query="AI research",
    search_domain_filter=["arxiv.org", "openai.com", "deepmind.com"]
)

Denylist Mode (exclude specified domains)

Use a - prefix to exclude domains:

results = perplexity_search(
    query="AI news",
    search_domain_filter=["-pinterest.com", "-facebook.com"]
)

Note: You cannot mix allowlist and denylist modes in the same request.

Best Practices

  1. Write specific queries - Use detailed queries with context for better results:

    # Better
    perplexity_search(query="artificial intelligence medical diagnosis accuracy 2024")
    
    # Avoid
    perplexity_search(query="AI medical")
    
  2. Use multi-query for research - When exploring a topic, use related queries:

    perplexity_multi_search(queries=[
        "quantum computing current state 2024",
        "quantum computing practical applications",
        "quantum computing vs classical computing advantages"
    ])
    
  3. Adjust token budgets - Use lower max_tokens_per_page for quick lookups:

    # Quick lookup
    perplexity_search(query="Python release date", max_tokens_per_page=512)
    
    # Deep research
    perplexity_search(query="Python GIL removal proposal", max_tokens_per_page=2048)
    

Error Handling

from strands_perplexity import perplexity_search, PerplexitySearchError

try:
    results = perplexity_search(query="AI news")
except PerplexitySearchError as e:
    print(f"Search failed: {e}")

Common errors:

  • Missing PERPLEXITY_API_KEY environment variable
  • API rate limits exceeded
  • Invalid parameters (e.g., more than 5 queries in multi-search)

Development

Setup

git clone https://github.com/mkmeral/strands-perplexity
cd strands-perplexity
pip install -e ".[dev]"

Running Tests

hatch run test

Running All Checks

hatch run prepare  # Runs format, lint, typecheck, and test

License

Apache 2.0 - see LICENSE for details.

Resources

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

strands_perplexity-0.1.0.tar.gz (13.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

strands_perplexity-0.1.0-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file strands_perplexity-0.1.0.tar.gz.

File metadata

  • Download URL: strands_perplexity-0.1.0.tar.gz
  • Upload date:
  • Size: 13.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for strands_perplexity-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f6835b574597672db8d9c7ab2899181be8136885e15b2ecf9aba3b78da9bc331
MD5 bfef24c905194e375ef491e1eb0b29c2
BLAKE2b-256 98242a53d149a474eb42964b54ca7f68345e8b6f003500932dc560ab329dcd82

See more details on using hashes here.

Provenance

The following attestation bundles were made for strands_perplexity-0.1.0.tar.gz:

Publisher: publish.yml on mkmeral/strands-perplexity

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file strands_perplexity-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for strands_perplexity-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b2b17461829b4118761a8f345c61b519de60f779a3b99fd88aa307de1d327d26
MD5 cb27527515ade6c244d655aa281f7212
BLAKE2b-256 2ea8b4216168fd4ed121a0a8ef5f491984a4cfe88859ea099e99a841f3e58404

See more details on using hashes here.

Provenance

The following attestation bundles were made for strands_perplexity-0.1.0-py3-none-any.whl:

Publisher: publish.yml on mkmeral/strands-perplexity

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page