> ## Documentation Index
> Fetch the complete documentation index at: https://docs.perplexity.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Code Mode

> Let the model write JavaScript programs that call your Agent API tools.

## Overview

With Code Mode, the model writes a JavaScript program that calls your tools. Perplexity runs the program and sends its output to the model. You do not write or run the program.

One program can do work that needs many direct tool calls:

* It can call a tool one time for each item in a list, in parallel.
* It can use the result of one tool call as the input of the next tool call.
* It can filter the tool results and send only the necessary data to the model.

Without Code Mode, the model makes each tool call directly and reads each result.

## Turn On Code Mode

Make these two changes to the `tools` array of a `POST /v1/agent` request:

1. To turn on Code Mode, add the object `{"type": "programmatic_tool_calling"}`.
2. To let programs call a tool, put `programmatic` in the `allowed_callers` array of that tool.

The model needs two or more steps to read the output of one program and then write a new program. When you use `model` without an effort level, set `max_steps`. See [Customize the loop](https://docs.perplexity.ai/docs/agent-api/building-agents/define-the-run.md#customize-the-loop-max-steps).

Version 0.50.0 of the Perplexity Python library and version 0.45.0 of `@perplexity-ai/perplexity_ai` do not have types for Code Mode. The examples on this page send HTTP requests directly.

```python Python theme={null}
import os

import httpx

response = httpx.post(
    "https://api.perplexity.ai/v1/agent",
    headers={"Authorization": f"Bearer {os.environ['PERPLEXITY_API_KEY']}"},
    json={
        "model": "openai/gpt-5.6-sol",
        "input": "Find the current stable release of Python, Node.js, Go, and Rust. Search for each one. Then give me a four-row table.",
        "tools": [
            {"type": "programmatic_tool_calling"},
            {"type": "web_search", "allowed_callers": ["programmatic"]},
        ],
        "max_steps": 5,
    },
    timeout=300,
)
response.raise_for_status()

for item in response.json()["output"]:
    if item["type"] == "program":
        print(item["code"])
    elif item["type"] == "program_output":
        print(item["status"])
    elif item["type"] == "message":
        print(item["content"][0]["text"])
```

```typescript Typescript theme={null}
const response = await fetch("https://api.perplexity.ai/v1/agent", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-5.6-sol",
    input: "Find the current stable release of Python, Node.js, Go, and Rust. Search for each one. Then give me a four-row table.",
    tools: [
      { type: "programmatic_tool_calling" },
      { type: "web_search", allowed_callers: ["programmatic"] },
    ],
    max_steps: 5,
  }),
});

if (!response.ok) {
  throw new Error(await response.text());
}

const data = await response.json();
for (const item of data.output) {
  if (item.type === "program") {
    console.log(item.code);
  } else if (item.type === "program_output") {
    console.log(item.status);
  } else if (item.type === "message") {
    console.log(item.content[0].text);
  }
}
```

```bash cURL theme={null}
curl https://api.perplexity.ai/v1/agent \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.6-sol",
    "input": "Find the current stable release of Python, Node.js, Go, and Rust. Search for each one. Then give me a four-row table.",
    "tools": [
      {"type": "programmatic_tool_calling"},
      {"type": "web_search", "allowed_callers": ["programmatic"]}
    ],
    "max_steps": 5
  }' | jq
```

The model wrote this program for the request. The program makes four searches in parallel and sends the results to the model:

```javascript theme={null}
const qs = [
  {query:"site:python.org/downloads latest stable Python release November 2026", domains:["python.org"], limit:5},
  {query:"site:nodejs.org/en/download current Node.js latest stable release November 2026", domains:["nodejs.org"], limit:5},
  {query:"site:go.dev/dl latest stable Go release November 2026", domains:["go.dev"], limit:5},
  {query:"site:rust-lang.org latest stable Rust release November 2026", domains:["rust-lang.org"], limit:5}
];
const rs = await Promise.all(qs.map(q => tools.search_web(q)));
rs.forEach((r,i)=>{ text(JSON.stringify({i, result:r})); });
```

The `output` array of the response has a `program` item, a `program_output` item, and the `message` item. The long values in this example are shortened:

```json theme={null}
[
  {
    "type": "program",
    "id": "prog_call_4e566c601ae4484cb3adc57342c25b08",
    "call_id": "call_4e566c601ae4484cb3adc57342c25b08",
    "code": "const qs = [\n  {query:\"site:python.org/downloads latest stable Python release November 2026\", ...",
    "fingerprint": "eyJ2ZXJzaW9uIjoxLCJjb2RlX2hhc2giOiI0Qzhz..."
  },
  {
    "type": "program_output",
    "id": "prog_out_call_4e566c601ae4484cb3adc57342c25b08",
    "call_id": "call_4e566c601ae4484cb3adc57342c25b08",
    "status": "completed",
    "result": "{\"format\":\"code_mode/v1\",\"output\":[{\"type\":\"text\",\"text\":\"...\"}]}"
  },
  {
    "type": "message",
    "id": "msg_4430d78e-b400-4b13-b972-3d6f87b55c5d",
    "role": "assistant",
    "status": "completed",
    "content": [
      {
        "type": "output_text",
        "text": "As of **November 30, 2026**, the latest stable releases are: ...",
        "annotations": []
      }
    ]
  }
]
```

The model can write a different program each time you send the same request.

## Set the Callers of a Tool

The `allowed_callers` array on a tool sets how the model can call that tool.

| `allowed_callers` | Result |
| - | - |
| `["programmatic"]` | Only programs call the tool. |
| `["direct", "programmatic"]` | The model calls the tool directly or from a program. The model makes the selection for each call. |
| `["direct"]`, or no `allowed_callers` | The model calls the tool directly. Programs cannot call it. |

These rules apply:

* A request can have only one `programmatic_tool_calling` object. The object accepts only `type`.
* If a tool has `programmatic` in `allowed_callers`, the request must have the `programmatic_tool_calling` object.
* An [`mcp` tool](https://docs.perplexity.ai/docs/agent-api/tools/mcp) accepts `allowed_callers`. A program cannot call an MCP tool that needs approval. That call fails with `ToolError: code_mode cannot execute a tool call requiring client approval`.
* [Custom functions](https://docs.perplexity.ai/docs/agent-api/tools/custom-functions.md) accept `allowed_callers`, including `["programmatic"]` and `["direct", "programmatic"]`. Add an optional `output_schema` JSON Schema on the function tool to describe the return shape to JavaScript programs.
* When a request has the `programmatic_tool_calling` object, a custom function cannot have the name `exec`.
* `tool_choice` cannot select a tool that only programs can call.

> [!NOTE]
>
> When a request has the `programmatic_tool_calling` object, a direct `web_search` call is a `function_call` item with the name `search_web` in `output`. Its `status` is `completed`, and the response has no `search_results` item for that call. Perplexity runs this call. It is not a call to one of your custom functions.

### Custom Functions in Code Mode

When a program calls a client-executed custom function (`await tools.<name>(args)`), Perplexity pauses the JavaScript runtime and returns the `program` item along with one or more `function_call` items. Each programmatic `function_call` item includes a `caller` object pointing back to the paused program:

```json theme={null}
{
  "type": "function_call",
  "id": "fc_call_...",
  "call_id": "call_...",
  "name": "get_price",
  "arguments": "{\"ticker\":\"AAPL\"}",
  "caller": {
    "type": "program",
    "caller_id": "call_ac793e8714dd486ca9f8fa6fb2cfdc32"
  },
  "status": "completed"
}
```

Execute the function calls on your side, then send the matching `function_call_output` items back (including `call_id`, `name`, `output`, and `caller`) with `previous_response_id` — or by replaying the full conversation with the unchanged `program` item and its `fingerprint`. Perplexity resumes the paused JavaScript runtime and emits the final `program_output` and `message` items.

## Programs

The model writes each program in JavaScript. A program has these properties:

* It calls a tool with `await tools.<name>(args)`. Each call returns a promise, so `Promise.all` runs calls in parallel.
* It sends a value to the model with `text(value)`. The model does not get the value of the last expression.
* It gets the name and description of each available function from `ALL_TOOLS`.
* It gets a `ToolError` when a tool call fails. A program can use `try` and `catch` to continue.
* It cannot import modules. `process` and `fetch` are not available. A program uses tools to get external data.
* It does not keep variables for the next program.

To change how the model writes programs, give directions in `instructions` or `input`. For example, tell the model to make one search for each item in parallel and to send only a short JSON array to the model.

### Function Names

The function names in a program can be different from the tool `type`. One tool can give the program more than one function.

| Tool `type` | Functions in a program |
| - | - |
| `web_search` | `search_web`, `search_academic`, `search_companies`, `search_patents`, `search_people`, `search_secgov`, `llm` |
| `fetch_url` | `fetch_url`, `fetch_image`, `fetch_people`, `snippets`, `embeddings` |
| `finance_search` | `finance_tickers_lookup`, `finance_quotes`, `finance_company_financials`, `finance_company_profile`, `finance_segments`, `finance_earnings_history`, `finance_earnings_transcript`, `finance_etf_holdings`, `load_skill` |
| `sandbox` | `bash`, `read`, `write`, `edit`, `grep`, `glob`, `apply_patch`, `share_file` |
| `people_search` | `search_people` |
| `image_search` | `search_images` |
| `mcp` | `<server_label>__<tool_name>` for each tool of the server. For example, `deepwiki__read_wiki_structure`. |

The `llm` function uses a model to extract structured data from the items that the program gives it.

Each MCP tool call that a program makes adds an `mcp_call` item to `output`.

## Response Items

Each program adds two items to `output`. They have the same `call_id`. Use `call_id` to connect the two items, not their positions in `output`.

A `program` item has the code that the model wrote:

| Field | Type | Description |
| - | - | - |
| `type` | string | Always `program`. |
| `id` | string | The ID of the item. |
| `call_id` | string | The ID that connects the program to its `program_output` item. |
| `code` | string | The JavaScript source of the program. |
| `fingerprint` | string | An opaque value. Send it back unchanged when you send the item in `input`. |

A `program_output` item has the result of the program:

| Field | Type | Description |
| - | - | - |
| `type` | string | Always `program_output`. |
| `id` | string | The ID of the item. |
| `call_id` | string | The `call_id` of the `program` item. |
| `status` | string | `completed` or `incomplete`. The status is `incomplete` when the program stops because of an error. |
| `result` | string | A JSON string. Parse it to get the output of the program. |

The parsed `result` is an object with these fields:

| Field | Type | Description |
| - | - | - |
| `format` | string | Always `code_mode/v1`. |
| `output` | array | The values that the program sent with `text()`. Each value is a `{"type": "text", "text": "..."}` object. This field is absent when the program sends no output. |
| `error` | string | The error that stopped the program. This field is absent when the program completes. |

A program that fails does not make the response fail. In this example, a tool call fails and the program does not catch the error. The response `status` is `completed`, and the `status` of the `program_output` item is `incomplete`. The parsed `result` keeps the output that the program sent before the error:

```json theme={null}
{
  "format": "code_mode/v1",
  "output": [
    {"type": "text", "text": "before"}
  ],
  "error": "ToolError: {\"error\":\"query must not be blank\"}\n    at <anonymous> (program.js:2:23)"
}
```

Some functions also add the usual item of their tool to `output`. For example, a `finance_quotes` call adds a `finance_results` item, and a `bash` call adds a `sandbox_results` item.

## Streaming

When you set `stream` to `true`, programs use the standard output item events:

1. A `response.output_item.added` event has the `program` item when the program starts.
2. A `response.output_item.done` event has the `program_output` item when the program stops.
3. A `response.output_item.done` event has the `program` item.

The `program` item in the `response.output_item.added` event has an empty `fingerprint`. Use the `program` item from the `response.output_item.done` event when you send the item in `input`.

The stream has no delta events for program code or program output.

## Usage

`usage.tool_calls_details` has entries for the tool calls that programs make. For example, when one program makes four `search_web` calls and each call completes, `usage.tool_calls_details.search_web.invocation` is `4`. A program does not have an entry of its own.

## Continue a Conversation

Code Mode works with `previous_response_id`.

To manage the conversation yourself, send the `program` and `program_output` items back in `input` with the other output items. Do not change `fingerprint`. A `program` item with no `fingerprint` or a changed `fingerprint` returns `400`.

Code Mode also works with `stream`, `background`, `store`, and [structured outputs](https://docs.perplexity.ai/docs/agent-api/output-control.md#structured-outputs).

## Errors

The API returns `400` with `type` `invalid_request` for these requests. `tools[N]` gives the position of the tool in the `tools` array, and the first position is 0.

| Cause | `message` |
| - | - |
| The request has the `code_mode` field. | `invalid request body: json: unknown field "code_mode"; add {"type":"programmatic_tool_calling"} to tools and set allowed_callers on each tool instead` |
| A tool has `programmatic` in `allowed_callers`, and the request has no `programmatic_tool_calling` object. | `invalid request: preset: invalid request: programmatic allowed_callers requires programmatic_tool_calling` |
| The request has two `programmatic_tool_calling` objects. | `validation failed: programmatic_tool_calling must appear only once` |
| The `programmatic_tool_calling` object has a field other than `type`. | `validation failed: tools[N]: programmatic_tool_calling accepts only type` |
| `allowed_callers` is an empty array. | `validation failed: tools[N]: allowed_callers must be a nonempty array of direct and/or programmatic` |
| `allowed_callers` has a value other than `direct` or `programmatic`. | `validation failed: tools[N]: allowed_callers must contain only direct or programmatic` |
| `allowed_callers` has the same value two times. | `validation failed: tools[N]: allowed_callers must not contain duplicates` |
| A custom function has the name `exec`, and the request has the `programmatic_tool_calling` object. | `invalid request: preset: invalid request: programmatic_tool_calling reserves the exec tool name` |
| `tool_choice` selects a tool that only programs can call. | `invalid request: preset: invalid request: tool_choice names a programmatic-only tool` |
| A `program` item in `input` has no `fingerprint`. | `validation failed: input[N]: program item requires fingerprint` |
| A `program` item in `input` has a changed `fingerprint`. | `invalid request: input[N].program: unsupported program fingerprint` |

## Next Steps

> [card] [PyPI Release Watchlist](https://docs.perplexity.ai/docs/cookbook/examples/code-mode-research-table/README.md)
>
> Run a recipe that compares one Code Mode request with direct tool calls.

> [card] [Tools Overview](https://docs.perplexity.ai/docs/agent-api/tools/overview.md)
>
> See the tools that an Agent API request can use.

> [card] [Customize the Loop](https://docs.perplexity.ai/docs/agent-api/building-agents/define-the-run.md#customize-the-loop-max-steps)
>
> Set the number of steps that a run can take.
