How to Use Ollama in a Chatbot, Hosted or Local
How to use Ollama in chatbot projects comes down to one idea: your bot needs an OpenAI-style chat endpoint, and the same code can point at a local runner or at a hosted API. This guide builds the bot against a hosted endpoint so you can skip the GPU.
Updated
Key points
- A chatbot is a loop that resends the message history to /v1/chat/completions and prints the reply.
- Switching between a local runner and this hosted API means changing the base URL, the key and the model ID.
- SillyTavern and LangChain both accept a custom OpenAI-compatible endpoint, so no adapter code is needed.
- Trim history, stream replies and handle HTTP 429 with a retry, and the bot stays stable under load.

What a chatbot needs from a model endpoint
Strip away the interface and a chatbot is small. It keeps a list of messages, sends that list to a model, gets text back, appends it to the list, and waits for the next user message. The model itself has no memory between calls. Everything it knows about the conversation is whatever you put in the messages array on that request.
That is why the OpenAI chat format became the common denominator. Local runners such as Ollama, LM Studio, the llama.cpp server and vLLM can expose an OpenAI-style endpoint, and hosted services copy the same shape. If your bot talks to that shape, you can move it between a model on your own machine and a model in a data center without rewriting the logic.
The API on this site uses that shape. It accepts POST /v1/chat/completions and GET /v1/models, takes a standard bearer key, and serves one model with the ID uncensored. It is text only, so a bot that needs images or audio will need a separate service for those parts. Details are in the API docs.
Why use a hosted endpoint at all when you have Ollama on your laptop? A few honest reasons. A larger model may not fit in your VRAM. A bot that serves several people at once needs a server that stays up. And you may not want your machine pinned at full load every time someone sends a message. If none of those apply, local is a fine choice and the code below still works with a changed URL.
A working chatbot loop in Python
Install the official SDK with pip install openai. The client only needs the base URL and your key. Replace YOUR_KEY with the key from your dashboard.
from openai import OpenAI
client = OpenAI(
base_url="https://api.ollamauncensored.top/v1",
api_key="YOUR_KEY",
)
history = [
{"role": "system", "content": "You are Mira, a dry-witted assistant who answers briefly."}
]
while True:
user_text = input("you> ")
if user_text.strip() in ("/quit", "/exit"):
break
history.append({"role": "user", "content": user_text})
stream = client.chat.completions.create(
model="uncensored",
messages=history,
temperature=0.8,
stream=True,
)
reply = ""
print("bot> ", end="", flush=True)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
reply += piece
print(piece, end="", flush=True)
print()
history.append({"role": "assistant", "content": reply})
Three details matter here. The system message sits at index 0 and sets the persona, so it never leaves the list. Every assistant reply is appended back, because the model will not remember it otherwise. And stream=True prints tokens as they arrive, which makes a slow answer feel much faster to the person waiting.
The same bot in Node
The JavaScript SDK works the same way. Install it with npm install openai and run the file as an ES module.
import OpenAI from "openai";
import readline from "node:readline/promises";
const client = new OpenAI({
baseURL: "https://api.ollamauncensored.top/v1",
apiKey: process.env.API_KEY,
});
const history = [
{ role: "system", content: "You are Mira, a dry-witted assistant who answers briefly." },
];
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
while (true) {
const text = await rl.question("you> ");
if (text === "/quit") break;
history.push({ role: "user", content: text });
const stream = await client.chat.completions.create({
model: "uncensored",
messages: history,
stream: true,
});
let reply = "";
process.stdout.write("bot> ");
for await (const chunk of stream) {
const piece = chunk.choices[0]?.delta?.content ?? "";
reply += piece;
process.stdout.write(piece);
}
process.stdout.write("\n");
history.push({ role: "assistant", content: reply });
}
rl.close();
Pointing existing chat frontends at the API
You may not want to write the loop at all. Most roleplay and chat frontends already speak the OpenAI format, so the job is only to fill in three fields.
SillyTavern
SillyTavern lets you add an OpenAI-compatible endpoint. Open the API connection panel, choose Chat Completion, and pick the custom OpenAI-compatible source. Then enter:
- Endpoint:
https://api.ollamauncensored.top/v1 - API key: the key from your dashboard
- Model:
uncensored
Press connect. If the status turns green, the frontend reached /v1/models and your key was accepted. Character cards, lorebooks and author notes are all assembled by the frontend into one messages array, which is exactly what the endpoint expects. For fiction and companion-style chat among adults, this is the usual way people use the service.
LangChain
LangChain ships an OpenAI chat wrapper that accepts a custom base URL, so the endpoint drops in without a new class.
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.ollamauncensored.top/v1",
api_key="YOUR_KEY",
temperature=0.7,
)
answer = llm.invoke([
SystemMessage(content="You are a concise support agent for a bike shop."),
HumanMessage(content="My chain keeps slipping. What should I check first?"),
])
print(answer.content)
From here you can wrap the model in a chain, add a memory component, or bind tools. The service supports tool calling with tools and tool_choice, with results returned as role: "tool" messages, so agent-style bots that call your functions work as well.
Keeping history inside the window
The loop above has a flaw: the list only grows. Each turn resends everything, so the prompt gets longer and the cost of each request rises with it. The context window here is 100,000 tokens, prompt and completion together, which is a lot of room for chat but not infinite. A bot that runs for weeks in one thread will hit it.
A simple policy covers most bots. Keep the system message, keep the last N turns, and drop the middle. A slightly better policy asks the model to summarize the dropped turns into one short message that you insert after the system prompt.
from openai import OpenAI
client = OpenAI(base_url="https://api.ollamauncensored.top/v1", api_key="YOUR_KEY")
def trim(history, keep_last=24):
system, rest = history[0], history[1:]
return [system] + rest[-keep_last:]
# before each request
messages = trim(history)
reply = client.chat.completions.create(
model="uncensored",
messages=messages,
)
Count in messages if you want it quick, or count tokens if you want precision. A rough rule is that one token is about three quarters of an English word, so 100,000 tokens is on the order of 75,000 words. You will almost never need that much per request. Shorter prompts are faster and cheaper, and a trimmed bot often stays more on topic than one dragging a huge thread behind it.
For more on the model behind the endpoint, see Uncensored Qwen via API, and check the docs for the exact request fields.
Handling load and errors
A bot that works for you alone can break when ten people message it at once. Know the limits before you ship. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent requests and 60 per minute. Going over returns 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 the same moment. On temporary overload the API also returns 429 with a Retry-After: 5 header.
One thing catches people out: a streamed request holds its concurrency slot until the stream ends. If a user opens a reply and walks away from a half-read stream on your side, that slot stays busy. Close streams you no longer need.
A small retry wrapper handles most of it:
import time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.ollamauncensored.top/v1", api_key="YOUR_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")
For a bot with many users, put a semaphore of size 8 in front of the call, or a queue, so requests wait in your code instead of bouncing off the limit. Failed or refused requests are not charged, so retries do not cost you anything extra.
Each response also carries headers worth logging: X-Request-Id to quote if you contact support, and X-Balance-USD so the bot can warn you when credit runs low.
What it costs to run a chatbot
Billing is pay as you go from prepaid credit: $0.15 per 1M input tokens and $0.50 per 1M output tokens. There is no subscription, and credit does not expire. A typical chat turn is small, so the numbers are friendly.
Take a turn with 2,000 tokens of history and system prompt going in and a 500-token reply coming out. Input costs 2,000 x $0.15 / 1,000,000 = $0.0003. Output costs 500 x $0.50 / 1,000,000 = $0.00025. The turn totals $0.00055, so 1,000 turns cost $0.55.
New accounts can claim $0.50 of trial credit with one click on the key page after sign-up. It needs no card and lasts 7 days, which is enough to test a bot end to end. Top-ups start at $20; see pricing for the bonus tiers. To get a key, go to the API key page.
Before you ship
Run through this list once. Put the key in an environment variable, never in a frontend bundle. Cap history length. Stream replies. Retry on 429 with a pause. Log the request ID. Test with the trial first, then top up when the bot behaves.
The model is tuned to answer without content refusals for lawful adult use, and one rule is fixed: no sexual content involving minors. If your bot is public, state your own rules in the system prompt and moderate who can talk to it. Prompts sent through the API are not used for training.
More guides
Questions and answers
Can I use Ollama itself as the backend for a chatbot?
Yes. Ollama can expose an OpenAI-style endpoint on your machine, and the loops above work against it by changing the URL, key and model name. This site's endpoint is the hosted alternative, using the model ID uncensored.
Do I need to change my code to switch from a local runner?
Usually only three values: the base URL, the API key and the model ID. The message format, streaming and tool calling follow the OpenAI chat shape.
How many users can one key serve?
A full key allows 8 concurrent requests and 300 requests per minute. Queue requests in your bot so extra users wait instead of receiving 429 errors.
Does the chatbot remember earlier conversations?
No. The model keeps no memory between requests, so your bot must resend the history each time and decide what to trim or store.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.