> ## 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.

# Build a PyPI release watchlist with Code Mode

> Use Code Mode in the Agent API to check PyPI releases and return a table of versions, dates, and source URLs.

Use Code Mode in the Agent API to find and fetch PyPI release pages for your dependencies in one request. The model writes a JavaScript program that keeps only the evidence needed for a table of versions, dates, and source URLs.

## What you need

* Python 3.14 and a shell. The example runs on Linux.
* A [Perplexity API key](https://docs.perplexity.ai/docs/admin/api-key-management.md).

Install `httpx` in a virtual environment and set your API key. The script sends HTTP requests with `httpx` because version 0.50.0 of the Perplexity Python library does not have types for the Code Mode tool and output items.

```bash theme={null}
mkdir release-watchlist && cd release-watchlist
python3 -m venv .venv && source .venv/bin/activate
python -m pip install httpx
export PERPLEXITY_API_KEY="your-api-key-here"
```

## How the request works

The script sends ten package names to `POST /v1/agent`. It adds `programmatic_tool_calling` to `tools` and puts `programmatic` in `allowed_callers` on `web_search` and `fetch_url`.

The instructions ask the model to write one program. The program searches for each package with `tools.search_web` and `Promise.all`, then fetches the matching PyPI pages with `tools.fetch_url`. It calls `text()` with the page URLs, version headings, and release dates instead of the full tool results.

The response contains the JavaScript in a `program` item and its status in a `program_output` item with the same `call_id`. The script reads the table from the assistant's message, not from either program item. The request's JSON Schema defines the table fields, and the script checks the package order, date format, and source URLs.

## Run the script

Save this script as `release_watchlist.py` in your working directory.

> [accordion] release\_watchlist.py
>
> ```python release_watchlist.py theme={null}
> """Check current PyPI releases through the Perplexity Agent API."""
>
> import argparse
> import json
> import os
> from datetime import date
> from decimal import Decimal
> from time import perf_counter
>
> import httpx
>
> URL = "https://api.perplexity.ai/v1/agent"
> MODEL = "openai/gpt-5.6-sol"
> PACKAGES = (
>     "black", "hatch", "httpx", "mypy", "poetry",
>     "pre-commit", "pytest", "ruff", "tox", "uv",
> )
>
> TASK = """For each package, find its canonical PyPI project page with web
> search and fetch that page. Batch the fetches if the tool accepts a list of
> URLs. Report the package name, latest stable release version, release date
> (YYYY-MM-DD), and source URL. Use only evidence from
> the fetched page. Do not use prereleases or the search snippets as evidence.
> If the page does not verify both a stable version and its release date, set
> version, released, and source_url to JSON null. Do not use placeholders.
> Return one row for every package, in the supplied order."""
>
> PROGRAM = r"""Write one JavaScript program to do the research.
> Use Promise.all to run one tools.search_web({query, limit: 5}) per package.
> Search for 'site:pypi.org/project/<package>/ <package> PyPI'. Each tool result
> is an array. Find the hit whose url, after split(/[?#]/)[0].toLowerCase(),
> equals 'https://pypi.org/project/<package>/'. Do not use the URL constructor.
> The search must supply that URL.
> Collect the matched URLs and call tools.fetch_url({urls}) once. If no URLs
> match, skip the fetch. Fetch returns an array; use each page's url and content.
> Use these selectors on each page's full content, with pkg set to its package:
> const heading = content.split("\n").find(line => line.toLowerCase().startsWith("# " + pkg + " ")) ?? null;
> const keyDates = (content.split("\n## Key dates\n")[1] ?? "").split("\n## ")[0];
> const released = keyDates.split("- **Released:**")[1]?.trimStart().split("\n")[0]?.trim() ?? null;
> Keep only package, URL, heading, and released. Do not emit the original results.
> Catch individual search failures and a fetch failure. Preserve failed packages
> as entries with no evidence. Call text() once with the compact evidence array.
> From that evidence, return the requested JSON. Do not run another program."""
>
> FIELDS = ("package", "version", "released", "source_url")
> SCHEMA = {
>     "type": "object",
>     "additionalProperties": False,
>     "required": ["rows"],
>     "properties": {
>         "rows": {
>             "type": "array",
>             "items": {
>                 "type": "object",
>                 "additionalProperties": False,
>                 "required": list(FIELDS),
>                 "properties": {
>                     "package": {"type": "string", "enum": list(PACKAGES)},
>                     **{field: {"type": ["string", "null"]} for field in FIELDS[1:]},
>                 },
>             },
>         },
>     },
> }
>
>
> def build_request(code_mode: bool) -> dict:
>     tools = [{"type": "web_search"}, {"type": "fetch_url"}]
>     if code_mode:
>         for tool in tools:
>             tool["allowed_callers"] = ["programmatic"]
>         tools.insert(0, {"type": "programmatic_tool_calling"})
>     return {
>         "model": MODEL,
>         "input": "Packages: " + ", ".join(PACKAGES),
>         "instructions": TASK + ("\n\n" + PROGRAM if code_mode else ""),
>         "tools": tools,
>         "max_steps": 16,
>         "text": {
>             "format": {
>                 "type": "json_schema",
>                 "name": "release_watchlist",
>                 "schema": SCHEMA,
>                 "strict": True,
>             }
>         },
>     }
>
>
> def parse_rows(response: dict) -> list[dict]:
>     if response["status"] != "completed":
>         raise ValueError(f"Response status: {response['status']}")
>     parts = [
>         part["text"]
>         for item in response["output"]
>         if item["type"] == "message" and item["role"] == "assistant"
>         for part in item["content"]
>         if part["type"] == "output_text"
>     ]
>     if not parts:
>         raise ValueError("No assistant output text")
>     rows = json.loads("".join(parts))["rows"]
>     if tuple(row["package"] for row in rows) != PACKAGES:
>         raise ValueError("Expected one row per package, in input order")
>     for row in rows:
>         package, version, released, source_url = (row[field] for field in FIELDS)
>         if version is None and released is None and source_url is None:
>             continue
>         if not isinstance(version, str) or not version.strip():
>             raise ValueError(f"{package}: missing version")
>         try:
>             valid_date = isinstance(released, str) and date.fromisoformat(released).isoformat() == released
>         except ValueError:
>             valid_date = False
>         if not valid_date:
>             raise ValueError(f"{package}: expected release date in YYYY-MM-DD format")
>         if source_url != f"https://pypi.org/project/{package}/":
>             raise ValueError(f"{package}: expected the canonical PyPI project URL")
>     return rows
>
>
> def programs(response: dict) -> list[tuple[dict, dict | None]]:
>     outputs = {
>         item["call_id"]: item
>         for item in response["output"]
>         if item["type"] == "program_output"
>     }
>     return [
>         (item, outputs.get(item["call_id"]))
>         for item in response["output"]
>         if item["type"] == "program"
>     ]
>
>
> def print_programs(program_items: list[tuple[dict, dict | None]]) -> None:
>     for program, output in program_items:
>         status = output["status"] if output else "no output"
>         print(f"\nProgram {program['call_id']} [{status}]")
>         print(program["code"])
>         if output:
>             error = json.loads(output["result"]).get("error")
>             if error:
>                 print(f"Program error: {error}")
>
>
> def metrics(response: dict, program_count: int, elapsed: float) -> dict:
>     usage = response["usage"]
>     calls = {
>         name: detail["invocation"]
>         for name, detail in sorted(usage.get("tool_calls_details", {}).items())
>         if detail.get("invocation")
>     }
>     return {
>         "Programs": program_count,
>         "Tool calls": ", ".join(f"{name}: {count}" for name, count in calls.items()) or "none",
>         "Input tokens": usage["input_tokens"],
>         "Output tokens": usage["output_tokens"],
>         "Total cost (USD)": usage["cost"]["total_cost"],
>         "Wall time (s)": f"{elapsed:.1f}",
>     }
>
>
> def print_table(headers: tuple, rows: list[tuple]) -> None:
>     rendered = [[str(value) if value is not None else "unverified" for value in row] for row in rows]
>     widths = [max(map(len, column)) for column in zip(headers, *rendered)]
>     for row in [headers, *rendered]:
>         print("  ".join(value.ljust(width) for value, width in zip(row, widths)).rstrip())
>
>
> def run(client: httpx.Client, code_mode: bool) -> dict:
>     request = build_request(code_mode)
>     start = perf_counter()
>     result = client.post(URL, json=request)
>     elapsed = perf_counter() - start
>     result.raise_for_status()
>     response = result.json(parse_float=Decimal)
>     program_items = programs(response)
>     print_programs(program_items)
>     if code_mode != bool(program_items):
>         raise ValueError("The response did not use the requested tool calling mode")
>     rows = parse_rows(response)
>     print("\n" + ("Code Mode" if code_mode else "Direct tool calls"))
>     print_table(FIELDS, [tuple(row[field] for field in FIELDS) for row in rows])
>     return metrics(response, len(program_items), elapsed)
>
>
> def main() -> None:
>     parser = argparse.ArgumentParser(description=__doc__)
>     parser.add_argument("--compare", action="store_true", help="also run direct tool calls")
>     args = parser.parse_args()
>     key = os.environ.get("PERPLEXITY_API_KEY")
>     if not key:
>         parser.exit(1, "Set PERPLEXITY_API_KEY first.\n")
>     try:
>         with httpx.Client(headers={"Authorization": f"Bearer {key}"}, timeout=180) as client:
>             code = run(client, code_mode=True)
>             if args.compare:
>                 direct = run(client, code_mode=False)
>                 print()
>                 print_table(("Metric", "Code Mode", "Direct"), [
>                     (item, code[item], direct[item]) for item in code
>                 ])
>             else:
>                 print()
>                 print_table(("Metric", "Code Mode"), list(code.items()))
>     except (httpx.HTTPError, ValueError) as error:
>         parser.exit(1, f"{error}\n")
>
>
> if __name__ == "__main__":
>     main()
> ```

Run the script to print the generated JavaScript, the program status, the release table, and request usage.

```bash theme={null}
python release_watchlist.py
```

If the model cannot verify a release, the script prints `unverified` for that row's version, date, and URL. The script does not check whether a release is compatible with your project.

## Compare with direct tool calls

Use `--compare` to send a second request with the same model, tools, package list, and output schema. The second request omits the Code Mode marker, caller restrictions, and program instructions.

```bash theme={null}
python release_watchlist.py --compare
```

The script prints both tables and the request metrics side by side. It reads tool counts from `usage.tool_calls_details` and total cost from `usage.cost.total_cost`.

In this recorded run, both requests returned the same ten rows. The program sent the model only the selected evidence, while direct tool calls sent fetched page text.

| Metric | Code Mode | Direct tool calls |
| - | -: | -: |
| Programs | 1 | 0 |
| `search_web` calls | 10 | 6 |
| `fetch_url` calls | 1 | 8 |
| Input tokens | 4543 | 516651 |
| Output tokens | 992 | 1845 |
| Total cost (USD) | 0.03704 | 1.0111 |
| Wall time (s) | 10.3 | 29.9 |

Results and metrics can change on each run. Check the release rows before you compare the request metrics.

## Next steps

* See [Code Mode](https://docs.perplexity.ai/docs/agent-api/tools/code-mode.md) for the `allowed_callers` rules, the response items, streaming events, and error messages.
* See [Fetch URL Content](https://docs.perplexity.ai/docs/agent-api/tools/fetch-url-content.md) and [Web Search](https://docs.perplexity.ai/docs/agent-api/tools/web-search.md) for the two tools that the program calls.
