EN ▾
Get API key

How to Use the ChatGPT API and Compatible Ones

Learning how to use the ChatGPT API takes about ten minutes, and the skills carry over to any OpenAI-compatible service. This guide walks through keys, requests, streaming, tools and errors, with code that runs against an uncensored endpoint.

Updated

Key points

  • The ChatGPT API is OpenAI's; its request format has become a standard that many providers copy.
  • Any OpenAI SDK works with this service after you change the base URL and key.
  • The core call is POST /v1/chat/completions with a model and a list of messages.
  • Streaming, tool calling and JSON mode all work with the same client code.
Terminal connected by a data pipe to a server, illustrating an OpenAI-compatible API request

What the ChatGPT API actually is

"ChatGPT API" is the everyday name for OpenAI's chat completions interface. You send a list of messages over HTTPS, and the server sends back the next message. ChatGPT, the consumer app, is a separate product. When you build something, you call the API, pay per token, and handle your own interface and memory.

The useful part is that the request shape became a de facto standard. Other providers, local servers and hosted services accept the same JSON. That means a program written for one of them usually needs only two changes to talk to another: the base URL and the API key. This page uses an uncensored, OpenAI-compatible service as the example, but every step below is the same pattern you would use elsewhere. To be clear, this service is not OpenAI's API and not a router across vendors. It runs one open-weight model, and the model ID is uncensored.

Get a key and test it

Sign up with Google or with email and password, then open the API key page. New users can claim $0.50 of trial credit there with one click. It lasts 7 days and needs no payment details, which is plenty for everything in this guide. Authentication is a standard bearer header: Authorization: Bearer YOUR_KEY.

First check that the key works by listing models:

# the list should include the model ID: uncensored
curl https://api.nsfwchatgpt.top/v1/models \
  -H "Authorization: Bearer YOUR_KEY"

You should get a JSON list that includes uncensored. If you get a 401, the key was copied wrong. Keep the key in an environment variable and never in code you commit.

export UNCENSORED_API_KEY="paste-your-key-here"

Your first chat request

The method is POST /v1/chat/completions. The body needs a model and a messages array. Each message has a role (system, user, assistant or tool) and content.

curl https://api.nsfwchatgpt.top/v1/chat/completions \
  -H "Authorization: Bearer $UNCENSORED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Explain what a token is in two sentences."}
    ],
    "temperature": 0.7
  }'

The reply holds a choices list. The text is at choices[0].message.content, and the usage object tells you how many prompt and completion tokens you used. The response headers carry X-Request-Id for support and X-Balance-USD for your remaining credit.

The same call in Python

Install the official SDK with pip install openai. You only point it at a different base URL.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nsfwchatgpt.top/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "Explain what a token is in two sentences."},
    ],
)
print(resp.choices[0].message.content)
print(resp.usage)

The same call in Node

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.nsfwchatgpt.top/v1",
  apiKey: process.env.UNCENSORED_API_KEY,
});

const resp = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Give me three names for a fantasy tavern." }],
});
console.log(resp.choices[0].message.content);

Keeping a conversation going

The API has no memory. Each request stands alone, so a chat is just you resending the earlier messages every time. Append the assistant's answer to your list, add the new user message, and send the whole list again.

history = [{"role": "system", "content": "You are a helpful assistant."}]

def ask(text):
    history.append({"role": "user", "content": text})
    r = client.chat.completions.create(model="uncensored", messages=history)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(ask("Name a colour."))
print(ask("Now name one that goes well with it."))

This has a cost consequence. Input tokens grow with each turn because the old turns are billed again as input. The window is 100,000 tokens for prompt plus completion, so very long chats eventually need trimming or a short summary of the early part. The pricing page shows the per-token rates so you can estimate this.

Streaming, JSON mode and tools

Streaming

Set stream: true and the server sends server-sent events, so text appears as it is generated. Usage arrives at the end. A streamed request keeps its concurrency slot until the stream closes.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a four-line poem about rain."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

JSON mode

Pass response_format={"type": "json_object"} and the reply will be valid JSON. Also tell the model in the prompt what shape you want, because the flag only guarantees syntax, not your schema.

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Return JSON with keys city and country for Paris."}],
    response_format={"type": "json_object"},
)
print(r.choices[0].message.content)

Tool calling

Define functions in tools, optionally steer with tool_choice, and the model returns tool_calls when it wants one run. You execute the function, then send the result back as a message with role: "tool" and the matching tool_call_id. Streamed tool calls are supported too. The integration docs list every supported parameter, including temperature, top_p, stop, seed and the penalties.

Parameters worth knowing

Most requests need only model and messages. A few optional fields change behaviour in ways you will notice quickly.

  • temperature controls randomness. Around 0.2 suits extraction and code, 0.7 to 1.0 suits writing and dialogue.
  • top_p trims the pool of likely next words. Change either it or temperature, not both at once, so you can see what each does.
  • max_tokens is optional here. Without it the completion can use whatever remains of the 100,000-token window. Set it when you want to cap cost or force short answers.
  • stop ends generation when a given string appears, which is handy for structured output or role-play turns.
  • seed makes outputs more repeatable while you compare prompts.
  • frequency and presence penalties discourage repetition in long generations.

A common beginner mistake is putting instructions only in the user message and then wondering why they fade in a long chat. Put standing rules in the system message and keep it short. Another is forgetting that the model name is a string that must match exactly; here it is always uncensored.

Errors, limits and costs

Four things go wrong most often. A 401 means a bad or missing key. A 429 with the code rate_limited means you exceeded the request-per-minute limit, and a 429 with concurrency means too many requests were open at once. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Temporary overload also returns 429, with a Retry-After: 5 header. The fix is a retry with a short delay:

import os, time
from openai import OpenAI, RateLimitError

client = OpenAI(
    base_url="https://api.nsfwchatgpt.top/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

def chat(messages, tries=4):
    for i in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError:
            time.sleep(5 * (i + 1))
    raise RuntimeError("still rate limited")

The body limit is 8 MB. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription. A request with 1,000 tokens in and 500 out costs 1,000 x 0.15 / 1,000,000 + 500 x 0.50 / 1,000,000 = $0.00015 + $0.00025 = $0.0004. Failed or refused requests are not charged.

Choosing between OpenAI's service and a compatible one

Use OpenAI's own API when you need their specific models or features, and check their current pricing and policies on their site. Use an OpenAI-compatible service like this one when you want a single open-weight model that answers without content refusals for lawful adult use, prepaid billing and no subscription. It handles text only, so there is no image, audio or video generation, no embeddings and no fine-tuning. One hard rule applies: no sexual content involving minors.

Treat the key like a password. Do not put it in front-end JavaScript, where any visitor can read it; call the API from a server you control and let your page talk to that server. If a key leaks, create a new one and stop using the old one. For a first project, a small script that reads from an environment variable is enough, and you can move to a proper backend when real users arrive. Watch the X-Balance-USD header in the first days so you learn what your typical request costs before you scale anything up.

The good news is that the choice is cheap to reverse. Because the client code is identical, you can keep both configurations and switch with an environment variable. For a use-case-specific walkthrough, see the NSFW AI API guide. Prompts sent here are not used for training.

Questions and answers

Is the ChatGPT API free?

OpenAI sets its own pricing, so check their current terms. On this service, new users can claim $0.50 of trial credit with one click, valid for 7 days, then pay as you go from $20.

Can I use the official OpenAI SDK with another provider?

Yes. Set base_url to the provider's endpoint and use their key. For this service that is https://api.nsfwchatgpt.top/v1 with the model uncensored.

Does the API remember earlier messages?

No. You resend the conversation in the messages list on every request, and earlier turns count as input tokens again.

What does a 429 error mean?

You hit a limit or the service is briefly overloaded. Check the error code, wait a few seconds and retry.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key