Chatbot API in Python: A Minimal Working Bot
A chatbot api python script needs surprisingly little code: install the OpenAI package, point it at a base URL, keep a list of messages and loop. This guide builds that bot in about 40 lines, then adds streaming, history limits and proper error handling.
Updated

Setup in two minutes
You need Python 3.9 or newer and an API key from the API key page. New accounts can claim $0.50 of trial credit there, which is plenty for everything in this article.
pip install openai
export API_KEY="your-key-here"
The endpoint is OpenAI-compatible, so you use the regular OpenAI client and only change the base URL: https://api.unfilteredaichatbot.cc/v1. The model ID is uncensored. The service serves one open-weight model, tuned to answer without content refusals for lawful adult use, and it handles text only.
The smallest working bot
Here is a chatbot api python example that remembers the conversation:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.unfilteredaichatbot.cc/v1",
api_key=os.environ["API_KEY"],
)
messages = [{"role": "system", "content": "You are a helpful, direct assistant."}]
while True:
user = input("you> ").strip()
if user in {"exit", "quit"}:
break
messages.append({"role": "user", "content": user})
resp = client.chat.completions.create(model="uncensored", messages=messages)
reply = resp.choices[0].message.content
print("bot>", reply)
messages.append({"role": "assistant", "content": reply})
The key idea: the API keeps no state. Each call must carry the whole conversation you want the model to see, which is why messages grows every turn. Forget to append the assistant reply, and the bot behaves as if it has amnesia.
Add streaming
Waiting for a full reply feels slow. With stream=True the text arrives in pieces over server-sent events:
def stream_reply(messages):
stream = client.chat.completions.create(
model="uncensored",
messages=messages,
stream=True,
stream_options={"include_usage": True},
)
text = ""
for chunk in stream:
if chunk.choices:
piece = chunk.choices[0].delta.content or ""
text += piece
print(piece, end="", flush=True)
if getattr(chunk, "usage", None):
usage = chunk.usage
print()
return text, usage
Usage is reported at the end of the stream, so you can log exact token counts per turn. One thing to remember: a streamed request holds its concurrency slot until the stream finishes. A full key has 8 slots and a trial key has 2.
Error handling that matches the cause
Different failures need different reactions, and the OpenAI SDK raises different exceptions for each.
| Exception | Meaning | Response |
|---|---|---|
AuthenticationError | HTTP 401, bad key or header | Stop and show a config message; retrying will not help |
RateLimitError | HTTP 429: rate_limited, concurrency or temporary overload | Wait, then retry |
APIConnectionError | Network problem | Retry a few times |
BadRequestError | HTTP 400, malformed request | Fix the request; do not retry |
import time
from openai import AuthenticationError, RateLimitError, APIConnectionError
def safe_create(messages, tries=5):
for i in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except AuthenticationError:
raise SystemExit("Check API_KEY and the base URL.")
except RateLimitError as e:
wait = float(e.response.headers.get("Retry-After", 2 ** i))
time.sleep(wait)
except APIConnectionError:
time.sleep(2 ** i)
raise RuntimeError("Gave up after retries")
The pattern is worth copying into every client you write: fail fast on errors that retrying cannot fix, and back off on the ones it can. Failed or refused requests are not charged, so retrying costs nothing extra. The SDK also retries some errors on its own; pass max_retries=0 to the client if you want your logic to be the only one.
Keep history under control
Input tokens cost $0.15 per 1M, so a long history is cheap, but not free, and the total of prompt plus reply must stay within 100,000 tokens. A simple strategy keeps the system message and the most recent turns:
def trim(messages, max_chars=24000):
system, rest = messages[0], messages[1:]
while rest and sum(len(m["content"]) for m in rest) > max_chars:
rest.pop(0)
return [system] + rest
A rough rule is 4 characters per token for English, so 24,000 characters is about 6,000 tokens. At that size each request costs about 6,000 x $0.15 / 1M = $0.0009 in input, plus the reply. For better memory than blunt trimming, summarise dropped turns into one message, as the chatbot overview discusses.
Save conversations and serve them over HTTP
Persist the list so the bot survives a restart:
import json, pathlib
path = pathlib.Path("chat.json")
if path.exists():
messages = json.loads(path.read_text())
# after each turn:
path.write_text(json.dumps(messages, ensure_ascii=False, indent=2))
For many users, store one list per user ID in a database and load it per request. Keep the API key on the server; never ship it in a browser or mobile app.
A tiny Flask endpoint turns the bot into a service your front end can call:
from flask import Flask, request, jsonify
app = Flask(__name__)
sessions = {} # user_id -> list of messages
@app.post("/chat")
def chat():
data = request.get_json()
msgs = sessions.setdefault(data["user_id"], [
{"role": "system", "content": "You are a helpful, direct assistant."}])
msgs.append({"role": "user", "content": data["text"]})
resp = client.chat.completions.create(model="uncensored", messages=trim(msgs))
reply = resp.choices[0].message.content
msgs.append({"role": "assistant", "content": reply})
return jsonify(reply=reply)
The in-memory dictionary is fine for a demo. Use a database once you run more than one process, or sessions will be lost on restart and differ between workers.
Log cost per turn
The response includes a usage object with prompt and completion token counts. Turning that into dollars takes three lines, and it tells you early if a prompt is more expensive than expected:
def cost(usage):
return usage.prompt_tokens * 0.15 / 1e6 + usage.completion_tokens * 0.50 / 1e6
resp = safe_create(messages)
print(f"turn cost: ${cost(resp.usage):.6f}")
Example: 2,000 prompt tokens and 300 completion tokens give $0.0003 + $0.00015 = $0.00045. You can also read the remaining balance from the X-Balance-USD response header, or call GET /v1/balance. Setting an alert when the balance drops under a threshold stops a running bot from failing at the worst moment.
Next steps
A few habits make the bot easier to run in practice. Log the X-Request-Id header with every error, because it lets support find the exact request. Set a client timeout, for example 60 seconds, so a stuck connection does not hang your loop. Test the failure paths on purpose: use a wrong key to see the 401 message, and fire three requests at once on a trial key to see a 429. Finding out how your code behaves in those cases is much cheaper before launch than after.
From here you can add tool calling, JSON mode with response_format={"type": "json_object"}, or wrap the function in a web framework. All parameters follow the OpenAI format, and the docs list the supported options. Prices are $0.15 per 1M input and $0.50 per 1M output tokens, with top-ups from $20 in crypto (USDT on TRC20 or USDC on Base) listed on the pricing page. If you build a persona-driven bot, read about running a free unfiltered chat bot. Remember that the service is for lawful adult use, and content involving minors is blocked.
More guides
Questions and answers
Do I need a special library?
No. The standard openai package works. Set base_url to this site's API address and the model to uncensored.
Does the API remember earlier messages?
No. Send the full conversation you want the model to see in the messages list on every request.
How do I handle a 429 error?
Wait and retry, using the Retry-After header when present. 429 can mean rate_limited, concurrency or a temporary overload.
How much does a chat turn cost?
With 2,000 input and 300 output tokens it costs $0.0003 plus $0.00015, which is $0.00045.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Key points
- Install openai, set the base URL and key, use model uncensored; everything else is the standard chat completions API.
- The API is stateless: your code owns the message list and sends it each time.
- Handle 401, 429 and connection errors separately; they need different responses.
- Trim history by token estimate to control cost and stay within the 100,000 token window.
Start with trial credit
Email and password, key on screen right away.