Sandbox Tool: Code Execution, Search Integration, and Artifacts
How the Agent API sandbox runs code for exact answers, in-container search, shareable files, and how to verify sandbox_results.
This page summarizes Perplexity documentation on the sandbox built-in tool for the Agent API: when to enable it, how runs combine with web search and People Search, cookbook patterns that depend on computed output, and how to confirm the model executed code instead of guessing.
Language models approximate exact arithmetic and data manipulation rather than computing them. The sandbox tool gives the agent an isolated Linux container to run real code and use the output in its answer — for results that must be exact, like a computed number, a transformed dataset, or a generated report.
— Perplexity, Run code
sandbox tool: what it does and when to use it
Section titled “sandbox tool: what it does and when to use it”The sandbox tool lets the model run code during an Agent API request in an isolated container, inspect stdout and stderr, and fold the result into its answer. You do not supply the code: you add {"type": "sandbox"} to the request tools array, and the model decides when to call it from your input and instructions.
You don’t supply the code. You enable the tool, and the model writes and runs the code itself based on your prompt and instructions - then reads its own stdout/stderr back and uses it in the answer. The exact code the model ran is returned to you in the response (see Response shape), so you can verify what executed.
— Perplexity, Sandbox
Reach for the sandbox when an estimate from plain chat is not acceptable. Perplexity’s Run code guide lists typical cases:
| Situation | Why sandbox helps |
|---|---|
| Numeric or statistical answers | Counts, aggregates, and shares must be computed |
| Data cleaning and parsing | Structured transforms over real inputs |
| Logic checks and reproduction | Execute code to validate behavior |
| File artifacts | CSV, JSON, HTML, PDF via code plus share_file |
| Multi-step jobs | Intermediate files and state between steps |
Cookbook flows such as Competitor Buzz Tracker, Daily News Digest with LLM Deduplication, and Talent Sourcer treat the sandbox as the engine: the agent writes Python, loops over search results, and returns downloadable files while your script only submits requests and polls.
How sandbox runs work: steps, background mode, and max_steps
Section titled “How sandbox runs work: steps, background mode, and max_steps”Research that combines sandbox and web_search needs several agent steps: load instructions, write code, run it, read output, and possibly iterate. Set max_steps high enough for that loop; without it, the run defaults to one step (Sandbox).
Long sandbox sessions should use background: true, then poll responses.retrieve until status is terminal (completed, failed, cancelled, or incomplete). Examples in Daily News Digest with LLM Deduplication and Competitor Buzz Tracker use this pattern because a single container run can take minutes.
Competitor Buzz Tracker: two chained requests with JSON between them
Section titled “Competitor Buzz Tracker: two chained requests with JSON between them”Competitor Buzz Tracker splits analysis and charting into two Agent API calls so each prompt stays short, you can use a cheaper model for mechanical search-and-count, and you get an inspectable JSON checkpoint.
Request 1 (analytics) gets the sandbox tool and a response_format schema. The model searches each query from inside the sandbox, pools the results, deduplicates by URL, regex-matches each article against the keyword rules, and counts mentions per brand plus its share of voice.
— Perplexity, Competitor Buzz Tracker
Request 2 receives only that validated JSON plus sandbox again, renders a PDF with matplotlib, and shares it via share_file. The client script refuses analytics output unless the response contains a sandbox_results item so the model cannot skip the tool and return invented counts.
Daily news digest: code fetches, model groups, code assembles
Section titled “Daily news digest: code fetches, model groups, code assembles”Daily News Digest with LLM Deduplication uses one request with a fixed three-phase workflow in instructions: sandbox code searches each topic and saves results.json; the model groups articles into stories by judgment (not string matching or embeddings); a final sandbox execution builds digest.md and stories.json and shares both files. Persistent deduplication lives in stories.json you pass back on the next run.
Search from inside the sandbox: web_search, People Search, and Fetch URL
Section titled “Search from inside the sandbox: web_search, People Search, and Fetch URL”From inside the container, agent-written code can call Perplexity Web Search, Fetch URL Content, and People Search without listing those tools on the outer request—each billed at its standard per-invocation rate (Run code, Sandbox).
The sandbox can reach Perplexity search from inside the run, so the model pulls the articles itself and classifies them in the same request — no separate scraping step, no glue code, no extra tool to wire up.
— Perplexity, Competitor Buzz Tracker
Talent Sourcer declares only sandbox on the request; Python inside the run calls people_search for wide collection and web_search to verify role, location, tenure, and public links—discipline the model cannot hold reliably in a single tool call.
For direct People Search outside the sandbox, the Search API accepts search_type="people" (People Search); the Agent API exposes a people_search tool the model invokes when prompts target professionals (People Search). Agent tool billing is $5 per 1,000 people_search invocations per that reference page.
sandbox_results: how to verify computed answers
Section titled “sandbox_results: how to verify computed answers”When code runs, the response output array includes one or more sandbox_results items alongside the final message. Each item carries executed code, language, and a results array with stdout, stderr, exit_code, and status (Run code).
for item in response.output: if item.type == "sandbox_results": print(item.code) print(item.results[0].stdout)Production scripts should treat missing sandbox_results as failure when numbers or files must come from execution—as Competitor Buzz Tracker does for analytics. Completed runs may also include share_file items; download artifacts via responses files endpoints (referenced from cookbook examples).
Track What the Web Said Each Week About a Topic, and Build a Report uses sandbox for arithmetic the narrative must not invent: the model saves JSON to a file inside the container and prints counts only from executed Python—a pattern worth copying whenever large payloads would otherwise be retyped into generated scripts.
Pricing, limits, and cost patterns
Section titled “Pricing, limits, and cost patterns”Sandbox billing has three axes:
| Axis | Notes |
|---|---|
| Model tokens | Per selected model; see Agent API model pricing |
| Sandbox session | $0.03 per container lifecycle (up to 20 minutes active use for billing) |
| In-sandbox tools | Web Search, Fetch URL, People Search at standard tool rates |
Invocation counts appear under usage.tool_calls_details.sandbox.invocation. Competitor Buzz Tracker notes each run bills two Agent API requests (two sandbox sessions plus in-sandbox searches). Talent Sourcer warns thorough people plus web verification inside one sandbox loop can cost dollars, not cents.
Coverage and counts depend on live indexes—cookbooks repeat that output varies by topic and time (Competitor Buzz Tracker).
Skills and office artifacts (PDF without hand-written chart code)
Section titled “Skills and office artifacts (PDF without hand-written chart code)”Not every artifact needs custom matplotlib in sandbox. Daily AI Stock News PDF with Skills and Skills combine a built-in office skill (format routing, including PDF) with an inline design-system skill for house fonts and layout. Submit with background: true, poll until complete, then download files from the response. Use sandbox when you need inspectable computation; use skills when the main job is styled document generation from a natural-language brief.
Built-in tools alongside sandbox
Section titled “Built-in tools alongside sandbox”Enable tools by type on the request (Tools overview):
type |
Role |
|---|---|
web_search |
Live web with filters |
sandbox |
Isolated code execution |
people_search |
Professional lookup (when declared on the request) |
fetch_url |
Extract specific URLs |
finance_search |
Structured market data |
image_search |
Image results with filters |
Build a Data Analytics Agent Using Custom Connectors places sandbox in a larger profile (connector, versioned skill, instructions) where the agent chooses tools per turn; the same verification mindset applies: rely on tool output items, not uncited prose.
Common mistakes when using the sandbox tool
Section titled “Common mistakes when using the sandbox tool”- Trusting chat text for counts — Require
sandbox_resultsand stdout that matches your schema or script checks (Competitor Buzz Tracker). max_stepstoo low — Multi-step search-plus-code loops stall after one step (Sandbox).- Mixing sandbox with incompatible request options — e.g.
web_searchdate filters on the same request as sandbox (agent-api-story-timeline). - Huge JSON pasted into generated code — Instruct the model to write input to a file first; keeps token use and copy errors down (agent-api-story-timeline).
- One broad
people_searchfor large lists — Wide sourcing needs many segmented searches and per-row verification in code (Talent Sourcer). - Embedding-only dedupe for news — Same-event grouping is judgment; cookbooks forbid embedding or string-only grouping (Daily News Digest with LLM Deduplication).
How to check this on your site
Section titled “How to check this on your site”- Send a minimal Agent API request with
tools=[{"type": "sandbox"}], a numeric or countinginput, andmax_stepsgreater than 1; confirm the completed response includessandbox_resultswithexit_code0 and non-emptystdout, following Sandbox. - Re-run with instructions that forbid estimation; verify the final answer cites values that appear in
sandbox_resultsstdout, as described in Run code. - If your flow uses in-sandbox search, inspect returned
codefor search calls and cross-checkusage.tool_calls_detailsfor sandbox and search invocations (Sandbox). - For file outputs, list response files after
completedand confirm a shared PDF or HTML matches what Competitor Buzz Tracker or Talent Sourcer documents. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page disagrees with the linked Perplexity docs or does not match what you see in your integration, email yimasynthetic@gmail.com with the page URL and the exact sentence you are questioning.