EN ▾
Get API key

How to Create an AI Chat Bot in Python With an API

To learn how to create an ai chat bot, you need three pieces: an API key, a list of messages that you keep between turns, and a loop that sends them to the model and prints the answer. This guide builds that in Python, then adds streaming and memory trimming.

Updated

Two glass speech bubbles linked by a looping ribbon of light, representing a chat bot conversation loop
Isometric scale weighing stacks of token blocks against coins, illustrating per-token API pricing
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

  • A chat bot is a loop around one API call; the memory is just a list you resend each turn.
  • Streaming makes replies feel instant; set stream=True and print chunks.
  • Trim old messages to stay inside the 100,000 token window and keep costs flat.
  • A typical turn costs a fraction of a cent at $0.15 and $0.50 per 1M tokens.

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

  • Python 3.9 or newer and the openai package: pip install openai.
  • An API key. Sign up and use the API key page; new users can claim $0.50 of trial credit there with one click, no card needed.
  • The endpoint address https://api.uncensoredaichat.cc/v1 and the model ID uncensored.

The service follows the OpenAI request format, so any tutorial written for the OpenAI SDK applies. If you want the basics of calling an API first, read how to use an AI API. Set the key as an environment variable so it never ends up in your source code:

export CHAT_API_KEY="your-key-here"

Step 1: one request

Start with a single call so you know the connection works.

import os
from openai import OpenAI

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

reply = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a friendly assistant. Keep answers short."},
        {"role": "user", "content": "What can you help me with?"},
    ],
)
print(reply.choices[0].message.content)

The messages list is the whole conversation. The system message sets behavior, user messages are what the person typed, and assistant messages are the model's earlier answers. The model has no memory of its own between calls. Everything it knows about the conversation is in that list.

Step 2: the chat loop with memory

Memory is the part beginners overthink. You append each user message and each reply to the same list, then send the whole list again.

import os
from openai import OpenAI

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

history = [{"role": "system", "content": "You are a friendly assistant. Keep answers short."}]

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

Run it, tell the bot your name, then ask for it three turns later. It remembers because the earlier lines are in history. Delete that list and it forgets.

Step 3: stream the reply

Waiting for the full answer feels slow. With stream=True the API sends the text in small chunks as it is generated, using server-sent events.

def ask(history):
    stream = client.chat.completions.create(
        model="uncensored", messages=history, stream=True
    )
    parts = []
    print("Bot: ", end="", flush=True)
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            piece = chunk.choices[0].delta.content
            parts.append(piece)
            print(piece, end="", flush=True)
    print()
    return "".join(parts)

Replace the call inside the loop with answer = ask(history). Token usage is sent at the end of the stream, so you can still log what each turn cost. One detail matters for later: a streamed request holds its concurrency slot until the stream ends. A bot that opens many streams and never reads them to the end will hit the limit.

Step 4: trim memory before it grows

Resending the whole conversation means each turn costs more than the last, and the list eventually fills the context window. The window here is 100,000 tokens, prompt and completion together. That is a lot, but a long-running bot will get there. A simple rule keeps it bounded: keep the system message and the last N messages.

MAX_MESSAGES = 20

def trim(history):
    system, rest = history[0], history[1:]
    return [system] + rest[-MAX_MESSAGES:]

Call history = trim(history) before each request. For a bot that must remember facts for a long time, keep a short running summary as a second system message and rewrite it every few turns. A counting approach by characters is good enough to start: four characters is roughly one token for English text, which gives a quick estimate without a tokenizer.

Give the bot a personality and settings

The system message is where a generic bot becomes your bot. Keep it specific and short: who the bot is, how it talks, what it should refuse to guess, and the format of its answers.

SYSTEM = (
    "You are Mira, a support assistant for a small bike shop. "
    "Answer in two or three sentences. "
    "If you do not know a price or opening time, say so and ask the user to check with the shop."
)

Instructions like "say so if you do not know" cut down on invented details. Two settings change the feel of the replies:

  • temperature: lower values (around 0.2) give steadier, more repeatable answers, which suits support bots. Higher values (0.8 and up) give looser, more varied text, which suits creative chat.
  • max_tokens: optional here, because a completion can use whatever is left of the window. Set it when you want to cap the length of a reply, for example in a chat widget with limited space.

Change one setting at a time and rerun the same five questions. If you change the prompt and the temperature together you will not know which one fixed or broke the answer. Keep those five questions in a file; they become your first test set, and you can rerun them whenever you edit the prompt.

What a conversation costs

Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Consider a turn with 1,000 tokens of history and prompt, and a 300 token answer:

  • Input: 1,000 / 1,000,000 x $0.15 = $0.00015
  • Output: 300 / 1,000,000 x $0.50 = $0.00015
  • One turn: $0.0003, so 1,000 turns cost $0.30

With 20 messages kept, a turn might send around 3,000 input tokens. Then input is $0.00045 and a turn with a 300 token answer costs $0.0006. Even then a turn costs well under a tenth of a cent. Trimming is what keeps the figure from drifting upward. For a comparison with another provider, check their current pricing; the article how much is the OpenAI API explains how to estimate costs for any token-priced service.

Failed or refused requests are not charged, and credit never expires. The minimum top-up is $20, with bonuses of +5% from $50, +10% from $100 and +15% from $200. See the pricing page for the details.

Handling errors, limits and next steps

A real bot should survive a bad moment. Wrap the call and retry on 429.

import time
from openai import RateLimitError

def safe_create(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")

A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Going over returns HTTP 429 with the code rate_limited (per minute) or concurrency (too many at once). A temporary overload also sends 429 with Retry-After: 5. If your bot serves many users, queue their messages instead of firing all of them together.

Next steps

Once the loop works, extend it in small steps: store history per user in a database, wrap the loop in a web framework or a chat platform bot, or add tool calling so the bot can look things up. The endpoint supports tools, JSON mode and the usual sampling settings. The docs list each one, and the uncensored API overview explains how the model behaves.

The model is one open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It does not generate images, audio or video, and it has a hard limit against sexual content involving minors. Prompts are not used for training.

Questions and answers

Do I need a framework to build a chat bot?

No. A loop around one API call and a list of messages is enough for a working bot. Frameworks only help when you add a web interface or many users.

Why does the bot forget things?

The model has no memory between calls. It only knows what is in the messages list you send, so keep the history and resend it.

How do I stop the bot from getting expensive?

Trim the history to the last N messages and keep the system prompt short. Cost grows with the input tokens you send each turn.

Can I try this without paying?

Yes. New users can claim $0.50 of trial credit on the API key page, valid for 7 days and without a card.

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.