---
title: "PentestLLM Python quick-start with the OpenAI SDK"
description: "pip install openai, point base_url at api.pentestllm.ai/v1 and call a cybersecurity model: a first request, streaming, model list, rate limits, real output."
canonical: https://pentestllm.ai/guides/python
generated: 2026-12-03T14:14:53.081Z
source: https://pentestllm.ai/guides/python
base_url: https://api.pentestllm.ai/v1
---

# Python quick-start: the OpenAI SDK on the cybersecurity models

pip install openai, point base_url at api.pentestllm.ai/v1 and call a cybersecurity model: a first request, streaming, model list, rate limits, real output.

Steps checked November 30, 2026 · prices as of December 3, 2026

Four Python scripts on the official OpenAI SDK: a first request to a cybersecurity model, a streamed reply, the list of model ids and a call that retries through rate limits. Each one ran against the live API on 2026-11-28, and its output is pasted below it as printed. The prompts stay inside authorized testing.

## Install the SDK and set your key

The stock `openai` package is all you need; nothing is forked or patched. The runs on this page used openai 2.48.0 on Python 3.9. Create a key in the [console](https://app.pentestllm.ai/console) (it starts with `sk-ptl-` and is shown once) after a top-up from $3, and keep it in an environment variable rather than in the script.

```bash
python3 -m pip install openai
export PENTESTLLM_API_KEY="sk-ptl-live-…"
```

Every sample passes `base_url="https://api.pentestllm.ai/v1"` to the client. The URL ends at `/v1`; the SDK adds `/chat/completions` and `/models` itself.

## A first chat completion

A system message that states the engagement, a question, and a `max_tokens` cap so the reply stays short and the cost stays known. The model is [minimax-m3.1-flash-cybersecurity](https://pentestllm.ai/models/minimax-m3.1-flash-cybersecurity), a fast security build.

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.pentestllm.ai/v1",
    api_key=os.environ["PENTESTLLM_API_KEY"],
)

response = client.chat.completions.create(
    model="minimax-m3.1-flash-cybersecurity",
    messages=[
        {"role": "system", "content": "You assist a penetration tester on an authorized engagement."},
        {"role": "user", "content": "Explain what an SQL injection is and how to test a login form for it in an authorized engagement. Keep it under 150 words."},
    ],
    max_tokens=400,
)

print(response.choices[0].message.content)
print(response.usage)
```

What it printed, unedited:

```
SQL injection (SQLi) occurs when application-built SQL queries incorporate user input without proper parameterization. An attacker may alter the query’s logic, potentially bypassing authentication or accessing unauthorized data.

For an authorized login test:

1. Use a dedicated test account and backups; avoid production credentials.
2. Submit a single quote (`'`) in the username and password fields. Note unexpected errors, changed behavior, or HTTP 500 responses.
3. Try benign authentication probes such as:
   - `admin'--`
   - `' OR '1'='1'--`
   - `admin' OR '1'='1'--`
4. Compare responses, status codes, redirects, and error messages with normal failed logins.
5. If permitted, use a scanner such as sqlmap against a staging copy or with strict rate limits:
   `sqlmap -u "https://target/login" --data="user=admin&pass=test" --level=1 --risk=1`
6. Confirm findings manually, document affected parameters and evidence, and stop before destructive actions or extracting sensitive data.

Fixes include parameterized queries, allow-list validation, and safe error handling.
CompletionUsage(completion_tokens=391, prompt_tokens=68, total_tokens=459, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=151, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cache_write_tokens=None, cached_tokens=0), cost=0.0017)
```

The `usage` block counts the tokens, reasoning tokens included, and in this run it also carried the request’s charge in US dollars as `cost`. The console’s usage log lists the same request.

## Streaming

`stream=True` returns chunks as the model writes. With `stream_options={"include_usage": True}` the last chunk carries the usage block and no choices, which is why the loop checks `chunk.choices` before reading it. This sample calls the uncensored variant of the same build.

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.pentestllm.ai/v1",
    api_key=os.environ["PENTESTLLM_API_KEY"],
)

stream = client.chat.completions.create(
    model="minimax-m3.1-flash-cybersecurity-uncensored",
    messages=[{"role": "user", "content": "List five checks for reflected XSS on a search field, one line each, for an in-scope web app test."}],
    max_tokens=400,
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage)
```

What it printed, unedited:

```
1. Submit a unique marker such as `xssTEST123` and confirm where it is reflected in the HTML response.
2. Test `<script>alert(1)</script>` and case variants to check whether script tags are filtered or output-encoded.
3. Test an attribute breakout payload such as `" autofocus onfocus=alert(1) x="` when the reflection is inside an HTML attribute.
4. Test markup-context payloads such as `"><svg/onload=alert(1)>` and `</textarea><script>alert(1)</script>` for missing context-aware encoding.
5. Confirm execution in the browser while checking the response source, JavaScript console, and URL parameters for unencoded reflected input.
 CompletionUsage(completion_tokens=352, prompt_tokens=599, total_tokens=951, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=204, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cache_write_tokens=None, cached_tokens=0), cost=0.002606)
```

## List the models your key can call

`client.models.list()` returns every id the key may use; listing costs nothing. Filtered to the cybersecurity builds:

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.pentestllm.ai/v1",
    api_key=os.environ["PENTESTLLM_API_KEY"],
)

ids = sorted(m.id for m in client.models.list() if "cybersecurity" in m.id)
print(len(ids), "cybersecurity models")
print("\n".join(ids))
```

```
12 cybersecurity models
gemma-4-26b-a4b-it-cybersecurity
gemma-4-26b-a4b-it-cybersecurity-uncensored
glm-5.3-flash-cybersecurity
glm-5.3-flash-cybersecurity-uncensored
minimax-m3.1-flash-cybersecurity
minimax-m3.1-flash-cybersecurity-uncensored
orca-zero-1.5-cybersecurity
orca-zero-1.5-cybersecurity-uncensored
qwen3.8-27b-cybersecurity
qwen3.8-27b-cybersecurity-uncensored
qwen3.8-flash-next-cybersecurity
qwen3.8-flash-next-cybersecurity-uncensored
```

Any id from the full list works in `model=`, including the abliterated and uncensored builds on the [models page](https://pentestllm.ai/models).

## Rate limits

Your account’s tier caps how many requests it sends a minute and how many run at once, across all its keys; it rises with the balance, and a key’s own limits apply on top. The [acceptable use policy](https://pentestllm.ai/acceptable-use#rate-limits) lists the three tiers and what moves an account up. For a script, that means a thread pool wider than your tier’s “at once” figure only queues refusals.

A refused call comes back as `429` with `rate_limited` and a `retry-after` header, and nothing is charged for it. The SDK already retries a 429 after the wait the header gives; `max_retries` sets how many times. This sample raises it to five and catches the case where every retry was refused:

```python
import os
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.pentestllm.ai/v1",
    api_key=os.environ["PENTESTLLM_API_KEY"],
    max_retries=5,  # the SDK waits out 429s, honoring retry-after
)

try:
    response = client.chat.completions.create(
        model="deepseek-v4.1-flash-1017-heretic-uncensored-thinking-uncensored",
        messages=[{"role": "user", "content": "In two sentences: what is the difference between a vulnerability scan and a penetration test?"}],
        max_tokens=800,
    )
    print(response.choices[0].message.content)
except RateLimitError as err:
    print("still limited after retries:", err.message)
```

What it printed, unedited (the call was not limited):

```
A vulnerability scan is automated and broad — it enumerates systems and matches known signatures or misconfigurations against a database, producing a list of potential weaknesses without confirming exploitability. A penetration test is human-driven and targeted — it chains discovered weaknesses through actual exploitation to demonstrate real, validated impact on the target.
```

## Errors you may meet

- `AuthenticationError` (401): the key is wrong, revoked or missing from the environment.
- `APIStatusError` with status 402: the balance cannot cover the request, or the key reached its monthly spend limit. Nothing was charged; top up in the console.
- `NotFoundError` (404): the model id is misspelled or not listed. Compare it with `client.models.list()`.
- `RateLimitError` (429): the account’s tier or the key’s own limit refused the call. When it was the tier, `e.response.headers["x-rate-tier"]` says which one.

## What these calls cost

The three models above, priced live. Prices change; the [models page](https://pentestllm.ai/models) always has the current ones. [What PentestLLM costs and how to pay](https://pentestllm.ai/what-is-pentestllm) covers top-ups and payment methods.

Detected refusals and invalid non-streamed JSON qualify for automatic refunds within the daily cap. [Verify your receipt](https://pentestllm.ai/statements/verify).

| Model | Build | Input $/M | Output $/M |
| --- | --- | --- | --- |
| [OrcaCyber MiniMax M3.1 Flash](https://pentestllm.ai/models/minimax-m3.1-flash-cybersecurity) minimax-m3.1-flash-cybersecurity | Security | $2.00 | $4.00 |
| [OrcaCyber MiniMax M3.1 Flash (Uncensored)](https://pentestllm.ai/models/minimax-m3.1-flash-cybersecurity-uncensored) minimax-m3.1-flash-cybersecurity-uncensored | Security | $2.00 | $4.00 |
| [Uncensored DeepSeek V4.1 Flash 1017 Heretic Thinking](https://pentestllm.ai/models/deepseek-v4.1-flash-1017-heretic-uncensored-thinking-uncensored) deepseek-v4.1-flash-1017-heretic-uncensored-thinking-uncensored | Abliterated | $0.825 | $3.30 |

Prices per million tokens, read from the live catalog on 2026-12-03.

## Questions

### What base URL does the OpenAI Python SDK use for PentestLLM?

https://api.pentestllm.ai/v1, passed as base_url to OpenAI(). The key goes in api_key and starts with sk-ptl-.

### Which model should a Python script start with?

minimax-m3.1-flash-cybersecurity is a fast security build and the one the first sample calls. client.models.list() shows every id your key can use. See the models page.

### How do I raise my rate limit?

Move the account up a tier: a larger balance, more added over time or auto top-up raises it, as the acceptable use policy sets out. A key set higher than its tier gains nothing. See the rate limits.

### Does streaming work with the OpenAI SDK here?

Yes. Pass stream=True, and stream_options={"include_usage": True} if you want the token counts in the last chunk.

[Model list](https://pentestllm.ai/models) · [Pricing](https://pentestllm.ai/pricing) · [Families](https://pentestllm.ai/uncensored)

[Get a key](https://app.pentestllm.ai/console) Prepaid from $3, no subscription.

## New models and price changes, once a month.

New uncensored builds with their prices, price moves, and what the daily model check found.
