Skip to content

LearnTutorials

Build a Search as Code agent with the Perplexity API

Let an AI model write and run its own search code in the Perplexity Agent API sandbox, for research with many parts, in about 20 minutes.

By Recaply EditorsAdvanced21 min5 stepsUpdated

A hand holds three magnifying glasses fanned out above a small sandbox tray with a toy shovel in it

What you need

  1. Step 1: Create a key and add credits

    4 min

    The Agent API runs on prepaid credits, and every request needs a key from your API project.

    1. Go to console.perplexity.ai and sign in with your Perplexity account.
    2. Under Project, open Settings and fill in your project details if it asks.
    3. In Billing, click Add payment method, then buy credits.
    4. On the API Keys page, generate a key and copy it right away.

    You should see a new key that starts with pplx-, shown on screen once.

    Your key stops working after a few runs?

    You've probably run out of credits, and Perplexity blocks keys at a zero balance. Buy more credits, or turn on Auto reload in Billing.

    Perplexity shows the full key only once. Save it in a password manager, and keep it out of code, prompts and shared files.

  2. Step 2: Install the SDK and set your key

    3 min

    The Python SDK sends your requests and reads the key from your environment, so the key never sits in your code.

    1. Open a terminal.
    2. Run the commands below, with your key in place of [YOUR API KEY].
    3. Check the install with pip show perplexityai.
    Run this
    mkdir sac-agent && cd sac-agent
    python3 -m venv .venv
    source .venv/bin/activate
    pip install perplexityai
    export PERPLEXITY_API_KEY="[YOUR API KEY]"

    You should see the install finish with no errors, and a version number from pip show perplexityai.

    pip can't find a matching version?

    The package needs Python 3.10 or newer. Check with python3 --version, install a newer Python, then make the .venv again.

    The export line lasts only for this terminal window. In a new window, run it again before you run the script.

  3. Step 3: Describe the whole task

    5 min

    The model plans its searches from the full job, so it can split the work before it runs any code.

    1. Save the script below as sac.py in the sac-agent folder.
    2. Replace [YOUR TASK] with the whole job: the items, the facts you need and the format you want.
    3. Keep both tools and max_steps as they are.
    Your script
    from perplexity import Perplexity
    
    client = Perplexity()  # reads PERPLEXITY_API_KEY
    
    TASK = "[YOUR TASK]"
    
    response = client.responses.create(
        model="openai/gpt-5.6-sol",
        input=TASK,
        tools=[{"type": "sandbox"}, {"type": "web_search"}],
        max_steps=10,
        instructions=(
            "Write and run Python in the sandbox to do the searches. "
            "Plan every query first, run them in parallel, and drop duplicate URLs. "
            "Print only a short table of findings with a source URL for each. "
            "Then answer from that table."
        ),
    )
    
    for item in response.output:
        if item.type == "sandbox_results":
            print("--- Code the model ran ---")
            print(item.code)
    
    print("--- Answer ---")
    print(response.output_text)
    print("Cost in USD:", response.usage.cost.total_cost)

    You should see sac.py in your folder, with your own task in the TASK line.

    A good task names every item and fact. For example: "Compare the free plans of 5 note-taking apps: storage, device limits and price, with a source for each."

  4. Step 4: Run it and read the code

    5 min

    The response returns the exact code the model ran, so you can see how it chose to search.

    1. Run the command below and wait. A run with many searches takes a minute or more.
    2. Read the printed code. Look for many queries sent at once, filters and duplicate checks.
    3. Check the answer and the cost line at the end.
    Run this
    python sac.py

    You should see one or more blocks of Python, then a short answer with sources, then the cost in US dollars.

    You get a 401 error?

    The key isn't set in this terminal window. Run the export line from step 2 again in the same window, then run the script.

    With a direct model, max_steps starts at 1. The agent spends its first step loading the sandbox, so 1 step leaves no room to run code.

  5. Step 5: Refine the search plan

    4 min

    You change the plan in plain words, and the model writes new code on the next run.

    1. Note what the first run missed, such as old pages, a skipped item or repeated sources.
    2. Add a line like the one below to the end of instructions, inside the quotes.
    3. Run python sac.py again and compare the new code with the first run.
    Add to your instructions
    Only use pages published after [DATE]. Search each item on its own, and prefer each maker's official site.

    You should see new code with a date filter or one query per item, and a fresher answer.

    A big task times out?

    Add background=True to the request. Then call client.responses.retrieve(response.id) every few seconds until the status is completed.

    To change speed and cost, swap the model for another one on Perplexity's Models page.

You get

A research agent that writes its own search code, runs it in a sandbox and shows you every line it ran

Did this guide work for you?

Sources