EN ▾
Create key

Setting a System Prompt via the API: Code

This nsfw llm system prompt api example is all code: the system message in curl, Python and Node, then a way to test prompt changes and keep versions under control. Everything uses the OpenAI request format and the model ID uncensored.

Summary

  • The system prompt is the first object in messages, with role system.
  • Resend it on every request; the API keeps no session state for you.
  • Fix temperature and seed when comparing two versions of a prompt.
  • Store prompts as versioned files and log the request ID with each call.
Glowing data ribbon flowing from a console into stacked, versioned prompt file tiles

The request in curl

The smallest working call is one system message and one user message sent to /v1/chat/completions. Replace $API_KEY with your key.

curl -s https://api.nsfwllmsystemprompt.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "system", "content": "You are the narrator of an adult fantasy story. Reply in third person, under 120 words."},
      {"role": "user", "content": "The caravan reaches the border gate at dusk."}
    ],
    "temperature": 0.8
  }'

The reply text is at choices[0].message.content. The response also carries an X-Balance-USD header with your remaining credit, which is handy while you are experimenting. Failed or refused requests are not charged.

Python with the OpenAI SDK

Point the SDK at the site's base URL and keep the rest of your code as it is. Keeping the prompt in a constant, outside the function, makes it easy to swap later.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwllmsystemprompt.com/v1",
    api_key=os.environ["API_KEY"],
)

SYSTEM_PROMPT = (
    "You are the narrator of an adult fantasy story. "
    "Reply in third person, under 120 words, and end on a choice for the user."
)

def reply(history, user_text):
    messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    messages += history
    messages.append({"role": "user", "content": user_text})
    resp = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        temperature=0.8,
        max_tokens=300,
    )
    return resp.choices[0].message.content

Notice that the history list holds only user and assistant turns. The function puts the system message in front each time, so a bug in your history code cannot push it out of first position.

Node.js

The same pattern in JavaScript, with streaming turned on. Tokens arrive as server-sent events, and the final chunk includes usage.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.nsfwllmsystemprompt.com/v1",
  apiKey: process.env.API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  stream: true,
  messages: [
    { role: "system", content: "You are a dry-witted lighthouse keeper in a fictional town. Keep replies short." },
    { role: "user", content: "What is the weather doing tonight?" },
  ],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

A streamed request holds one of your concurrency slots until the stream ends. A full key allows 8 at once, a trial key 2, so close streams you no longer read.

Where the system message goes in a long chat

The model sees the whole messages array as one prompt. Put the system message first, then the turns in order. When the conversation approaches the 100,000-token window, drop or summarise the oldest turns, never the system message.

A simple rule works for most apps: keep the system prompt, keep the last N turns, and replace everything older with a short summary written by the model itself. Store that summary as an extra assistant or system line right after the main prompt. The summary call is a separate request with its own, much shorter system prompt.

Avoid sending several system messages scattered through the history. It is valid, but the instructions then compete, and you lose the clear picture of what the model was told at turn 40 versus turn 4.

Testing a prompt change

A prompt is code that fails silently, so give it tests. The cheapest useful setup is a fixed set of 10 to 20 short conversations (openers, edge cases, a few awkward user messages) that you replay against every new version.

  • Set temperature low (0 to 0.3) and pass a fixed seed, so differences between runs come mostly from the prompt, not from sampling.
  • Compare outputs for the properties you care about: length, format, whether the persona holds, whether the pause keyword works. Automate the checks you can (word count, JSON parses, banned phrase absent) and read the rest by eye.
  • Change one line at a time. If you rewrite the whole prompt, you will not know which edit helped.
import json
from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwllmsystemprompt.com/v1", api_key="YOUR_API_KEY")

def run_suite(system_prompt, cases):
    results = []
    for case in cases:
        resp = client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "system", "content": system_prompt},
                      {"role": "user", "content": case}],
            temperature=0.2,
            seed=42,
            max_tokens=250,
        )
        text = resp.choices[0].message.content
        results.append({"case": case, "words": len(text.split()), "text": text})
    return results

cases = ["Hello.", "Tell me about yourself.", "[pause] Can we change the scene?"]
print(json.dumps(run_suite("You are Mara, a lighthouse keeper. Be brief.", cases), indent=2))

Run it once per prompt version and diff the JSON files. Runs are short and cheap: a case with 2,000 input and 250 output tokens costs $0.000425, so 20 cases are under a cent.

Versioning prompts

Treat prompts as files, not strings buried in code. One file per prompt, kept in git, with a version in the name or header (narrator.v3.txt). Your app loads the file at start-up and records the version with every conversation.

Each response carries an X-Request-Id header. Log it next to the prompt version, the user ID and the timestamp. When a user reports a strange reply, you can tell which prompt produced it. With the Python SDK, read headers through the raw response:

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "system", "content": SYSTEM_PROMPT},
              {"role": "user", "content": "Hello."}],
)
request_id = raw.headers.get("X-Request-Id")
balance = raw.headers.get("X-Balance-USD")
completion = raw.parse()

To roll out a new version safely, send a small share of conversations to it first, compare your logged metrics, then switch everyone. Keep the previous file so rolling back is one config change.

Sampling settings that suit a persona prompt

The system prompt sets what the model should do. The sampling parameters set how adventurously it does it, and they interact. A few starting values for chat apps, all of which are passed through to the model:

  • temperature 0.7 to 0.9 for roleplay and fiction. Lower values give flat, repetitive scenes, while values near or above 1 start to drift out of character.
  • top_p 0.9 to 0.95 if you want to trim the unlikely tail of word choices. Change either temperature or top_p first, not both at once.
  • frequency and presence penalties of 0.1 to 0.4 when a character keeps repeating the same phrase. Heavy values make prose strange, so raise them slowly.
  • stop sequences when your prompt defines a format, such as a closing marker line, so the model does not continue past the end of its turn.

When you test prompt changes, freeze these values. When you test sampling changes, freeze the prompt. Mixing both in one experiment is the usual reason a team cannot say which change improved the output.

Limits and errors to handle

Retry logic belongs in the same wrapper as your prompt code. Over a limit the API returns HTTP 429 with an error code: rate_limited for requests per minute (300 on a full key, 60 on a trial key) or concurrency for too many requests at once. On temporary overload it also answers 429 and sends Retry-After: 5. Wait that long, then retry.

Details for every parameter are in the documentation, and the pricing page explains per-token billing. For the wider app around the prompt, see the NSFW chatbot page.

Here is a small wrapper that retries on 429 and waits the time the server asks for. It reads the Retry-After header when it is present and otherwise backs off for a few seconds:

import time
from openai import OpenAI, RateLimitError

client = OpenAI(base_url="https://api.nsfwllmsystemprompt.com/v1", api_key="YOUR_API_KEY")

def chat(messages, tries=4):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(
                model="uncensored", messages=messages, max_tokens=300
            )
        except RateLimitError as err:
            wait = 5
            retry_after = getattr(err.response, "headers", {}).get("Retry-After")
            if retry_after:
                wait = int(retry_after)
            time.sleep(wait * (attempt + 1))
    raise RuntimeError("still rate limited after retries")

The wrapper multiplies the wait on each attempt, so a short burst of overload clears without hammering the endpoint. If you see the concurrency code often, the fix is not a longer wait but a smaller number of requests in flight at once: add a semaphore that allows at most 8 calls, or 2 on a trial key.

Frequently asked questions

Which role name does the system prompt use?

Use role system, exactly as in the OpenAI chat format, as the first item in the messages array.

Do I need to send the system prompt with every request?

Yes. The API does not keep a session, so each request must include the full list of messages, system prompt first.

Can I use the Responses endpoint instead?

The service also exposes POST /v1/responses. The examples here use /v1/chat/completions, which is the most widely supported by SDKs and client apps.

How do I make test runs repeatable?

Pass a low temperature and a fixed seed. Both are passed through to the model, which makes runs far more comparable between prompt versions.

Start with free credits

Enter your email and password to receive your key instantly.