Skip to main content
Article
research-agentanswer-enginereal-time-searchapi-automationpythonai-searchfact-checking

Automate Factual Research with the Perplexity API

Use the Perplexity API to programmatically get cited, up-to-date answers. This pack shows how to perform real-time web searches and get synthesized responses for research tasks, replacing manual search engine queries.

beginner15 min4 steps
The play
  1. Get Your Perplexity API Key
    Navigate to your Perplexity account settings and find the 'API Keys' section. Generate a new key. This key is required to authenticate all requests to the API. For security, set it as an environment variable named `PPLX_API_KEY`.
  2. Run a Simple Online Search
    Make a POST request to the `/chat/completions` endpoint. Use a web-enabled model like `sonar-small-online` to have Perplexity search the internet in real-time for the most current information to answer your query.
  3. Control Response Style with System Prompts
    Add a `system` role message to your request to guide the AI's tone and format. This is useful for tailoring the output for specific applications, such as generating concise summaries or bulleted lists.
  4. Stream Responses for Real-Time Feedback
    Set `stream: true` in your API call to receive the response as a series of server-sent events. This allows you to process and display the answer as it's being generated, creating a more interactive and responsive user experience.
Starter code
import os
import requests
import json

# 1. Set your API key as an environment variable: export PPLX_API_KEY="your-key"
api_key = os.environ.get("PPLX_API_KEY")
if not api_key:
    raise ValueError("PPLX_API_KEY environment variable not set.")

url = "https://api.perplexity.ai/chat/completions"

# 2. Define the payload with your query and model
payload = {
    "model": "sonar-medium-online", # Or "sonar-small-online"
    "messages": [
        {
            "role": "system",
            "content": "You are an AI assistant that provides factual, cited answers."
        },
        {
            "role": "user",
            "content": "What were the key findings of the latest IPCC report on climate change?"
        }
    ]
}

headers = {
    "accept": "application/json",
    "content-type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# 3. Make the API request
try:
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status() # Raises an HTTPError for bad responses (4XX or 5XX)

    # 4. Print the response
    response_data = response.json()
    answer = response_data['choices'][0]['message']['content']
    
    print("--- Perplexity Answer ---")
    print(answer)
    print("-------------------------")

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
except KeyError:
    print("Error: Unexpected response format from API.")
    print(response.text)
Automate Factual Research with the Perplexity API — Action Pack