EN ▾
Get API key

How to Use an AI API in a Chat App: Step by Step

Using an AI API comes down to one HTTP call: you send a list of messages and get a reply back. This walkthrough builds a working chat app on an OpenAI-compatible endpoint, from the first curl to streaming and error handling.

Updated

Terminal connected by a stream of light to chat bubbles and a key, showing an API call powering a chat app
per 1M input tokens
$0.15
Output tokens / 1M
$0.50
token context
100,000
trial credit
$0.50
requests per minute
300

Key points

  • You need three things: a base URL, an API key, and a model ID. Here the model ID is uncensored.
  • The API is stateless, so your app stores the conversation and resends it with each request.
  • Stream replies with stream: true so users see text as it is written.
  • Treat HTTP 429 as a normal event and retry after a short wait.

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).

Get API key

What you need before you write code

If you want to know how to use ai api access in a real project, start by reducing it to three values. The base URL tells your code where to send requests. The API key proves who you are. The model ID picks which model answers. For this service they are:

  • Base URL: https://api.uncensoredaichat.cc/v1
  • Model ID: uncensored
  • Auth: an Authorization: Bearer YOUR_API_KEY header

The API follows the OpenAI format, so you have two endpoints to learn: POST /v1/chat/completions to get a reply and GET /v1/models to list models. Any OpenAI SDK works once you change the base URL and key, which means you can use the official Python or Node library instead of writing HTTP code by hand.

It is text only. There is no image, audio or video generation, no embeddings and no fine-tuning, so plan your app around chat, writing and structured text output.

Step 1: Get a key

Sign up with Google, or with an email and a password, on the API key page. After sign-up you can claim $0.50 of trial credit with one click. It is valid for 7 days, needs no payment, and is one per person, which is enough for several hundred test messages. Copy the key and store it as an environment variable named UNCENSORED_API_KEY (in a shell, export UNCENSORED_API_KEY=your-key), never in source code you push to a repository.

When the trial is used up, credit is prepaid from $20 to $500 by crypto only (USDT on TRC20 or USDC on Base), with no subscription. The pricing page has the full rate table: $0.15 per 1M input tokens and $0.50 per 1M output tokens.

Step 2: Send the first request

Before you build anything, prove the key works with curl. If this returns JSON with a reply, everything downstream is just plumbing.

curl https://api.uncensoredaichat.cc/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 an API key is in two sentences."}
    ]
  }'

The reply sits at choices[0].message.content. The same response carries a usage object with the prompt and completion token counts, and the headers include X-Request-Id and X-Balance-USD. Keep the request ID in your logs, because it is the first thing support will ask for if a call misbehaves.

Messages have three main roles: system for standing instructions, user for what the person typed, and assistant for earlier replies from the model.

Step 3: Call it from Python or Node

With the official SDKs the only difference from calling OpenAI is the constructor. Python first:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaichat.cc/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": "Give me three names for a fantasy tavern."},
    ],
    temperature=0.8,
)
print(resp.choices[0].message.content)

And the same call in Node (version 18 or later, with npm install openai):

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredaichat.cc/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);

Sampling settings such as temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model. Lower temperature gives steadier answers, and higher values give more varied ones.

Step 4: Keep the conversation going

The most important thing to understand when you build a chat app is that the API has no memory. Each request stands alone. To make the model remember what was said, your app keeps a list of messages and sends the whole list every time. A minimal loop looks like this:

import os
from openai import OpenAI

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

history = [{"role": "system", "content": "You are a friendly writing partner."}]

while True:
    text = input("you: ")
    if text.strip() in ("quit", "exit"):
        break
    history.append({"role": "user", "content": text})
    resp = client.chat.completions.create(model="uncensored", messages=history)
    reply = resp.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    print("bot:", reply)

The context window is 100,000 tokens, prompt plus completion, which is a lot of room. You still pay for the whole history on every call, so long chats cost more per turn than short ones. Once a conversation passes a size you pick, drop the oldest turns or replace them with a short summary that you generate with the same API. In a web app, store each user's history in your database, keyed by conversation ID, and build the message list on the server so your key never reaches the browser.

Step 5: Stream the reply

A long answer can take several seconds to finish. Streaming sends the text in pieces over server-sent events, so users see words appear right away. Set stream: true and read the chunks as they arrive:

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Tell a short story about a lighthouse keeper."}],
    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)

Usage is reported at the end of the stream, so you can still log the cost of each call. One detail matters for capacity planning: a streamed request holds its concurrency slot until the stream ends, so if your users read slowly and your code reads slowly with them, slots stay busy for longer.

Step 6: Ask for structured output

Chat is only one way to use an AI API. Many apps need the model to return data that code can read, such as a list of tags, a character sheet or a classification. JSON mode helps here. Set response_format to {"type": "json_object"} and also describe the shape you want in the prompt, because the setting guarantees valid JSON but not your field names.

import json, os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": 'Reply with JSON only: {"name": string, "traits": [string]}'},
        {"role": "user", "content": "Invent a grumpy dwarf blacksmith."},
    ],
)
character = json.loads(resp.choices[0].message.content)
print(character["name"], character["traits"])

Tool calling works the same way as in the OpenAI SDK. You pass a tools list with function schemas, the model replies with a tool_calls entry, your code runs the function, and you send the result back as a message with role: "tool". Use it when the app needs to look something up or take an action, such as fetching a user profile before the model answers.

Handle limits and errors

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Go over either and the API answers with HTTP 429. The error code tells you which limit you hit: rate_limited means too many requests per minute, and concurrency means too many at once. On temporary overload you also get a 429 with a Retry-After: 5 header. The correct response to all three is the same: wait, then retry. A small wrapper does it:

import os, time
from openai import OpenAI, RateLimitError

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

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

If you serve many users, put a queue in front of the API and cap your own workers at 8, so the limit is something you plan for instead of something users hit. The request body can be up to 8 MB. Failed or refused requests are not charged.

When you are ready for more, the same endpoint supports tool calling, JSON mode with response_format, and streamed tool calls. These are covered in the API documentation and in the integration guide.

Design choices that save trouble later

A few decisions are easy to make early and painful to change afterwards. Keep the API key on your server and have the browser talk to your own endpoint, which then talks to the AI API. Otherwise anyone who opens the developer tools can copy your key and spend your credit.

Pick one small feature to ship first. A chat box that sends a message, shows a streamed reply and keeps a history in your database is already a useful product, and each later addition (tools, JSON output, summaries) can be tested on its own.

Write the system prompt like a short job description: who the assistant is, how it should sound, and what it should avoid. Keep it under a few hundred tokens, since it is sent with every request. Test it against rude, vague and very long user messages before you launch, not after.

Log the request ID, the token counts and the time for every call. Those three fields answer most questions you will have later, from why a bill went up to which request failed. Finally, decide up front what happens when credit runs out: show a clear message to the user and notify yourself, rather than letting the chat window fail without explanation. The X-Balance-USD header makes that check cheap.

Questions and answers

Do I need to install anything special?

No. Any OpenAI SDK or client works. Install the official Python or Node package, set the base URL to https://api.uncensoredaichat.cc/v1 and use your key.

Why does the model forget earlier messages?

The API is stateless. Your app has to resend the earlier messages in the messages array on every request.

Is there a free way to test?

New users can claim $0.50 of trial credit with one click on the API key page, valid for 7 days. Trial keys allow 2 concurrent requests and 60 requests per minute.

Which model ID should I use?

Use uncensored in the model field. You can confirm the available ID with GET /v1/models.

What content is not allowed?

The model is tuned for lawful adult use without content refusals, but sexual content involving minors is a hard limit and is never allowed.

Your key is one form away

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

Start with trial credit

Email and password, key on screen right away.